Thursday, 25 April 2024

PlantUML: escape creole characters

Using ~ (tilde), we can escape creole characters.

Example

This is not ~*~*printed in bold~*~*

 

escapeCreole.txt

@startuml

scale 1.5

Client -> Server: Send message


note left of Client 
This is **printed in bold**
This is not ~*~*printed in bold~*~*
end note

@enduml

 

Above snippet generate below diagram.


 

  

Previous                                                    Next                                                    Home

PlantUML: Creole bulleted list

Bulleted lists are represented using *

Example

* message 1
* message 2
** submessage1
** submessage
* message 3
* message 4

** represent sub message.

 

bulletedList.txt

@startuml

scale 1.5

skinparam NoteBackgroundColor Wheat
skinparam NoteBorderColor red
skinparam NoteBorderThickness 3
skinparam NoteFontColor black
skinparam NoteFontName Papyrus
skinparam NoteFontSize 8
skinparam NoteFontStyle italic
skinparam NoteShadowing true
' skinparam NoteTextAlignment right

Client -> Server: Send message


note left of Client 
* message 1
* message 2
** submessage1
** submessage
* message 3
* message 4
end note

@enduml

Above snippet generate below diagram.




 

  

Previous                                                    Next                                                    Home

PlantUML: numbered lists using creole syntax

# symbol create numbered list.

Example

note left of Client 
# message 1
# message 2
## submessage1
## submessage
# message 3
* submessage 1
* submessage 2
# message 4
end note

 

## : specifies sub message

* : specifies bullet list

 

numberedList.txt

 

@startuml

scale 1.5

skinparam NoteBackgroundColor Wheat
skinparam NoteBorderColor red
skinparam NoteBorderThickness 3
skinparam NoteFontColor black
skinparam NoteFontName Papyrus
skinparam NoteFontSize 8
skinparam NoteFontStyle italic
skinparam NoteShadowing true
' skinparam NoteTextAlignment right

Client -> Server: Send message


note left of Client 
# message 1
# message 2
## submessage1
## submessage
# message 3
* submessage 1
* submessage 2
# message 4
end note

@enduml

 


 

Previous                                                    Next                                                    Home

Debugging streams with peek method

Java streams, introduced in Java 8, improvise how the collections of objects are processed. Streams represent a sequence of elements that can be processed using operations provided by the Stream API. In general, streams act as wrappers around a data source like an array, collection, or I/O channel.

 

How do streams streamline processing?

Stream processing entails below steps:

a.   creating a stream from a data source such as collections, arrays etc.,

b.   Apply a sequence of intermediate operations—like filter(), map(), and reduce()—to manipulate the elements.

c.    Finally, use a terminal operation such as collect() or forEach() to yield the desired outcome.

 


 

Stream advantages

a.   Conciseness: Stream operations can  represent the complex data processing logic in just a few lines of code, unlike traditional loops.

b.   Immutability: Streams do not modify/alter the original data source, encouraging immutability and enhancing code safety.

c.    Parallelization: Stream operations have the potential to be executed in parallel, leading to better performance on processors with multiple cores.

 

Intermediate and terminal operations

In Java streams, operations can be categorized into two types: intermediate and terminal. Intermediate operations transform one stream into another, processing elements one by one in a lazy manner. These operations have no effect until the pipeline starts. On the other hand, terminal operations mark the end of the stream lifecycle and initiate the pipeline's execution. In a stream pipeline, composed of a source, zero or more intermediate operations, and a terminal operation, the computation is performed lazily, only when the terminal operation is invoked.

 

peek() method

peek() is a fundamental method offered by the Stream interface, that lets developers quickly check the elements of a stream without disrupting the flow of stream operations.

 

The peek() method's signature is as follows:

Stream<T> peek(Consumer<? super T> action)

 

It takes a Consumer functional interface as its argument, and executes an action on each element of the stream without modifying them. Logging the elements of a stream is one of its main use case for peek() method.

 

PeekDemo.java

package com.sample.app.streams;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class PeekDemo {

	public static void main(String args[]) {
		List<String> names = Arrays.asList("Thulasi", "Ram", "Hari", "Chamu", "Tataji");

		Stream<String> namesStartsWithTAndInUppercase = names.stream()
				.peek(ele -> System.out.println("Processing the element " + ele)).filter(name -> name.startsWith("T"))
				.peek(ele -> System.out.println("\tElement received after applying the filter " + ele))
				.map(name -> name.toUpperCase())
				.peek(ele -> System.out.println("\tElement received after applying the transformation " + ele));

		System.out.println("Streams is defined with intermittent operations");

		namesStartsWithTAndInUppercase.forEach(ele -> System.out.println("Final element : " + ele + "\n"));

	}

}

Output

Streams is defined with intermittent operations
Processing the element Thulasi
	Element received after applying the filter Thulasi
	Element received after applying the transformation THULASI
Final element : THULASI

Processing the element Ram
Processing the element Hari
Processing the element Chamu
Processing the element Tataji
	Element received after applying the filter Tataji
	Element received after applying the transformation TATAJI
Final element : TATAJI

Adding peek() before and after the filter and map operations helps us to see which elements are being worked on and how these stream operations affects the stream. This is really useful for fixing errors, especially when the logic in the stream operations gets complicated.


Previous                                                 Next                                                 Home

Wednesday, 24 April 2024

Understanding Intermediate and Terminal Operations in Stream Processing

Java streams, introduced in Java 8, improvise how the collections of objects are processed. Streams represent a sequence of elements that can be processed using operations provided by the Stream API. In general, streams act as wrappers around a data source like an array, collection, or I/O channel.

 

How do streams streamline processing?

Stream processing entails below steps:

a.   creating a stream from a data source such as collections, arrays etc.,

b.   Apply a sequence of intermediate operations—like filter(), map(), and reduce()—to manipulate the elements.

Finally, use a terminal operation such as collect() or forEach() to yield the desired outcome.


Stream advantages

a.   Conciseness: Stream operations can  represent the complex data processing logic in just a few lines of code, unlike traditional loops.

b.   Immutability: Streams do not modify/alter the original data source, encouraging immutability and enhancing code safety.

c.    Parallelization: Stream operations have the potential to be executed in parallel, leading to better performance on processors with multiple cores.

 

Intermediate and terminal operations

In Java streams, operations can be categorized into two types: intermediate and terminal. Intermediate operations transform one stream into another, processing elements one by one in a lazy manner. These operations have no effect until the pipeline starts. On the other hand, terminal operations mark the end of the stream lifecycle and initiate the pipeline's execution. In a stream pipeline, composed of a source, zero or more intermediate operations, and a terminal operation, the computation is performed lazily, only when the terminal operation is invoked.

 

HelloWorld.java

package com.sample.app.streams;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class HelloWorld {

	public static void main(String args[]) {
		List<String> names = Arrays.asList("Thulasi", "Ram", "Hari", "Chamu", "Tataji");

		List<String> namesStartsWithTAndInUppercase = names.stream().filter(name -> name.startsWith("T"))
				.map(name -> name.toUpperCase()).collect(Collectors.toList());

		namesStartsWithTAndInUppercase.forEach(System.out::println);

	}

}

 

Output

THULASI
TATAJI

 

List<String> namesStartsWithTAndInUppercase = names
    .stream()
    .filter(name -> name.startsWith("T"))
    .map(name -> name.toUpperCase())
    .collect(Collectors.toList());

 

Above Java code snippet demonstrates the usage of Java streams to filter and transform a list of names.

 

Let's break it down.

a.   stream(): This is a terminal operation that converts the names list into a stream. It marks the beginning of the stream pipeline.

b.   filter(): This is an intermediate operation that filters the stream based on the given predicate. In this case, it filters names that start with the letter "T".

c.    map(): This is another intermediate operation that transforms each element of the stream. Here, it converts each name to uppercase using the toUpperCase() method.

d.   collect(Collectors.toList()): This is a terminal operation that collects the elements of the stream into a list. It consumes the stream and produces a new list containing the filtered and transformed elements.

So, in summary:

 

a.   Intermediate operations: filter() and map()

b.   Terminal operation: collect(Collectors.toList())

 

Intermediate operations will not get triggered until the terminal operation is initiated

 

PeekDemo.java
package com.sample.app.streams;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class PeekDemo {

	public static void main(String args[]) {
		List<String> names = Arrays.asList("Thulasi", "Ram", "Hari", "Chamu", "Tataji");

		Stream<String> namesStartsWithTAndInUppercase = names
				.stream()
				.peek(ele -> System.out.println("Processing the element " + ele))
				.filter(name -> name.startsWith("T"))
				.peek(ele -> System.out.println("\tElement received after applying the filter " + ele))
				.map(name -> name.toUpperCase())
				.peek(ele -> System.out.println("\tElement received after applying the transformation " + ele));

		System.out.println("Streams is defined with intermittent operations");
	
		namesStartsWithTAndInUppercase.forEach(ele -> System.out.println("Final element : " + ele + "\n"));

	}

}

Output

Streams is defined with intermittent operations
Processing the element Thulasi
	Element received after applying the filter Thulasi
	Element received after applying the transformation THULASI
Final element : THULASI

Processing the element Ram
Processing the element Hari
Processing the element Chamu
Processing the element Tataji
	Element received after applying the filter Tataji
	Element received after applying the transformation TATAJI
Final element : TATAJI

In this Java code snippet, a stream pipeline is defined for processing a list of names. The pipeline includes intermediate operations such as peek() to log information about each element as it passes through the stream, filter() to select only names starting with "T", and map() to convert each name to uppercase. However, despite defining these intermediate operations, no processing occurs until a terminal operation is invoked. Only when forEach() is called to print the final elements do the intermediate operations get triggered, executing the pipeline and producing the desired output. This highlights the lazy evaluation nature of Java streams, where intermediate operations are deferred until a terminal operation initiates the stream processing.

 

Previous                                                 Next                                                 Home

Pandas: Print the content of a group by data

We can iterate over the content of group by data using for loop.

Example

for group_name, group_data in group_by_object:
    print("Group Name:", group_name)
    print(group_data)

 

Find the below working application.

 

print_group_by_data.py
import pandas as pd

# Print the content of DataFrameGroupBy object
def print_group_by_result(group_by_object):
    for group_name, group_data in group_by_object:
        print("Group Name:", group_name)
        print(group_data)
        print()


# Create a sample DataFrame
data = { 'Name': ['Krishna', 'Chamu', 'Joel', 'Gopi', 'Sravya', "Raj"],
         'Age': [34, 25, 29, 41, 52, 23],
        'City': ['Bangalore', 'Chennai', 'Hyderabad', 'Hyderabad', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Male', 'Female', 'Male'],
         'Weight': [74, 58, 85, 87, 63, 79]}

df = pd.DataFrame(data)
print(df)

group_by_city = df.groupby('City')
print('\nGroup by city is')
print('type of group_by_city is : ', type(group_by_city))
print_group_by_result(group_by_city)

Output

      Name  Age       City  Gender  Weight
0  Krishna   34  Bangalore    Male      74
1    Chamu   25    Chennai  Female      58
2     Joel   29  Hyderabad    Male      85
3     Gopi   41  Hyderabad    Male      87
4   Sravya   52  Bangalore  Female      63
5      Raj   23    Chennai    Male      79

Group by city is
type of group_by_city is :  <class 'pandas.core.groupby.generic.DataFrameGroupBy'>
Group Name: Bangalore
      Name  Age       City  Gender  Weight
0  Krishna   34  Bangalore    Male      74
4   Sravya   52  Bangalore  Female      63

Group Name: Chennai
    Name  Age     City  Gender  Weight
1  Chamu   25  Chennai  Female      58
5    Raj   23  Chennai    Male      79

Group Name: Hyderabad
   Name  Age       City Gender  Weight
2  Joel   29  Hyderabad   Male      85
3  Gopi   41  Hyderabad   Male      87




  

Previous                                                 Next                                                 Home

Pandas: Apply one or more aggregation functions on groupby data

Using ‘agg’ method of DataFrameGroupBy object, we can apply one or more aggregation functions on groupby data.

I am using below data set to demonstrate the examples.

      Name  Age       City  Gender  Weight
0  Krishna   34  Bangalore    Male      74
1    Chamu   25    Chennai  Female      58
2     Joel   29  Hyderabad    Male      85
3     Gopi   41  Hyderabad    Male      87
4   Sravya   52  Bangalore  Female      63
5      Raj   23    Chennai    Male      79

Let’s aggregate the data by City column prior to applying the aggregation functions.

Group Name: Bangalore
      Name  Age       City  Gender  Weight
0  Krishna   34  Bangalore    Male      74
4   Sravya   52  Bangalore  Female      63

Group Name: Chennai
    Name  Age     City  Gender  Weight
1  Chamu   25  Chennai  Female      58
5    Raj   23  Chennai    Male      79

Group Name: Hyderabad
   Name  Age       City Gender  Weight
2  Joel   29  Hyderabad   Male      85
3  Gopi   41  Hyderabad   Male      87

Example 1: Applying ‘sum’ function on Age column and ‘mean’ function on ‘Weight’ column.

agg_result = group_by_city.agg({
    'Age' : 'sum',
    'Weight' : 'mean'
})

In the above example, to apply multiple aggregation functions to specific columns, I passed a dictionary to the agg() method. The keys of the dictionary represent the column names, and the values can be either a single aggregation function or a list of multiple aggregation functions.

 

‘agg_result’ point to below dataframe.

           Age  Weight
City                  
Bangalore   86    68.5
Chennai     48    68.5
Hyderabad   70    86.0

Example 2: Perform multiple operations on a given column

agg_result = group_by_city.agg({
    'Age' : ['sum', 'size'],
    'Weight' : 'mean'
})

Above snippet apply 'sum', 'size' functions on ‘Age’ column and ‘mean’ function on ‘Weight’ column.

 ‘agg_result’ point to below dataset.


          Age      Weight
          sum size   mean
City                     
Bangalore  86    2   68.5
Chennai    48    2   68.5
Hyderabad  70    2   86.0 

Example 3: If you have only numeric columns in the data frame, and want to apply same set of operations on the columns, then you can pass list of operations to the agg method like below.

group_by_city = df[['Age', 'City', 'Weight']].groupby('City')
agg_result = group_by_city.agg(['sum', 'mean', 'size'])

‘agg_result’ point to below dataset.

          Age            Weight           
          sum  mean size    sum  mean size
City                                      
Bangalore  86  43.0    2    137  68.5    2
Chennai    48  24.0    2    137  68.5    2
Hyderabad  70  35.0    2    172  86.0    2

Above snippet applies sum, mean and size operations on ‘Age’ and ‘Weight’ columns.

 

Find the below working Application.

 

one_or_more_aggregations.py

import pandas as pd

# Print the content of DataFrameGroupBy object
def print_group_by_result(group_by_object, label):
    print('*'*50)
    print(label,'\n')
    for group_name, group_data in group_by_object:
        print("Group Name:", group_name)
        print(group_data)
        print()
    print('*' * 50)


# Create a sample DataFrame
data = { 'Name': ['Krishna', 'Chamu', 'Joel', 'Gopi', 'Sravya', "Raj"],
         'Age': [34, 25, 29, 41, 52, 23],
        'City': ['Bangalore', 'Chennai', 'Hyderabad', 'Hyderabad', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Male', 'Female', 'Male'],
         'Weight': [74, 58, 85, 87, 63, 79]}

df = pd.DataFrame(data)
print(df)

group_by_city = df.groupby('City')
print('\nGroup by city is')
print('type of group_by_city is : ', type(group_by_city))
print_group_by_result(group_by_city, 'Group by city details')

# specify aggregation for each column separately
agg_result = group_by_city.agg({
    'Age' : 'sum',
    'Weight' : 'mean'
})
print('\nSum on Age column and mean on Weight column')
print(agg_result)

# Specify multiple operations on a column
agg_result = group_by_city.agg({
    'Age' : ['sum', 'size'],
    'Weight' : 'mean'
})

print('\nMultiple operations on a column')
print(agg_result)

group_by_city = df[['Age', 'City', 'Weight']].groupby('City')
agg_result = group_by_city.agg(['sum', 'mean', 'size'])
print('\nMultiple operations on a column')
print(agg_result)

Output

      Name  Age       City  Gender  Weight
0  Krishna   34  Bangalore    Male      74
1    Chamu   25    Chennai  Female      58
2     Joel   29  Hyderabad    Male      85
3     Gopi   41  Hyderabad    Male      87
4   Sravya   52  Bangalore  Female      63
5      Raj   23    Chennai    Male      79

Group by city is
type of group_by_city is :  <class 'pandas.core.groupby.generic.DataFrameGroupBy'>
**************************************************
Group by city details 

Group Name: Bangalore
      Name  Age       City  Gender  Weight
0  Krishna   34  Bangalore    Male      74
4   Sravya   52  Bangalore  Female      63

Group Name: Chennai
    Name  Age     City  Gender  Weight
1  Chamu   25  Chennai  Female      58
5    Raj   23  Chennai    Male      79

Group Name: Hyderabad
   Name  Age       City Gender  Weight
2  Joel   29  Hyderabad   Male      85
3  Gopi   41  Hyderabad   Male      87

**************************************************

Sum on Age column and mean on Weight column
           Age  Weight
City                  
Bangalore   86    68.5
Chennai     48    68.5
Hyderabad   70    86.0

Multiple operations on a column
          Age      Weight
          sum size   mean
City                     
Bangalore  86    2   68.5
Chennai    48    2   68.5
Hyderabad  70    2   86.0

Multiple operations on a column
          Age            Weight           
          sum  mean size    sum  mean size
City                                      
Bangalore  86  43.0    2    137  68.5    2
Chennai    48  24.0    2    137  68.5    2
Hyderabad  70  35.0    2    172  86.0    2


 

 

Previous                                                 Next                                                 Home