teleren/devto huggingface dataset:
Kotlin Code Smell 017 - Pattern Abusers
Tags: kotlin, codesmells, cleancode, programming
Published: 2023-03-11 05:05:16

---
title: Kotlin Code Smell 017 - Pattern Abusers
published: true
date: 2023-03-11 05:02:29 UTC
tags: kotlin,codesmells,cleancode,programming
canonical_url: https://yonatankarp.com/kotlin-code-smell-017-pattern-abusers
---

## Problems

- Over Design

- Readability

## Solutions

1. Measure the tradeoff of pattern usage.

2. Create solutions based on real-world names ([**essential**](https://maximilianocontieri.com/no-silver-bullet)) over accidental architecture.

3. Choose [**good names**](https://maximilianocontieri.com/what-exactly-is-a-name-part-ii-rehab).

4. Use the [**MAPPER**](https://maximilianocontieri.com/what-is-wrong-with-software) technique to find [**bijection**](https://maximilianocontieri.com/the-one-and-only-software-design-principle) real entities.

## Sample Code

### Wrong

```
class FileTreeComposite {
    // name should be inferred from behavior
}

class DateTimeConverterAdapterSingleton {
    // ...
}

class PermutationSorterStrategy {
    // ...
}

class NetworkPacketObserver {
    // ...
}

class AccountsComposite {
    // ...
}

```

### Right

```
class FileSystem {
    // These names map 1:1 to real-world concepts
}

class DateTimeFormatter {
    // ...
}

class BubbleSort {
    // ...
}

class NetworkSniffer {
    // ...
}

class Portfolio {
    // ...
}

```

## Conclusion

Choose when to apply a pattern solution. You are not being [smarter](https://yonatankarp.com/kotlin-code-smell-005-too-clever-for-your-own-good) by using too many patterns. You are smart if you choose the right opportunity to use the patterns.

* * *

Stay updated with my latest thoughts and ideas by registering for my [**newsletter**](https://yonatankarp.com/newsletter). Connect with me on [**LinkedIn**](https://www.linkedin.com/in/yonatankarp/) or [**Twitter**](https://twitter.com/yonatan_karp). Let's stay connected and keep the conversation going!

* * *

## Credits

- [Code Smell 25 - Pattern Abusers](https://maximilianocontieri.com/code-smell-25-pattern-abusers) by Maxi Contieri
What is Open Source Contribution?
Tags: opensource, contributorswanted, beginners, github
Published: 2023-03-11 04:54:59

Open source contribution is the act of participating in the development of open source software projects by contributing code, documentation, bug reports, feature requests, or other resources to the project. Open source software is software that is freely available and can be modified, distributed, and used by anyone.

Contributing to open source projects can help you improve your coding skills, learn new technologies, and build a network of connections in the tech industry. By contributing to open source projects, you can also help improve the quality and functionality of the software, as well as give back to the community.

There are many ways to contribute to open source projects, including:

Submitting bug reports and feature requests
Writing documentation or tutorials
Contributing code or patches
Participating in discussions and providing feedback
Helping to test software releases
Providing financial support to projects
Most open source projects have guidelines for contributing, including coding standards, testing requirements, and communication channels. To get started with open source contribution, you can find projects that interest you on websites such as GitHub, GitLab, or Bitbucket, and reach out to the project maintainers to ask how you can contribute.

My Github Profile : [https://github.com/minhaj-313](minhaj-313)
Here are the top 7 programming languages based on popularity and usage as of 2023:
Tags: programming, languages
Published: 2023-03-11 04:51:34

Java: Java is a general-purpose programming language that is used for developing complex applications, such as enterprise software, web applications, and Android apps.

Python: Python is a high-level, interpreted programming language that is easy to learn and widely used for data analysis, artificial intelligence, and web development.

JavaScript: JavaScript is a scripting language that is used for building dynamic user interfaces, web applications, and mobile apps.

C#: C# is a modern, object-oriented programming language developed by Microsoft that is used for developing Windows applications, games, and enterprise software.

C++: C++ is a general-purpose programming language that is used for developing high-performance applications, such as video games, system software, and operating systems.

PHP: PHP is a server-side scripting language that is used for developing web applications and dynamic websites.

Swift: Swift is a programming language developed by Apple for developing iOS, macOS, watchOS, and tvOS applications.
A Developer’s Guide to Avoiding the Pitfalls of Exposing the Domain Layer
Tags: programming, computerscience, codenewbie
Published: 2023-03-11 04:43:11

There are several reasons why developers may tend to develop domain and domain repositories exposing to the application layer

- Lack of understanding of the architecture: Developers who are not familiar with the principles of good software architecture may not fully understand the importance of separating the domain and application layers.

---


- Time constraints: Developers may be under pressure to deliver features quickly and may not take the time to properly separate the domain and application layers.

---

- Lack of experience: Developers who lack experience in building large, complex applications may not have the knowledge or skills to properly separate the domain and application layers.

---

- Lack of planning: Developers may not have taken the time to plan out the architecture of the application and may make decisions on the fly that lead to the domain and application layers being tightly coupled.

---



- Lack of consideration for long-term maintainability: Developers may not be thinking about the long-term maintenance and scalability of the application and may not see the benefits of keeping the domain and application layers separate.

---


- Complexity of the domain: Developers may find it difficult to separate the domain and application layers because the domain is complex and requires a lot of knowledge about the domain.

---


It’s important to note that exposing domain and domain repositories to app layer could cause technical debt in the long run. It’s better to avoid this kind of design and invest time to plan the architecture of the application in a way that separates the concerns and make the application more maintainable and scalable.

Thank you for reading ❤️.
Zerando HackerRank ( 12 )
Published: 2023-03-11 04:42:07

E no décimo segundo desafio desta serie que queima os miolos, vamos abordar um problema que envolve uma caça aos ratos.
Teremos o gato A, o gato B e o rato C.
O gato A vai receber um valor referente a sua posição assim como o gato B e o Rato C.
Então o problema consiste em qual gato vai pegar o rato primeiro.
No caso de empate o rato ganha.

Fez sentido? Nem um pouco, porem a vida é feita dessas coisas...

Primeira coisa que vamos fazer para facilitar nosso trabalho vai ser declarar as variáveis como nomes apropriados desta forma:

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

Depois disso faremos 3 condicionais.

A primeira é subtrair o valor do rato menos o gato A, juntamente ao subtração do valor do rato - o valor do gato B,
Se o valor da primeira subtração foi maior que o valor da segunda, a condicional retornara "Cat A".

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

A segunda é subtrair o valor do rato menos o gato B, juntamente ao subtração do valor do rato - o valor do gato A,
Se o valor da primeira subtração foi maior que o valor da segunda, a condicional retornara "Cat B".

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

E o terceiro são as mesmas subtrações, porem no caso dos dois valores serem iguais o retorno será "Mouse C".

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

Um detalhe importante é que é interessante usar a propriedade "Math.abs" para que os valores sejam absolutos, ou seja, valores negativos serão ajustados para positivos.

A função completa deve ficar assim:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxqcdmmputsjcaqul91z.png)
Django Takeoff! Course (FREE)
Tags: django, webdev, programming, python
Published: 2023-03-11 03:43:05

Find my entire Django Takeoff! course on my website/blog for FREE. 

[Django Takeoff! Course](https://www.devbalt.com/takeoff)

It's great for beginners who are trying to start building right away using Django. 

The course takes you from the fundamentals of how Django works to building a bike marketplace website and deploying it on Heroku with a custom domain.

- AWS S3 buckets is used to serve the images. 
- PostgreSQL for the database. 
- Heroku for the deployment .
+ a bunch of other technologies.

Happy programming!! 

[Youtube](https://www.youtube.com/channel/UChZR16e1XwZXy2yrk_8ymFg)
[Twitter](https://www.twitter.com/balt1794)
109. Leetcode Solution in JavaScript
Tags: javascript
Published: 2023-03-11 03:27:18

#solution:
```js
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {ListNode} head
 * @return {TreeNode}
 */
/**
 * @param {ListNode} head
 * @return {TreeNode}
 */
var sortedListToBST = function(head) {
    if (!head) return head;
    var slow = head;
    var fast = head;
    var prev = null;

    while (fast && fast.next) {
        fast = fast.next.next;
        prev = slow;
        slow = slow.next;
    }

    var node = new TreeNode(slow.val);
    // if prev is null, it means, slow and fast did not move, it means this half is done.
    // otherwise, prev is the end of the first half (left sub tree). And set prev.next = null.
    if (!prev) {
        head = null;
    } else {
        prev.next = null;
    }

    node.left = sortedListToBST(head);
    node.right = sortedListToBST(slow.next);

    return node;
};
```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
Turning objects into flexible arrays
Published: 2023-03-11 03:26:11

```javascript
// for-in loop
// const obj = { one: 1, two: 2 };

// for (const key in obj) {
//   console.log('value', obj[key]);
// }

// Object.keys(), Object.values(), Object.entries()
// const user = {
//   name: 'John',
//   age: 29  
// };

// console.log(Object.entries(user));

const users = {
  '2345234': {
    name: "John",
    age: 29
  },
  '8798129': {
    name: "Jane",
    age: 42
  },
  '1092384': {
    name: "Fred",
    age: 17 
  }
};

const usersOver20 = Object.entries(users).reduce((acc, [id, user]) => {
  if (user.age > 20) {
    acc.push({ ...user, id });
  }  
  return acc;
}, []);
console.log(usersOver20);

// const values = Object.keys(user).map(key => user[key]);
// console.log(values);
// console.log(Object.values(user));

// const monthlyExpenses = {
//   food: 400,
//   rent: 1700,
//   insurance: 550,
//   internet: 49,
//   phone: 95  
// };

// const monthlyTotal = Object.values(monthlyExpenses).reduce((acc, expense) => acc + expense, 0);
// console.log(monthlyTotal);
```
Default Parameters in PHP Functions
Tags: php, function, beginners, programming
Published: 2023-03-11 03:18:52

I hope you know what is a function and how to use a function. In short a function is a block of code which can take input and gives output but it is not necessary that a function will always take input and will always give output. It depends on the demand. 
Now we will learn about default parameter of a function. Suppose you want to design a function where some parameters will receive value from arguments. But if arguments are not provided the function will use some default values for those parameters. 

Here is an example: 

```php 
<?php
function donate($account, $amount=2.00){
    echo "$amount dollar has transfered to account: $account\n";
}

donate("2014323432", 50.00);

```
we are calling dontae function with two parameters. One is account number and amount of dollar. here 50.00 dollar has tranfered to 2014323432 account. But if you don't give amount, by default 2.00 dollar will be transfered to given account. 

**Note:** after the default parameter, there won't be any required parameters. By position all the required parameters will come first and rest of others may be default parameters.
Because without this format php cannot map the arguments with parameters.
Adverteren op Google
Published: 2023-03-11 03:09:35

Adverteren op Google betekent dat je betaalt voor het weergeven van advertenties op de zoekresultatenpagina's van Google of op websites die deel uitmaken van het Google Display-netwerk. Er zijn verschillende typen Google-advertenties, waaronder zoekadvertenties, displayadvertenties, videoadvertenties en shoppingadvertenties.

Om te adverteren op [Google](https://sparketing.eu/online-marketing/adverteren-op-google/) moet je een Google Ads-account maken en vervolgens campagnes opzetten. Je selecteert zoekwoorden en stelt biedingen in om te bepalen wanneer en waar je advertenties worden weergegeven. Je kunt ook targeting-opties selecteren, zoals geografische locaties en demografische kenmerken, om je advertenties te richten op de juiste doelgroep.

Het voordeel van adverteren op Google is dat je je kunt richten op mensen die op zoek zijn naar jouw producten of services en zo gerichte verkeer naar je website kunt genereren. Daarnaast kun je de resultaten van je campagnes bijhouden en analyseren om te zien hoe goed ze presteren en waar eventuele optimalisatiemogelijkheden liggen.
How Go Helped Save Healthcare.gov!
Tags: programming, go
Published: 2023-03-28 00:46:49

---
title: How Go Helped Save Healthcare.gov!
published: true
date: 2023-03-11 01:56:52 UTC
tags: programming,Go,Golang
canonical_url: https://www.ericsbinaryworld.com/2023/03/10/how-go-helped-save-healthcare-gov/
---

I recently used Mastodon to ask for recommendations for Go podcasts and one of the suggestions was [Go Time](https://changelog.com/gotime). One of the recent episodes in the feed was a rerun of an older episode about “[How Go helped saved HealthCare.Gov](https://changelog.com/gotime/262)“. This was extra interesting to me since I wrote my [Master’s Special Project on Healthcare.gov](https://www.ericsbinaryworld.com/wp-content/uploads/2014/05/Eric-Mesa-SYS800-Fall-2014-Final-Paper.pdf). (I haven’t read it in nearly a decade, so I don’t know if it’s cringe-worthy at this point). The episode had on one of the programmers who helped get things back on track for the site. It was incredibly informative about the problems that led to the site not being responsive enough and how they were able to help fix it without scrapping the entire site. No matter what side of the political spectrum you’re on or if you’re even an American, the episode is fascinating for understanding how things can go wrong even when everyone has the best intentions and how to fix a large, complex code base.

_header image from go.dev/blog post [about the macot](https://go.dev/blog/gopher)._
Selfhosted NodeJS ChatGPT Discord Bot
Tags: chatgpt, node
Published: 2023-03-11 01:43:12

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

We created a ChatGPT bot powered by NodeJS.

This bot integrates with both the [OpenAI](https://platform.openai.com/) and [Discord API](https://discord.com/developers/docs/intro) through a `config.json` file.

The bot requires users to have a payment account linked with OpenAI to record data usage. The data is affordable, with a power user costing about 10 cents a day and a regular user hardly a cent. Throttle management is available through the OpenAI API to help users monitor their usage.

Once connected to Discord, the bot can be assigned to a special channel where users can interact with it. Users can type in `/chat prompt` to create a private thread between themselves and ChatGPT or `/chat prompt --public` to open a public, collaborative thread. Public threads accept collaborative input from multiple parties, while private threads only allow the initiating user to participate.

The bot **remembers up to 50 interactions per thread**, providing the AI with a well-contextualized view of the conversation. Users can manually adjust the number of replies to remember in the codebase to control expenses.

GBTI Labs notes that while some powerful interpretations of a ChatGPT Discord bot exist, there is no official bot provided by OpenAI. However, users can still consider this bot model a starting point for other AI-powered language models.

## Repository

Please find our work at the following repo: 

[Self-hosted NodeJS ChatGPT Discord Bot](https://github.com/gbti-labs/nodejs-chatgpt-discord-bot)

## Support our work / Join the GBTI network!

[Become a supporter and join the GBTI Community](https://gbti.io/)
Using spread operators to get data from arrays
Published: 2023-03-11 01:32:23

```javascript
// In our restaurant, the chef has some favourite dishes in two different categories.
// The chef loves all dishes that start with "S", while the rest are regular dishes
// Use array destructoring to create arrays of the chefs favourite dishes of meat and
// fish, and to create arrays of the regular meat and fish dishes

const fishDishes = ['Salmon Rillettes', 'Grilled Tuna Provencal', 'Fish and Chips']
const meatDishes = ['Lasagna', 'Spaghetti', 'Satay Chicken Skewers']

// Modify these four variables first
let [chefsFishDishes, ...regularFishDishes] = fishDishes;

let [regularMeatDishes ,...chefsMeatDishes] = meatDishes;

// console.log(chefsFishDishes);
// console.log(regularFishDishes);
// console.log(regularMeatDishes);
// console.log(chefsMeatDishes);

// Finally, use the spread operator to create these two arrays as well
let chefsDishes = [...chefsMeatDishes, chefsFishDishes]
let regularDishes = [...regularFishDishes, regularMeatDishes];
console.log(chefsDishes);
console.log(regularDishes);
```

Of course you can use findByIndex but this is intended to explain spread operators
Bảng điện tử công nghiệp
Tags: bangdientucongnghiep, bodemsanpham, bangsanluong
Published: 2023-03-11 01:11:15

Bảng điện tử công nghiệp chuyên cung cấp các loại bộ đếm sản phẩm, bảng sản lượng chuyền may, đồng hồ điện tử cỡ lớn, đồng hồ nhiệt độ độ ẩm, bảng điện tử năng suất mang đến giải pháp tối ưu hoá sản xuất cho doanh nghiệp Địa chỉ: 86 Nguyễn Phúc Lai – Phường Ô chợ Dừa – Quận Đống Đa – TP Hà Nội. SĐT: 0903 418 369. Website: https://bangdientucongnghiep.com/	
![Uploading image](...)
Git Worktree: Enhance your Git Workflow
Tags: git, productivity, webdev, tutorial
Published: 2023-03-11 00:09:35

Have you ever been in the middle of coding a feature, and out of nowhere you get a notification that production is down?
If you're using Git you now have a few options: commit your work, stash your work, or discard your work.
All of these come with their problems depending on the situation.
If you commit half-baked code you may want to come back later and rebase to clean up your commit history.
Stashing can cause problems, because what if you need to stash additional code later before switching back to your original feature work?
Maybe I'll throw away my current changes if they're small, but otherwise no thanks.

I recently stumbled upon [Git worktree](https://git-scm.com/docs/git-worktree/2.39.0), and it has been an amazing boost in my productivity.

### What is Git Worktree?

Git worktree allows us to checkout multiple branches in a git repository. This lets us to switch between different branches in a Git repository without losing our non-committed work.
Git does this by creating new, separate directories called a "linked worktree" that is associated with a single "main worktree" (the directory created using `git clone` or `git init`).

To checkout a new worktree we use the `worktree add` command: `git worktree add <path> <branch_name>`.
Worktrees are created as new directories; we give the add command a path to where we want the new directory created and which git branch we want to checkout.

Just like `git checkout -b` we can create brand new branches by adding the `-b` argument (`git worktree add -b <branch_name> <path>`).

We can see all the worktrees we've created using the `git worktree list` command.

{% embed https://asciinema.org/a/4OQWztFetatQAkZblFz7cANUm %}

With our different linked worktrees created, we can safely modify code and switch between isolated instances of our codebase. The changes done in one worktree do not affect the other worktrees.

{% embed https://asciinema.org/a/mBldDWAWpgHtzmDl1BnsheDuj %}

What about if we want to commit and push our changes out to Github? No problem! Git worktree is a way to checkout multiple branches.
So once we're done making changes in our worktree we can `git add`, `git commit`, and `git push origin` just like if we are working on a different branch.
The changes would show up on Github under the `<branch_name>` we gave in `git worktree add <path> <branch_name>`.

Once we are done with any worktree we can call `git worktree remove <path_to_worktree>` to delete it.

### End

I keep all worktrees in a separate directory `~/.worktree`, outside of my general projects directory `~/projects`, to reduce clutter and keep "main worktrees" explicit from "linked worktrees".
I am constantly switching between branches and code, and Git worktree has been a huge help to my workflow!
AWS Cloud Quest: Analyzing Network Traffic Study Note
Tags: aws
Published: 2023-03-11 00:07:27

This is the DIY challenge of the Analyzing Network Traffic in AWS Cloud Quest.


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



### DIY Steps:
1. Add outbound rule similar to step 24-27