teleren/devto huggingface dataset:
Utilizando useContext no React
Tags: react, hooks, usecontext
Published: 2021-09-05 16:22:22

Mais um padrão essencial a ser empregado em projetos React, especialmente se você tem propriedades comuns que deseja reutilizar em seus componentes, e acaba escrevendo muitos props duplicados, é usar o React Context.

Por exemplo, se queremos compartilhar dados do usuário entre vários componentes, em vez de utilizar vários props repetidos (props drilling), poderíamos usar o recurso de contexto que está embutido na biblioteca React.

Primeiramente, temos que criar um contexto com React.createContext(). No caso abaixo a referência desse contexto é o UserContext:

``` 
const UserContext = React.createContext();
```

Depois deve-se envolver o App inteiro em um provider (Para esse exemplo foi envolvido o App inteiro, mas se for o caso de apenas um componente consumir o recurso pode ser envolvido apenas o componente):

``` 
    const user = {name: 'Gustavo'} 

    <UserContext.Provider value={user}>
        <App />          
    </UserContext.Provider>
```

No código acima o recurso compartilhado é um objeto user. Para compartilhar um recurso basta que seja atribuído ao atributo _value_.

Em seguida, podemos consumir esse contexto em nossos componentes individuais utilizando o hook `useContext`:

```
  const user = useContext(UserContext);
  return <div>Olá, {user.name} </div>;
 );
```

Concluindo, essa é uma forma de tornar o seu código mais limpo evitando a necessidade de utilizar várias e várias props.

Referências:
https://pt-br.reactjs.org/docs/hooks-reference.html#usecontext
HackerOne CTF - H1 Thermostat (Android)
Tags: cybersecurity, android, ctf, hackerone
Published: 2021-09-05 16:00:23

## :tada: Hello World

As my first article, I would like to make a write-up about H1 Thermostat, which is an Android CTF that can be found on a cybersecurity learning platform called Hacker101. It is worth to mention that Hacker101 is powered by HackerOne.

## :arrow_down: Download The App

Presumably you will see something like the image below, while accessing the CTF for the first time:

![Text telling you to refresh the page in a few seconds](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1i5frz0n3pvtk7qnoz3d.png)

If you are facing this message, all you have to do is press F5 after a few seconds of waiting, just like the page says. After refreshing the page, you will probably see a link to download your .apk file:

![Page containing a link to download the app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gmnbgld3n6jg50v58hmt.png)

Just download it :D<br><br>

## :wrench: Decompiling The App

In order to do that, I am going to be using Apktool. If you don't have it installed, just take a look at this guide, which works for Windows, Linux and MacOS: [Apktool - How to Install](https://ibotpeaches.github.io/Apktool/install/).

Once you have Apktool installed, basically, all you have got to do is go to the directory where you can find your .apk file, and execute the command below:

```javascript
apktool d thermostat.apk
```

Right below, we see the most common response that Apktool gives to this command:

![Terminal screen containing the apktool input and its default output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ozfz3hvbc044q7mcuq7e.png)<br><br>

## :checkered_flag: Getting All The Flags

At this moment, I feel like I should tell you that no knowledge about android developing is needed to catch the flags. Actually, you just have to go to the thermostat directory generated by Apktool and grep your flags, just like this:

```javascript
cd thermostat
grep -rnw ./ -e "FLAG"
```

Right below, you can see the results :)

![Terminal screen containing the grep results, including the flags](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kumu5mjmku0kh6rlcahf.png)

Alternatively, considering you don't want to use grep, you can also open any IDE or text editor and search for any "FLAG" register inside the directory. In this example, I also did the searching process by using Visual Studio Code:

![Visual Studio Code screen, containing the search result, including the flags](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgd0xrhi0o8w60mmmxbz.png)<br><br>

### :warning: P.S.

Notice that the file which contains the flags has this extension called smali. What does that mean? Well, I will be trying to explain a little bit about it in the next article :smile:
2021 week 35, CSS stacking and HTML parsing. Plus letter casing.
Tags: css, html, regex
Published: 2021-09-05 15:59:35

Stepping into September, 30% time left in 2021 and it's been a little difficult to find a common theme from these items I've just revisited or learned weekly, please bear with me. Three items this week, first two are about CSS stacking context and parsing HTML with regex respectively while the last one will compare sentence case to title case.

- **CSS**: stacking context is like an imaginary z-axis for HTML elements. `z-index` can be used to control the stacking order within the same parent stacking context and `isolation: isolate;` can be used to create new stacking context.

- **HTML**: best not to parse HTML with regex else you might risk summoning Cthulhu. Jokes aside, it's generally regarded as a bad practice although as most things, there might be suitable specific use cases. There are a couple of reasons behind this (e.g. HTML validity, nesting) but to put it simply, HTML is too complex for regex, use a library designed for that instead.

- **Letter casing**: Sentence case is generally regarded as more friendly, allow proper nouns to stand out while title case is perceived as more serious and more prominent. Regardless of preference between the two, being consistent will help readability.

This is my 8th weekly post, thank you for reading and do let me know if you have any feedback by leaving a comment.

### Related Links

- *[The stacking context](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context)* by MDN contributors.
- *[Parsing HTML the Cthulhu Way](https://blog.codinghorror.com/parsing-html-the-cthulhu-way/)* by Jeff Atwood.
- *[Making a case for letter case](https://medium.com/@jsaito/making-a-case-for-letter-case-19d09f653c98)* by John Saito.
Debug con Microsoft Edge para Javascript 🐞
Tags: javascript, debug, webdev, spanish
Published: 2021-09-05 15:59:27

Buenas buenas Devs!
Este post será super breve, así que ire al grano.
Posiblemente el título del post de entrada le quiete vistas, que clase de dev usa Edge? Creo que nadie en su sano jucio, pero bueno, Edge esta basado en **Chromium** es mismo motor que usa Google Chrome.
Ahora bien, VSCode es el rey de los editores de código, y de que empresa es? Aja, Microsoft. Entonces si lo pensamos desde ese angulo tiene sentido usar el Navagador de Microsoft + el editor de Microsoft verdad? 

Navegando por youtube ayer me encontre con un video donde otro dev realiza una configuración muy interesante para debuggear sus apps de javascript y me parecio genial. Acabo de probar su tutorial con un proyecto de react 17 y todo funciona fantástico con una config super sencilla, basta instalar una extensión y tienes casi todo para codear.

No quisiera explicarte el video por que seria redundar, mejor te lo dejo y pruebalo tu mismo:

{% youtube vHZPeohPHqo %}

> *Es en ingles pero se comprende muy bien, puedes usar los subs automáticos si deaseas.*

Buen domingo a todos!
Up Stream Website
Tags: php, mvc, website
Published: 2021-09-05 15:33:18

I created a stream website with simple PHP and MVC architecture.
In this project I used raw PHP without any external libraries.
Just using composer, php, sql, and bootstrap4.

It would be a pleasure for me if you check my project and give me your opinion about it. 
Also if you liked it please give it a star :)

https://github.com/amirhnajafiz/Up-Stream-Website
Upgrading the CSS only Multi-line Typewriter effect
Tags: css, html, webdev, beginners
Published: 2021-09-05 15:31:31

In this post, I will enhance [The Multi-line Typewriter](https://dev.to/afif/a-multi-line-css-only-typewriter-effect-3op3) to create a more fancy variation of the "writer effect" using only CSS.

<sub>**PS**: click the "rerun" button at the bottom right of each embedded Pen to run the animation again.</sub>

----

### The Filling

Let's update the color of an existing text letter by letter. 

{% codepen https://codepen.io/t_afif/pen/VwWKMeQ %}

### The Sliding

A sliding cursor to reveal the text, why not!

{% codepen https://codepen.io/t_afif/pen/bGRwYrg %}

### The One Shot

A letter-by-letter animation you said? Nah! let's show everything at once!

{% codepen https://codepen.io/t_afif/pen/RwgGjVw %}

### The Random

Not that random but it looks like

{% codepen https://codepen.io/t_afif/pen/XWgjyjE %}

### The Fragmentation

A last one from the future where I will consider the [Fragmentation effect I built with the CSS Paint API](https://dev.to/this-is-learning/exploring-the-css-paint-api-image-fragmentation-effect-3ekl)

Only Chrome and Edge support this for now. It should work with a multi-line text but Chrome is a bit buggy with `mask` when it comes to multi-line.

Get back to this in 2 years to have full support everywhere with 0 bugs.

{% codepen https://codepen.io/t_afif/pen/MWojOQG %}


---


### That's it!

Now you have plenty of CSS-only typewriter effects. Enjoy 👍

![The End](https://media.giphy.com/media/VHrFbmOtBwysbsYnka/giphy.gif?cid=ecf05e47y9xawp3rscaqcnyycar4v8ngdvb8vkm8wvgs864p&rid=giphy.gif&ct=g)
React, Jest, and Testing Library - Quick Overview
Published: 2021-09-05 15:22:45

This is a quick overview of creating tests using React, Testing Library, and Jest. Below you will find all the code writing for this project.

### Styles in `App.css`
```css
.App {
  margin: 20px;
  font-weight: bold;
}
```


### App Component in `App.js`
```jsx
import './App.css';
import { useState } from 'react';

export const multiplyByTwo = (num) => {
  return num * 2;
};

export default function App() {
  const [value, setValue] = useState(null);
  const total = multiplyByTwo(value);
  const resultsColor = isNaN(total) ? 'red' : 'darkgreen';

  return (
    <div className="App">
      <label htmlFor="value">Enter value</label>
      <input onChange={(e) => setValue(e.target.value)} id="value" />
      <p style={{ color: resultsColor }}>
        {value || 0} * 2 is: {total}
      </p>
    </div>
  );
}
```

### Tests in `App.test.js`
```js
import { multiplyByTwo } from './App';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import App from './App';

describe('multiplyByTwo function works correctly', () => {
  test('2 should equal 4', () => {
    expect(multiplyByTwo(2)).toBe(4);
  });
  test('15 should equal 30', () => {
    expect(multiplyByTwo(15)).toBe(30);
  });
});

test('displays correct sum and color for valid input', () => {
  render(<App />);

  const inputElement = screen.getByLabelText(/enter value/i);
  const totalElement = screen.getByText('* 2 is:', { exact: false });

  userEvent.clear(inputElement);
  userEvent.type(inputElement, '50');
  expect(totalElement).toHaveTextContent('100');
  expect(totalElement).toHaveStyle({ color: 'darkgreen' });
});

test('displays red color and NaN for invalid input', () => {
  render(<App />);

  const inputElement = screen.getByLabelText(/enter value/i);
  const totalElement = screen.getByText('* 2 is:', { exact: false });

  userEvent.clear(inputElement);
  userEvent.type(inputElement, 'dwed');
  expect(totalElement).toHaveTextContent('NaN');
  expect(totalElement).toHaveStyle({ color: 'red' });
});
```
Modern ES6 Class
Tags: javascript
Published: 2021-09-05 13:51:31

For this project, we are going to create a simple class called `Sablier` (hourglass in French), that takes a date and returns it in milliseconds.

In it we will emulate some of `Moment`'s cool features such as outputting `Moment<date>` when logged, function chaining or importing `isMoment` as a stand alone function. 

Features:
- `import sablier from "./sablier.js"`
- `import { isSablier } from "./sablier.js"`
- No need to use the `new` keyword to instantiate
- Can pass an unlimited number of arguments
- With function chaining
- `console.log(sablier(params))` outputs a custom string `Sablier<date_in_ms)>`
- `${sablier(params)}` outputs a custom string `date_in_ms`

```
// Custom console.log
// Deno: https://doc.deno.land/builtin/stable#Deno.inspect
const inspect = Symbol.for("Deno.customInspect")
// Node: https://nodejs.org/api/util.html#util_util_inspect_custom
// const inspect = Symbol.for('nodejs.util.inspect.custom');

class Sablier {
  constructor(date = new Date(), options) {
    // Set the class's properties
    this._date = date;
    this._options = options;

    // Run initialization tasks
    this.initialize();
  }

  initialize() {
    // if Date, convert time to milliseconds
    if (this._date instanceof Date) {
      this._date = this._date.getTime();
    }
  }

  // Output the result
  format() {
    return this._date;
  }

  // Chainable function
  add(amount) {
    this._date += amount;
    return this;
  }

  // Output all the parameters passed after the first one
  options() {
    return this._options;
  }

  // Custom console.log
  [inspect]() {
    return `Sablier<${this._date}>`;
  }

  // Custom String output
  toString() {
    return `${this._date}`;
  }
}

// Automatically instantiate class
const sablier = (date, ...options) => {
  return new Sablier(date, options);
}

// Stand-alone function
const isSablier = date => date instanceof Sablier;
// Access the stand-alone function from the Sablier instance
sablier.isSablier = date => isSablier(date);

export default sablier;
export { isSablier };
```

Link to live example: https://replit.com/@RilDev/ModernES6Class
5 Tips to Prepare for Online Classes for your Next Semester
Tags: tutoring, online, education
Published: 2021-09-05 15:06:47

As the new school semester is beginning so you may likewise be eager to go to your online classes and start your examination. However, here, we give you 5 hints that can assist you with planning for your online classes.

Be disciplined
Online classes don’t imply that you can show indiscipline. You guarantee that you go to them routinely and it is equivalent to that of an actual class. You can’t take it nonchalantly and can miss the classes since these are going on the web. You need to recollect that universities have stricter and you might wind up getting more tasks this time so you need to have a fitting outlook for this.

Make notes
Keep a pen and notebook ready so that you can make notes. You should not miss any crucial point and instantly write it down so that you can use it in the future. If it’s related to an assignment, you should never miss it since it’s helpful to you.

Make friends
We realize it might sound odd to make companions in online classes. However, you should plan to meet certain individuals who are in your online classes after the class is finished. You can reinforce your bond with them, share notes and data about the online class. This can likewise cause you to feel you are going to a customary class in particular.

Be organized
Online classes can be advantageous so you can wind up being disrupted. Be that as it may, you ought not submit this error. You ought to be prepared when your class begins. You ought not go to your group in night suits. You ought to be appropriately spruced up with the goal that you can be mindful of the class. This even puts an incredible impact on your guide and you can be cheerful with regards to it. This can get you more checks and your mentor can be dazzled with your discipline and promptness.

Don’t be nervous
It is common that you can be nervous in the first few online classes. But as time passes, you will be used to it and you can start enjoying it. Keep interacting with your tutor often so that you can stay in touch.

These are key tips you need to take when you prepare for your online class.

Remember, you cannot compromise your study because of the pandemic. Colleges have made their best efforts to ensure that the online classes can be beneficial for you and do not be a time-waste for you. Tutors have been using interactive and creative ways to make learning fun in these online classes and ensuring that the students do not miss their academic year.

If you are still nervous, write to us (QuizBroz) and let us counsel you for the best results.
JavaScript replace a powerful tool to manipulate string
Tags: webdev, javascript
Published: 2021-09-05 14:55:03

Javascript replace is the most powerful tool to manipulate string and regex at its core makes it really powerful. We will deep dive into examples from basic to advance.

Replace all the occurrence of space with an underscore, a simplest use case.
```javascript
const str = 'remove all the space with underscore'
str.replace(/ /g, '_')

// remove_all_the_space_with_underscore
```

Replace all the number from 0 to 5 with @
```javascript
const str = 'replace 1 3 5 9 all 0 to 5 number with @'
str.replace(/[0-5]/g, '@')

// replace @ @ @ 9 all @ to @ number with @
```

Replace all the numbers between 0 to 5 with its square.
```javascript
const str = 'replace 1 3 5 7 all 0 to 5 number with its square'

str.replace(/([0-5])/g, (match, id) => {
 return id*id 
})

// replace 1 9 25 9 7 all 0 to 25 number with its square
```
You can write your own replacer function and return manipulated data. Even manipulate date inside string or deal with emoji.


  Some fun
```javascript
const str = 'cry replace with smile'
str.replace(/ /g, ' ')

// 'cry replace with smile'
```

Thank you for reading.
Ou Isso ou Aquilo: Entendendo os Desvios Condicionais (Parte 1)
Tags: javascript, algorithms
Published: 2021-09-05 14:54:57

## Em primeiro lugar: o que são desvios condicionais?

Desvios condicionais são estruturas que usamos que tomar decisões de acordo com o resultado de uma condição (teste lógico).

## Desvios condicionais simples

São estruturas que contém um bloco que será executado se uma condição for verdadeira.

```javascript
if(expressão) {
   // faça algo
}
```

## Desvios condicionais compostos

São estruturas que incorporam `else` na sintaxe, ou seja, se a primeira condição não se cumprir, a segunda condição será acionada.

```javascript
if(expressão) {
   // faça algo
} else {
  // faça algo
}
```

## E se houver várias condições?!

Podemos usar `else if` até que uma condição seja verdadeira.

```javascript
if(expressão) {
   // faça algo
} else if {
  // faça algo
} else {
  // faça algo
}
```

## Desvios condicionais encadeados

Usamos os desvios condicionais encadeados quando existe a necessidade de verificar condições sucessivas nas quais uma ação será executada se um conjunto de condições for satisfeito.

```javascript
if(expressão) {
  // faça algo
} else {
  if (segunda expressão) {
     // faça algo
  } else {
    // faça algo
  }
}
```

## Porém... Existe uma alternativa!

Podemos usar `Switch / Case` para verificar condições. 

```javascript
switch (expressão) {
   caso 1:
      // faça algo
      break;
   caso 2:
      // faça algo
      break;
   caso 3:
      // faça algo
      break;
   default:
      // faça algo
}
```

## E por que usar o `break` dentro de `Switch / Case`?!

A gente usa `break` para finalizar uma determinada verificação. Se não o usamos, a verificação de casos nunca vai parar.

Espera! Porque ainda temos o...

## Operador Ternário

O que é isso?! O operador ternário é um operador condicional com três operandos, como mostra a estrutura abaixo:

```javascript
condicao ? expressao1 : expressao2
```

O operador ternário deixa o código mais simples e fácil de ler, porque não há necessidade de usar `if / else`.

E aí? Gostaram? Até a próxima anotação! 😊
Amazing way to learn: compare languages and contribute with your code!
Tags: beginners, webdev, tutorial, firstyearincode
Published: 2021-09-05 14:54:55

## [Code Comparison](https://www.codecomparison.me/)

During my studies with elixir, I wanted to create something simple just to try [LiveView](https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html).

So I had an idea of creating an app that shows the difference between programming languages by topics.

For example, you want to know how to create a map in `Python` or `Go`, you just select in the dropdown.

All the code is in the repo, allowing the user to contribute with their own code in Github, which is a great way for beginners to learn and help others.

You can see the site in action here: https://www.codecomparison.me/

![Code Comparison](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wiahso0frt7650fnglqb.png)

## How to contribute?

### Forking the project or Creating the PR via Github.com

**Forking the project** 

- Access the repo: [https://github.com/Lgdev07/code_comparison](https://github.com/Lgdev07/code_comparison)
- Fork the repository
- In the root directory, the `topics` folder is where you can create a new one, change a code that already exists or create a new file with the language you know.
- After finishing your code, create a new branch `git checkout -b my-feature`
- Commit the changes `git add . && git commit -m 'feat: My new feature'`
- Push the changes `git push origin my-feature`
- Open the Pull Request

**Or Creating the PR via Github.com**

- Access the topics folder: [https://github.com/Lgdev07/code_comparison/tree/main/topics](https://github.com/Lgdev07/code_comparison/tree/main/topics)
- The `topics` folder is where you can create a new one, change a code that already exists or create a new file with the language you know.
- For example, if I want to create a new file in the `map` topic
- I go to map, and click on `Create new file`

    ![Creating a file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jkdu1tidfhgnlqfopg6a.png)

- After finishing your code, you can create a pull request by the end of the page, clicking on `Propose new file`

    ![Creating the PR](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hss9grq3kplhqf0hxoix.png)

- Don't forget to describe your commit and PR.

Github code: [https://github.com/Lgdev07/code_comparison](https://github.com/Lgdev07/code_comparison)

I appreciate everyone who has read through here, if you guys have anything to add, please leave a comment.
Cara Mengatasi Ruang Penyimpanan Penuh
Tags: ruangpenyimpanan, ponsel, handphone
Published: 2021-09-05 14:46:19

Setiap Ponsel tentunya memiliki sebuah ruang penyimpanan. Ruang penyimpanan yang tersedia pada setiap ponsel tentunya sangatlah berbeda-beda juga. Semakin tinggi harga ponsel, maka akan semakin besar juga kapasitas memori yang tersedia kosong. 

Namun tentunya kita akan resah apabila ponsel kita mempunyai peringatan "Ruang Penyimpanan Penuh" tentunya kita akan sangat kesal. Tetapi tenang saja karena saya akan memberikan beberapa tips agar anda bisa mengatasi masalah tersebut, berikut tips yang bisa anda pakai.

Tips Pertama, Menghapus dan membersihkan cache setiap aplikasi. Tentunya setiap aplikasi yang terpasang pada ponsel kita akan menyimpan cache yang lumayan besar dan menguras kapasitas memori ponsel kita. Kita cukup ke pengaturan saja dan buka setiap aplikasi, lalu anda tinggal pilih bersihkan cache. Lakukan cara ini berulang kali pada setiap aplikasi yang terpasang pada ponsel anda.

Tips Kedua, Menghapus Aplikasi berat. Mulai sekarang cobalah anda hapus aplikasi-aplikasi yang memberatkan ponsel anda, karena hal aplikasi yang berat cenderung memakan kapasitas memori yang cukup besar. Jika ponsel anda tidak sanggup untuk menjalankan aplikasi yang berat, maka hapuslah aplikasi tersebut karena akan memakan kapasitas memori.

Tips Ketiga, Atur Penyimpanan. Hal ini bisa kita lakukan jika kita memasang memori eksternal pada ponsel kita. Dengan memasang memori eksternal, kita bisa harus bisa mengatur penyimpanan dan mensamaratakan antara memori internal dan eksternal. Jika anda sudah bisa mengatur hal ini, maka anda sudah sangat bijak. Selain itu kita juga bisa menggunakan aplikasi drive sebagai media penyimpanan.

Source : https://www.infoocampuran.xyz