teleren/devto huggingface dataset:
Building Training Plan builder: Dealing w/ complex forms in Remix
Tags: devjournal, react, todayilearned, showdev
Published: 2022-08-07 18:09:00

Hello! Continuing this mini-series I'd like to share with you how I dealt with complex forms in Remix. You see, I'm creating this training plan builder, that currently looks like this

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

The Remix expects you to process data, sent to the backend, via `actions`. It's pretty cool when you're dealing with simple forms, but here I have these columns and each column has multiple exercises, so it'd be great if I could group the data somehow. 

The first idea was to deal with it as they have it in [docs](https://remix.run/docs/en/v1/tutorials/blog#actions), so something like this 
```
export const action = async ({ request }) => {
  const formData = await request.formData();

  const title = formData.get("title");
  const slug = formData.get("slug");
  const markdown = formData.get("markdown");
  ...
}
```

This way I would somehow call `Object.entries` on formData while giving the input names like `col-1-ex-1`. You can imagine how tedious that was/would be. So, I searched for a solution and I found a pretty clever one with the help of the `qs` (querystring) package. 

The package ensures I can give each of the exercise inputs names like

- phases[${idx}][${exercise.id}][title]
- phases[${idx}][${exercise.id}][sets]
- phases[${idx}][${exercise.id}][reps]

which, after parsing the request with this snippet

```
export const action: ActionFunction = async ({ request }) => {
  const text = await request.text();
  const parsed = qs.parse(text) as YourCustomType

  ...
}
```

gives the following structure

```
phases: [
  {
     exerciseId: { 
        sets: number,
        reps: number,
        title: string,
     },
     exerciseId2: { 
        sets: number,
        reps: number,
        title: string,
     }
  },
  {
     exerciseId3: { 
        sets: number,
        reps: number,
        title: string,
     }
  },
  {
     exerciseId4: { 
        sets: number,
        reps: number,
        title: string,
     },
     exerciseId5: { 
        sets: number,
        reps: number,
        title: string,
     }
  },
] // 3 objects represent 3 columns (phases) in the app
```

This structure is much easier to work with. And the best thing is that I got this structure using only two lines of code 😅 

Thanks for reading and hope this helps someone! Take care 😉

Source code -> [Strongion](https://github.com/Attanox/strongion)

Original thread -> [github discussion](https://github.com/remix-run/remix/discussions/1541)
The Odin Project Update: Part I
Tags: devjournal, programming, beginners, javascript
Published: 2022-08-07 18:04:05

## I've finally completed the Foundations curriculum.
 My experience completing the curriculum has been really good. It took me about 8 weeks since I wasn't exactly learning from scratch. I was already familiar with HTML, CSS and using the Document Object Model.

I just wished I had known about this course sooner. I actually like the way TOP forces you to learn and think like a real programmer. Of all the Udemy courses I've taken along with FreeCodeCamp, the projects I've completed have been really challenging but in a good way. I learned more about how to build projects using JavaScript. And it also helped me learn how to problem solve. 

Although I still have a long way to go until I feel more confident using JavaScript, I would say this course has helped me a ton. Yeah, it's a lot of reading involved, but usually I skim through it if it's something I already know. But overall, I usually take my time and process things slowly to make sure I understand everything. The most difficult portion of the course begins when it's time to use REAL JavaScript code to build the project. And by REAL, I mean more than 10 lines of JavaScript code. 

Taking this course has pushed me out of my comfort zone and forced to to think and code like a real programmer. Now, I'm even more excited to see what the Full Stack JavaScript curriculum will have in store. I'm pretty sure the projects will be even more challenging but hey, as long as I'm learning and developing better problem solving skills, I'm all for it!

## Here are the projects I've built so far:

- [The landing Project](https://taepal467.github.io/landingPage/)
- [Rock Paper Scissors](https://taepal467.github.io/rock_paper_scissors/)
- [Etch-A-Sketch](https://taepal467.github.io/Etch_A_Sketch/)
- [Calculator](https://taepal467.github.io/calculator/) (_This one I found the hardest to do_)
Java Efetivo Essencial - Criação de Objetos
Tags: java, programming, javaefetivo, performance
Published: 2022-08-07 18:04:00

## Evite a criação de objetos desnecessários

_Esta é uma série baseada no entendimento de tópicos relacionados ao livro com foco no resumo._

**Iniciando os trabalhos...**

O livro cita a importância de reutilização de objetos, especialmente quando um novo objeto tem a mesma função.
Além disso ele ressalta a importância da imutabilidade de objetos, pois isso facilita mais ainda a reutilização.
E para tomar como exemplo ele usa a classe String, que além de ser imutável é um ótimo exemplo de reutilização do nosso dia a dia.

**String**

```java
//exemplo A
// Neste exemplo o Java irá verificar se já existe uma instância na memória com a mesma sequência de caracteres
String nomeA = "Paula";

//exemplo B
//Neste exemplo será criada uma nova instância em memória apesar de já termos uma instância com a mesma sequência de caracteres
String nomeB = new String("Paula");

```

**Como?**

 Uma das formas de evitarmos a criação desnecessária de objetos seria através do uso de métodos static factory, no lugar de construtores em classes imutáveis.
Apesar de podermos fazer isso em classes mutáveis precisamos considerar que elas podem sofrer alterações ao longo de sua utilização então poderia perder o propósito de ser reutilizada.
Se o objeto requer muito trabalho para ser criado vale considerarmos armazená-lo em cache para facilitar seu uso.

**Mais situações**

 O livro cita exemplos internos do Java que utilizam essa premissa e outras partes que foram recriados e utilizaram para melhorar sua performance.
Mas diria que outro ponto que é citado que acamos utilizando muito no dia a dia é o uso de **autoboxing** .
**Autoboxing e Autounboxing é o uso de primitivos com tipos primitivos empacotados.**
Vamos ver um exemplo a seguir.

**Autoboxing**

```java
// O código abaixo terá um problema de desempenho pois toda vez que a variável i que é primitiva for somada a variável soma que é um tipo primitivo empacotado, ou seja uma classe,é criada uma nova instância. 

Integer total = 1;
for (int i = 0; i < 100; i++) {
    total += i;
}

// O livro deixa claro que devemos sempre preferir o uso de primitivos e evitarmos o uso de autoboxing involuntário no nosso código.

```

**Casos para evitar**

 O uso dessa abordagem em alguns cenários deve ser avaliada, isso se aplica apenas em algumas situações, em especial construção de objetos complexos, como por exemplo em casos em pool de objetos. O livro até cita como exemplo o pool de conexão com banco de dados, que no caso o custo de se obter esse objeto vale a sua reutilização, mas nem sempre compensa reutilizarmos, devemos analisar situação a situação.

**Analise quando usar**

 Outro ponto abordado é que esse item do livro vai de encontro com outro item que incentiva cópias defensivas, e ele explica que nesse cenário é importante ter em mente que cópias defensivas evitam problemas através de bugs e falhas de segurança, enquanto a reutilização de instâncias tem como objetivo estilo e desempenho.O que faria o item de cópias defensivas ser mais importante do que evitar a criação de objetos.
How to create your first npm package? 🧰
Published: 2022-08-07 17:37:00

## What is NPM
NPM stands for **N**ode **P**ackage **M**anager and is the default JavaScript package manager powered by *Node.js*. The npm manager has two parts:

- **CLI** (*Command Line Interface*) — a tool for publishing and downloading packages,
- [online repositories](https://www.npmjs.com) containing over 2 million JavaScript packages.

## Don't have an account?
Navigate to [npmjs.com](https://www.npmjs.com) and click sign up.

## 1. Create an npm project
- Create a folder named `arraySort`
```
mkdir arraySort
```

## 2. Initialize project as npm package
### a) Using npm init -y or -yes
- This process will automatically generate a `package.json` file with default options.

```
npm init -y
```

![CLI process](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4o2bx5btm5ju7ezsfylg.png)
 

### b) Using npm init
- In this process, you will be asked a number of questions such as the name of the author, the description, and the license, etc.

```
npm init
```

![CLI process](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rmv6ikhlo3mhkzzujxiz.png)
 

## 3. Create a file named `index.js` with this content:

```
function arraySort(array, compareFunction) {
    const cloned = array.slice();
    if (compareFunction) {
        return cloned.sort(compareFunction);
    }

    return cloned.sort();
}

module.exports = arraySort;
```

## 4. Create a README.md (optional)
- You should provide a brief description of the repository and its functions.

## 5. Login into NPM
```
npm login
```

## 6. Publish the package
```
npm publish
```

## You Did It!
Congratulations, you have published your first NPM package!
Disable Rails SQL logging in console
Published: 2022-08-07 17:36:38

To turn it off:

old_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil
To turn it back on:

ActiveRecord::Base.logger = old_logger
[Solution 2](https://sqlerrors.com/):

Here's a variation I consider somewhat cleaner, that still allows potential other logging from AR. In config/environments/development.rb :

config.after_initialize do
  ActiveRecord::Base.logger = Rails.logger.clone
  ActiveRecord::Base.logger.level = Logger::INFO
end
Solution 3:

This might not be a suitable solution for the console, but Rails has a method for this problem: Logger#silence

ActiveRecord::Base.logger.silence do
  # the stuff you want to be silenced
end
How I Plan to use coding as a tool to save my future
Tags: coding, webdev, javascript, programming
Published: 2022-08-07 17:31:13

Now, we've all seen this meme that says "Will Code For Food", and thought it's just that, a joke. Little did you know that people literally do that in poor countries, and today I will talk about how I aim to code for food in order to survive.


According to Google, a frontend dev in the US earns about $105,344 per year, so about 8700$ per month pretaxed. wow that's good you'd say but here in Lebanon, it's over 2.9 million LBP per month. Jesus! you'd become a billionaire so essily! Now hold on a minute, at today's exchange rate, that's a bloody 96.6$ per month working 8 hours per day.


Horrible? I know. So why the hell would I spend years of my life learning to code you ask? Just like fresh college graduates are happy to settle with 120$ salary per month. Speaking of college, I had the choice of paying 5000$ per year (imagine if you earn 100$/m, that's 5 years of work) for a private University or public one where they  shutdown for 3+ month every now and then because of poverty. 


Now imagine your self in my shoes for a moment, you go to the gym to achieve your dream body, just to find out each time you buy meat or chicken it'll cost you 10% of your monthly salary. You get unmotivated and decide to watch a movie, hold on a second, you're in Lebanon, Haven't seen the government's electricity in 4 month. One might lose hope and complain but when does that ever work? **It was a get up or give up moment**, I decided to look for solutions.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/896r5e9o5i6jr2otidmk.jpg)


Here I am, Working day and night on personal projects I know will get me where I want to be, Learning to code was the best decision I took as a 17 year old, and im certain it'll save me from starving like many in my country are. 


Thank you for ready and if you are interested in any topic I wrote about leave a comment and let me know.

Here is my portfolio website for those who are interested. 
[Portfolio](elvito.netlify.app)
Cloud-Native Application Protection Platforms
Tags: kubernetes, cloudnative, security, cnapp
Published: 2022-08-07 16:56:06

With more & more enterprises adopting micro services based architecture and Kubernetes based orchestration toolings, as part of their cloud native movement, the application security has become far more critical than ever!

In this episode, I will be taking you through one of the most sensible way for enterprises to embrace this indispensable requirement of cloud native application security.

The episode is right below here. Hope you all like it!

{% youtube SeIRUiVUCG0 %}
PHP: Getters and Setters
Tags: php, java, algorithms, tutorial
Published: 2022-08-07 16:42:10

In this guide, we are going to show you how to create “Getters” and “Setters” using PHP.

“Getters” and “Setters” are class functions that allow you to control access to an object’s properties.

Sometimes, people will refer to them as “mutator methods”.

To sum it up:

A “getter” allows you to retrieve or get a given property.

A “setter” allows you to set the value of a given property.

## [read more](https://professional-writer0.blogspot.com/2022/08/getter-and-setter-in-php.html)
Label you Emails with Google App script
Tags: googlecloud, javascript, tutorial, productivity
Published: 2022-08-07 16:38:00

## when you have 5000 emails in your inbox
it happens some times when your really busy and you've subside to many news letters or web sites that provide daily notifications _(e.g LinkedIn...)_ 
To manage the messages can be little time consuming special if you open your inbox in the early morning ,trust me 🙃️

So one day I've checked my email to find that I've **5000 emails** in my inbox from resources as I said previously _(LinkedIn,Google Scholar..)_ and others. 

In order to manage those as a first **non consuming time** is I'v e used **App script**,

![github star gif image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/awy55v62s7apwz1k77wl.gif)

that was useful for me and others so I decide to **publish it**, in order to publish more usable script give it a **[star](https://gist.github.com/Abdeladim101Basraoui/8fba66bdf214942d3195a155451d910d/stargazers)**



`here is the code`

{% embed https://gist.github.com/Abdeladim101Basraoui/8fba66bdf214942d3195a155451d910d.js %}
Resetting the Blog
Published: 2023-04-29 21:26:38

---
title: Resetting the Blog
published: true
date: 2022-08-07 16:33:42 UTC
tags: 
canonical_url: https://mikestaszel.com/2022/08/07/resetting-the-blog.html
---

I’m giving myself a new personal challenge - to write at least one blog post per week, for the rest of 2022.

These posts might be poor quality, but they’ll be better than not posting at all.

The motivation behind the challenge is to write more.

I don’t have any topics or posts ready to go or pre-written. I’ll have to think of something. I’m not sure if this posts counts as one of the first weekly posts.

Since I’m a software engineer, resetting the blog also means that I had to revamp the underlying technology. I switched from Medium to Hugo, but will probably continue to “cross-post” content in both places.

See you in a week (or earlier)!
9 GIT Tips For Beginners
Tags: git, github, webdev, programming
Published: 2022-08-07 16:26:00

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9rd1skfe9xbse2ftctmy.png)
Check out my 9 tips for you to learn GIT:

1. Do you use "git checkout my-branch" to switch to a branch? Maybe it is time to start using "git switch my-branch". It is the same command, but the name is straight forward.

2. Do you know what dash means in "git checkout -"? It is an alias for "@{-1}". It represents the name of the previous current branch. That is why "git checkout -" checks out the previous branch. Magic!

3. Did you know what "--" (two dashes) mean in "git checkout" command? They make sure that when you provide a file name, it is not interpreted as a branch etc. For example in "git checkout -- file.txt" command that discards changes to a file (restores last version)

4. "git checkout" is the most important GIT command. It has many features. It is used to switch between branches, create a new one, or rollback changes to a file!

5. A branch is like a copy of your files, you can work separately on. The work done on a new branch does not affect the previous one.

6. Saving changes from a working directory to the local repository happens in two steps:

💬 Staging - Deciding what you want to save
💬 Committing - Is like hitting the "save" button

Point 7. Have you ever cried over a deleted file? GIT offers the command "git rm -r my-file". It will only work if you have saved your changes!

Point 8. GIT actions vocabulary:

☀️ Working directory - your current copy of files
☀️ Staging - changes from working directory you choose to save to the local branch
☀️ Committing - saving staged changes to the local branch
☀️ Pushing - updating remote branch with local branch changes

Point 9. A merge is a process of synchronizing different "copies" of your project. If you changed the same line of code in two branches, GIT will ask you what version is the proper one. This process is called a conflict resolution.

Thank you for reading. If you want more upvote the article and follow me.

Also, check out Summon The JSON: GIT deck that has 65 cards to learn GIT and is also a game: [GIT Flashcards](https://summonthejson.com/products/git-flashcards). It is free to click the link!
Context
Tags: go
Published: 2022-08-07 16:17:00

Context allow you to send cancellation signal to asynchronous process/ go-routine.
[context](https://go.dev/blog/context)

Methods provided by context interface:-

**Value(key)** This method returns the value associated with the specified key.

**Done() **This method returns a channel that can be used to receive a cancelation notification.

**Deadline()** This method returns the Time that represents the deadline for the request and a bool value that will be false if no deadline has been specified.

**Err()** This method returns an error that indicates why the Done channel received a signal. The context package defines two variables that can be used to compare the error: Canceled indicates that the request was canceled, and DeadlineExeeded indicates that the deadline passed.

Functions https://pkg.go.dev/context#pkg-functions

- Background()
- WithCancel(ctx)
- WithDeadline(ctx,time)
- WithTimeout(ctx,duration)
- WithValue(ctx, key,val)


```
package main

import (
	"sync"
	"time"
	"fmt"
	"context"
)

func processRequest(ctx context.Context, wg *sync.WaitGroup, count int) {
	total := 0
	for i := 0; i < count; i++ {
		select {
		case <-ctx.Done():
			fmt.Println("Stopping processing - request cancelled")
			goto end
		default:
			fmt.Printf("Processing request: %v \n", total)
			total++
			time.Sleep(time.Millisecond * 250)
		}
	}
	fmt.Println("%v Request processed...", total)
end:
	wg.Done()
}
func main() {
	waitGroup := sync.WaitGroup{}
	waitGroup.Add(1)
	fmt.Println("Request dispatched...")
	ctx, cancel := context.WithCancel(context.Background())

	go processRequest(ctx, &waitGroup, 10)
	time.Sleep(time.Second)
	fmt.Println("Canceling req")
        cancel()
	waitGroup.Wait()
	
}

---

% go run contxt.go
Request dispatched...
Processing request: 0 
Processing request: 1 
Processing request: 2 
Processing request: 3 
Canceling request
Stopping processing - request cancelled
```
Generating GitHub Personal Access Token (GPAT)
Tags: github, tutorial, webdev, git
Published: 2022-08-07 16:11:00


![header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/740ze828of2i0pr68byv.png)

GitHub Personal Access Tokens (GPAT) are at times required instead of passwords when working with `Git`. It should be kept secret from others as they might get access to your repositories if they have the token. You might have encountered the need for GPAT when making a push to your GitHub repo or when creating CodeBuilds in AWS or needed for other reason.

This is simple and let's dive right in to generate our GPAT in less that a minute.



#### Login to your account and go to _Settings_


![settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/125ef8jdwp10chykbgl7.png)

#### Scroll down and click on _Developer Settings_.

![devSettings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qr4afoj55atpifco9efw.png)

#### Click on _Personal Access Token_

![pat](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ulonl0xt9jb6xmy2ipm7.png)

#### Click on _Generate new token_


![generate](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dwiv0d9oh2d5lxs6s3n8.png)

#### Type any name you prefer for the token


![name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mynbcqykay77y13lngbx.png) 

#### Select the expiry duration for the token

> This defines how long the token will be valid


![duration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kr73ao80jkwzy4fu3xvw.png)

#### Select the scopes for the token

> Scopes generally means, the permissions that the access token should have. Select them carefully, you might mistakenly delete all or loose access to your repositories.


![scope](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/17dt7y4zkfiqvuzxvca0.png)

#### Finally click on _Generate token_

![generated](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aysfp3ixdffetj8ay0w9.png)

## Token Preview

> Your access token also serves as password and you don't wanna loose it to anyone. 

![preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qu2i2l3ymj3mqa087cp5.png)
Stopwatch in React
Tags: javascript, react, css
Published: 2022-08-07 16:05:00

>**The Website:** [Link](https://mazhugasergei.github.io/stopwatch/)

I made a stopwatch in React.
The source code is located down below.

####❔How it works
> We have variables: `time` which we can see on the display, `startTime` (the time when we click play button), `stopTime` = 0 (the time when we click pause/stop button), `elapsedTime` (the time between start and pause/stop clicks).
**1. If you click start and it's 9h00m00s00ms right now**
`startTime` = 9h00m00s00ms. Now every millisecond `elapsedTime` = `Date.now()` - `startTime` and `time` = `stopTime` + `elapsedTime` which is the same as `elapsedTime` until the first stop.
**2. If you click pause button and it's 9h1m20s10ms now**
`stopTime` = `time` (1m20s10ms). If we click again, we'll return to the first step but it'll start count not from 0s but from 1m20s10ms.
**3. If you click reset**
All variables are reset and stopwatch stops.
**4. If you click lap button**
Current time is recorded

#The Source Code
> **GitHub:** [Link](https://github.com/mazhugasergei/stopwatch)
ReactJS vs SolidJS
Tags: react, solidjs, discuss
Published: 2022-08-07 15:52:00


I have had experience with [ReactJS](https://github.com/facebook/react) for a while, and recently, I found a new interesting framework which is [SolidJS](https://www.solidjs.com/). Its community is still very small (~21k stars now on [Github](https://github.com/solidjs/solid)), so I'm not sure it's mature enough for enterprise products.

Right now I'm standing for ReactJS because of the huge community support but I believe SolidJS will have a bright future too.

I raised this post to get your opinions about SolidJS vs ReactJS.

A few questions in my mind

- SolidJS is good enough for real web development?
- Which one is faster in terms of web performance?
- If you choose SolidJS, why?
- Any strong points from SolidJS that can replace ReactJS in the future?

I really appreciate your precious ideas and welcome all open discussions.

Happy coding!