teleren/devto huggingface dataset:
Porque você não deveria usar funções de debounce o tempo todo
Tags: frontend, javascript, performance
Published: 2023-10-24 15:23:09

E porque essa técnica muito legal é gambiarra.

---

Hoje eu vi outro post ensinando a criar uma função de debounce pra diminuir a quantidade de requisições desnecessárias.

Se você não viu, tem [esse ótimo post do FreeCodeCamp](https://www.freecodecamp.org/portuguese/news/debounce-como-atrasar-a-execucao-de-uma-funcao-em-javascript-exemplo-com-js-es6/) ensinando.

O debounce é ~~uma gambiarra~~ um recurso super útil e que pode te ajudar bastante a controlar a quantidade de requisições feitas ao servidor, principalmente quando os recursos são limitados. Geralmente usado em campos de autocomplete, você espera até o usuário parar de digitar por determinado tempo (300 ou 500ms) pra fazer a requisição, assim você não faz uma requisição pra cada letra e diminui a quantidade de requests "desnecessários".

## Isso faz sentido?
Hoje podemos escalar aplicações como nunca em horários de pico, e poupar grana enquanto elas não estão sendo utilizadas. A obsessão por performance do lado do backend é frequente. Será que a API não consegue resolver isso sozinha?

A resposta é: **sim, deveria**. Estratégias de cache, bancos em memória, indexação, e um mundo de ferramentas criadas para fornecer uma resposta super rápida sem onerar o banco principal. APIs respondendo em 50ms enquanto a gente vai lá e mete um debounce de 300ms :clown_face:

## A experiência do usuário
Todo mundo, principalmente quem é heavy user, já passou por apps ou sistemas onde você precisa esperar um tiquinho depois de digitar pra ver os resultados. É pouco tempo, mas é irritante quando você compara com ferramentas como a busca da Amazon, Google Maps, ou outras do tipo. 

Se você já colocou o delay e a API demora um pouco a mais pra responder, soma os tempos e você vai ver o usuário triste.

>  "Aí, travou essa *****"
– Usuário triste

Depois, abre o seu inspector e faz uma pesquisa no Google Maps pra você ver quantas requisições ele faz.

## Ah, mas DDoS...
Se você confia no seu frontend pra te poupar de um DDoS, meu amigo... você tá em uma situação complicada. Acho que só outro post mesmo pra caber, mas me avisa aqui que eu faço.

## Então eu não devo usar debounce?
Calma... depois de virar dev sênior, você aprende que é pago pra dizer "depende" pra tudo. E mais uma vez aqui: DEPENDE.

Se você trabalha em um frontend que consome uma API nova, e o backend não consegue dar conta de muitas requests, remove o debounce e pede pra ele consertar esse treco aí. Manda o print do inspector do site da Amazon e avisa quantas pessoas usam diariamente.

Agora, se você trabalha em um sistema legado onde a API não dá conta da quantidade de requests, ou se o chefe não deixar o backend consertar o bug, ou se vc quiser salvar dinheiro pq a API do Google Places tá comendo seu orçamento, aí sim vc usa o debounce, mas não acostuma com ele. Debounce é gambiarra, não deixa te convencerem do contrário.
How to automatic deployment from GitHub to server via FTP (GitHub Actions)
Tags: ftp, github, server
Published: 2023-10-24 15:20:45

We are going to take a look at how we can automate deployment from GitHub to server via FTP. To do that we have to create some folder and file in project root where **.git** folder exist. Such as:

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

Now, we need to add below code in **server-deploy-via-ftp** file, which we created before.

```
name: CI-FTP

# Controls when the action will run.
on:
  # Triggers the workflow on push or pull request event but only for the main branch
  push:
    branches: [ main ]
  #  pull_request:
  #    branches: [ main ]

  # Allows to run this workflow manually from the Actions tab
  workflow_dispatch:

# A workflow run is made up of one or more job that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "FTP"
  deploy-via-ftp:
    runs-on: ubuntu-latest
    steps:
      # Checkouts repository under $GITHUB_WORKSPACE, so job can access it
      - uses: actions/checkout@v2

      - name: FTP Deploy
        uses: SamKirkland/FTP-Deploy-Action@4.3.2
        with:
          server: ${{ secrets.SERVER }}
          username: ${{ secrets.USERNAME }}
          password: ${{ secrets.PASSWORD }}

          # File will copy to under this path
          server-dir: ${{ secrets.SERVER_DIR }}
```

Then we need to create some secrets on GitHub. For creating GitHub secrets, go to repository **Settings**, then click on **Secrets** from sidebar. Secrets are:

```
SERVER: Your server address
USERNAME: Your ftp username
PASSWORD: Your ftp password
SERVER_DIR: Where GitHub project will be uploaded
```

Now push project on GitHub. And check status from **Actions** in repository.
How to automatic deployment from GitHub to server via SFTP (GitHub Actions)
Tags: sftp, github, server
Published: 2023-10-24 15:03:21

We are going to take a look at how we can automate deployment from GitHub to server via SFTP. To do that we have to create some folder and file in project root where **.git** folder exist. Such as:

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

Now, we need to add below code in **server-deploy-via-sftp** file, which we created before.

```
name: CI-SFTP

# Controls when the action will run.
on:
  # Triggers the workflow on push or pull request event but only for the main branch
  push:
    branches: [ main ]
  #  pull_request:
  #    branches: [ main ]

  # Allows to run this workflow manually from the Actions tab
  workflow_dispatch:

# A workflow run is made up of one or more job that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "SFTP"
  deploy-via-sftp:
    runs-on: ubuntu-latest
    steps:
      # Checkouts repository under $GITHUB_WORKSPACE, so job can access it
      - name: Checkout
        uses: actions/checkout@v3

      - name: SFTP Deploy
        uses: wlixcc/SFTP-Deploy-Action@v1.2.4
        with:
          server: ${{ secrets.SERVER }}
          port: 22 # default is 22
          username: ${{ secrets.USERNAME }}
          ssh_private_key: ${{ secrets.SSH_PRIVATE_KEY }}

          # Puts all file to under this path
          local_path: ./server/* # default is ./*
          # File will copy to under this path
          remote_path: ${{ secrets.REMOTE_PATH }}

          # Arg
          args: "-o ConnectTimeout=5"
```
Here we need **SSH** private key, which is basically a method of authenticating GitHub to make changes on deployment server. So for this we are gonna have to generate an SSH key pair and to do that we are gonna have to open up a terminal where need to access deployment server. Then, we need to enter below command:

```
ssh-keygen -t rsa
```
Now hit **Enter** to save the key. And keep empty **passphrase**.

We need to get public & private key. For that need to write below commands:

```
cd ~/.ssh
```

```
ls
```
Now, we can see two files, such as

- id_rsa -> private key 
- id_rsa.pub -> public key

And also we need to create some secrets on GitHub and a new file **authorized_keys** in **.ssh** folder in deployment server, where need to write **public key** (id_rsa.pub content) and for creating GitHub secrets, go to repository **Settings**, then click on **Secrets** from sidebar. Secrets are:

```
SERVER: Your server address
USERNAME: Your server username
REMOTE_PATH: Where GitHub project will be uploaded
SSH_PRIVATE_KEY: Recently created private key on deploment server (id_rsa)
```

Now push project on GitHub. And check status from **Actions** in repository.
शतरंज प्रतियोगिता में PMS 40 BN PAC की छात्रा आहना धीमान Aahna Dhiman ने प्राप्त किया प्रथम स्थान - Param Himalaya
Tags: paramhimalaya, aahnadhiman, chess, news
Published: 2023-10-24 14:59:42

शतरंज प्रतियोगिता में PMS 40 BN PAC की छात्रा आहना धीमान  [Aahna Dhiman](https://www.paramhimalaya.com/2023/10/Aahana-dhiman-PMS-40-bn-PAC-stood-first-chess-competition.html
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2m2q128r77q0dg13myvq.png)) ने प्राप्त किया प्रथम स्थान  - Param Himalaya
NPM package to validate CSV
Published: 2023-10-24 14:53:36

I would like to introduce you to a project called "validator-csv". Validator CSV is an easy-to-use tool for checking the integrity and quality of CSV files. If you deal with data in CSV format in your work or projects, this is a tool that can make all the difference.

## What is "CSV Validator"?

"Validator CSV" is a library that provides the ability to validate CSV files effectively. Whether you want to ensure your CSV files are well-formatted, meet header specifications, or meet your application's specific requirements, "Validator CSV" has you covered.

## How to install

Installation is simple and can be done through npm. Make sure you have Node.js installed on your system.

`npm i validator-csv`

## How to use

The project offers two ways to validate CSV files, either through the file path or directly from a buffer. Here are examples of both approaches:

CSV validation via file path:
const path = require("node:path");

const validator = require('validator-csv');
const Yup = require("yup");

const filePath = path.resolve(__dirname, "uploads", "clientes.csv");

const validationSchema = Yup.object().shape({
age: Yup.number().min(18, "Invalid age, customer must be over 18.").required("The age field is mandatory."),
});

validator.validateCSV({
filePath,
headers: ["name", "age", "gender"],
schema: validationSchema,
}).then((data) => {
console.log(data);
}).catch((error) => {
console.error("Error:", error);
});

CSV validation through a buffer:
const fs = require("node:fs");
const path = require("node:path");

const validator = require('validator-csv');
const Yup = require("yup");

const filePath = path.join(__dirname, "uploads", "clientes.csv");
const csvBuffer = fs.readFileSync(filePath);

const validationSchema = Yup.object().shape({
age: Yup.number().min(18, "Invalid age, customer must be over 18.").required("The age field is mandatory."),
});

validator
.validateCSVFromBuffer({
buffer: csvBuffer,
headers: ["name", "age", "gender"],
schema: validationSchema,
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error("Error:", error);
});

If you would like to obtain more information or explore the project in detail, I invite you to visit the github project!.📊🔍

[github](https://github.com/daviaquino87/validator-csv)
[NPM](https://www.npmjs.com/package/validator-csv)

thanks!
newbie question on limits
Tags: python
Published: 2023-10-24 14:41:13

Hi there, I've decided to dive headlong into python by writing a program I've been thinking about for years now; I'm trying to build a system that can import, manage and improve quality of my music collection, which holds over 400k songs.

the first snag i'm hitting is with a recurring filescanner; I wonder what a realistic upper limit is when it comes to the lists I'm using. Can I let it parse the entire filetree or should I build in a safety feature to offload to a database at intervals of say max 1k?
Day 75: Countdown timer
Tags: webdev, frontend, html, 100daysofcode
Published: 2023-10-24 14:40:17

# Challenge

Your task is to create an HTML and CSS code snippet that  shows launch countdown timer. 

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


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



### 📰 Details

For the necessary assets, design specification, please refer to the Github repository: [Github - Launch Countdown Timer](https://github.com/dhrn/launch-countdown)


**Note**: This challenge is sourced from Frontend Mentor.
Create a constraint in xcode
Tags: mobile, beginners, ios, swift
Published: 2023-10-24 14:34:01

**How to add constraints**
![image 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ev4728n8jzzt8hue8hkk.png)

![image 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qoc0gziqepj0gicsmxlv.png)

![image 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uytu337ca98qwawk16fo.png)

![image 4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/id7owep6sz16fj31dfox.png)

**How to remove constraints**
![image 4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5b2p2fjmcl88w2bqvgn2.png)

**Vertical spacing between elements**
![image 5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wdh2aj2yxxagzl014g96.png)

**Create a stack view among buttons**
![image 6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trwtapha2j3egfhnyj0j.png)
Back Button Navigation - Angular
Tags: angular, web, javascript, router
Published: 2023-10-24 14:33:49

I will go straight to the point, in a web app where I work the need emerged to standardize the behavior of such a simple button to navigate backwards. 
Not to navigate backwards in the hierarchy of routes, for example:
`Products => Product Detail => Edit Product`
but to navigate backwards in the navigation history that the user had done.

First we thought about the simple history.go(-1), but the problem is that we didn't want to exit the web app, suppose the user arrives at a particular page of my web app and clicks the back button, I would exit the web app; and we didn´t want that.

Searching the internet we realized that such a simple task was not, or at least without making the task too complex, so I'm going to share our solution, at least with Angular.
 _*I have removed all styles to simplify the example._

`back-button.component.ts` Our logic 👇
```
import { Location } from '@angular/common';
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'back-button',
  templateUrl: './back-button.component.html',
  standalone: true,
})
export class BackButtonComponent {
  constructor(private _location: Location, private _router: Router) {}

  goBack() {
    if (window.history.state.navigationId === 1) {
      this._router.navigate(['/home']);
    } else {
      this._location.back();
    }
  }
}

```
In the `goBack` function, we are checking if the `navigationId` property inside `window.history.state` is 1, which means that we are where the user first arrived in our web app, so instead of navigating outside our app we redirect user to the dashboard, otherwise just go back once.
**Important**: This `navigationId` is something that Angular pushes to the native state of the history and keeps incrementing it on location changes. We are using Angular 15.

`back-button.component.html` Our simple html 👇
```
<button (click)="goBack()">
  Back
</button>
```
To conclude, I think it is a simple solution using the help that Angular gives us to keep track in some way the count of navigations between routes in our application.
Data transfer between view controllers
Tags: beginners, ios, swift, mobile
Published: 2023-10-24 14:33:37


![main images](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g35zzob9zq0nfcyl08fd.png)

1.Use segue between button and thirdVC
- check button is connected to thirdVC
- this method is called automatically when we use segue to connect two view controllers

```swift
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        var result:String = ""
        guard let num = Int(numberTextField.text!) else {
            return
        }

        if num % 2 == 0 {
            result = "Even"
        } else {
            result = "Odd"
        }

        guard let vc = segue.destination as? thirdVC else {
            return
        }
        vc.result = result
    }
```

2.Use segue between whole secondVC and thirdVC 
- click square on secondVC - connect to thirdVC
- click segue and give identifier in the insepector area (navigateToThirdVC) under storyboard segue > identifier
- this line will initiate relationship between secondVC and thirdVC

```swift
performSegue(withIdentifier: "navigateToThirdVC", sender: nil)
```

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

3.Give unique identifier to thirdVC
- click thirdVC controller > identity inspector > Storyboard ID > resultVC
- get a reference to the result screen (thirdVC)
- this does not use segue at all! -> so don't need prepare() method

```swift
guard let resultScreen = storyboard?.instantiateViewController(withIdentifier: "resultVC") as? thirdVC else {
            print("can't find thirdVC")
            return
}
```

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

```swift
// pass the data to thirdVC
resultScreen.result = result

// Several options we can get to the thirdVC
        
// 1.navigate to result screen using parent contoller - navigationController
// this way, this page have back button!
self.navigationController?.pushViewController(resultScreen, animated: true)
        
// 2.we can also use modal presentation instead of navigationController
// this will pop up like a card! user can dismiss the card!
self.present(resultScreen, animated: true)
        
// 3.another option in modal presentation - card that user can't dismiss! (force)
resultScreen.modalPresentationStyle = .fullScreen
self.present(resultScreen, animated: true)
```
Create another view controller in Xcode
Tags: mobile, beginners, ios, swift
Published: 2023-10-24 14:31:41

1.+ > view controller > drag and drop it to main
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3x12i0nel1aoo6fl2hkt.png)

Now, we have empty view controller created
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a3iqxd8dz379srth7b4i.png)

2.we need a file for the new view controller
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/in6fzy68k8r7qniz13pa.png)

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

3.now, we have secondVC 

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

4.need to link the secondVC to the design
click blue square
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y2jwq3y7zsygzd187l6j.png)

go to identity inspector > change class name to secondVC in Customer Class
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7mg89im25mh1vmkxsulc.png)
How to add navigation controller in Xcode
Tags: mobile, beginners, ios, swift
Published: 2023-10-24 14:30:58

1.select the view controller you want navigation controller to embed
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3kyq4zncp9xkv3wbeml.png)

2.select editor > embed in > navigation controller
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vyu558mrsa7gqui03oon.png)

3.Now, root view controller of navigation controller is firstVC.
my application now will start at this navigation controller -> boot up firstVC. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ykco4uz597xxh1rynnp.png)

Note: navigation controller is just a container.
Change class name in Xcode
Tags: mobile, beginners, ios, swift
Published: 2023-10-24 14:30:33

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

1.create a new file
2.select Cocoa Touch Class
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9gkkpemfjh5oqmailwwr.png)
3.enter file name (firstVC)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqbfy5ckzsxqfsgbiheh.png)
4.go to main > click blue circle
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/21aw865vdv13b1aplibl.png)

5.change class name to file you just created (firstVC) in identity inspector > custom class > class
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6n852hbb3b3so7am88p.png)

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

Now, class name is changed from ViewController -> firstVC
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fpsur6df5anlc9eq9t2k.png)
Documentation as an Open-Source Practice
Tags: hacktoberfest23, opensource, 100daysofcode, depthshq
Published: 2023-10-24 13:03:47

The provided text offers valuable insights on how to make open source repositories more welcoming and conducive to growth through documentation and contributions. Here's a summary of the key points:

**1. Documentation Like Code:** Make documentation an integral part of your open-source practice. Document features before coding and add comments as you go, making your codebase more understandable to future contributors.

2. **Be Deliberate with Documentation:** Avoid over-documentation within code files. Code should be readable and follow a style guide, with comments providing context where needed. Don't make your code harder to read with excessive comments.

3. **Test and Maintain Docs:** Just like code, documentation needs testing and regular maintenance. Update comments and related documentation when modifying code to avoid a last-minute documentation push.

4. **Include Community-Focused Documentation:** Share your project with the world through open source repositories. Essential files to include are:
   - `README.md`: Describe the project and its goals.
   - `CONTRIBUTING.md`: Provide instructions for potential contributors.
   - Optionally, a `CODE_STYLE.md` for code best practices.
   - `CODE_OF_CONDUCT.md`: Set community values and expectations.
   - `CONTRIBUTORS.md` or `AUTHORS.md` to recognize contributors.

5. **Support End Users:** Include tutorial-style documentation to guide users on how to use the software. Write documentation as if you are a beginner, and consider user testing to ensure it's meaningful and user-friendly.

6. **Encourage Documentation Contributions:** Consider documentation updates as valuable contributions. Encourage diverse voices to contribute to your documentation. Acknowledge and welcome code and documentation contributions equally to build a community around your project.

7. **Make Documentation Inclusive:** Foster inclusivity and accessibility in documentation:
   - Use welcoming and unbiased language.
   - Provide natural language translations.
   - Consider the reading level of your audience.
   - Explore alternative formats, like audio and visual components.
   - Optimize for screen readers.
   - Ensure A11Y compliance for web-based tutorials.

8. **Connect with the Community:** Seek resources and opportunities to connect with others working on open source and documentation. The Write the Docs community is recommended for comprehensive resources.

Incorporating these practices can help open source projects attract a wider audience, foster a sense of community, and provide valuable resources for both developers and end users.