Sharing IT Knowledge and Life – Chia sẻ kiến thức IT và đời sống

Saturday, July 24, 2021

Installation mdbootstrap 5

Install MDB (Material Design for Bootstrap) UI Kit

Step 1

Download the package

Step 2

Unzip the downloaded package and open it in your code editor.

Step 3

Open the Dreamweaver editor and create an HTML site.

Find a template site, copy an index.html file into your project and compose your website. And yes, it's that simple!

Importing CSS file

To import the MDB stylesheet, please use the following syntax:

<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" />

<!-- Google Fonts Roboto -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" />

<!-- MDB -->
<link rel="stylesheet" href="css/mdb.min.css" />

Importing JS file

<script src="js/mdb.min.js"></script>

Run

Click the index.html file to open it in your browser, and it works!

Source code

IntegratedMaterialDesignAdminDemo

Reference document

https://mdbootstrap.com/docs/standard/getting-started/installation/

Wednesday, March 3, 2021

Amazon SQS as an Event Source to AWS Lambda 

 What is Amazon Simple Queue Service?

Amazon Simple Queue Service (Amazon SQS) offers a secure, durable, and available hosted queue that lets you integrate and decouple distributed software systems and components (send, receive, and delete a message). Amazon SQS offers common constructs such as dead-letter queues and cost allocation tags. It provides a generic web services API that you can access using any programming language that the AWS SDK supports.

Amazon SQS supports both standard and FIFO queues. For more information, see Queue types.

In AWS, SQS can be an event source to Lambda, all that heavy lifting of managing message polling and deleting has been offloaded to the Lambda service, which is now your SQS consumer. It should be called Lambda SQS Consumer Service.

 Lambda is doing the scaling of consumers of YOUR SQS queue for messages, receiving messages, and passing those messages to your Lambda function, and then deleting those messages when your Lambda function successfully handles the message(s) received. This is all explained in more detail here.

Below is a nice visual of what’s going on with this integration.


If you already know enough about SQS as an event source and how the AWS Lambda integration works, skip the preamble and move onto Get Started using the included end-to-end CloudFormation template and then come back for a deeper dive.

Get Started — Backend

I created a CloudFormation template that will provision: 

  1. A standard SQS queue.
  2. A dead letter queue.
  3. AWS Lambda function for handling messages.
  4. The event source mapping.
  5. Lambda execution permissions to SQS and SNS for sending SMS text message. 

Click on the template to launch the CloudFormation console to begin building your stack. The template defaults to the US West Oregon region (us-west-2).

Once the stack completes, you can now test the setup as follows:

1. In the Amazon SQS console, send messages to the queue.

2. AWS Lambda polls the queue and when it detects new messages, it invokes your Lambda function by passing in the event data from the queue.

3. Your function executes and creates logs in Amazon CloudWatch. You can verify the logs reported in the Amazon CloudWatch Logs console.

To really see the value of SQS, checkout my sample iOS Swift application (you can download it from GitHub here) that demonstrates single and batch messages.

AWS Lambda service (not your Lambda function, but a Lambda SQS long-poll service running on your behalf) polls your SQS queue continually for incoming messages. When a message arrives, it receives the message(s) and then invokes your Lambda function by passing the message(s) as a parameter.

Configuring a queue to trigger an AWS Lambda function (console)

You can use an AWS Lambda function to process messages in an Amazon SQS queue. Lambda polls the queue and invokes your Lambda function synchronously with an event that contains queue messages. You can specify another queue to act as a dead-letter queue for messages that your Lambda function can't process. 

A Lambda function can process items from multiple queues (using one Lambda event source for each queue). You can use the same queue with multiple Lambda functions. 

If you associate an encrypted queue with a Lambda function but Lambda doesn't poll for messages, add the kms:Decrypt permission to your Lambda execution role. 

Note the following restrictions:

Your queue and the Lambda function must be in the same AWS Region.

An encrypted queue that uses the default key (AWS managed CMK for Amazon SQS) cannot invoke a Lambda function in a different AWS account. 

For information about implementing the Lambda function, see Using AWS Lambda with Amazon SQS in the AWS Lambda Developer Guide. 

Prerequisites

To configure Lambda function triggers, you must meet the following requirements:

If you use an IAM user, your Amazon SQS role must include the following permissions:

lambda:CreateEventSourceMapping

lambda:ListEventSourceMappings

lambda:ListFunctions

The Lambda execution role must include the following permissions:

sqs:DeleteMessage

sqs:GetQueueAttributes

sqs:ReceiveMessage

If you associate an encrypted queue with a Lambda function, add the kms:Decrypt permission to the Lambda execution role. 

For more information, see Overview of managing access in Amazon SQS. 

To configure a queue to trigger a Lambda function (console) 

1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/

In the navigation pane, choose Queues. 

On the Queues page, choose the queue to configure. 

On the queue's page, choose the Lambda triggers tab. 

On the Lambda triggers page, choose a Lambda trigger. 

If the list doesn't include the Lambda trigger that you need, choose Configure Lambda function trigger. Enter the Amazon Resource Name (ARN) of the Lambda function or choose an existing resource. Then choose Save. 

Choose Save. The console saves the configuration and displays the Details page for the queue. 

On the Details page, the Lambda triggers tab displays the Lambda function and its status. It takes approximately 1 minute for the Lambda function to become associated with your queue. 

To verify the results of the configuration, send a message to your queue and then view the triggered Lambda function in the Lambda console. 



Source:

Tuesday, March 2, 2021

Beginning Amazon DynamoDB

What Is Amazon DynamoDB?

Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. 

NoSQL is a term used to describe nonrelational database systems that are highly available, scalable, and optimized for high performance. Instead of the relational model, NoSQL databases (like DynamoDB) use alternate models for data management, such as key-value pairs or document storage. For more information, see http://aws.amazon.com/nosql.

Friday, January 1, 2021

VUE3 for Java developer

What is Vue.js and VUE 3 features?

Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries (opens new window)

Vue 3 was officially released on September 18, 2020. While it has some great new features, especially having full TypeScript support which is the same as Angular 10. New Features in Vue 3 are

  •     Composition API (built-in now)
  •     Full TypeScript support
  •     Portals
  •     Fragments
  •     Suspense
  •     Global Mounting/Configuration API change
  •     Multiple v-models
  •     Custom Directive API
  •     Multiple root elements (Template syntax )
  •     Better reactivity
  •     Emits Component Option

Easy integration is one important feature of VUE so that It is now easy to integrate with java frameworks such as Apache wicket, Play framework, Spring framework.. Java backend developer can be easy to understand VUE 3 so that they will improve their weakness with frontend.

Some VUE 3 details

The Composition API is introduced in Vue 3 as an alternative to the Options API in vuejs 2.x. 
It would be much nicer if we could collocate code related to the same logical concern. And this is exactly what the Composition API enables us to do. To start working with the Composition API we first need a place where we can actually use it. In a Vue component, we call this place the setup.
The setup option should be a function that accepts props and context which we will talk about later. Additionally, everything that we return from setup will be exposed to the rest of our component (computed properties, methods, lifecycle hooks and so on) as well as to the component's template. The setup method is also where all the action happens. This method gets called after beforeCreate and right before the created lifecycle hooks. Notice that setup is the only function inside our component.  
beforeCreate() => setup() => create()

For example:

import {defineComponent, ref, computed} from 'vue';

export default defineComponent({
  name: 'HelloNewYear',
  components: {},
  props: {
    msg: Object,
  },
  setup(props) {
      const msg = ref('msg');      
      const updateMsg = (newValue) => msg.value = newValue;
  
      return { msg, updateMsg }
  }
});

Lifecycle inside setup() includes 9 lifecycles:
  •     onBeforeMount
  •     onMouted
  •     onBeforeUpdate
  •     onUpdated
  •     onBeforeUnmount
  •     onUnmount
  •     onActivated
  •     onDeactivated
  •     onErrorCaptured
  •     onRenderTracked
  •     onRenderTriggered


Full TypeScript support

Vue 3 has full TypeScript support. For example, 

To create mixins in TypeScript, we must first create our mixin file, which contains the data we share with other components.

Create a file called MsgMixin.ts inside the mixins directory and add the following mixin, which shares the project name and a method to update the project name.

import { Component, Vue } from 'vue-property-decorator'
@Component
class MsgMixin extends Vue {
  public msgName: string = 'My Message
  public setMsgName(newVal: string): void {
    this.msgName = newVal
  }
}
export default MsgMixin

Multiple root elements (template syntax )
In Vue 2,  the template tag can only take one root element. In Vue 3, There is no need for a root element anymore.
We can use any number of tags directly inside the <template></template> section:

<template>
  <p> Count: {{ count }} </p>
  <button @click="increment"> Increment </button>
  <button @click="decrement"> Decrement</button>
</template>
Equivalent code in Vue 2:

<template>
  <div class="counter">
    <p> Count: {{ count }} </p>
    <button @click="increment"> Increment </button>
    <button @click="decrement"> Decrement</button>
  </div>
</template>


Suspense

Suspense is a special component that renders a fallback content instead of your component until a condition is met. 


Provide / inject

In Vue 2, we used props for passing data – such as string, arrays, objects, and so on – from a parent component directly to its children component. But in many cases, we also need to pass data from the parent component to a deeply nested child component which is, not so appropriate and becoming complicated in normal cases.
Vue 3 use the new Provide and inject pair to pass data with vuex.


Teleport is a new feature that makes it easy to display a component outside its default position i.e the #app container where Vue apps are usually wrapped. You can, for example, use Teleport to display a header component outside the #app div. Please note that you can only Teleport to elements that exist outside of the Vue DOM.

Global Mounting/Configuration API Change
It has simple command as following
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

app.config.ignoredElements = [/^app-/]
app.use(/* ... */)
app.mixin(/* ... */)
app.component(/* ... */)
app.directive(/* ... */)

app.mount('#app')


Multiple v-Models
for example, to bind and listen to multiple properties in components:
<NameComponent
  v-model:fornames="forname"
  v-model:surname="surname"
/>

Understanding Vue 3 Ref for Reactive Variables

In this section, we'll learn about the ref() function in Vue 3. In Vue 3, you can use the ref() function to define a reactive variable. It can wrap any primitive or object and return it’s reactive reference. The value of passed element will be kept in a value property of the created reference. For example if you want to access value of count reference you need to explicitly ask for count.value. 


ParametersANGULARVUE
Easy Integration

Angular is a Javascript framework, making easier for developers to integrate it with third-party components and other Javascript-based technologies.

 

On the other hand, Vue is a versatile and a flexible framework. It facilitates front-end libraries integration easily.



Flexibility

Angular framework is considered highly flexible as it offers official support to multiple systems without any restriction.

At the same time, Vue is not as flexible as Angular. It's a bit rigid. There are some rules which need to be followed while working on an application. Still, it provides flexibility for modular solutions.

Complexity

Angular framework is much more complex than Vue when it comes to design and API. A non-trivial application development takes more time with Angular than Vue.

Developing a non-trivial application takes less time when integrating with Vue. If we talk about design and API, Vue is considered simpler.

TypeScript

The learning resources provided by Angular are Typescript based so it acts as a booster for the developers and at the same time difficult for the beginners to learn.

Vue recently got the Typescript functionality, but it is not currently in use.

 

Performance

Angular has performed well till date. It doesn't disappoint. Angular is best known for its fast performance. Despite having a lot of watchers, Angular guarantee the same performance metrics on different platforms. 

Vue also delivers the same quality performance as Angular. Both of them perform outstandingly on different benchmarks and at the same time addressing similar issues.

Data bindingAngular utilizes a two-way binding process between scopes. In addition to this, it supports asynchronous services to assist developers when they develop third-party components to integrate with the app.

On the other hand, Vue supports one-way data flow between the components. It facilitates non-trivial app development quickly. 

VUE 3 and Angular are both using TypeScript and html/css template opposed to ReactJS that uses HTML (JSX) inside JavaScript.

Thursday, December 31, 2020

Mockito vs JMockit

A Brief analysis on Mockito And Jmockit

Mockito

JMockit

1. We can achieve Static method/constructor mocking by the combination of Mockito with Powermock.

Tuesday, October 27, 2020

MyBatis introduction

 MyBatis is a Java persistence framework that couples objects with stored procedures or SQL statements using an XML descriptor or annotations.

MyBatis is free software that is distributed under the Apache License 2.0.

MyBatis is a fork of iBATIS 3.0 and is maintained by a team that includes the original creators of iBATIS. 

MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records

Wednesday, September 16, 2020

Python Cheat Sheet for Java Developers

English version

What is Python?

Python is an object-oriented programming language created by Guido van Rossum in 1989. It is hugely popular and runs on many operating systems, including Windows, Linux, Ubuntu and macOS. Python is an interpreted language, so anyone can open a terminal and type Python commands directly. It is widely used in AI & Machine Learning, live streaming data processing, Big Data, mathematics, physics and many other scientific fields. Python complements Java; it cannot fully replace Java in the global IT market.

Learning Python quickly as a Java developer

Java developers can pick up Python fast by comparing it directly with Java and noting the similarities and differences. A cheat sheet is therefore the most efficient way to learn the basics.

1. Basic Syntax

1.1 End of statements

  • Java: every statement ends with a semicolon ;.
  • Python: no ; needed (a newline ends the statement). You may still use ; to put several statements on one line.

Printing:

// Java
System.out.println("Hello Blogger!");

# Python
print("Hello Blogger!")

1.2 Code blocks and indentation

  • Java: curly braces {} delimit blocks.
  • Python: indentation (4 spaces) defines blocks.
LanguageExample
Java
if (5 == value) {
    System.out.println("Value is five");
} else {
    System.out.println("Value is not five.");
}
Python
if 5 == value:
    print('Value is five')
else:
    print('Value is not five.')

2. Variables & Data Types

Python is dynamically typed: you do not declare a variable's type.

2.1 Declaring and assigning

# Single assignment
number = 27
string = "A short sample string"

# Multiple assignment
a, b = False, True
a = b = c = 7
a, b, c = 3, 4, "mary"

2.2 Numeric types

Python converts between numeric types automatically when needed.

TypeJavaPythonNotes
Integerint a = 27;a = 27Signed integer
Longlong a = 90210L;a = 90210Python 3 handles big integers automatically
Floatfloat a = 7.25f;a = 7.25Floating point
ComplexNot built ina = 2.5JComplex number

3. Data Structures

3.1 String

Strings can use single quotes '...', double quotes "...", or triple quotes """...""" for multi-line text.

OperationJavaPython
Find positionstr.indexOf() / str.charAt()str.find() / str.index()
Lengthstr.length()len(str)
Replacestr.replace()str.replace()
Convert to stringString.valueOf() / toString()str()
Trim whitespacestr.trim()str.strip(), str.lstrip(), str.rstrip()
Comparestr1.equals(str2)str1 == str2

3.2 Boolean & falsy values

Every object in Python has a Boolean value. The following evaluate to False:

  • None (equivalent to null in Java)
  • False
  • The number 0
  • Empty collections: "", (), [], {}
Note: in Java null != false, but in Python None behaves as falsy in a Boolean context.

3.3 List (like Java's ArrayList)

A list is mutable and can hold elements of different types (heterogeneous).

A = []                      # empty list
B = [3, 14, 59, 26]         # list of 4 numbers
C = [8, 6, 'mary']          # mixed types
D = ["Z", B, C]             # list containing other lists

ArrayList (Java) vs List (Python):

OperationJava (ArrayList)Python (List)
CreateList<Object> list = new ArrayList<>();list = []
Addlist.add(obj);list.append(obj)
Accesslist.get(i);list[i]
Lengthlist.size();len(list)
Copylist2 = list.clone();list2 = list[:] or list.copy()

3.4 Tuple (fixed / immutable list)

A tuple looks like a list but is immutable. It is used in place of a static array for better performance.

A = ()                      # empty tuple
B = (2, 71, 82, 8)         # tuple of 4 numbers
C = (9, 5, 'peter')          # heterogeneous tuple
D = ("Z", B, C)             # nested tuple

3.5 Dictionary (like Java's HashMap)

A dictionary stores key: value pairs. Keys are unique and may be of different types.

# Create
hotel_rooms = {'anna': 215, 'bob': 118}

# Add / update
hotel_rooms['anna'] = 507
hotel_rooms['linh'] = 402

# Get all keys
print(hotel_rooms.keys())

# Check whether a key exists
if 'linh' in hotel_rooms:
    print("Exists!")

HashMap (Java) vs Dictionary (Python):

OperationJava (HashMap)Python (Dict)
CreateMap<K, V> map = new HashMap<>();my_dict = {}
Clearmap.clear();my_dict.clear()
Copymap.clone();my_dict.copy()
Check keymap.containsKey(key);key in my_dict
Get valuemap.get(key);my_dict.get(key) or my_dict[key]
Get keysmap.keySet();my_dict.keys()
Add / updatemap.put(key, value);my_dict[key] = value
Removemap.remove(key);my_dict.pop(key)
Sizemap.size();len(my_dict)

4. Operators & Precedence

4.1 Arithmetic

JavaPythonDescription
None**Exponentiation
--Unary negation
**Multiplication
//Division
%%Modulus
+ / -+ / -Addition / subtraction

4.2 Logical & bitwise

JavaPythonDescription
!notLogical NOT
&&Bitwise AND
||Bitwise OR
^^Bitwise XOR
&&andLogical AND
||orLogical OR

4.3 Comparison

JavaPythonDescription
< / >< / >Less than / greater than
<= / >=<= / >=Less or equal / greater or equal
====Value equality (like Java's .equals())
!=!=Not equal
== (reference)isIdentity (same object in memory)

5. Conditionals

5.1 if - elif - else

Python writes else if as elif.

var1 = 20

if var1 <= 10:
    print("Case A: " + str(var1))
elif var1 == 20:
    print("Case B: " + str(var1))
elif var1 >= 30:
    print("Case C: " + str(var1))
else:
    print("Out of range!")

5.2 Combining conditions

skill1 = "spring"
skill2 = "django"

# Both conditions are true
if skill1 == "spring" and skill2 == "django":
    print("Both conditions are met")

# At least one condition is true
if skill1 == "spring" or skill2 == "django":
    print("At least one condition is met")

6. Looping

for loop with range()

In Python, for is usually combined with range(start, stop, step) to iterate over indices.

# 2 to 7 (same as for(int x=2; x<8; x++) in Java)
for x in range(2, 8):
    print("Loop count: " + str(x))

# Custom step: from 20 down to 5, step -5
for x in range(20, 0, -5):
    print(x)

7. Advanced Differences Between Python and Java

  • Multiple inheritance: Python supports it directly for classes; Java does not (it only allows multiple interface implementation).
  • Tuple type: Java has no tuple. In Python, a tuple is like a list/array but immutable: you can create it but not change it afterwards.
  • Attribute initialization: in Python, instance attributes are defined inside __init__() (the equivalent of a Java constructor):
def __init__(self, color, model, year):
    self.color = color
    self.model = model
    self.year = year

self vs this:

  • In Java, an object refers to itself with this:
    public void setColor(String color) {
        this.color = color;
    }
    Note: in Java, this can be omitted implicitly when accessing fields.
  • In Python, self plays the same role, but unlike this in Java it is mandatory when creating or accessing instance attributes.

You can also define attributes in __init__() and use the @property decorator to control access (the equivalent of a Java getter):

class Car:
    def __init__(self, color, model, year):
        self.color = color
        self.model = model
        self.year = year
        self._voltage = 12

    @property
    def voltage(self):
        return self._voltage
  • Naming convention: a leading underscore (_voltage) signals an internal/protected attribute.
  • @property decorator: works like a Java getter, letting you write car.voltage instead of car.getVoltage(), which is cleaner and more "Pythonic".

Học nhanh Python dành cho lập trình viên Java (Tiếng Việt)

Python là gì?

Python là một ngôn ngữ lập trình hướng đối tượng được sáng tạo bởi Guido van Rossum vào năm 1989. Ngôn ngữ này rất phổ biến và có mặt trên nhiều hệ điều hành khác nhau, từ Windows cho đến Linux, Ubuntu hay macOS. Python là ngôn ngữ thông dịch (interpreted language), cho phép bất kỳ ai cũng có thể mở terminal và gõ trực tiếp các lệnh Python. Python được sử dụng rộng rãi trong các lĩnh vực AI & Machine Learning (Trí tuệ nhân tạo & Học máy), xử lý dữ liệu phát trực tiếp (live streaming data), Big Data, Toán học, Vật lý và nhiều ngành khoa học khác. Python đóng vai trò bổ trợ cho Java và không thể thay thế hoàn toàn Java trên thị trường IT toàn cầu.

Học nhanh Python cho lập trình viên Java

Các lập trình viên Java có thể dễ dàng tiếp cận Python bằng cách so sánh trực tiếp với Java, qua đó nắm rõ điểm tương đồng cũng như khác biệt giữa hai ngôn ngữ. Vì vậy, một tài liệu tóm tắt (cheat sheet) là giải pháp tối ưu để học nhanh các kiến thức Python cơ bản.

1. Cú pháp cơ bản (Basic Syntax)

1.1 Kết thúc câu lệnh

  • Java: mọi câu lệnh kết thúc bằng dấu chấm phẩy ;.
  • Python: không cần dấu ; (dùng xuống dòng bằng Enter). Tuy nhiên vẫn có thể dùng ; nếu muốn viết nhiều câu lệnh trên cùng một dòng.

In ra màn hình (print):

// Java
System.out.println("Hello Blogger!");

# Python
print("Hello Blogger!")

1.2 Khối lệnh và thụt lề (Indentation)

  • Java: dùng cặp ngoặc nhọn {} để bao khối lệnh.
  • Python: dùng thụt lề (4 khoảng trắng) để định nghĩa khối lệnh.
Ngôn ngữCú pháp ví dụ
Java
if (5 == value) {
    System.out.println("Value is five");
} else {
    System.out.println("Value is not five.");
}
Python
if 5 == value:
    print('Value is five')
else:
    print('Value is not five.')

2. Biến & Kiểu dữ liệu (Variables & Data Types)

Python là ngôn ngữ kiểu động (dynamically typed): không cần khai báo kiểu dữ liệu trước.

2.1 Khai báo và gán giá trị

# Khai báo đơn
number = 27
string = "A short sample string"

# Khai báo nhiều biến đồng thời
a, b = False, True
a = b = c = 7
a, b, c = 3, 4, "mary"

2.2 Các kiểu số cơ bản (Numbers)

Python tự động chuyển đổi kiểu số khi cần thiết.

Kiểu dữ liệuJavaPythonGhi chú
Integerint a = 27;a = 27Số nguyên có dấu
Longlong a = 90210L;a = 90210Python 3 tự động xử lý số nguyên lớn
Floatfloat a = 7.25f;a = 7.25Số thực
ComplexKhông hỗ trợ sẵna = 2.5JSố phức

3. Cấu trúc dữ liệu (Data Structures)

3.1 Chuỗi (String)

Hỗ trợ nháy đơn '...', nháy kép "..." và nháy ba """...""" (dành cho chuỗi nhiều dòng).

Thao tácJavaPython
Tìm vị trístr.indexOf() / str.charAt()str.find() / str.index()
Độ dàistr.length()len(str)
Thay thếstr.replace()str.replace()
Chuyển kiểu chuỗiString.valueOf() / toString()str()
Xóa khoảng trắngstr.trim()str.strip(), str.lstrip(), str.rstrip()
So sánh chuỗistr1.equals(str2)str1 == str2

3.2 Boolean & giá trị Falsy

Mọi đối tượng trong Python đều có giá trị Boolean. Các giá trị sau được tính là False:

  • None (tương đương null trong Java)
  • False
  • Số 0
  • Tập hợp rỗng: "", (), [], {}
Lưu ý: trong Java null != false, nhưng trong Python None được đánh giá là Falsy trong ngữ cảnh Boolean.

3.3 List (tương đương ArrayList trong Java)

List là danh sách có thể thay đổi (mutable), chứa các phần tử không cùng kiểu (heterogeneous).

A = []                      # List rỗng
B = [3, 14, 59, 26]         # List chứa 4 số
C = [8, 6, 'mary']          # List chứa nhiều kiểu dữ liệu
D = ["Z", B, C]             # List chứa List khác

So sánh ArrayList (Java) vs List (Python):

Thao tácJava (ArrayList)Python (List)
Khởi tạoList<Object> list = new ArrayList<>();list = []
Thêm phần tửlist.add(obj);list.append(obj)
Truy xuấtlist.get(i);list[i]
Độ dàilist.size();len(list)
Sao chép (Clone)list2 = list.clone();list2 = list[:] hoặc list.copy()

3.4 Tuple (mảng cố định / immutable list)

Tuple có cấu trúc giống List nhưng không thể sửa đổi (immutable). Được dùng thay cho mảng tĩnh (static array) để tối ưu hiệu năng.

A = ()                      # Tuple rỗng
B = (2, 71, 82, 8)         # Tuple 4 số
C = (9, 5, 'peter')          # Heterogeneous Tuple
D = ("Z", B, C)             # Tuple lồng nhau

3.5 Dictionary (tương đương HashMap trong Java)

Dictionary lưu trữ dữ liệu dạng cặp Key: Value. Key không trùng lặp và có thể thuộc các kiểu dữ liệu khác nhau.

# Khởi tạo
hotel_rooms = {'anna': 215, 'bob': 118}

# Thêm / Cập nhật
hotel_rooms['anna'] = 507
hotel_rooms['linh'] = 402

# Lấy danh sách keys
print(hotel_rooms.keys())

# Kiểm tra Key tồn tại
if 'linh' in hotel_rooms:
    print("Exists!")

So sánh HashMap (Java) vs Dictionary (Python):

Thao tácJava (HashMap)Python (Dict)
Khởi tạoMap<K, V> map = new HashMap<>();my_dict = {}
Xóa sạchmap.clear();my_dict.clear()
Sao chépmap.clone();my_dict.copy()
Kiểm tra Keymap.containsKey(key);key in my_dict
Lấy giá trịmap.get(key);my_dict.get(key) hoặc my_dict[key]
Lấy tập Keymap.keySet();my_dict.keys()
Thêm/Sửamap.put(key, value);my_dict[key] = value
Xóa phần tửmap.remove(key);my_dict.pop(key)
Kích thướcmap.size();len(my_dict)

4. Toán tử & Thứ tự ưu tiên (Operators)

4.1 Toán tử số học (Arithmetic)

JavaPythonMô tả
Không có**Lũy thừa (Exponentiation)
--Đổi dấu (Unary negation)
**Nhân
//Chia
%%Chia lấy dư (Modulus)
+ / -+ / -Cộng / Trừ

4.2 Toán tử logic & bit (Logical & Bitwise)

JavaPythonMô tả
!notPhủ định (Logical NOT)
&&AND theo bit
||OR theo bit
^^XOR theo bit
&&andĐiều kiện AND
||orĐiều kiện OR

4.3 Toán tử so sánh (Comparison)

JavaPythonMô tả
< / >< / >Nhỏ hơn / Lớn hơn
<= / >=<= / >=Nhỏ hơn hoặc bằng / Lớn hơn hoặc bằng
====So sánh giá trị (tương đương .equals() của Java)
!=!=Khác nhau
== (ref)isSo sánh địa chỉ ô nhớ / identity (cùng một đối tượng)

5. Cấu trúc điều kiện (Conditionals)

5.1 Cú pháp if - elif - else

Trong Python, else if được viết gọn thành elif.

var1 = 20

if var1 <= 10:
    print("Case A: " + str(var1))
elif var1 == 20:
    print("Case B: " + str(var1))
elif var1 >= 30:
    print("Case C: " + str(var1))
else:
    print("Out of range!")

5.2 Kết hợp nhiều điều kiện

skill1 = "spring"
skill2 = "django"

# Cả hai điều kiện đều đúng
if skill1 == "spring" and skill2 == "django":
    print("Both conditions are met")

# Ít nhất một điều kiện đúng
if skill1 == "spring" or skill2 == "django":
    print("At least one condition is met")

6. Vòng lặp (Looping)

Vòng lặp for với range()

Trong Python, vòng lặp for thường kết hợp với hàm range(start, stop, step) để duyệt chỉ số.

# Chạy từ 2 đến 7 (tương đương for(int x=2; x<8; x++) trong Java)
for x in range(2, 8):
    print("Loop count: " + str(x))

# Tùy chỉnh bước nhảy (step)
# Chạy từ 20 về 5 với bước nhảy -5
for x in range(20, 0, -5):
    print(x)

7. Những điểm khác biệt nâng cao giữa Python và Java

  • Đa kế thừa (Multiple inheritance): Python hỗ trợ đa kế thừa trực tiếp trong lớp (class), trong khi Java thì không (Java chỉ cho phép implement nhiều interface).
  • Kiểu dữ liệu Tuple: Java không có Tuple. Trong Python, Tuple tương tự List (hoặc Array) nhưng bất biến (immutable): chỉ có thể khởi tạo chứ không thể thay đổi sau khi tạo.
  • Khởi tạo thuộc tính: trong Python, các thuộc tính của đối tượng được khai báo bên trong phương thức __init__() (tương đương constructor trong Java):
def __init__(self, color, model, year):
    self.color = color
    self.model = model
    self.year = year

Từ khóa self và this:

  • Trong Java, đối tượng tự tham chiếu đến chính nó bằng từ khóa this:
    public void setColor(String color) {
        this.color = color;
    }
    Lưu ý: trong Java, this có thể được ngầm định (bỏ đi) khi truy cập thuộc tính.
  • Trong Python, self đóng vai trò tương tự, nhưng khác với this trong Java, self là bắt buộc khi tạo hoặc truy cập thuộc tính của đối tượng.

Bạn cũng có thể khai báo thuộc tính trong __init__() và dùng decorator @property để quản lý truy cập (tương đương Getter trong Java):

class Car:
    def __init__(self, color, model, year):
        self.color = color
        self.model = model
        self.year = year
        self._voltage = 12

    @property
    def voltage(self):
        return self._voltage
  • Quy ước tên biến: dấu gạch dưới _voltage báo hiệu đây là thuộc tính nội bộ (internal/protected).
  • Decorator @property: đóng vai trò như Getter trong Java, cho phép truy cập thuộc tính như một biến thông thường (car.voltage) thay vì gọi hàm (car.getVoltage()), giúp code gọn gàng và đúng phong cách Python (Pythonic).
Java vs Python

Reference / Tài liệu tham khảo

Tuesday, September 15, 2020

Unit tests with jmockit

What is JMockit?

JMockit is open source software unit testing library, It includes APIs for mocking, faking, and combining with a code coverage tool. This library is used together with a testing framework such as JUnit or TestNG.  IntelliJ IDEA is a good ide for testing with JMockit.

Sunday, August 30, 2020

Dart language from view of Java Developer

Lately, I keep hearing about the Dart language all over the Internet, so this weekend I decided to take a quick look at it.

Dart is a programming language developed by Google for building mobile, web, desktop and IoT applications, and it has even been used for Google’s advertising products. Its best-known use today is Flutter, Google’s UI framework that lets you build apps for iOS, Android and more from a single codebase.

If you come from Java, JavaScript or TypeScript, Dart’s syntax will feel familiar. It borrows many ideas from these languages (classes, generics, async/await, and Streams similar in spirit to RxJS) while adding its own improvements. In this post, I will skim through the basics, mainly by comparing Dart with Java.

Sunday, August 9, 2020

Apache Wicket 9 news

 With emerging of ReactJS and  Angular and Microservices, Apache Wicket framework seems darkly because many people think that only ReactJS, Angular, VueJS can work with Microservices. But apache wicket is also a FrontEnd framework and can communicate with Microservices over internet by JSON format data exchange and It is still safely, more stronger. Following is the news from https://wicket.apache.org site:

POPULAR | PHỔ BIẾN

TAGS

VIEWS