teleren/devto huggingface dataset:
Node.js REST API with Docker, Redis and MongoDB
Tags: node, mongodb, redis, docker
Published: 2020-04-26 14:51:50

Hi guys, this is my first post and I want to share a simple Node.js REST API (Express) that includes Docker, Redis and MongoDB.

You can run this project with docker-compose, we won't explain anything about it but you refer these links [Docker](https://docs.docker.com/install/) and [Docker Compose](https://docs.docker.com/compose/install/). Check the repo link at the end to be able to run the GitHub project.

In the file api.js, we use mongoose to connect to MongoDB server:
```javascript
mongoose.connect(`mongodb://${process.env.MONGO_INITDB_ROOT_USERNAME}:${process.env.MONGO_INITDB_ROOT_PASSWORD}@${process.env.MONGO_CONTAINER_NAME}/${process.env.MONGO_INITDB_DATABASE}?authMechanism=SCRAM-SHA-1&authSource=admin`,
    { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true }
, (err) => {
    if (err) {
        console.log('could\'t connect to Mongo DB ', err);
    }
});
```

Inside libs/redis-client.js you can see the Redis connection:
```javascript
const redis = require('redis');
const { promisify } = require('util');
const client = redis.createClient(process.env.REDIS_URL);

client.on("error", (error) => {
    console.error(`Error to connect Redis: ${error}`);
});
```

Then let's use it:
mongoose -> api/routes/users.js. (Check User schema inside models/user)
```javascript
// retrieve users
let users = await User.find({}).lean().exec();
```

redis -> api/routes/users.js.
```javascript
// retrieve user
const rawData = await redisClient.getAsync(req.params.email);
// save user
await redisClient.setAsync(req.params.email, JSON.stringify(user));
```

The repo is available at: [https://github.com/renacargnelutti/express-mongo-redis](https://github.com/renacargnelutti/express-mongo-redis)

I hope you enjoy the post!
Let me know any question.
Short Circuit Evaluation with React
Tags: react, javascript, beginners
Published: 2020-04-26 17:06:13

I've been playing with React for several months now. I love it. Reusable components makes front end developing so much easier and enjoyable. Rendering these components using conditional rendering is something I enjoy coding, and I'm not sure why. It's not hard, it's sometimes not easy but I like it regardless. In this blog post, I'm going to show you how to render a component using the "logical `&&`" method.

Let's consider this code:

```js
import React, { useState } from 'react'
import Welcome from '../components/Welcome'

function About() {

  const [showWelcome, setShowWelcome] = useState(false)

  return (
    <div>
      {showWelcome ? <Welcome /> : null}
    </div>
  )
}

export default App
```
The code above is a crude illustration of a homepage. If a user is logged in, we want to greet them by rendering `<Welcome />`. If the user isn't logged in, we don't want to show anything. 

So, in between the `div`s we have a ternary operator. A ternary operator is basically a shorthand for an `if... else` statement. 

`if` `showWelcome` is `true` then render `<Welcome />` or `else` render nothing.

But there's a simpler way to do this using "logical `&&`". Using the same logic, we can code the following:

```js
{showWelcome && <Welcome />}
```

Wait a minute 🧐. 

At first, it may not make sense. It didn't for me. Let's think about. The `&&` logical operator means that both conditions on either side of it have to be met in order for it to be `true`. Right now, as the code stands, `showWelcome` is `false` because that's what it's initially set at by `useState`. So nothing, or `null`, would be rendered. If it were set to `true`, however, both conditions would be successfully met and then render `<Welcome />`. 

I thought this was a clever way of rendering a component if there wasn't a need for an `else` statement. If you do need to render one component or another, it's best to use a normal ternary operator as shown in the first code block!
Twilio Hackton: getting started late in the game
Tags: twiliohackathon, wecoded
Published: 2020-04-26 17:15:18

Happy Sunday!!!

When I read about the twilio Hackton weeks ago I wanted to be part of it, but pandemic life happened and I forgot about it.
Yesterday my dear friend Corbin mentioned that to be, and since I want to apply for the Twilio Hatch program, that would be a great experience and addition to my resume.

The challenge is, I have 4 days!
I enlisted my brothers to help me brainstorm.
I got a simple yet usefull idea.

Can I do it?
Maybe!
 Let's see how it goes and wish me lucky!
Easily remove or extract the audio from a video with ffmpeg
Tags: ffmpeg, productivity, video, linux
Published: 2020-04-26 17:42:11

{% youtube FUqkMWDhWFk %}

It turns out removing the audio from a video is very easy with FFMPEG!

To remove the audio from a video:
```sh
ffmpeg -i video.mp4 -c:v copy -an out.mp4
```
The `-an` option will completely remove the audio from a video, and since we're just copying the video codec as is, this most likely will only takes seconds.

To extract the audio from a video:
```sh
ffmpeg -i video.mp4 -vn audio.wav
```

As you might have guessed, the `-vn` option will remove the video stream from the output, leaving only the audio. In this case, I'm re-encoding the audio as WAV, as that is a very good encoding to work with in terms of further processing.
Send API response directly to a variable using hooks.
Tags: javascript, webdev, react, beginners
Published: 2020-04-26 18:11:06

We will be cruising through the following topics
- What the heck is SWR?
- Usage of SWR
- What if there are multiple endpoints?

## What the heck is SWR
This is an awesome library for remote data fetching.
The name “SWR” is derived from `stale-while-revalidate`, an HTTP cache invalidation strategy popularized by RFC 5861.

SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.

You can read more about SWR [here](https://swr.now.sh/).

## Usage of SWR
To demonstrate the usage, I will be taking an example which involves the use of the following [API](https://covid19.mathdro.id/api/)

For instance, let's assume we want to load [https://covid19.mathdro.id/api/](https://covid19.mathdro.id/api/) into a variable.
Usually, we use `axios` library inside `useEffect` hook and store the data using a state created by `useState` hook.

But now, SWR simplifies all your hard work into one command.
```js
const { data,error } = useSWR(
    "https://covid19.mathdro.id/api/",
    url => fetch(url).then(_ => _.json())
  );
```

Now the `data` variable contains the response fetched from the API endpoint. The `console.log(data)` looks like this.

![Code example](https://dev-to-uploads.s3.amazonaws.com/i/m5qyzwzd771yh3uq6gr0.png)

Wow, sounds perfect right 🙌🏻

## What if there are multiple endpoints?
Now you may be wondering 🤔 what if there are multiple endpoints you need to get data from, how to name the variables `data` and `error`.

We can name them in the way shown in the below snippet to overcome this problem.
```js
const { data: generalDetails, error: generalDetailsError} = useSWR(
    "https://covid19.mathdro.id/api/",
    url => fetch(url).then(_ => _.json())
  );

const {data: dailyData, error:dailyDataError} = useSWR(
        "https://covid19.mathdro.id/api/daily",
        url => fetch(url).then(_ => _.json())
    );

const {
    data: covidCases,
    error: covidCasesError,
  } = useSWR("https://covid19.mathdro.id/api/confirmed", (url) =>
    fetch(url).then((_) => _.json())
  );
```

Now you can use them as different variables.
I am not inserting the images of the log statements in the console, because these responses are enormous.

Hope you enjoyed the article.
Peace ✌🏻,
Rohith Gilla
A cool new progress bar for python!
Tags: python, showdev, inthirtyseconds, sideprojects
Published: 2020-04-27 20:25:37

Hello!

I'm the author of [alive-progress](https://github.com/rsalmei/alive-progress), a new kind of Progress Bar for python like you've never seen, with real time throughput, eta and very cool animations!

It's also very easy to use and feature-packed, take a look!

![animating](https://raw.githubusercontent.com/rsalmei/alive-progress/master/img/alive-main.gif)

There's a plethora of builtin spinner styles to choose from!

![spinners](https://raw.githubusercontent.com/rsalmei/alive-progress/master/img/showtime-spinners.gif)

And you can easily create your own, there's builtin support for several special effects like frames, scrolling, bouncing, delayed and compound spinners! Get creative!

Also bar styles!

![bars](https://raw.githubusercontent.com/rsalmei/alive-progress/master/img/showtime-bars.gif)

To install, just:

```bash
$ pip install alive-progress
```

That's it, you're good to go!

More details in [alive-progress](https://github.com/rsalmei/alive-progress), enjoy!

Kind Regards,
Rogério.
Calculate the length of the opposite of a right triangle
Tags: help
Published: 2020-04-26 20:56:38

Hiya, I am trying to solve something but it's driving me mad, please save me, no this is not math homework I am 30 years old.

I have this triangle here:

Hypot = 60
Adjacent = 30
Opposite ??

lets give them nice names 
Hypot = C
Adjacent = A
Opposite = B

I do not know the angles apart from that this is a right angle triangle.

What are the steps to solve this?

I am JavaScript centric so code in this language or explanations in code would be super! (math is not my strongest suit sometimes)
Sağ Tık Eklentisi(Yönetici olarak çalıştır, run as root)
Published: 2020-04-28 17:19:42

Bazı durumlarda yetkiden dolayı dosya işlemleri yapamayız. Bunun için bazı işlemleri ya komut satırından yönetici olarak yapmamız gerekir ya da "sudo thunar" komutu ile pencereyi yönetici olarak çalıştırıp yapmamız gerekir. Aşağıda yapacağımız sağ tık eklenti ile komut satırı açmadan sağ tık ile yönetici yetkili pencere açabiliriz. 
Bunun için;
Dosya Yöneticisini açtıktan sonra düzenle>Özelleştirilmiş eylemleri yapılandır'a tıklayınız. 
Ve aşağıdaki bilgileri giriniz.

![](https://i.ibb.co/YZzRpMw/Screenshot-2020-04-28-00-32-22.png)
![](https://i.ibb.co/qByx2tB/Screenshot-2020-04-28-00-44-51.png)
Ayarları yaptıktan sonra aşağıdaki gibi gözükmesi gerekmektedir.(Simge seçeneğinden istediğiniz simgeyi de seçebilirsiniz.)
![](https://i.ibb.co/x61sVRc/Screenshot-2020-04-28-00-31-39.png)
![](https://i.ibb.co/8NQ1ssr/Screenshot-2020-04-28-00-32-49.png)
![](https://i.ibb.co/Ypw3Y0C/Screenshot-2020-04-28-00-33-20.png)
Şifrenizi girdikten sonra thunar üzerinde işlemlerinizi yönetici(root) olarak yapabilirsiniz.
Essential Javascript for the React Developer
Published: 2020-04-27 02:00:12

Pt. 1 of 4

Learning a front-end javaScript framework /library is essential for developers as it speeds up the production process while minimizing the lines of code. For JavaScript developers, the most common frameworks are React.js, Angular, and Vue.js. Today, we’re going to focus our attention on React.js.

Before jumping headfirst into React, it is important that you have a very solid foundation in JavaScript as there are several concepts that all burgeoning react developers must become familiar/comfortable with to get the most out of this useful tool.

Var vs. Let vs. Const

ECMA6 introduced a new way to declare variables that differs from the traditional way variables are declared using the “var” keyword, the previous js standard. It is highly advised that javascript developers use “let” and “const” keywords as opposed to using “var” when declaring variables. 

The reasoning behind this is that ‘let’ utilizes “function” scope while ‘let’ and ‘const’ use “block” scope. This is an important distinction as block scoping is preferred because we don’t want to give access to our variables outside of a defined block.

function helloWorld() {
  for (var i = 0; i < 5; i++) {
    console.log(i)
  } 
  console.log(i)
}
helloWorld()

In the previous example, we have a helloWorld function. Within that function is a for loop that increments by one as long as ‘i’ is less than 5. In this example, we have 2 console logs, one within the function scope and the other within the for loop block. Using var to declare our variable allows the 2nd console log to have access to the ‘i’ variable within the for loop, which as we described previously, is not ideal. Now, let’s take a look at the same example, but this time we’ll use the let keyword.

function helloWorld() {
  for (let i = 0; i < 5; i++) {
    console.log(i)
  } 
  console.log(i)
}
helloWorld()

Using the let keyword, the 2nd console log should throw an error as the i variable will only be accessible within the for loop, as let is block scoped, not function scoped.

That leaves us with “let” and “const” as our preferred methods of declaring variables. “Const” is used when we have a variable that will not change and “let” if a variable will be reassigned at a later time, therefore, const would not be a good choice for an incrementing for loop.

Objects

Properties and Methods
In javascript, objects are collections of related data consisting of ‘key-value’ pairs in the for of variables, also known as properties, and functions which are referred to as methods.

Dot and Bracket Notation
When we know which particular property or method we’d like to access, dot notation works well.
let dog = {
  name = "Fido",
  age = 3,
  color = "black",
  owner = "Kevin"
}
dog.owner = "Richard"

On the other hand, we use bracket notation when we are unsure of the property or method we want to be able to access.

let dog = {
  name = "Fido",
  age = 3,
  color = "black",
  owner = "Kevin"
}
let newOwner = 'owner'
dog[newOwner.value] = "Richard"

In our next installment, we’ll be taking a look at the ‘this’ keyword.
Paid education: the seed for classism
Tags: covid, education, coursera, university
Published: 2020-04-27 03:24:02

I try, I swear it. But when I come across **Coursera**, **Lynda**, and other platforms of eLearning... oh, it pisses me off.

The best part comes when you talk to them about the Free Online University, and they say: *"there is a lot of information on the internet, you do not need to pay if you want!"*. Well, let me tell you, please, one thing:

  - if you have time to put order to the chaos you ignored till yesterday, and...
  - if you do not mind to study something that will not provide you with any official (by the State and the Law) homologation or accreditation...

...then yes, pick a course on Coursera and fill better with yourself.

But, honestly, I can see, with these little things, why universe is smaller than I used to think.

Is it so difficult to understand the relevance of sharing what we know, as a collective, to be trustable?

Ok, we conform with this situation, where each person uses the law that that bastards (sorry, politicians, but you have not yet solved free education, you are just bastards opportunists) created to take **profit** from and **advantage** of the rest of the society.

I feel sad to check that **unefficiency** and inoperance are key for capitalism to keep itself healthy with mediocre leaders, in the economical, educational, political.

People that need to exploit others ignorance to fit in society as they think they deserve.

Remember that, when I share an apple, I lose one apple. When I share a knowledge, I do not lose the knowledge.

Of course, elitism, classism, imposed ignorance or different ways of social supremacy, like the economy tries to, are too fashion to be overcome.

We are only at 2020. Covid-19 is not enough to see that we are already rich, that it is our poor mentality of life what makes extreme poverty and extreme wealth, dirty the natural identity of human beings.
Gabut Mode On: Bikin Aplikasi Inventaris Kosan (Bagian 2 - Analisa Tipe Data)
Tags: webdev, javascript, beginners, bahasa
Published: 2020-04-27 11:34:56

## Halo lagi.

Pada bagian [sebelumnya](https://dev.to/farishan/gabut-mode-on-bikin-aplikasi-inventaris-kosan-bagian-1-rencana-591a), saya sudah sampai ke fitur apa saja yang akan masuk ke dalam MVP. Yaitu:

1. Mencatat barang-barang
2. Menampilkan daftarnya
3. Menghapus data barang

### TL;DR
Mau yang to the point? langsung scroll ke paling bawah aja.

---

Kata "barang" menjadi poin utama di aplikasi ini. Barang ini adalah data, yang tipe/bentuknya baru mau saya pikirkan. Yang paling sederhana itu _string_.

```javascript
  let barang = 'meja'
```

Tapi untuk berjaga-jaga kalau user minta yang aneh-aneh, misalnya mau mencatat harga barang tersebut, masuk ke daftar barang kapan, dan informasi tambahan lainnya, aneh kan kalau masuk ke string yang sama?

```javascript
  let barang = 'meja | 100 ribu'
  // atau
  let barang = 'meja, 100.000'
```

Selain aneh, malah ribet jadinya. Harus motong-motong string. Gimana kalau tipe data barang itu _array_?

```javascript
  let barang = ['meja'] // gini?
  // kalau pakai informasi tambahan gimana?
  let barang = ['meja', 100000] // gitu?
```

Lumayan keren sih, tapi gimana developernya tau kalau 100000 itu harga barangnya? Lupakan array. Coba string aja semua, tapi jelas.

```javascript
  let barang = 'meja'
  let hargaBarang = 100000
```

Sejauh ini bentuk data di atas yang ternyaman untuk dipahami.

---

Bagaimana kalau masih ada bentuk data yang lebih nikmat?

Barang itu objek. Ada atributnya. Nama barangnya apa. Harganya berapa. Pasti lebih cocok kalau tipe datanya _object_ dong? Nih:

```javascript
  let barang = {
    nama: 'Meja',
    harga: 100000
  }
```

Lebih enak lagi kalau di-bahasa-inggris-in. Bener deh. Nih:

```javascript
  let thing = {
    name: 'Meja',
    price: 100000
  }
```

Kenapa 'Meja' ga jadi 'Table'? 
Karena yang akan masukin namanya bukan saya sebagai developer (yang _keminggris_) ini, tapi user. Hak user mau masukin barang dengan bahasa apa kesitu. Tapi kalau object dan _attribute_/_properties_-nya, itu saya usahakan selalu bahasa inggris. Lebih cocok sama _syntax_ aja. Namanya juga selera. Maafkan ya. Hehe.

---

## Kesimpulan. Seadanya.

Sudah ditetapkan bahwa barang adalah sebuah _object_, dengan bentuk tunggal seperti ini:

```javascript
  let thing = {
    name: 'Meja',
    price: 100000
  }
```
Sedangkan untuk bentuk jamaknya, sudah pasti array. Jadinya _array of objects_. 

```javascript
  let thing = {
    name: 'Meja',
    price: 100000
  }

  let thing2 = {
    name: 'Kursi',
    price: 20000
  }

  let things = [thing1, thing2]
```

---

Demikian analisa yang seadanya ini. Jalan panjang di depan akan selalu beraroma array of objects. Jangan pusing dulu karena masih bagian 2, sampai jumpa di bagian [selanjutnya](https://dev.to/farishan/gabut-mode-on-bikin-aplikasi-inventaris-kosan-bagian-3-setup-2hek). Dadah.
Using dotenv to manage environment variables in Nodejs
Tags: node, webdev, javascript, codenewbie
Published: 2020-04-27 14:23:46

#### Have you ever faced any of these scenarios: 
1. You have some dynamic values in your code which you don't want to hardcode. 
2. You have API Keys in your opensource project which you obviously don't want to push to GitHub
3. You have some values in your code that depend on what environment you are building your code for.

*If you fall into any of the above-mentioned scenarios I have a got a solution for you.* 😃

##### Node Environment Variables Using dotenv

In Node, there is something called environment variables which you can see by logging `process.env`. 
For example, you can set a `NODE_ENV` variable which is basically used to define what environment you want to build your code for.
```javascript
process.env.NODE_ENV='dev'
```
Then further use this variable to generate different builds.

Instead of setting these environment variables ourselves, we will be using the `dotenv` package.

```bash
$ npm i --save dotenv 
```

Once dotenv is installed let's create a `.env` file in the root of our project 
and add the `PORT` variable into it.

`.env`
```
PORT=3000
```

Now let's see how we can use this `.env` file in our code. We will create a basic node server and use `PORT` defined in our `.env`.
NOTE: If you do not understand the server part, don't worry. It's not important to understand how to use `dotenv`.

`app.js`
```javascript

require('dotenv').config()
const http = require('http')

const server = http.createServer(callback)

server.listen(process.env.PORT || 4000)

```

### Let's see what we just did here. 
We basically created a server in node and the server is listening on the port defined in our node environment variables. If it's not defined there we give it a fallback value.
Now the value of this `PORT` can be different depending upon where you deploy your server be it Heroku or something else.

dotenv is loaded first and it has a config function that basically reads our `.env` file and populates the environment variables.

You can use dotenv to store your server configuration or use it with webpack to define global variables using webpack's definePlugin.

PS: 
1. You need to load your env config once in your webpack config or in your entry file and also never commit your `.env` files
2. In order to maintain multiple `env` files each for different environment you can use `dotenv-flow` package. You must set your `process.env.NODE_ENV` variable first as `dotenv-flow` uses that variable to decide which env file to pick. https://www.npmjs.com/package/dotenv-flow

If you face any problem in implementing this, let me know in the comments. I will be happy to resolve.

Thanks for reading 😀
Money Is Not Everything
Tags: work, personal, money
Published: 2020-04-27 14:46:44

I am currently searching for new work. 
I tend to phrase it as "looking for new opportunities" or "challenges". 
But let's call it as it is. **I am on a job hunt.** 

## The money question 

Quite often I find myself in an interview baffled by a question about my financial terms.
Some interviewers require a range, some a single number. 
It is easier if the job ad has the offered range specified from the beginning, but only a little.

Having been a professional software developer for almost 15 years (i.e. since I started my [self-employment](https://www.infoza.pl) in 2006) I am not shy to ask for the top offered value. 
Unfortunately there is a catch with this tactic.

I have found that MANY companies LIE about the actual salary range they are capable or willing to pay. 
I have been turned down a few times because my salary expectations were said to be too high. 
The recruiters wrote: "we value your expertise, and we would like to have you on board, but you a) have too much of experience and we would not be able to challenge you enough or b) we cannot meet financial expectations". WTF, I ask you?

I have since came to realise, that I do not want to work for a company that misleads its prospective employees.
Just do not waste time.

> I guess I needed to get this out of my chest and in the open.

In both of my previous jobs I got to enjoy the feeling of not having to work at all, because the people there and the things we got to do, made it seem like so much fun.
The most important thing is that we bonded and supported each other. This allowed everyone to grow. **No money can buy that!** 

# Tell me what you think is fair

That is my default answer now.

Money is important. It is the means with which we can support our goals and dreams, but **it is not the deciding factor**.
As it turns out - it never has been!

I am sure we can come to a mutually beneficial arrangement if we just keep honest and open about our expectations and capabilities.

Now, Let's talk how we can work together!

> original post: https://www.tegh.net/misc/money-is-not-everything/