teleren/devto huggingface dataset:
Separation of concerns in JS (cleaner code) Part 1
Tags: javascript, codequality
Published: 2021-01-29 15:08:08

A fundamental step in the journey to software engineering is to make applications with proper structure. Here, I try to mention some fundamental methods to structure JavaScript code for when apps grow and get more complex.

This example uses vanilla JS, so the dependencies are set simply through `<script>` tags. So unlike frameworks like React or Angular the separation of concerns has to be built from scratch. Dealing with plain JavaScript really gives insight into why frameworks are so effective. 

So initially I used a class-based approach to have some modularity and used an `Adapter` to encapsulate most of the logic (data and presentational). Then also created classes for the models to set their attributes.

[Adapter Code](https://github.com/SantiagoSalazarPavajeau/chords_beats_frontend/blob/8bb8d753c8f2b6737484e6ec7f0f977dde75e016/adapter.js)

This was an initial step, but it was not taking functionality into account. So eventually the `Adapter` became cluttered with many methods with unrelated functionalities that had the potential to be categorized. 

In Javascript, some of the main functionalities include API requests, event handling, and DOM manipulation. The way specific types of functions can be organized is through making files that will only contain one category of functionality.

In an initial step to decluttering the `Adapter` class I divided the methods into three files:

* `apiHelper.js`: methods with server-side requests.

* `domEventHelper.js`: methods with event handling and DOM manipulation.

* `stateHelper.js`: global variables needed throughout the application.

[Link to repository](https://github.com/SantiagoSalazarPavajeau/chords_beats_frontend)

In the next blog, I further break down the `domEventHelper.js` into a file/module with only DOM manipulation and another only with event handling.

Feel free to reach out with any ideas/thoughts through [LinkedIn](https://www.linkedin.com/in/santiago-salazar-pavajeau/) or [Twitter](https://twitter.com/santispavajeau).
Seletores css que facilitam a vida de um frontend
Tags: css
Published: 2021-01-29 15:07:54

A ideia por trás deste post, é apresentar 3 seletores que tornaram a minha vida como dev frontend mais fácil. 👍🏿


### **Seletor de Atributo**

O seletor de atributo é um dos mais práticos que existem, basicamente você vai estilizar o elemento usando como identificador algum atributo que ele possui, que pode ser o name, type…, no código abaixo temos um exemplo, onde o botão com o name igual a first-button recebe o background vermelho (caso alguém não conheça variável em css recomendo utilizar).

```html
<div>
  <h2>Seletor de Atributo</h2>
  <h3>Exemplo: [name='first-button']</h3>
  <div>
    <button name='first-button'>BOTÃO 1</button>
    <button name="second-button">BOTÃO 2</button>
  </div>
  </div>
```

```css
button[name='first-button'] {
  background: var(--main-bg-red);
}
```

![seletor](https://dev-to-uploads.s3.amazonaws.com/i/q855yk8udc9qej6bm8mw.png)

### **Seletor +**

O seletor + é um dos meus seletores favoritos, ele serve para estilizar um elemento seguido de outro elemento, no código abaixo temos um exemplo, onde o botão seguido de outro botão recebe como background a cor vermelha.

```css
button + button {
  background: var(--main-bg-red);
}
```

![seletor](https://dev-to-uploads.s3.amazonaws.com/i/yzk4pdri45924x5h0zh1.png)

### **Seletor :nth-of-type**

O seletor :nth-of-type é mais versátil de todos os seletores apresentados, ele é parecido com o :nth-child, mas a diferença é que ele pega diretamente o elemento em vez dos filhos dele, no código abaixo temos um exemplo, onde o botão que está na primeira posição recebe como background a cor vermelha.

```css
button:nth-of-type(1){
  background: var(--main-bg-red);
}
```

![seletor](https://dev-to-uploads.s3.amazonaws.com/i/pvzymwl2g9u4zcl44r9u.png)

Caso você tenha interesse em descobrir mais sobre os seletores de css recomento dar uma olhada nos links abaixo:

[Mozilla](https://developer.mozilla.org/pt-BR/docs/Web/CSS/Getting_Started/Seletores)
[DevMedia](https://www.devmedia.com.br/css3-selectors-conhecendo-os-seletores-do-css3/24782)
[Maujor](https://www.maujor.com/tutorial/guia-completo-seletores-css3.php)
How to convert and use SVG in an android app
Tags: android, svg, androiddev, androidstudio
Published: 2021-01-29 15:07:10

####How to convert jpg or png to SVG

To use SVG in android there are a number of ways but the one i used was to create a vector of a SVG and then putting that into a drawable. It sounds straightforward but it was not for me, had to solve some pesky issues before i got it working.

First, convert your png or jpg to SVG using any online tool, you can find it on google. 
Then create a vector drawable with that SVG by going to below link:

[svg2vector](https://svg2vector.com/)


Now put that xml in your drawable folder and then you can use that in your `ImageView` resource.
Install `nano` on EdgeOS (2.x)
Tags: edgeos, edgerouter, ubiquiti, router
Published: 2021-01-29 15:05:10

If you want to edit a (config) file on EdgeOS (2.X.X), you can. EdgeOS comes with `vi`. Not the easiest editor to get started with, especially if you just want to update a simple setting in eg. a OpenVPN client config file.

To make editing the occasional file a bit easier, you can install the `nano` package from the Debian repositories. To do that, SSH into your EdgeRouter:

```
ssh {your-webinterface-username}@{your-router-ip} -p 22
```
Eg. `ssh johndoe@192.168.1.1 -p 22`

When logged in, start configuration mode:

```
configure
```

Now set the Debian system package, by issuing these commands in the configuration mode:

```
set system package repository stretch components 'main contrib non-free' 
set system package repository stretch distribution stretch
set system package repository stretch url http://http.us.debian.org/debian
```

Apply the configuration by committing, save and exit:

```
commit; save; exit
```

Now update the system package cache:

```
sudo apt-get update
```
 
### Do _NOT_ upgrade system packages, that will break some of the packages your EdgeRouter depends on! 

You can now install `nano`:

```
sudo apt-get install nano
```

Now `nano ` is installed, we can remove the apt-cache, and remove the Debian repository again from the config:

```
sudo rm -R /var/lib/apt/lists
sudo rm -R /var/cache/apt/archives
```

Enter the configuration mode again, and remove the Debian system package repository:

```
configure
delete system package repository stretch
commit; save; exit
```

### Enjoy using `nano` for a quick config file edit :)
Props de react chidas y bien explicadas.
Tags: react, spanish, beginners, programming
Published: 2021-01-29 15:04:34

Las propiedades o por la forma mas común **props** es la manera de enviar datos a los componentes, pasándolos por parámetros.
ejemplo:
Queremos crear un componente que sea una tarjeta de usuario, el cual se llene con datos de cada usuario.
hacemos algo como esto:![Tarjeta de usuario](https://dev-to-uploads.s3.amazonaws.com/i/q7lc82egsgca85q34tz2.png)
Ahora nuestro componente ocupa los datos [ *nombre, sexo, nickname, edad, nacionalidad* ]

podríamos establecerlos directamente en nuestro texto, pero eso no seria muy dinamico de nuestra parte

entonces aquí entran las props, que vendrían siendo **parámetros** con valores dados por el sistema o usuario.

## como enviamos las propiedades a nuestros componentes?

Para enviar un valor por props los enviamos desde donde estamos llamando al componente, siguiendo la siguiente estructura:


    <NombreComponente
      nombre_propiedad =  'valor_de_la_propiedad'  
	  .
	  .
	  .  
    />

podemos poner cuantas propiedades sean necesarias para nuestro componente.
![Componente con props](https://dev-to-uploads.s3.amazonaws.com/i/erfnhkv091fwn7jnspah.png)

Ya enviamos nuestras propiedades bien dinamicas a nuestro objeto, pero ahora...
## Como obtenemos las propiedades en nuestro objeto?

Estos llegan a los parámetros de nuestro componente y la forma mas común de  obtenerlos es con un objeto que se llame **props** y de ahí llamar cada propiedad según la necesitemos.
![Componente recibiendo props](https://dev-to-uploads.s3.amazonaws.com/i/0irevmdawu7muee54gvk.png)

*(El nombre de las propiedades debe ser el mismo que le colocamos cuando las enviamos)*

(El nombre **props** es un nombre estándar, pero si podemos colocarle el nombre que nosotros gustemos.)
![Componente con props re-bautizadas](https://dev-to-uploads.s3.amazonaws.com/i/qr59tjho461fbqwalld9.png)

## Trucos con las props

Como las estamos pasado por parámetros, podemos utilizar la funcionalidad de [Desestructuracion](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Operadores/Destructuring_assignment) y así evitamos la palabra props y colocamos únicamente el nombre del elemento que estamos pasando, haciendo mas entendible nuestro código.
![Componente desestructurado](https://dev-to-uploads.s3.amazonaws.com/i/77rzzi75x3p3h6pxlgag.png)

En cualquier caso, si lo desestructuras o no, el resultado siempre seguirá siendo el mismo.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/m8yt047fxzpwcphj0plj.PNG)
*(El nombre de las propiedades al ser desestructuradas debe ser el mismo que le colocamos cuando las enviamos)*
Getting a JSON element from a DB in Eloquent
Tags: php, laravel, tutorial
Published: 2021-01-29 15:02:25

So I had an issue come up today that required me to pull some data out of a DB for a report. That included some data that was stored in a JSON object. 

So we have a column called params and in that we have a JSON Object that looks like so

```json
{"1": "one", "2": "two", "3": "three", "4": "four"}
```

So in my report, I need to access number 3, and how we do that is by using json_extract(), like so

```php
$results = DB::table('testing')
                   ->select(
                       DB::raw('json_extract(params, "$.4") as number'))->get();
```
So in the json_extract the first param it expects is the column name and following that is the field. You can then add more items to the select statement using a comma and we can write a full query like so 

```php
$results = DB::table('testing')
             ->select(
                'id',
                DB::raw('json_extract(params, "$.4") as number'),
                'type'
                'created_at'
)->get();
```

And that will pull the data we need and all is great! 

Enjoy folks and as always any updates or code reviews on this post please leave a comment down below
Experiment with Web3 technologies on 3327.io
Tags: blockchain, javascript, security, hiring
Published: 2021-01-29 14:48:49

Hi guys, 
I just wanted to let you know that our technology incubator is live! The idea behind it is simple - to encourage and foster idea generation and experimentation to achieve breakthroughs in the Web 3.0 industry. We're now spreading the word.

We can experiment together, build all kinds of innovative products and tools, bring ideas to life (yours, ours, or from anyone in the community), share knowledge, organize hackathons, and many other things. If it seems interesting, let's get to know each other. You can join us on our newly-created Discord server - https://discord.gg/ZWZ9Jk77vt
🚀10 Trending projects on GitHub for web developers - 29th January 2021
Tags: react, javascript, css, typescript
Published: 2021-01-29 14:48:11

Trending Projects is available as a weekly newsletter please sign up at [www.iainfreestone.com](https://www.iainfreestone.com) to ensure you never miss an issue.

### 1. JerryScript

JerryScript: JavaScript engine for the Internet of Things. A lightweight JavaScript engine for resource-constrained devices such as microcontrollers. It can run on devices with less than 64 KB of RAM and less than 200 KB of flash memory.

{% github https://github.com/jerryscript-project/jerryscript %}

---

### 2. react-big-calendar

An events calendar component built for React and made for modern browsers (read: IE10+) and uses flexbox over the classic tables-ception approach.

{% github https://github.com/jquense/react-big-calendar %}

---

### 3. React Select

The Select Component for React.js. A flexible and beautiful Select Input control for ReactJS with multiselect, autocomplete, async and creatable support.

{% github https://github.com/jedwatson/react-select %}

---

### 4. Reactour 

Tourist Guide into your React Components

{% github https://github.com/elrumordelaluz/reactour %}

---

### 5. Terminalizer

Record your terminal and generate animated gif images or share a web player

{% github https://github.com/faressoft/terminalizer %}

---

### 6. Filepond

A JavaScript library that can upload anything you throw at it, optimizes images for faster uploads, and offers a great, accessible, silky smooth user experience.

{% github https://github.com/pqina/filepond %}

---

### 7. Blueprint

Blueprint is a React-based UI toolkit for the web. It is optimized for building complex, data-dense web interfaces for desktop applications which run in modern browsers and IE11. This is not a mobile-first UI toolkit.

{% github https://github.com/palantir/blueprint %}

---

### 8. ress

Modern CSS reset

{% github https://github.com/filipelinhares/ress %}

---

### 9. Constate

Write local state using React Hooks and lift it up to React Context only when needed with minimum effort.

{% github https://github.com/diegohaz/constate %}

---

### 10. Lazy Collections

Collection of fast and lazy operations

{% github https://github.com/RobinMalfait/lazy-collections %}

---

Trending Projects is available as a weekly newsletter please sign up at [www.iainfreestone.com](https://www.iainfreestone.com) to ensure you never miss an issue.

If you enjoyed this article you can [follow me](https://twitter.com/iain_freestone) on Twitter where I regularly post bite size tips relating to HTML, CSS and JavaScript.
7 easy ways to become a better developer
Tags: codenewbie, webdev, programming, beginners
Published: 2021-01-29 14:45:10

## Introduction

I've read dozen of articles on how to become a better developer in the past year

Here are 7 ways to do so

## 1. Code every day for as much as you can. 

This is important especially when you're first starting.

You can code for as little as 15 minutes.

It's a lot better to learn for one hour every day than for 7 hours in one day once a week.

## 2. Practice makes perfect. 

The only difference between you and the developers that are better than you is that they practiced more.

But it's also very important how you practice which leads us to the point 3...

## 3. Active learning >> passive learning.

What this means? It's a lot better to learn by building projects and playing around with the concepts you learned than just watching the tutorial.

So start building something as fast as you can.

## 4. Google.

Use Google as much as you can. Every time you don't remember something or can't solve a problem use Google.

Googling is one of the most important skills of a developer. Use it as a tool to get your job done faster.

## 5. Find what resources work the best for you.

Some people learn the best from video courses. Others from books. And others just from building something.

Make sure you take some time to find which one works the best for you.

## 6. Avoid Tutorial Hell

What does Tutorial Hell mean? It's that thing when you go from one tutorial to another without building something.

This is the worst thing you can do to yourself because you feel that you're learning something but in reality, you are not.

## 7. Avoid distractions when learning how to code

If you want to learn something new you need to be 100% focused on that. 

If you check your phone every 5 minutes you'll get nowhere.

Remember that 1 hour of focused work is a lot better than 3 hours of distracted work.

## End

I hope that you liked this article and learned something new. And if you did so make sure follow me on [Twitter](https://twitter.com/VladPasca5) where I post Tweets related to this article everyday.
Fun with Units of Measure
Tags: csharp, unitsofmeasure, opensource
Published: 2021-01-29 14:44:02

A while ago I read about F#'s Units Of Measure Support. Inspired by this, I just wanted to have some fun and do something like that in C#. The result has come to a point, where I am willing to let it loose to the world.

This is open source. So if someone would like to add something, feel free to make a pull request.

#What I have so far
I already implemented metric, imperial and usually some astronomic and/or fun equivalent units of
- Distance 
- Area 
- Volume 
- Mass
- Velocity
- Frequency
- Time

BigDoubles, which are necessary, when converting f.e. between the mass of our sun and gram, are taken from [Razenpok - Break Infinity](https://github.com/Razenpok/BreakInfinity.cs) and modified slightly.

The interesting part was, to allow for automatic conversion between units of the same "area", but only those - and to enforce those restrictons already at compile time. I wanted the compiler to tell you, that you can not convert 10 cm to seconds instead of a runtime exception.

Have fun with it and maybe contribute your own favorite fun equivalent: [Units Of Measure](https://github.com/DerGuru/UnitsOfMeasure).
Bringing Dark Theme to Medium in Chrome
Tags: darktheme, medium, chrome, devtool
Published: 2021-01-29 14:40:23

I remember myself running the same script in my Chrome Console. Thanks to Chrome Dev Tool Snippets, now you can save and run your favorite and frequently used code snippets on any site in Chrome. The good thing is that these snippets are aware of the Javascript Context of the page.

For this article, I wrote a script that will bring **Dark Theme** to Medium web.

![Javascript Snippet for Medium Dark Theme](https://cdn-images-1.medium.com/max/9440/1*n4Jx24W1dF0LIVMwHvhPqA.png)

First, we add the above snippet in Chrome and see if it is working.

1. Open Chrome Dev Tool by pressing **Ctrl + Shift + Ins** or **Right-click** and select **Inspect**.
![Open Dev Tools](https://cdn-images-1.medium.com/max/3840/1*ilPvTWG62qZcao1v91u14w.png)

2. Click on the **Sources** Tab. You can see a list of options on the left like Page, Filesystem, Overrides, etc.
![Switch to Sources Tab](https://cdn-images-1.medium.com/max/3840/1*qfDPoWvoyx2JIJAaiM1dJw.png)

3. Click the **»** button and select **Snippets**.
![Select Snippets Option](https://cdn-images-1.medium.com/max/3840/1*aIydbfFbSkUhWn9euYw0RQ.png)

4. Now click **New snippet** to add a snippet. Give a meaningful name to the snippet. I am giving mine **darkTheme**.
![Add New Snippet](https://cdn-images-1.medium.com/max/3866/1*UAqI5dTvUL2xziOEEWGQvQ.png)

5. Now copy the below code from the [**gist**](https://gist.github.com/ganeshkumarm1/69039d06017c188b307764455586860b) and paste it in the editor. Now press **Ctrl + S** to save the changes
![Javascript Code for Dark Theme](https://cdn-images-1.medium.com/max/9440/1*pPg1BYw1r8pirhLmLILtaA.png)

6. Open any medium article and open the snippet by following the above steps.

7. Right-click on the snippet and select **Run**
![Run the snippet](https://cdn-images-1.medium.com/max/3840/1*FuHfA715QTMmlzGKDinI2g.png)

8. Voila, Now you can read Medium articles with Dark Theme.
![My [article ](https://medium.com/javarevisited/mos-algorithm-range-queries-made-easy-6c35047369ca)with and without Dark Theme](https://cdn-images-1.medium.com/max/7496/1*vYX3AfrXmL79rzegGnwX3w.png)*My [article ](https://medium.com/javarevisited/mos-algorithm-range-queries-made-easy-6c35047369ca)with and without Dark Theme*

## Conclusion

And there you have it, your Medium in Dark Theme. Currently, Chrome doesn't have an option to run the script automatically but I hope we get the option in the future. Thank you for reading, I hope you found this article helpful!

[Linkedin ](https://www.linkedin.com/in/ganesh-kumar-m-47b876111/)| [Github](https://github.com/ganeshkumarm1)
Minimal Switch in Flutter
Tags: flutter, widget, switch, ui
Published: 2021-01-29 14:29:42

In this article, we are going to create a minimal custom Switch Widget in Flutter. Flutter provides a built-in **Switch Widget** which looks simple. We are going to create our own **Flat Style** switch widget.

### The switch has two parts:

* The base

* The knob

We will start writing code for the base and the knob separately.

## Base

The base is nothing but the background of the switch which is in a **rounded rectangle** shape.

![Widget for Switch Base](https://cdn-images-1.medium.com/max/3208/1*4tn3qxEf3qEOtvIaXJ40kg.png)

1. **AnimatedContainer**vis used instead of the container because we are going to add animations when the switch is turned ON and OFF.

1. **widget.value** holds either **true** or **false** which represents whether a switch is **ON** or **OFF** respectively

## The Knob

The knob is the **circular** button inside the base that we use to toggle the state of the switch.

![Widget for Switch Knob](https://cdn-images-1.medium.com/max/4264/1*0VUtnsZhd1Zm-Pj0jALP1w.png)

1. **AnimatedAlign** is used to animate the movement of the switch when the user clicks it.

The final output looks as follows:

![Final Output](https://cdn-images-1.medium.com/max/2000/1*-VpT6_RrlEAM3knJLfkVug.gif)

Take a look at the below Gist to view the full code with functionality:

{% gist https://gist.github.com/ganeshkumarm1/17feb594a0d83b58b5f92e10232fba42 %}


## Wrapping Up

Well, that’s everything! It’s a short and sweet tutorial but I hope you found it helpful.

[Linkedin ](https://www.linkedin.com/in/ganesh-kumar-m-47b876111/)| [Github](https://github.com/ganeshkumarm1)