Monday, 10 March 2025

Introduction to css Animations

CSS Animation is a powerful feature in CSS (Cascading Style Sheets) that allows you to create smooth transitions and visual effects directly on HTML elements without the need for JavaScript or Flash. CSS animations can change the style of an element over a specified duration, making it possible to animate properties like position, size, color, and other visual aspects of elements.


CSS animations typically consist of two main components:

 

1.   Keyframes: These define the states and changes at specific points during the animation timeline. For example, you can specify what styles an element should have at the start (from), at the end (to), or at different percentages along the way (e.g., 50%).

 

2.   Animation Properties: These are applied to the HTML elements to define the animation's behavior, such as its duration, timing function, delay, iteration count, and direction.

 

Example of animation using from and to

Step 1: Create a keyframe.

/* Defining keyframes */
@keyframes moveAndChangeColor {
    /* Using from and to */
    from {
        transform: translateX(0);
        background-color:red;
    }
    to {
        transform: translateX(300px);
        background-color: green;
    }
}

 

@keyframes moveAndChangeColor { ... }: This defines the keyframes for the animation named moveAndChangeColor. It specifies the changes that should happen over the duration of the animation.

 

from { ... } and to { ... }: These keywords specify the starting and ending styles for the animation. In this case, the animation starts with the box at its original position and color (red) and ends with the box 300px to the right and with a new color (green).

 

Step 2: Apply this keyframe.

 

.box {
    animation: moveAndChangeColor 5s infinite;
}

animation: moveAndChangeColor 5s infinite;

This applies the animation to the .box class. The moveAndChangeColor animation runs for 5s (5 seconds) and repeats infinitely. The animation property is shorthand for several animation-related properties, which can be expanded as follows:

 

1.   animation-name: moveAndChangeColor;  Specifies the name of the keyframes to use.

2.   animation-duration: 5s; Specifies how long the animation should take.

3.   animation-iteration-count: infinite; Specifies that the animation should repeat infinitely.

 

hello-world.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Animation Example</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }

        .box {
            width: 100px;
            height: 100px;
            background-color: #3498db;
            animation: moveAndChangeColor 5s infinite;
        }

        /* Defining keyframes */
        @keyframes moveAndChangeColor {
            /* Using from and to */
            from {
                transform: translateX(0);
                background-color: red;
            }
            to {
                transform: translateX(400px);
                background-color: green;
            }
        }

    </style>
</head>
<body>
    <div class="box"></div>
</body>
</html>

 

Open above page, you can see that the animation is applied on the box element.

 

Apply animation with percentages

You can specify intermediate steps using percentage values. For example, if you want the box to pause in the middle, you can modify the keyframes like this.

@keyframes moveAndChangeColor {
    0% {
        transform: translateX(0);
        background-color: red;
    }
    50% {
        transform: translateX(150px);
        background-color: green;
    }
    100% {
        transform: translateX(300px);
        background-color: blue;
    }
}

 

In this example:

 

1.   At 0%, the box starts from its original position with the original color.

2.   At 50%, it moves to 150px and changes to a green color

3.   At 100%, it completes the movement to 300px and changes to red blue.

 

animation-percentages.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Animation Example</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }

        .box {
            width: 100px;
            height: 100px;
            background-color: #3498db;
            animation: moveAndChangeColor 5s infinite;
        }

        /* Defining keyframes */
        @keyframes moveAndChangeColor {
            0% {
                transform: translateX(0);
                background-color: red;
            }
            50% {
                transform: translateX(150px);
                background-color: green;
            }
            100% {
                transform: translateX(300px);
                background-color: blue;
            }
        }


    </style>
</head>
<body>
    <div class="box"></div>
</body>
</html>

 


 

Previous                                                    Next                                                    Home

Sunday, 9 March 2025

Mode to represent central tendency

Mode represents the most frequent value in the dataset.

Example 1: For the data set {1, 2, 4, 5, 2, 3, 5,  5}, mode is 5, as it occurred 3 times in the dataset.

 

Example 2: For the data set {1, 2, 3, 4, 5} mode is undefined, as no value appears more than other in the dataset.

 

Unimodal mode: Mode is exactly one value.

 

For example, in the dataset {1, 2, 3, 4, 5, 1}. The Number 1 is repeated twice, and it is unimodal mode.

 

Bimodal mode: Mode is exactly two values.

 

For example, in the dataset {1, 2, 3, 4, 5, 1, 3}. The numbers 1 and 3 are repeated twice, and the numbers {2, 3} together represent bimodal mode.

 

Multimodal mode: Mode is more than two values.

 

For example, in the dataset {1, 2, 3, 4, 5, 1, 3, 2}. The numbers 1, 2 and 3 are repeated twice, and the numbers {1, 2, 3} together represent Multimodal mode

 

Advantages of mode

  1. Easy to implement
  2. Not affected by outliers
  3. Used for data sets that are not normally distributed.

 

Examples in real world

  1. Favourite game of students in a class
  2. Busiest time in a restaurant
  3. Most popular movies in 2023
  4. Most popular names in India

 

Find the below working application.

 

mode_calculator.py 

def calculate_mode(data_points):
    # Create a dictionary to count the occurrences of each value
    data_points_count = {}

    # Initialize the maximum count
    max_count = 0

    # Initialize the mode list
    mode_list = []

    for value in data_points:
        if value in data_points_count:
            data_points_count[value] += 1
        else:
            data_points_count[value] = 1

        # Update the maximum count
        if data_points_count[value] > max_count:
            max_count = data_points_count[value]

    # Find all values with the maximum count (modes)
    for key, value in data_points_count.items():
        if value == max_count:
            mode_list.append(key)

    return mode_list


data = [1, 2, 2, 3, 4, 4, 4, 5, 2]

# Calculate the mode(s)
modes = calculate_mode(data)

print("Modes:", modes)

 

Output

Modes: [2, 4]

 

Previous                                                    Next                                                    Home

Median to represent central tendency

 

Median represent the middle value of the data points, when the data points are arranged in either ascending or descending order.

 

How to calculate median?

Step 1: Sort the data points in either ascending or descending order.

 

Step 2: Find the middle value.

 

  1. If you have an odd number of data points, then median is the middle value in the ordered list.
  2. If you have an even number of data points, then median is the average of the two middle values.

 

Example 1: with odd number of values

 

Suppose you have a data points like below.

 

[3, 5, 6, 2, 1, 4, 5]

 

Let’s sort the data points : [1, 2, 3, 4, 5, 5, 6] and the middle value 4 is the median.

 

Example 2: with even number of values

 

Suppose you have a data points like below.

 

[3, 5, 6, 2, 1, 4]

 

Let’s sort the data points : [1, 2, 3, 4, 5, 6] and the middle values are 3 and 4.

 

Median is (3 + 4)/2 = 7/2 = 3.5

 

median.py

import numpy as np

# Create a sample dataset
data1 = np.array([3, 5, 6, 2, 1, 4, 5])
data2 = np.array([3, 5, 6, 2, 1, 4])

# Calculate the median
median1 = np.median(data1)
median2 = np.median(data2)

# Print the median
print(f"median1: {median1}")
print(f"median2: {median2}")

Output

median1: 4.0
median2: 3.5

 

Unlike mean, median is less affected by extreme values, for example, let’s see the below example with some outliers in house prices.

 

medain_using_pyplot.py

import matplotlib.pyplot as plt
import numpy as np

# Sample dataset
house_prices = [350000, 100000, 120000, 150000, 170000, 200000, 700000, 900000]

# Calculate the mean
mean = np.mean(house_prices)
median = np.median(house_prices)

# Create a scatter plot of data points
plt.scatter(house_prices, range(len(house_prices)), label='Data Points', color='blue', marker='o')

# Add a vertical line at the mean
plt.axvline(x=mean, color='red', linestyle='--', label='Mean')
plt.axvline(x=median, color='blue', linestyle='--', label='Median')

# Add labels and a title
plt.xlabel('House prices')
plt.ylabel('Index')
plt.title('Scatter Plot with Mean')

# Add a legend
plt.legend()

# Show the plot
plt.show()

 

Output

 


As you see above diagram, mean is impacted by the outliers in the data points as compared to median.

 

Advantages of median

  1. It is easy to calculate.
  2. Less affected by outliers.


Previous                                                    Next                                                    Home

Understanding the matrix() transformation function in CSS

 

The matrix() function in CSS is a part of the CSS Transform module, and it allows you to perform complex transformations like translation, rotation, scaling, and skewing, all in one function. This function is particularly powerful because it directly manipulates the transformation matrix, which is the mathematical representation of these transformations.

 

Understanding the matrix() Function

The matrix() function takes six values as parameters, representing a 2D transformation matrix. These values are:

 

Syntax

matrix(a, b, c, d, e, f)

 

These parameters correspond to the following:

 

1. a and d: These control scaling.

·      a is the scaling factor in the X direction (horizontal).

·      d is the scaling factor in the Y direction (vertical).

 

2. b and c: These control skewing.

·      b is the skewing factor in the Y direction.

·      c is the skewing factor in the X direction.

 

3. e and f: These control translation (moving).

·      e is the translation (moving) factor in the X direction (horizontal).

·      f is the translation (moving) factor in the Y direction (vertical).

 

Example

transform: matrix(2, 0.5, 0, 1.5, 100, 50);

 

·      a = 2 (scaling X by 2)

·      b = 0.5 (skewing Y by 0.5)

·      c = 0 (no skewing in the X direction)

·      d = 1.5 (scaling Y by 1.5)

·      e = 100 (translation X by 100 pixels)

·      f = 50 (translation Y by 50 pixels)

 

matrix.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .transform-box {
            width: 100px;
            height: 100px;
            background-color: lightblue;
        }

        .transform-box:hover{
            transform: matrix(2, 0.5, 0, 1.5, 100, 50);
        }
    </style>
    <title>CSS Matrix Transformation Example</title>
</head>
<body>
    <div class="transform-box"></div>
</body>
</html>

 Above snippet generate below box.


 Hover the mouse, you can see that the widget will change like below.



Previous                                                    Next                                                    Home