teleren/devto huggingface dataset:
Microservice with Domain Driven Design - the art of writing good code (production-ready example)
Tags: domaindrivendesign, java, architecture, webdev
Published: 2022-06-15 10:00:42

##Full Spring Boot authentication microservice with Domain-Driven Design approach and CQRS.

Domain-Driven Design is like the art of writing a good code. Everything around the code e.g. database (maria, postgres, mongo), are just tools that support the code to work. Source code is the heart of the application and You should pay attention mostly to that. DDD is one of the approaches to create beautiful source code.

**This is a list of the main goals of this repository:**

- Showing how you can implement a Domain-Drive design
- Showing how you can implement a CQRS
- Presentation of the full implementation of an application
- This is not another proof of concept (PoC)
- The goal is to present the implementation of an application that would be ready to run in production
- Showing the application of best practices and object-oriented programming principles

**GitHub repo**
[repo](https://github.com/tlandeka/authentication-microservice-with-domain-driven-design)

**Your contribution:**
- feedback for pros&cons
- if You like the repo, star it and share 


###A brief overview of the architecture

The used approach is DDD which consists of 3 main layers: **Domain**, **Application**, and **Infrastructure**.

**Domain** - Domain Model in Domain-Driven Design terms implements the business logic. Domain doesn't depend on Application nor Infrastructure.

**Application** - the application which is responsible for request processing. It depends on Domain, but not on Infrastructure. Request processing is an implementation of CQRS read (**Query**) / write (**Command**). Lots of best practices here.

**Infrastructure** - has all tool implementations (eg. HTTP (HTTP is just a tool), Database integrations, SpringBoot implementation (REST API, Dependency Injection, etc.. ). Infrastructure depends on Application and Domain. Passing HTTP requests from SpringBoot rest controllers to the Application Layer is solved with “McAuthenticationModule”. In this way, all relations/dependencies between the Application Layer and Infrastructure layer are placed into only one class. And it is a good design with minimized relations between layers.

**Tests**
The type of tests are grouped in folders and it is also good practice and it is fully testable which means - minimised code smells. So the project has:

- integration tests
- unit test
Being a programmer sucks, most of the time.
Tags: programming, devjournal, beginners, discuss
Published: 2022-06-15 10:00:19

Let's be honest, folks.

Coding is brutally, punishingly frustrating.

Nothing has ever made me feel like an idiot so regularly than computer programming. In fact, I took 3 years off this job, thinking "_I'm done. no more!_"

![computer programming](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wphr8970tiw06gftv4il.jpeg)

It means going through failure after failure, spending hours-sometimes days- on a problem only to reveal a tiny typo, a missing colon.

Sometimes you write a few lines of code, something fairly simple, then you run a test and… it doesn’t work. Sometimes everything works and your mind goes, "_what about that improvement?_" (so you change code and _tada!!!_)

![Code refactoring](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9nmdkx8p7u0iwlrr2nma.png)

But, there's something interesting about it. Isn't it?

When you finally open your pull-request, tests run smoothly and you tick off items from the development todo list, you experience an absolute sense of mastery and joy.

I remember when I started studying computer science back in high-school.

I've always been a logical and systematic human being. The one who crosses the street stepping on or avoiding particular floor tiles.

![perfectionist](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w9942xh7oaf8knszbddp.jpg)

And I immediately fell in love working with machines that do whatever you say — but only if you are perfectly, utterly precise in your instructions.

Sure, in the beginning is hard. One small mistake, one misplaced bracket, and the whole thing stops working. But...

**Programming is like martial arts.**

The more you train, the more able you become to handle crushing and incessant failures and roadblocks.

**Software engineering helps you approach problems methodically, break big tasks down into tiny steps and develop sound solutions.**

This is a prerequisite in many modern jobs.

**Not only programmers, but researchers, entrepreneurs and white-collars of any kind benefit from this mindset.**

If you're able to tackle with the psychological storm and endure such a grind of this job, you'll:

- develop a strong **ability** to deal with pain (a "painability")
- become **fearless** of new challenges
- work on **interesting** stuff that will make you proud
- have lots of **digital friends**
- break production code and make customers go crazy before fixing the bug and pretending **you just saved their life**

Trust me, this one of the most rewarding jobs out there. I've sold my successful real estate company, just to come back and work again as a programmer. I really like it.

_**Mattia, what's the real secret of a programmer?**_

To succeed in life, you must be great at analyzing details, facing challenges and automating tasks.

Programmers are really good at it.

And programming can also improve your relationships, because you know... women appreciate attention to details and men, well, they're men (they're cute dogs). _Marry a programmer!_

Let me know what you think, in the comments ;-)
See ya!
How to use preload script in Electron Webview with React
Tags: react, electron, tutorial, programming
Published: 2022-06-15 09:49:31

The preload attribute requires to use the file: protocol.
Because of the way electron and webpack work, it's a nightmare to use the preload attribute from the Renderer process, in the DOM.

The trick is to do it from the Main process.

In src/main/main.ts:

```
app.on('web-contents-created', (_event, contents) => {
  contents.on('will-attach-webview', (_wawevent, webPreferences, _params) => {
    webPreferences.preloadURL = `file://${__dirname}/webview-preload.js`;
  });
});
```

In src/main/webview-preload.js:

```
document.addEventListener(
  'DOMContentLoaded',
  () => {
    // YOUR CODE HERE
  },
  false
);
```

If this article helped you, please have a look at our Browser built with Electron, React, TypeScript and Redux: https://github.com/danielfebrero/bonb-browser
Paperfly Courier Integration Package for Laravel Framework
Tags: laravel, php, paperfly
Published: 2022-06-15 06:50:34



## Step 1

```
composer require wddyousuf/paperfly
php artisan vendor:publish --provider=Wddyousuf\Paperfly\PaperflyServiceProvider
php artisan config:cache
```
This will create a courier.php in the config/ directory. Set your desired provider as default_provider and fill up the necessary environment variable of that provider.

## Step 2

Set .env configuration 
```
COURIER_USERNAME="XXXXXXXX"
COURIER_PASSWORD="XXXXXXXXXX"
COURIER_API_KEY="Paperfly_~La?Rj73FcLm"
COURIER_PROVIDER="PAPERFLY"
```

## Sample Code For Requesting a Pick Up

```
use Wddyousuf\Paperfly\Facades\PaperflyCourier;

$OrderInformation=[
    "OrderNo" => "111111",
    "MerchantName" => "Mr. X",
    "MerchantAddress" => "Test",
    "MerchantThana" => "Dhanmondi",
    "MerchantDistrict" => "Dhaka",
    "MerchantPhone" => "017xxxxx",
    "SizeWeight" => "standard",
    "productDetails" => "Usb Fan",
    "packagePrice" => "0",
    "deliveryType" => "regular",
    "CustomerName" => "Mr. Y",
    "CustomerAddress" => "Road 27, Dhanmondi",
    "CustomerThana" => "Adabor",
    "CustomerDistrict" => "Dhaka",
    "CustomerPhone" => "017xxxxx",
    "max_weight" => "10",
];
$response = PaperflyCourier::sendRequest($OrderInformation);

//Collect Thana list from paperfly
//Collect District list from paperfly
// max_weight is only for weight Enabled Pickup Request
//If Thana and District doesn't match with paperfly list,It will occur error
```

## Sample Code For Tracking an Order

```
use Wddyousuf\Paperfly\Facades\PaperflyCourier;

$orderId='XXXXXXX';
$response = PaperflyCourier::trackOrder($orderId);
```

## Sample Code For Invoice

```
use Wddyousuf\Paperfly\Facades\PaperflyCourier;

$orderId='XXXXXXX';
$response = PaperflyCourier::courierInvoice($orderId);
```

## Sample Code For Cancel Order

```
use Wddyousuf\Paperfly\Facades\PaperflyCourier;

$orderId='XXXXXXX';
$response = PaperflyCourier::CourierOrderCancel($orderId);
```

If you feel something is missing then make a issue regarding that. Your can pull reques. If you want to contribute in this library, then you are highly welcome to do that....
For accesing to repo and all method list visit github link from here https://github.com/wddyousuf/paperfly
Kunci Jawaban Brain Out Detektif Level 10
Tags: tutorial, beginners, brainout
Published: 2022-06-15 09:40:45

https://bit.ly/3MOclTf - Buat yang ingin memecahkan misteri Brain Out Detektif tentang sebuah pembunuhan misterius di sebuah kantor, maka saya sudah mengantongi informasi seputar pelakunya.

Mungkin tidak bisa saya jelaskan di sini secara utuh. Namun kamu bisa melihatnya jawaban lengkapnya melalui tautan yang sudah saya cantumkan di bawah ini.

https://bit.ly/3MOclTf
Find the Middle Index in Array
Tags: leetcode, dsa, theabbie
Published: 2022-06-15 09:30:42

Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones).

A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`.

If `middleIndex == 0`, the left side sum is considered to be `0`. Similarly, if `middleIndex == nums.length - 1`, the right side sum is considered to be `0`.

Return _the **leftmost**_ `middleIndex` _that satisfies the condition, or_ `-1` _if there is no such index_.

**Example 1:**

**Input:** nums = \[2,3,-1,8,4\]
**Output:** 3
**Explanation:** The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4

**Example 2:**

**Input:** nums = \[1,-1,4\]
**Output:** 2
**Explanation:** The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0

**Example 3:**

**Input:** nums = \[2,5\]
**Output:** -1
**Explanation:** There is no valid middleIndex.

**Constraints:**

*   `1 <= nums.length <= 100`
*   `-1000 <= nums[i] <= 1000`

**Note:** This question is the same as 724: [https://leetcode.com/problems/find-pivot-index/](https://leetcode.com/problems/find-pivot-index/)

**SOLUTION:**

    class Solution:
        def findMiddleIndex(self, nums: List[int]) -> int:
            n = len(nums)
            if n == 1:
                return 0
            total = sum(nums)
            curr = 0
            if curr * 2 == total - nums[0]:
                return 0
            for i in range(n - 1):
                curr += nums[i]
                if curr * 2 == total - nums[i + 1]:
                    return i + 1
            return -1
Passwords, No more pain
Tags: password, pain, nopassword
Published: 2022-11-01 06:43:50

---
title: Passwords, No more pain
published: true
date: 2022-06-15 09:11:23 UTC
tags: password, pain, nopassword
canonical_url: https://mojoauth.com/blog/passwords-no-more-pain/
---

Overview Passwords are like the common cold: they induce headaches, no one is immune, and there is no cure. But they are necessary for this era of digital data, where everything from paying bills to passing notes to sharing photos is done online through user accounts that require some proof that you are who you say you are.The use of passwords knows as it should be easy to remember and difficult to guess by anyone .

[Read On](https://mojoauth.com/blog/passwords-no-more-pain/)
JavaScript's unsafe optional chaining is crazy |:
Tags: javascript, lint, webdev, discuss
Published: 2022-06-15 08:58:18

### Optional chaining:

[Optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)  has made life of `javaScript` programmer easy by handling the checks using the syntax `?.` 

However, here we are **NOT** to discuss how awesome it is, rather solving a issue how of to safely use it.

---

### no-unsafe-optional-chaining 
[no-unsafe-optional-chaining][1] is an amazing `eslint` rule, which help us identify what are we doing wrong with **optional chaining** and disallows use of optional chaining in contexts where the `undefined` value is not allowed.


I have one case where I need to perform a `sort` operation on `id` which could be in `string` type which make sense to **throw error** because it could result in `NaN`, if `order` is not a number as follows:

---

### The issue
```js
  const sortComparer = (a, b) => (+a?.order) - (+b?.order)
```

---

### My solution
However, if i do handle `no-unsafe-optional-chaining` as follow it still **throws error** and does not work:

```js
  const sortComparer = (a, b) => (+a.order || 0) - (+b.order || 0),
```

---

### The way it worked
The only way to make it work is like this:

```js
  const sortComparer = (a, b) => (a?.order ? +a.order : 0) - (b?.order ? +b.order : 0),
```

## Question ? :S
Does anyone know how to fix this in a better way to avoid this issue ?


  [1]: https://eslint.org/docs/rules/no-unsafe-optional-chaining


Regards.


{% link https://dev.to/mnathani/welcome-to-imposter-syndrome-d-3edl %}
(beta) yugabyted GUI
Tags: yugabytedb, cloud, gui, database
Published: 2022-06-15 08:55:24



**⚠️ this content is now obsolete. the YugabyteDB UI is GA and started automatically by `yugabyted` and is now on port 15433**
```
docker run -d --name yb -p 5433:5433 -p 15433:15433 -p 7000:7000 \
 docker.io/yugabytedb/yugabyte:2.17.0.0-b24                      \
 bin/yugabyted start --daemon=false

```
and open http://localhost:15433

---

To get started with YugabyteDB (PostgreSQL-compatible distributed SQL database) you have two easy ways:
- [cloud.yugabyte.com](cloud.yugabyte.com) for a managed service (free tier available)
- [yugabyted](https://docs.yugabyte.com/preview/reference/configuration/yugabyted/) which starts quickly the required `yb-master` and `yb-server` (free and open source)

Currently (version 2.13), the GUI available with `yugabyted` is a read only web console from the `yb-master` and `yb-server`. In the managed cloud, you have a smarter console with settings, performance tabs and more.

This smart console is now coming into `yugabyted` for the best user experience in free and open source YugabyteDB:

{% embed https://twitter.com/skahleryb/status/1536846170538053633?s=20&t=mI__mROJ_wy8h1diIYybdA %}

## Test it

I can't wait to test it. Here is my `Dockerfile` which can be used like the PostgreSQL Docker image (creating a database and user on startup) and including the first beta version of `yugabyted-ui`:

```sh
cat > Dockerfile <<'DOCKERFILE'
FROM docker.io/yugabytedb/yugabyte:2.13.2.0-b135
ENV POSTGRES_USER     demo
ENV POSTGRES_PASSWORD demo
ENV POSTGRES_DB       demo
CMD pip install --upgrade pip
CMD pip install sqlalchemy pandas psycopg2-yugabytedb
EXPOSE 5433
EXPOSE 7000
EXPOSE 7002
ADD https://github.com/yugabyte/yugabyte-db/releases/download/v1.0.0-beta-yugabyted-ui/yugabyted-ui-1.0.0-linux-x86_64.tar.gz yugabyted-ui-1.0.0-linux-x86_64.tar.gz
RUN tar -xvf yugabyted-ui-1.0.0-linux-x86_64.tar.gz
CMD  \
     until PGPASSWORD=yugabyte bin/ysqlsh -v ON_ERROR_STOP=1 \
      -h $(hostname) \
      -c "create database ${POSTGRES_DB} " \
      -c "create user ${POSTGRES_USER} password '${POSTGRES_PASSWORD}' " \
      2>/dev/null && ./yugabyted-ui ; do \
       echo 'Waiting for YugabyteDB to be up...' ; sleep 3 ; \
      done & \
     bin/yugabyted start --daemon=false \
     --tserver_flags='ysql_enable_auth=true' --listen 0.0.0.0
DOCKERFILE
```

This builds the image and starts a first node:
```sh
docker build -t ybui .
docker network create -d bridge yb
docker run -d --network yb --name yb0 \
 -p 5433:5433 -p 7000:7000 -p 7002:7002 ybui

```

You can already access the UI on http://localhost:7002

Here is how it looks like:

![queries](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vowapiel7swwxotr4fxm.png)
 
![metrics](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kr5efata5ks87cbmalw9.png)
Fix Github PR by removing unwanted commits
Tags: webdev, beginners, programming, github
Published: 2022-06-15 08:46:00

Step-1: Make sure your working directory is clean (commit or stash your current changes).

Step-2: One can use the git-rebase command to easily make changes to one’s history.

`$ git rebase -i HEAD~n # here n will for number of commits you need to view`

Now git rebase command will get the following in your editor


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sc7ozlqknjqzf5myy94v.png)

Step-3: Change pick to drop in order to “drop” the commit. Don't touch anything else. Delete a commit by deleting that particular line.

Step-4: Save and Exit (Ctrl + X and to save "y")

Step -5: Finally Push the changes by using the below command to update your master and the commit will be removed.

`git push origin -branch-name-here --force`
Play sound in SWIFT 5
Published: 2022-06-15 08:37:45



```
import AVKit

class ViewController: UIViewController {
    var player: AVAudioPlayer?

    @IBAction func buttonPressed(_ sender: UIButton) {
        playSound(soundTitle:sender.currentTitle!)
    }

    func playSound(soundTitle:String) {
        let path = Bundle.main.path(forResource: "soundName",ofType:"mp3")
        
        let url = URL(fileURLWithPath: path!)

        do {
            player = try AVAudioPlayer(contentsOf: url)
            player?.play()
            
        } catch let error {
            print(error.localizedDescription)
        }
    }
}


```
Minimum Index Sum of Two Lists
Tags: leetcode, dsa, theabbie
Published: 2022-06-15 08:30:38

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.

You need to help them find out their **common interest** with the **least list index sum**. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.

**Example 1:**

**Input:** list1 = \["Shogun","Tapioca Express","Burger King","KFC"\], list2 = \["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"\]
**Output:** \["Shogun"\]
**Explanation:** The only restaurant they both like is "Shogun".

**Example 2:**

**Input:** list1 = \["Shogun","Tapioca Express","Burger King","KFC"\], list2 = \["KFC","Shogun","Burger King"\]
**Output:** \["Shogun"\]
**Explanation:** The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).

**Constraints:**

*   `1 <= list1.length, list2.length <= 1000`
*   `1 <= list1[i].length, list2[i].length <= 30`
*   `list1[i]` and `list2[i]` consist of spaces `' '` and English letters.
*   All the stings of `list1` are **unique**.
*   All the stings of `list2` are **unique**.

**SOLUTION:**

    class Solution:
        def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
            l1pos = {}
            l2pos = {}
            for i, num in enumerate(list1):
                l1pos[num] = i
            for i, num in enumerate(list2):
                l2pos[num] = i
            common = set.intersection(set(list1), set(list2))
            sums = {}
            for c in common:
                curr = l1pos[c] + l2pos[c]
                sums[curr] = sums.get(curr, []) + [c]
            return sums[min(sums.keys())]
extending hyper — ->
Tags: javascript, hyper, extension, saas
Published: 2022-03-02 18:14:32

---
title: extending hyper — ->
published: true
date: 2022-01-28 14:59:51 UTC
tags: javascript,hyper,extension,saas
canonical_url: https://hyper-io.medium.com/extending-hyper-e5e3bba57074
---

> TL;DR; Check out our new hyper extension — [https://github.com/hyper63/hyper-ext-counter](https://github.com/hyper63/hyper-ext-counter) — with this extension you can use the cache service to increment, decrement counters by a key name.

#### extensibility

hyper is designed with the ability to extend any API without directly affecting the core API design and functionality, the counter module is our first implementation of extending the hyper core API. The counter module leverages the cache API to create a more specialized API that increments, decrements and resets a numeric value in your hyper cache store. This specialization, will enable developers to quickly implement counter functionality in their applications. We plan to continue to provide extensions for the hyper-connect client that compose the primitive services together for more specialized services, while maintaining a general purpose.

#### hyper-ext-counter

The counter extension gives developers the ability to easily increment and decrement a unique key in the cache store.

#### Install

```
npm install hyper-connect hyper-ext-counter
```

> ⚡️ create a free hyper account at [https://dashboard.hyper.io](https://dashboard.hyper.io) then get a connection string and create an ENVIRONMENT VARIABLE   
>   
> HYPER=[CONNECTION STRING]

#### Initialize

```
import { connect } from 'hyper-connect'
import { counter } from 'hyper-ext-counter'

const hyper = counter(connect(process.env.HYPER))
```

#### Increment

The increment command will read the current value from the cache and increment that value by 1 and store the new value on the cache and return the new value.

```
const widgetCount = await hyper.ext.counter.inc('widgets')
console.log(widgetCount)
```

#### Decrement

The decrement command will read the current value from the cache and decrement the value by 1 and store the new value on the cache return the new value.

```
const widgetCount = await hyper.ext.counter.dec('widgets')
console.log(widgetCount)
```

#### Reset

The reset command will reset the current value in the cache to zero and return zero to the caller.

```
const widgetCount = await hyper.ext.counter.reset('widgets')
console.log(widgetCount)
```

Each of these commands take a single argument, this argument is a unique key in the cache store and can be called whatever the developer chooses as long as it is alphanumeric and does not contain any non-alphanumeric characters and starts with an alpha character (a-z).

#### summary

hyper services are built to extend and provide consistent general value that can be combined in several ways to create re-usable purposeful functionality. These extensions can speed up application development of business rules as well as maintain a clear separation from the business layer and the services layer.
mongotemplate 进行unset操作
Published: 2022-06-15 08:08:10

## 背景

需要将某个数据的某个字段移除，并非设置为null，或者空字符串等 。

mongo shell操作可以如下

```bash
db.集合名称.updateOne({id:"xxx"},{
    $unset: {"属性":"" }
})
```

翻译成kotlin的写法如下

```kotlin
override fun unsetPicture(id: String) {
    val query = Query()
    query.addCriteria(Criteria.where("id").`is`(id))
    val update = Update()
    update.unset("picture")
    mongoTemplate.updateFirst(query, update, clz)
}
```

如果没有存储id，使用_id 进行判断即可