teleren/devto huggingface dataset:
The Difference Between Class Components and Functional Components
Tags: react, javascript
Published: 2021-06-27 01:17:45

During my last 2 months at Flatiron, I was learning about React and its ability to easily create a template for creating a webpage.  When it came time to create my final project, I had chosen to design my components with class components as opposed to functional components.  While I was creating my project, I really did not know the difference between class and functional components.

(https://dev-to-uploads.s3.amazonaws.com/uploads/articles/py2q0594o6qf463l0rfr.png)
This is my project from Flatiron: as you can see the css is the default code written up when running `react-create-app`. I'll be looking into making this application cleaner and more personalized.

When I was making the project, I used a template that one of my instructors had posted that made use of class components.  I followed this template, but now that I am looking to polish and add to my projects I find it rather difficult to format and stylize my web application using CSS.  Class components are easy to use, but as I have been doing research on fleshing out web page applications, I realized that using a class component is good for functionality, but ends up having a very barebones design.  Every tutorial and blog post that I have looked at have functional components as their component template.

In addition, since my React project was based in Redux, I never had a real chance to create a pure React app that incorporates a backend.  As a result, making changes to my project to add a navigation bar or sidebar has been difficult.  It may just be my lack of experience that has made me unable to see the solution to my problem, but I found that it would be better to begin a new project, and while I don't have a clear idea of what I want to do with it, I figured I'd use it to learn how to code strictly in React, especially since functional components are standard with regards to web development.  

(https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wl2ygyrxofe49pkntej4.png)
This is my new project that will strictly React and will not use Redux. It's much more visually appealing compared to the default css given by React.

(https://dev-to-uploads.s3.amazonaws.com/uploads/articles/plfqjx6ndfxz9f608aui.png)
I managed to build in a navigation bar using react-icons which can be found here: https://react-icons.github.io/react-icons/icons?name=io5.

My idea for this project will either be a replication of my Flatiron project without the use of Redux, or (if I can change the format and styling of my original project) try to create one of my older Rails-based project using React.
¿Cómo alojar un sitio web de forma gratuita?
Tags: webdev, hosting, html, domain
Published: 2021-06-27 01:29:36

No se preocupe, hay bastantes servicios de alojamiento web GRATUITOS en el mercado.

¡En este artículo nos encontraremos con algunos de ellos!

1️⃣ Github pages
GitHub, Inc. es un proveedor de alojamiento de Internet para el desarrollo de software y el control de versiones mediante Git.

Aloje su sitio web directamente desde su repositorio de GitHub.

Simplemente edite, presione y sus cambios estarán activos.

Las páginas de GitHub no solo son buenas, sino también la forma más fácil de alojar su sitio web porque probablemente esté enviando su proyecto a GitHub de todos modos (si no, comience a hacerlo), y después de enviar sus archivos al repositorio de GitHub con unos pocos clics, puede ir EN VIVO con tus proyectos y compártelo con todos.

![github](https://res.cloudinary.com/practicaldev/image/fetch/s--AlWXrRzS--/c_imagga_scale,f_auto,fl_progressive,h_1080,q_auto,w_1080/https://dev-to-uploads.s3.amazonaws.com/i/3uy5od7tw2jf4fh7ldlv.jpeg)


2️⃣ Netlify
Netlify es un flujo de trabajo intuitivo basado en Git y una potente plataforma sin servidor para crear, implementar y colaborar en aplicaciones web.

Cree experiencias increíbles para la web en un tiempo récord, sin pensar ni una sola vez en servidores o devops.

![netlify](https://media-exp1.licdn.com/dms/image/C4E0BAQEAt7-u6GJMlw/company-logo_200_200/0/1583277392105?e=2159024400&v=beta&t=m6tOVslELtoH9vqJo-vP47orqRK0kqIK9m-lS26Rzbw)


3️⃣ Vercel
Implemente proyectos web con la mejor experiencia de desarrollador de frontend y el mayor rendimiento para el usuario final.

Vercel es una plataforma en la nube para sitios estáticos y funciones sin servidor que se adapta perfectamente a su flujo de trabajo.

![vercel](https://mms.businesswire.com/media/20210216006039/en/859393/23/vercel.jpg)


4️⃣ Heroku
Heroku es una plataforma que permite a los desarrolladores crear, ejecutar y operar aplicaciones completamente en la nube.

Ya sea que esté construyendo un prototipo simple o un producto crítico para el negocio, la plataforma completamente administrada de Heroku le brinda el camino más simple para entregar aplicaciones rápidamente.

![heroku](https://estebanromero.com/wp-content/uploads/2018/02/heroku1.png)


5️⃣ Firebase
Firebase es una plataforma desarrollada por Google para crear aplicaciones web y móviles.

Con un solo comando, puede implementar rápidamente aplicaciones web y entregar contenido estático y dinámico a una CDN (red de entrega de contenido) global.

![Firebase](https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/Firebase_Logo.svg/1280px-Firebase_Logo.svg.png)


El alojamiento gratuito es bueno para cualquiera que desee crear su primer sitio web.
¡El fin!

Si deseas crear una página web te recomiendo a [Smart Domain](https://www.instagram.com/smart.domain/) ellos tienen paquetes muy accesibles y hacen un excelente trabajo.

Espero que este artículo le haya resultado valioso. Si es así, hágamelo saber en los comentarios 😊
LeetCode 153. Find Minimum in Rotated Sorted Array
(javascript solution)
Tags: algorithms, javascript
Published: 2021-06-27 00:56:58

###Description:
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

You must write an algorithm that runs in O(log n) time.


###Solution:
Time Complexity : O(log(n))
Space Complexity: O(1)

```javascript
// Binary Search 
var findMin = function(nums) {
    let left = 0, right = nums.length-1;
    while(left < right) {
        const mid = left + Math.floor((right-left)/2)
        // Move right pointer if num at mid is less than or equal to num at right. This means that the smallest number must be on the left side of mid including mid.
        if(nums[right] >= nums[mid]) {
            right = mid
        } else {
            left = mid+1
        }
    }
    return nums[left]
};
```
Binary tree in data structure
Tags: algorithms, computerscience, beginners, python
Published: 2021-06-27 00:18:38

Hi, this the part 2 of the tree in the data structure, we're going to talk about **binary tree** and its famous types.

## Definition of binary tree

**Binary tree**: is one of the most famous tree data structure which each node should have at most 2 children (*left child* and *right child*), in this type of trees, all nodes contains three items which are **data**, **pointer to left child**, **pointer to right child**.

## Types of binary tree


#### Full Binary tree

+ In this type of trees, all nodes except the leaves have two children

![full binary tree in data structure Aya Bouchiha](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mx2leaqgmxm29y77jh4e.jpg)

#### Perfect Binary tree

+ All internal nodes have exactly two children and all the leaves are at the same level. 

![perfect binary tree in data structure Aya Bouchiha ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gspulau74n4gtwaew25g.jpg)

#### Degenerate binary tree

+ In This kind of tree, all nodes have only one child.

![degenerate binary tree in data structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lld9xcngc5ktz4vhn5ae.jpg)

#### Complete Binary tree

+ Like a full binary tree, All levels are filled, but All the leaves should lean towards the left

![complete binary tree in data structure Aya Bouchiha](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aoszkp1y8lpgr16w7sh0.jpg)

#### Balanced Binary tree

+ the absolute value of the height  difference between the left and the right subtree is smaller than or equal 1. `| height(left_sub_tree) - height(right_sub_tree) | <= 1`

![Balanced binary tree in data structure Aya Bouchiha](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57xiu9k0tmjzxd9g90va.jpg)

#### Skewed Binary tree

+ All nodes have only one child except the last one (leaf) which hasn't a child. It divided into two types: *left skewed binary tree* and *right skewed binary tree*

![Skewed binary tree in data structure Aya Bouchiha](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69k5ahxgt2qvhkjhsoc9.jpg)

## References and useful Resources

+ [https://www.geeksforgeeks.org/binary-tree-data-structure/](https://www.geeksforgeeks.org/binary-tree-data-structure/)
+ [https://www.programiz.com/dsa/binary-tree](https://www.programiz.com/dsa/binary-tree)
+ [https://www.programiz.com/dsa/perfect-binary-tree](https://www.programiz.com/dsa/perfect-binary-tree)
+ [http://www.cs.kent.edu/~durand/CS2/Notes/10_Binary_Trees/ds_treesB.html](http://www.cs.kent.edu/~durand/CS2/Notes/10_Binary_Trees/ds_treesB.html)
+ [https://www.programiz.com/dsa/balanced-binary-tree](https://www.programiz.com/dsa/balanced-binary-tree)
+ [https://www.journaldev.com/43957/balanced-binary-tree-check](https://www.journaldev.com/43957/balanced-binary-tree-check)
+ [https://www.programiz.com/dsa/complete-binary-tree](https://www.programiz.com/dsa/complete-binary-tree)
Deploying To Heroku Rails API back end and React front end
Tags: react, heroku, ruby, javascript
Published: 2021-06-27 00:17:32

#Intro

In this blog, we will go over the ways to deploy to [Heroku](https://https://www.heroku.com) both rails API and React front end.

#Rails API
First, we need to create a react app to skip the steps below I recommend installing it with postgresql. Starting off type 

`rails new your-app-name-here --api --database=postgresql`

In the terminal or if you have normal rails that's okay too.

##--Steps you can skip if you have the line above-- 

###Step 1
You want to delete anything that has to do with sqlite3, head over to your gem file and install 

`gem 'pg'`

Make sure you deleted

`gem 'sqlite3', '~> 1.4'`

###Step 2

In the config/database.yml Change the default adapter to 
`postgresql`, and the development database, test, and production and delete everything that has to do with sqlite3 and replace it with 

`app_name_development, app_name_test, and app_name_production`

To their specific category.

###Step 3

Delete your `Gemfile.lock` then bundle install. this will help reduce errors in having any SQLite data in your Gemfile.lock.

#Continue from here if you launched rails with --database=postgresql.

###Step 4  

In your terminal type `Heroku login` this will enable you to log into the Heroku server. after, go ahead and create an app in Heroku or you can do `Heroku create <your app name>` in your terminal.

###Step 5 

Run rails db:create to create your new database.

###Step 6 

Run 

```
git add .

git commit -m "your message"

heroku git:remote -a <your App name>

git push Heroku master
```

###Step 7

Run rails db:migrate and as well as Heroku rake db:migrate you can do the same if you have seeded data.


##--And that's the deployment steps for Rails API--

#Deplying React Front End 

###Step 1

This part is pretty simple create your react app as so 

`
npx create-react-app <your app name>
`

###Step 2

In this step log into Heroku and do. 

`heroku login` 

this will log you into the Heroku server.

###Step 3

`Heroku create <your app name>`

this will create your app. 

###Step 4

run 
```
git add .

git commit -m "your message"

heroku git:remote -a <your App name>

git push Heroku master
```
this will go and push your app to Heroku and deploy it.



#Finally 

Enjoy your deployed app! for your front end to connect to your back end make sure you copy the restful route Heroku gives you for you app link.
How to start an Nginx server or service in Linux?
Tags: resource
Published: 2021-06-27 00:00:00

---
  title: How to start an Nginx server or service in Linux?
  published: true
  tags: Resource
  date: Sun Jun 27 2021 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/start-nginx-server-service-linux
  cover_image: https://melvingeorge.me/_next/static/images/main-1ef0aca55a6b9f83d7036fad9e208215.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/start-nginx-server-service-linux)
  
To start an Nginx server or service, we can use the `systemctl` command-line utility followed by the `start nginx` command in Linux.

```bash
# Starts Nginx service
sudo systemctl start nginx
```

### What is `systemctl`?

- The `systemctl` is a command-line utility that is used to control and manage the `systemd` services.
- It is widely used with web server services like Nginx, Apache, etc.

### Feel free to share if you found this useful 😃.

---
What is the ROI of Test-Driven Development?
Tags: practices, tdd, productivity
Published: 2021-06-30 15:14:04

---
title: What is the ROI of Test-Driven Development?
published: true
date: 2021-06-27 00:00:00 UTC
tags: practices,tdd,productivity
canonical_url: https://jhall.io/archive/2021/06/27/what-is-the-roi-of-test-driven-development/
---

[Test-Driven Development](https://jhall.io/archive/2021/02/28/test-driven-vs-test-first/), or TDD, is the practice of writing tests, then code, in short iterations of a few seconds to a few minutes.

A common trope I hear coming from some moderate TDD detractors, is that TDD makes sense, when you’re willing to wait long enough to reach the break-even point.

This sounds reasonable on the surface. We routinely calculate the break-even point or payback period for any thing that requires a large up-front investment for a long-term pay off.

In this way of thinking, the TDD break-even point can be visualized with a chart something like this:

 ![](https://jhall.io/posts/images/perceived-roi-tdd.png)

Unfortunately, this calculation is completely wrong, where experienced TDD practitioners are involved. This is becuase TDD _makes development faster_.

A more accurate view is something like this:

 ![](https://jhall.io/posts/images/actual-roi-tdd.png)

I wrote a lot more about this in [a long-form blog post](https://jhall.io/posts/tdd-roi/) if you’re interested.

* * *

A few weeks ago, I had a good conversation with George Stocker about TDD on the Tiny DevOps podcast. Have a [listen](https://share.transistor.fm/s/da70d5c2) or [watch](https://www.youtube.com/watch?v=qM1Zc_49Eas).

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
Escrevendo textos no formato Markdown usando o Notepad++
Tags: markdown, notepad, markdownviewer
Published: 2021-06-26 23:55:22

O Notepad++ é um editor de texto de código aberto, simples, leve e prático de ser utilizado, pois ele permite trabalhar com arquivos de textos simples e código-fonte de diversas linguagens de programação.

Poucas pessoas sabem, mas é possível adicionar novas funcionalidades a esta ferramenta através da instalação de alguns plugins e neste artigo irei abordar o plugin **MarkdownViewer++**  

O MarkdownViewer++ é um plugin do Notepad++ que permite digitar um arquivo do tipo Markdown e ver a visualização em tempo real, em um painel de visualização.

![exemplo-markdownviewer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6251s9eiciavlp47pky.png)
 
## Instalação

Para instalá-lo, use o gerenciador de plugins do Notepad++

Abra o Notepad++ e vá para Plugins → Gerenciador de plugins → Mostrar Gerenciador de plugins

![gerenciador-de-plugins-notepad-plus](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vxoqvxf9z7mtqtj800uh.png)

Pesquise por "MarkdownViewer++", selecione e clique na opção "Instalar"

![gerenciador-de-plugins-notepad-plus-markdonwviewer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zd2culy4pvds2xg1xwv8.png)
 
Será feito o download e instalação de forma automática. Nesse ponto, o editor deve ser reiniciado e perguntará se você deseja fazê-lo imediatamente (para que não haja risco de perder seu trabalho).

Após a reinicialização, basta escrever um documento texto e selecionar a opção Plugins → MarkdownViewer++ → MarkdownViewer++

![markdownViewer-notepad-plus](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/46097lm0b9pkbmlua8g0.png)

![exemplo-markdownviewer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6251s9eiciavlp47pky.png)

Além desta funcionalidade, com o plugin MarkdownViewer você tem:

- Suporte ao CommonMark
- É possível exportar o resultado para HTML ou PDF
- O painel de visualização pode ser movido, redimensionado e encaixado

![top](https://media.giphy.com/media/3o6Zt7mutmbv76m0ko/giphy.gif)
Custom Hooks in React
Tags: react, webdev, javascript, tutorial
Published: 2021-06-26 23:40:49

![a hook](https://cdn-images-1.medium.com/max/2000/0*pllR4ALVef3evFxQ.jpeg)

I’m going to assume you know the basics about hooks in React but if not or you’d like to dive a bit deeper into this concept check out the links at the end of this blog. So what are custom hooks? If you’ve used earlier versions of React you’ve probably come across patterns like higher-order components and render props (you can read about these in my previous blogs, [higher-order components](https://dev.to/coderjay06/higher-order-components-in-react-52d0), and [render props](https://dev.to/coderjay06/render-props-26m5)). These patterns (just like hooks) let you reuse stateful logic in your React components, though hooks offer a less complex way to achieve the same result of reusability. With custom hooks, we can make our own hooks and customize them to contain whatever logic we choose to add to them. This gives us more flexibility to solve a specific problem we might have.

Let’s start with an example of when you might feel the need to create a custom hook. Say we wanted to add a timer to the React application we’re building. We can simply just build it within our component that needs to use it and we’re good to go right!? But what if we needed to reuse our timer across several components? This would be a great opportunity for a custom hook! So to create our custom hook we should always start with the word *use* followed by a relevant name for it. In this case, we’ll call it *useTimer*. Then we can import any of the built-in react hooks that we’ll need inside of our custom one.

{% gist https://gist.github.com/CoderJay06/05bf5639e0485f8194c9c4ef3f50823b.js %}

Now with this code, anywhere a timer is needed within our app we just import our custom useTimer() hook and display it within our component. In this case the Timer component.

{% gist https://gist.github.com/CoderJay06/bcb9be75a5e46024e59c9d3c53330dff.js %}

Here we’re just rendering the return value from the useTimer() hook we've just created. This timer updates each time the setInterval() inside of useEffect() is invoked.

Custom hooks are great for reusing the business logic across your React application. When you need something less abstract and a bit more tailored towards your component they can come in handy. Instead of just using built-in hooks we can have more flexibility by adding customized code into a reusable hook.

## More resources

* [React Hooks](https://reactjs.org/docs/hooks-intro.html)

* [Building your own hooks](https://reactjs.org/docs/hooks-custom.html)

*Originally published at [https://coderjay06.github.io](https://coderjay06.github.io/custom_hooks_in_react) on June 24, 2021.*
Rust - Function & Comment
Tags: rust, programming, beginners, codenewbie
Published: 2021-06-26 22:44:04

Seperti halnya _variable_, 
__Rust__ menggunakan _snake case_ sebagai gaya penulisannya.

Dan seperti beberapa bahasa pemrograman lain,
_Rust_ mengguanakan `main` _function_ sebagai _entry point_ program.


> Semua materi merupakan rangkuman belajar.
>
> Untuk bacaan yang lebih langkap & update, dipersilahkan akses pada
> [The Book](https://doc.rust-lang.org/stable/book/ch03-03-how-functions-work.html)


Okay, berikut contoh format penuh dari sebuah _function_
```
use rand::Rng;

fn main() {
	let kamu = "aku".to_string();
	let doi = String::from("dia");
	let is_jodoh = jodohin(&kamu, &doi);

	println!("apakah aku jodoh dengan {}, {}", doi, is_jodoh);
}

fn jodohin(a: &String, b: &String) -> bool {
	// Generate angka acak untuk menentukan jodoh
	let random_nasib: u8 = rand::thread_rng().gen_range(0..2);

	println!("{}", random_nasib);
	if random_nasib == 1 {
		println!("{} dan {} berjodoh", a, b);
		return true;
	}

	println!("{} dan {} tidak berjodoh", a, b);
	// Rust merupakan expression-based language
	// Kamu bisa mengembalikan nilai
	// menggunakan expression seperti ini
	// di akhir & tanpa ;
	// bila menggunakan ;
	// harus dengan keyword return
    	false
}
```

- `main` _function_ merupakan _entry point_ program.
- Fungsi ditandai dengan keyword `fn`
- Rust tidak peduli dimana letak fungsi yang dipanggil, bisa sebelum pemanggilan, atau setelahnya
- _Parameter_ ditulis dalam tanda kurung &  bersama tipe datanya
	
	`(a: &String, b: &String)`
- _Argument_ ditulis berurutan sesuai penulisan _parameter_

	`jodohin(&kamu, &doi);`
- _Body_ fungsi ditulis dalam kurung kurawal `{ }`
- _Nilai Return_ ditandai tanda panah & hanya ditulis tipe datanya

	`-> bool`
- Cara mengembalikan nilai
	- Statement, harus dengan keyword `return` dan tanda `;`
	- Expression, diletakkan di akhir fungsi dan tanpa `;`

> Statement, adalah instruksi/code yang tidak mengembalikan nilai
> Expression, mengembalikan nilai


## Comment

Rust hanya mendukung _inline comment_ dengan tanda `//`.
Yang artinya, jika kita ingin menulis _multiline comment_, kita harus menuliskan `//` tiap barisnya, heheee.

Contohnya ada di atas.


> Rust menggunakan `use` untuk _import_ package/dependency dari luar, 
> jangan lupa menulisakan package nya pada `Cargo.toml` 
>
> Dan contoh pembuatan String seperti di atas,
> lebih jelasnya akan dilanjutkan pada bahasan tersendiri


Terima kasih.
My experience in creating Css with Pubg UC online store
Tags: css, design
Published: 2021-06-26 22:39:54

Check out my Pubg UC sell store. All the website’s images were designed by photoshop. The web page was built by CSS code.
[شدات ببجي](https://saudi-uc.com)

What do you think about it? If you have any further recommendations, please let me know.
Combining Two Arrays Using the concat Method
Tags: javascript, devops, beginners, programming
Published: 2021-06-26 22:18:37

* Concatenation means to join items end to end. JavaScript offers the `concat` method for both strings and arrays that work in the same way. For arrays, the method is called on one, then another array is provided as the argument to `concat`, which is added to the end of the first array. It returns a new array and does not mutate either of the original arrays. 
* Here's an example:
```
[10, 20, 30].concat([40, 50, 60]);
```
* The returned array would be `[10, 20, 30, 40, 50, 60]`.

* Now let's use the `concat` method in the `nonMutatingConcat` function to concatenate `attach` to the end of `begin`. The function should return the concatenated array.
```
function nonMutatingConcat(original, attach) {
  // Only change code below this line

  // Only change code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingConcat(first, second);
```
* Answer:
```
function nonMutatingConcat(original, attach) {
  return original.concat(attach)
}

var first = [1, 2, 3];
var second = [4, 5];
console.log(nonMutatingConcat(first, second)); // willreturn  [1, 2, 3, 4, 5]
```


Larson, Quincy, editor. “Combine Two Arrays Using the concat Method.” Https://Www.freecodecamp.org/, Class Central, 2014, twitter.com/ossia.