teleren/devto huggingface dataset:
System Design: Command and Query Responsibility Segregation (CQRS)
Tags: distributedsystems, architecture, tutorial
Published: 2022-09-15 05:11:14


Command Query Responsibility Segregation (CQRS) is an architectural pattern that divides a system's actions into commands and queries. It was first described by [Greg Young](https://twitter.com/gregyoung).

In CQRS, a _command_ is an instruction, a directive to perform a specific task. It is an intention to change something and doesn't return a value, only an indication of success or failure. And, a _query_ is a request for information that doesn't change the system's state or cause any side effects.

![command-and-query-responsibility-segregation](https://raw.githubusercontent.com/karanpratapsingh/portfolio/master/public/static/courses/system-design/chapter-III/command-and-query-responsibility-segregation/command-and-query-responsibility-segregation.png)

The core principle of CQRS is the separation of commands and queries. They perform fundamentally different roles within a system, and separating them means that each can be optimized as needed, which distributed systems can really benefit from.

## CQRS with Event Sourcing

The CQRS pattern is often used along with the Event Sourcing pattern. CQRS-based systems use separate read and write data models, each tailored to relevant tasks and often located in physically separate stores.

When used with the Event Sourcing pattern, the store of events is the write model and is the official source of information. The read model of a CQRS-based system provides materialized views of the data, typically as highly denormalized views.

## Advantages

Let's discuss some advantages of CQRS:

- Allows independent scaling of read and write workloads.
- Easier scaling, optimizations, and architectural changes.
- Closer to business logic with loose coupling.
- The application can avoid complex joins when querying.
- Clear boundaries between the system behavior.

## Disadvantages

Below are some disadvantages of CQRS:

- More complex application design.
- Message failures or duplicate messages can occur.
- Dealing with eventual consistency is a challenge.
- Increased system maintenance efforts.

## Use cases

Here are some scenarios where CQRS will be helpful:

- The performance of data reads must be fine-tuned separately from the performance of data writes.
- The system is expected to evolve over time and might contain multiple versions of the model, or where business rules change regularly.
- Integration with other systems, especially in combination with event sourcing, where the temporal failure of one subsystem shouldn't affect the availability of the others.
- Better security to ensure that only the right domain entities are performing writes on the data.


---

_This article is part of my open source [System Design Course](https://github.com/karanpratapsingh/system-design) available on Github._

{% github karanpratapsingh/system-design %}
System Design: Event Sourcing
Tags: distributedsystems, architecture, tutorial
Published: 2022-09-15 05:10:46


Instead of storing just the current state of the data in a domain, use an append-only store to record the full series of actions taken on that data. The store acts as the system of record and can be used to materialize the domain objects.

![event-sourcing](https://raw.githubusercontent.com/karanpratapsingh/portfolio/master/public/static/courses/system-design/chapter-III/event-sourcing/event-sourcing.png)

This can simplify tasks in complex domains, by avoiding the need to synchronize the data model and the business domain, while improving performance, scalability, and responsiveness. It can also provide consistency for transactional data, and maintain full audit trails and history that can enable compensating actions.

## Event sourcing vs Event-Driven Architecture (EDA)

Event sourcing is seemingly constantly being confused with [Event-driven Architecture (EDA)](https://karanpratapsingh.com/courses/system-design/event-driven-architecture). Event-driven architecture is about using events to communicate between service boundaries. Generally, leveraging a message broker to publish and consume events asynchronously within other boundaries.

Whereas, event sourcing is about using events as a state, which is a different approach to storing data. Rather than storing the current state, we're instead going to be storing events. Also, event sourcing is one of the several patterns to implement an event-driven architecture.

## Advantages

Let's discuss some advantages of using event sourcing:

- Excellent for real-time data reporting.
- Great for fail-safety, data can be reconstituted from the event store.
- Extremely flexible, any type of message can be stored.
- Preferred way of achieving audit logs functionality for high compliance systems.

## Disadvantages

Following are the disadvantages of event sourcing:

- Requires an extremely efficient network infrastructure.
- Requires a reliable way to control message formats, such as a schema registry.
- Different events will contain different payloads.


---

_This article is part of my open source [System Design Course](https://github.com/karanpratapsingh/system-design) available on Github._

{% github karanpratapsingh/system-design %}
System Design: Event-Driven Architecture (EDA)
Tags: distributedsystems, architecture, tutorial
Published: 2022-09-15 05:10:34


Event-Driven Architecture (EDA) is about using events as a way to communicate within a system. Generally, leveraging a message broker to publish and consume events asynchronously. The publisher is unaware of who is consuming an event and the consumers are unaware of each other. Event-Driven Architecture is simply a way of achieving loose coupling between services within a system.

## What is an event?

An event is a data point that represents state changes in a system. It doesn't specify what should happen and how the change should modify the system, it only notifies the system of a particular state change. When a user makes an action, they trigger an event.

## Components

Event-driven architectures have three key components:

- **Event producers**: Publishes an event to the router.
- **Event routers**: Filters and pushes the events to consumers.
- **Event consumers**: Uses events to reflect changes in the system.

![event-driven-architecture](https://raw.githubusercontent.com/karanpratapsingh/portfolio/master/public/static/courses/system-design/chapter-III/event-driven-architecture/event-driven-architecture.png)

_Note: Dots in the diagram represents different events in the system._

## Patterns

There are several ways to implement the event-driven architecture, and which method we use depends on the use case but here are some common examples:

- [Sagas](https://karanpratapsingh.com/courses/system-design/distributed-transactions#sagas)
- [Publish-Subscribe](https://karanpratapsingh.com/courses/system-design/publish-subscribe)
- [Event Sourcing](https://karanpratapsingh.com/courses/system-design/event-sourcing)
- [Command and Query Responsibility Segregation (CQRS)](https://karanpratapsingh.com/courses/system-design/command-and-query-responsibility-segregation)

_Note: Each of these methods is discussed separately._

## Advantages

Let's discuss some advantages:

- Decoupled producers and consumers.
- Highly scalable and distributed.
- Easy to add new consumers.
- Improves agility.

## Challenges

Here are some challenges of event-drive architecture:

- Guaranteed delivery.
- Error handling is difficult.
- Event-driven systems are complex in general.
- Exactly once, in-order processing of events.

## Use cases

Below are some common use cases where event-driven architectures are beneficial:

- Metadata and metrics.
- Server and security logs.
- Integrating heterogeneous systems.
- Fanout and parallel processing.

## Examples

Here are some widely used technologies for implementing event-driven architectures:

- [NATS](https://nats.io)
- [Apache Kafka](https://kafka.apache.org)
- [Amazon EventBridge](https://aws.amazon.com/eventbridge)
- [Amazon SNS](https://aws.amazon.com/sns)
- [Google PubSub](https://cloud.google.com/pubsub)


---

_This article is part of my open source [System Design Course](https://github.com/karanpratapsingh/system-design) available on Github._

{% github karanpratapsingh/system-design %}
How do I trim whitespace from a string in Python?
Tags: python, beginners, programming
Published: 2022-09-15 04:58:23

When working with Python strings, a pretty common question is how to trim whitespace from a string. Whitespace characters are the space (` `), tab (`\t`), newline (`\n`), and carriage return characters (`\r`). Here are 3 different methods to trim whitespace from a string in Python.

### Remove leading and trailing whitespace characters

Use the `str.strip()` method to remove whitespace characters from both the beginning and end of a string.

```py
'  Hello  '.strip()    # 'Hello'
```

### Remove leading whitespace characters

Leading whitespace characters are the whitespace characters at the start of a string. To remove them, use the `str.lstrip()` method.

```py
'  Hello  '.lstrip()   # 'Hello  '
```

### Remove trailing whitespace characters

Trailing whitespace characters are the whitespace characters at the end of a string. To remove them, use the `str.rstrip()` method.

```py
'  Hello  '.rstrip()   # '  Hello'
```

---

_Do you like short, high-quality code snippets and articles? So do we! Visit [30 seconds of code](https://www.30secondsofcode.org/) for more articles like this one or follow us on [Twitter](https://twitter.com/30secondsofcode) for daily JavaScript, React and Python snippets!_ 👨‍💻
How to redirect from www to non-www URL using Cloudflare for free
Tags: seo, drupal, wordpress, cloudflare
Published: 2022-09-16 00:12:08

---
title: How to redirect from www to non-www URL using Cloudflare for free
published: true
date: 2022-09-15 01:53:51 UTC
tags: SEO,Drupal,WordPress,cloudflare
canonical_url: https://davidloor.com/2022/09/14/how-to-redirect-from-www-to-www-using-cloudflare/
---

![How to redirect from www to non-www URL using Cloudflare for free](https://i0.wp.com/davidloor.com/wp-content/uploads/2022/09/pexels-photo-5845730.jpeg?resize=800%2C533&ssl=1)

After doing a quick SEO audit to this website, I found that https://davidloor.com/ and https://www.davidloor.com/ were both up. Since search engines see them as two different websites, it may arises issues because of duplicated content. So, I needed to pick one of the domains and redirect the other to the one selected. On the internet there is a big debate about which version is better, but I like the non www because it is shorter, also this website is simple and there is not too much content in it yet, but in bigger websites I may be inclined to use the www version.

This website has cloudflare as its CDN, so the steps to add a page rule to accomplish the redirect are as follows:

1.- Log in to your Cloudflare account from [https://dash.cloudflare.com/login](https://dash.cloudflare.com/login) and go to the domain that you want to add the redirect to in case you have more than one.

2.- Go to Rules -> Page Rules and click on Create Page Rule

![](https://i0.wp.com/davidloor.com/wp-content/uploads/2022/09/create-page-rules-cloudflare.png?resize=800%2C348&ssl=1)
_Create Page Rule_

3.- Enter the URL that you are redirecting from, in my example, I am need to enter the www version (www.davidloor.com)

4.- Pick the **Forwarding URL** setting and the status code should be **301 – Permanent Redirect**

5.- In the destination URL field we should enter the URL that we are redirecting to, adding **/$1** at the end, in my example it is the non www version (https://davidloor.com/$1)

![](https://i0.wp.com/davidloor.com/wp-content/uploads/2022/09/Screen-Shot-2022-09-14-at-9.19.55-PM.png?resize=800%2C626&ssl=1)

6.- Click on Save Page Rule, and go to your website to test that the redirect is working. It should work almost immediately.
2007. Leetcode solution in python
Tags: python, programming, productivity
Published: 2022-09-15 04:39:44

```
class Solution:
  def findOriginalArray(self, changed: List[int]) -> List[int]:
    ans = []
    q = deque()

    for num in sorted(changed):
      if q and num == q[0]:
        q.popleft()
      else:
        q.append(num * 2)
        ans.append(num)

    return [] if q else ans
```
#leetcode
#challenge
here is the link for the problem: 
https://leetcode.com/problems/find-original-array-from-doubled-array/
Add AWS CDK to an existing nx project
Published: 2022-09-15 04:16:57

Credit to this [post](https://dev.to/alexvladut/how-to-add-aws-cdk-to-an-existing-project-2d30).

### Pre-requisites
- nx project
- nx @nrwl/workspace library 

### 1. In the root of your project, reate a new folder to place your cdk files.

```
md cdk
```

### 2. Run the cdk init command

```
npx cdk init app --language=typescript
```

### 3 Moved `cdk.json` file from cdk folder to your project root. And replace app with custom js path.

```
{
  "app": "dist/iac/main.js",
  ...
}
```


### 4 Install aws cdk package

```
npm i --save-dev aws-cdk
npm i aws-cdk-lib constructs
```

### 5 Copy the content of the file `cdk/bin/cdk.ts` into iac/src/main.ts. Copy the file `cdk/lib/cdk-stack.ts` to `iac/src/app.stac.ts` and update the import in main.ts to correctly point to it.

### 6 Build your nx library 

### 7 run `cdk bootstrap` (if its the first time you're using cdk)

### 8 run `cdk deploy --profile=zeke  --app=dist/libs/iac/src/main.js`
Why is it recommended to use only the default constructor to create a Fragment?
Tags: android
Published: 2022-09-15 04:06:21

---
title: Why is it recommended to use only the default constructor to create a Fragment?
published: true
description: In this blog, we are going to learn why is it recommended to use only the default constructor to create a Fragment.
tags: Android
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7e7ozz5w9tid8mb62by9.png
canonical_url: https://amitshekhar.me/blog/default-constructor-to-create-a-fragment
---

I am [**Amit Shekhar**](https://amitshekhar.me), a mentor helping developers in getting high-paying tech jobs.

Today, in this blog we will discuss an Android Interview Question.

**Question:** Why is it recommended to use only the default constructor to create a Fragment?

It is one of the commonly asked questions during the Android Interview.

**This article was originally published at [amitshekhar.me](https://amitshekhar.me/blog/default-constructor-to-create-a-fragment).**

Let’s discuss the answer.

So, Whenever the Android Framework decides to recreate our Fragment for example in case of **orientation changes**. Android calls the **no-argument constructor** of our Fragment.

The reason why **can’t** it call the constructor with the argument is that Android Framework has no idea what constructor we have created. So it can’t.

Let’s look at the recommended way of creating the `newInstance` of Fragment:

Here is the code:

```kotlin
private const val EXTRA_PDF_ID = "EXTRA_PDF_ID"

fun newInstance(pdfID: Long): PdfFragment {
    val fragment = PdfFragment()
    val bundle = Bundle()
    bundle.putLong(EXTRA_PDF_ID, pdfID)
    fragment.arguments = bundle
    return fragment
}
```

Here this `setArguments` method is very important.

```kotlin
 fragment.arguments = bundle
```

We must notice that we are passing the Bundle inside it. So when we create the instance for the first time using this `newInstance` method. The Android Framework can extract the bundle and store it.

So, when in case of Orientation changes, the Android Framework recreates the new fragment using the no-argument constructor and can attach the bundle to the fragment as it has stored the bundle earlier.

And later again, we can access that data in our `onCreate()` method by using `getArguments()` like this.

```kotlin
val pdfID = arguments?.getLong(EXTRA_PDF_ID)
```

It means that when the system restores a fragment, it will automatically restore our bundle. And we will be able to restore the state of the fragment to the same state the fragment was initialized with.

So, now we know the answer to Why is it recommended to use only the default constructor to create a Fragment?

That's it for now.

Thanks

[**Amit Shekhar**](https://amitshekhar.me)

You can connect with me on:

- [Twitter](https://twitter.com/amitiitbhu)
- [LinkedIn](https://www.linkedin.com/in/amit-shekhar-iitbhu)
- [GitHub](https://github.com/amitshekhariitbhu)
- [Facebook](https://www.facebook.com/amit.shekhar.iitbhu)
What is Unit in Kotlin?
Published: 2022-09-15 03:56:57

Unit is an object. The type with only one value return: the Unit object. This type corresponds to the **<u>void</u>** type in Java.

Example:
**onClick: () -> Unit**
 onClick is a Function Unit return, just like void in  java.

Source:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/
AWS compare EBS volumes
Tags: aws, ebs
Published: 2022-09-15 03:54:54

|     |     |     |     |     |
| --- | --- | --- | --- | --- |
| **Volume Name** | **General Purpose SSD** |     | **Provisioned IOPS SSD** |     |
| **Volume type** | gp3 | gp2 | io2 | io1 |
| **Description** | General Purpose SSD volume that balances price performance for a wide variety of transactional workloads | General Purpose SSD volume that balances price performance for a wide variety of transactional workloads | High performance SSD volume designed for **business-critical** latency-sensitive applications | High performance SSD volume designed for latency-sensitive transactional workloads |
| **Use Cases** | virtual desktops, medium sized single instance databases such as MSFT SQL Server and Oracle DB, low-latency interactive apps, dev & test, boot volumes | Boot volumes, low-latency interactive apps, dev & test | Workloads that require sub-millisecond latency, and sustained IOPS performance or more than 64,000 IOPS or 1,000 MiB/s of throughput | Workloads that require sustained IOPS performance or more than 16,000 IOPS and I/O-intensive database workloads |
| **Volume Size** | 1 GB – 16 TB | 1 GB – 16 TB | 4 GB – 16 TB<br><br>/ 64 TB for io2 block express | 4 GB – 16 TB |
| **Durability** | 99.8% – 99.9% durability | 99.8% – 99.9% durability | 99.999% | 99.8% – 99.9% |
| **Max IOPS / Volume** | 16,000 | 16,000 | 64,000<br><br>/ 256,000 for io2 block express | 64,000 |
| **Max Throughput  / Volume** | 1000 MB/s | 250 MB/s | 1,000 MB/s<br><br>/ 4,000 MiB/s for io2 block express | 1,000 MB/s |
| **Max IOPS / Instance** | 260,000 | 260,000 | 160,000<br><br>/ 260,000 MiB/s for io2 block express | 260,000 |
| **Max IOPS / GB** | N/A | N/A | 500 IOPS/GB<br><br>/ 1,000 IOPS/GB for io2 block express | 50 IOPS/GB |
| **Max Throughput / Instance** | 7,500 MB/s | 7,500 MB/s | 4,750 MB/s<br><br>/ 7,500 MB/s for io2 block express | 7,500 MB/s |
| **Latency** | single digit millisecond | single digit millisecond | single digit millisecond | single digit millisecond |
| **Multi-Attach** | No  | No  | Yes | Yes |


|     |     |     |
| --- | --- | --- |
| **Volume Name** | **Throughput Optimized HDD** | **Cold HDD** |
| **Volume type** | st1 | sc1 |
| **Description** | Low cost HDD volume designed for frequently accessed, throughput-intensive workloads | Throughput-oriented storage for data that is infrequently accessed<br><br>Scenarios where the lowest storage cost is important |
| **Use Cases** | Big data, data warehouses, log processing | Colder data requiring fewer scans per day |
| **Volume Size** | 125 GB – 16 TB | 125 GB – 16 TB |
| **Durability** | 99.8% – 99.9% durability | 99.8% – 99.9% durability |
| **Max IOPS / Volume** | 500 | 250 |
| **Max Throughput  / Volume** | 500 MB/s | 250 MB/s |
| **Max IOPS / Instance** | 260,000 | 260,000 |
| **Max IOPS / GB** | N/A | N/A |
| **Max Throughput / Instance** | 7,500 MB/s | 7,500 MB/s |
| **Multi-Attach** | No  | No  |
Song Chắn Rác 300x500 Gang cầu GOAT
Tags: songchanracgang, songchanrac300x500, goat
Published: 2022-09-15 03:10:16

Song chắn rác 300x500 mm thường được lắp đặt ở hố thoát nước lề đường, tầng hầm, rãnh thoát nước, khuôn viên khu đô thị, công viên, khu công nghiệp, nhà máy... 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ygm13m9miozzu58bfdze.jpg)
Song chắn rác 300x500 gang GOAT - Mã [SCR-G-300x500] 
[Song chắn rác SCR-G-300x500](https://naphoga.vn/song-chan-rac-300x500-goat-chat-lieu-gang-cau.html) là sản phẩm của Công ty TNHH Thương mại và Dịch vụ GOAT. 

Đây là loại song chắn rác gang đậy miệng hố ga thoát nước mưa. Với thiết kế nhỏ gọn, sản phẩm được ưu tiên sử dụng bởi giá tốt và dễ dàng lắp đặt.

Với tâm niệm: "Sức mạnh đến từ chất lượng - Bạn hàng đến từ sự uy tín", GOAT luôn mong muốn được hợp tác và đề xuất những phương án lựa chọn song thoát nước gang phù hợp, tiết kiệm chi phí nhất cho nhà thầu. 

Mọi thắc mắc về sản phẩm, vui lòng liên hệ GOAT qua Hotline: **0987.382.388**

Theo dõi chúng tôi tại: 
[https://vimeo.com/naphogagoat](https://vimeo.com/naphogagoat)
[https://www.diigo.com/user/naphogagoat](https://www.diigo.com/user/naphogagoat)
[https://flipboard.com/@naphogagoat](https://flipboard.com/@naphogagoat)
Memiliki banyak pengikut di Instagram
Published: 2022-09-15 02:20:18

Memiliki banyak pengikut di Instagram tentu sangat berguna untuk membangun merek, baik untuk bisnis atau influencer.
Tentu saja apa yang dicari bukan hanya kuantitas, tetapi pengikut juga harus asli untuk meningkatkan kualitas keterlibatan.
Saat ini banyak yang menawarkan pengikut Instagram yang membeli dan menjual layanan yang menggunakan akun bot.
Teknik-teknik seperti ini memang dapat menambah pengikut instan seperti dikutip dari situs [mediasari.com](https://www.mediasari.com/), tetapi akun bot tentu tidak seaktif pengikut asli untuk meninggalkan komentar atau suka disukai di pos.
Alih-alih menghabiskan uang untuk membeli pengikut yang mungkin tidak selalu meningkatkan keterlibatan, lebih baik mempelajari sains dasar untuk mendapatkan pengikut Instagram yang aktif secara organik.
Meskipun tidak instan, setidaknya pengikut yang diperoleh harus menjadi orang yang nyata dan aktif.
Optimalisasi Akun Instagram
Pastikan akun Instagram Anda sudah memiliki bio, foto profil, nama pengguna, dan keterangan foto yang jelas sehingga akun dan merek Anda dapat segera diketahui.
Untuk Bio Instagram, isi informasi penting yang terkait dengan bisnis Anda termasuk kepribadian merek, deskripsi merek, ajakan bertindak, dan tautan tautan.
Gunakan nama pengguna Instagram yang mudah ditemukan dan tidak menambahkan karakter atau angka di belakangnya. Jika nama bisnis Anda terlalu lama, dapat dipersingkat untuk memudahkan audiens diakui.
Pilih [font pack pixellab](https://www.mediasari.com/font-pack-gratis/) waktu yang konsisten. Jangan mengunggah konten dalam waktu acak dan ceroboh. Digunakan untuk memposting konten secara teratur dan konsisten sesuai dengan waktu yang ditentukan.
Anda dapat memanfaatkan fitur Insights di Instagram untuk mengetahui jam ketika pengikut yang paling aktif. Laporan ini sudah berisi informasi lengkap tentang berbagai konten dan waktu.