teleren/devto huggingface dataset:
How to return a value from an asynchronous function (JavaScript)
Tags: javascript, webdev
Published: 2021-08-03 13:14:39

Consider the following code. Suppose, you have a function, and what you want it to do is return a certain value after 5 seconds. So, you do this.

```javascript
function getValue() {
    setTimeout(() => {
        return 42;
    }, 5000);
}
```

This won't work. Why? Because you're really returning from the callback function that is acting as the first argument of `setTimeout`. Essentially, what you're doing is this - 

```javascript
function getValue() {
    function cb() {
        return 42;
    }

    setTimeout(cb, 5000);
}
```

As you can see, `getValue` isn't returning anything here.

You might face the same problem while making other similar asynchronous calls, like using the `fetch` API (or other Promise-based API) for example.

```javascript
function getUserList() {
    fetch("users.json")
        .then(r => r.json())
        .then(d => { return d })
}
```

You can take multiple approaches, but I'm just going to talk about the most simple one - building your own Promise using the constructor function and returning it. Let's try to modify the `getValue` function using Promises.

```javascript
function getValue() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(42);
        }, 5000);
    })
}
```


A Promise constructor, if you recall, takes a callback function as its only parameter, which in turn takes in two callbacks, resolve and reject, which determine if the promise was fulfilled or rejected, accordingly. If you wanted, you could modify the code above to include a rejection criterion:

```javascript
function getValue() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
        if(Math.random() > 0.5)
            resolve(42);
        else
            reject(-1);
        }, 5000);
    })
}
```
> A `Promise` is an object that will hold a value in the future.

And now that the function works this way, you can easily call it with an `async`/`await` combo to make it look like it was synchronous. (The `await` keyword pauses the program execution until the Promise it's acting upon is settled)

```javascript
(async function () {
    try {
        // promise resolution
        let meaningOfLife = await getValue();
        console.log(meaningOfLife);
    }
    catch (e) {
        // promise rejection
        console.error(e);
    }
})();
```

> I've wrapped it in an immediately-invoked function expression (IIFE), but you could easily do it with a regular `async` function.

Hope that helped!

[Photo by Adi K from Pexels]
How to Create A Simple API: ExpressJS
Published: 2023-04-23 11:28:17

---
title: How to Create A Simple API: ExpressJS
published: true
date: 2021-08-03 13:11:16 UTC
tags: 
canonical_url: https://chrisdevcode.hashnode.dev/how-to-create-a-simple-api-expressjs
---

Express JS is a backend framework that runs on Node JS.

It really comes in handy when creating backend microservices for our applications.

I will take you through simple steps in creating a simple API with Express.

## Installing dependencies

This should be the simplest of all:

On the project root, open up your terminal/CMD and install express using the following command:

```
npm install express

```

## Create a server file

While still on the root of your project, create a JavaScript file; `app.js`

## Creating A server:

On the newly created file (app.js), let's create a simple server:

```
// importing express
const express = require('express')

// creating a instance of express
const app = express();

```

After bringing express into the app, let's create a simple server:

```
app.listen(5000, console.log('App Running On Port 5000!'))

```

[The .listen() method binds and listens for connections on the specified host and port.](http://expressjs.com/en/5x/api.html#app.listen)

Your file should now have the following code:

```
// importing express
const express = require('express')

// creating a instance of express
const app = express();

app.listen(5000, console.log('App Running On Port 5000!'))

```

On your terminal, run the server using:

```
node app.js

```

![run1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627993632364/uETsDecIQ.png)

When you see the message: 'App Running On Port 5000!' on your terminal, well! you are good to GO.

## Getting the API

Well normally, your backend application will be sending data to a client site, let's create a simple server.

On the same folder, create a new file "data.js" with the following data:

```
const colors = [
  {
    color: 'red',
    value: '#f00',
  },
  {
    color: 'green',
    value: '#0f0',
  },
  {
    color: 'blue',
    value: '#00f',
  },
  {
    color: 'cyan',
    value: '#0ff',
  },
  {
    color: 'magenta',
    value: '#f0f',
  },
  {
    color: 'yellow',
    value: '#ff0',
  },
  {
    color: 'black',
    value: '#000',
  },
]

module.exports = colors

```

let's write the code to server the data from the file from our server:

```
// getting the data file
const color = require('./data')

// serving data
app.get('/api/colors', (req, res) => {
    res.send(color)
})

```

First, we bring in the data file and create the route for getting the data.

```
// importing express
const express = require('express')

// getting the data file
const color = require('./data')

// creating a instance of express
const app = express();

// serving data
app.get('/api/colors', (req, res) => {
    res.send(color)
})

app.listen(5000, console.log('App Running On Port 5000!'))

```

Run the server and go to http://localhost:5000/api/colors on your browser.

![results.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627995834660/69ZwbpgZY.png)

Wasn't that simple!
Create a Netflix clone from Scratch: JavaScript PHP + MySQL Day 8
Tags: javascript, webdev, tutorial, php
Published: 2021-08-03 12:49:09

Netflix provides streaming movies and TV shows to over 75 million subscribers across the globe. Customers can watch as many shows/ movies as they want as long as they are connected to the internet for a monthly subscription fee of about ten dollars. Netflix produces original content and also pays for the rights to stream feature films and shows.

In this video,we will  create Database Class

{% youtube iXNKCWSKq9Q %}

In this video,we will create a method to make Database class accessible

{% youtube Rv_9mhF0nKQ %}

If you like my work, please consider
[![Buy me a coffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jm11knj7d8zwcvo150q2.png)](https://www.buymeacoffee.com/cglikpo)
so that I can bring more projects, more articles for you

If you want to learn more about Web Development, feel free to [follow me on Youtube!](https://www.youtube.com/c/ChristopherGlikpo)
Get all the documents out of a collection in MongoDB
Tags: mongodb
Published: 2021-08-05 01:11:03

---
title: Get all the documents out of a collection in MongoDB
published: true
date: 2021-08-03 12:48:53 UTC
tags: MongoDB
canonical_url: https://donaldfeury.xyz/get-all-the-documents-out-of-a-collection-in-mongodb/
series: "Small Bytes of MongoDB"
---

For a full overview of MongoDB and all my posts on it, check out my [overview](https://donaldfeury.xyz/introduction-to-mongodb/).

The most simple way to read all the documents out of a collection in MongoDB is to use the `find` method on a collection.

Let's say you have a collection in your database called `users`. If you wanted to read all the documents out of it, you can do this:

```
db.users.find()
```

This will return a cursor that you can iterate over to get each document from the collection. Keep in mind, most tooling you can use to interact with your data will automatically do some iteration for you.
Building a collaborative community through Evrone meetups
Tags: eventsinyourcity, writing, webdev, programming
Published: 2021-08-03 12:39:43

For IT companies, meetups are an important tool for promotion, finding partners and clients, learning, and much more. The speakers’ reports help spread and sell your expertise, and among the participants, you can find many potential partners.

[Read an article](https://evrone.com/evrone-meetups) on how to train your employees and keep your audience while holding online and offline events.
Create a Wordcloud of News Headlines in Python!
Tags: python, programming, beginners, sideprojects
Published: 2021-08-03 12:33:23

###Today, I'll be showing you a simple way to make a wordcloud of news headlines in python!

*********
If you haven't read [this tutorial](https://dev.to/code_jedi/scrape-news-headlines-with-python-1go6) explaining how to scrape news headlines in python, make sure you do.
In summary, here's the code for scraping news headlines in python:
```python
import requests
from bs4 import BeautifulSoup

url='https://www.bbc.com/news'
response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')
headlines = soup.find('body').find_all('h3')
for x in headlines:
    print(x.text.strip())

```

To create a wordcloud out of these news headlines, first import these 2 libraries beside the libraries needed to scrape our news source:
```python
import requests
from bs4 import BeautifulSoup
from wordcloud import WordCloud #add wordcloud
import matplotlib.pyplot as plt #add pyplot from matplotlib
```
Next, replace
```python
for x in headlines:
    print(x.text.strip())
```
with
```python
h3text = ''
for x in el:
    h3text = h3text + ' ' + x.text.strip()
```
* _This will first define the "h3text" string, then add every news headline to the string and seperate them with spaces._

********
**Before we make the wordcloud, you can check the news headlines by using `print(h3text)`**

********
#### To make the wordcloud, add these lines of code to the end of your script:
```python
wordcloud = WordCloud(width=500, height=500, margin=0).generate(soup.get_text(h3text))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.margins(x=0, y=0)
plt.show()
```
**Let me explain...**
* _First create a wordcloud(well, more like a box in this case) sized 500 by 500._
* _Next, our wordcloud will be created using "plt.imshow()" (`interpolation='bilinear'` just makes the words in the wordcloud easier to read)._
* _`plt.axis("off")` and `plt.margins(x=0, y=0)` make sure our wordcloud isn't displayed as a graph._
* _Finally, our wordcloud is displayed using "plt.show()"._

**********
####If you run your code, your wordcloud should look something like this:
![wordcloud](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jrw1zwfc14j7mkin3u12.png)
_Of course, your wordcloud will probably be quite different since news headlines change all the time._ 

***********
### That's it for this Tutorial/Mini-project!

*************

*************

If you're a beginner who likes discovering new things about python, try [my weekly python newsletter](https://rebrand.ly/Python_Explore)

![Newsletter thumbnail](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d3tzwrb1iw2wesc8gdc5.png)
 
***********
Byeeeee👋
Scrape News Headlines With Python in <10 Lines of Code!
Tags: python, programming, beginners, sideprojects
Published: 2021-08-03 12:29:45

#### Today I'll show you a way to scrape news headlines in python in under 10 lines of code!

***********
## Let's get started...
First of all, make sure to import these libraries at the beginning of your python script:
```python
import requests
from bs4 import BeautifulSoup
```

*********
For this tutorial, I'll be using [BBC news](https://www.bbc.com/news) as my news source, use these 2 lines of code to get it's url:
```python
url='https://www.bbc.com/news'
response = requests.get(url)
```

*********
**Now we're ready to scrape using BeautifulSoup!**

Head over to [BBC news](https://www.bbc.com/news) and inspect a news headline by right clicking and pressing inspect.
As you'll see, all news headlines are contained within an "h3" tag:
![h3 tags](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yk0yvi5qqo9cofx0ddwg.png) 

**********
Now add these 4 lines of code to scrape and display all the h3 tags from BBC news:
```python
soup = BeautifulSoup(response.text, 'html.parser')
headlines = soup.find('body').find_all('h3')
for x in headlines:
    print(x.text.strip())
```
* _First, we define "soup" as the innerHTML of the BBC news webpage._
* _Next, we define "headlines" as an array of all h3 tags found within the webpage._ 
* _Finally, paddle through the "headlines" array and display all of it's contents one by one ridding each element of it's outerHTML using the "text.strip()" method._

***********
**Full code**
```python
import requests
from bs4 import BeautifulSoup

url='https://www.bbc.com/news'
response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')
headlines = soup.find('body').find_all('h3')
for x in headlines:
    print(x.text.strip())
```

Now if you run your script, your output should look something like this:
![h3 results](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/41118qoy3tgz99q3hge5.png)

*************

Byeeeee👋
Day 9 - Some failed problems
Published: 2021-08-03 12:28:00

###Day 9: Some failed problems
Tried 2 problems:
1. https://leetcode.com/problems/interleaving-string - Few test cases failing
2. https://leetcode.com/problems/median-of-two-sorted-arrays/ - Time exceeded (O(n) vs O(log(n))

Not planning to check discussions as I was close. Bookmarking them and winding up for today

You can connect with me at &nbsp;
[LinkedIn](https://www.linkedin.com/in/abh1navv)
[Twitter/@abh1navv]
(https://www.twitter.com/abh1navv)
How I set up AWS Kubernetes Jenkins pipeline? 
Published: 2021-08-03 11:33:01

{% youtube ENNBdmNn4r0 %}

In this lab session I will be setting up Kubernetes jenkins pipeline on AWS.

This will be a long session but I will be setting up everything from the scratch.

Here are steps which we will go through  - 

1.  Setting up AWS EC2 Machine - First we need to set up EC2 machine where we will be installing the Jenkins along with Gradle, kubectl, eksctl, docker. We can not use t2.micro instance because we will need more CPU and memory to run Jenkins and Gradle.

2. Connect to EC2 machine - After starting the EC2 machine we will use the private key-pair file to connect to EC2 instance.

3. Install JDK - As we need to install Jenkins so we need to have JDK(https://adoptopenjdk.net/) pre-installed onto the EC2 machine. For this lab session I will be using adopt open JDK 11.

4. Install and Setup Jenkins - In this step we are going to install Jenkins and also going to the setup admin user 

5. Assign administrative privileges to Jenkins user - After installing and setting up the Jenkins on EC2 machine we need to assign root privileges so that we can execute Docker and Gradle commands inside the Jenkins pipeline

6. Install Docker - The next step would be to install docker so that we can create a docker image and push the docker image to docker hub

7. Install and Configure AWS CLI - After installing the docker we need to install and configure AWS CLI so that we can use EKSCTL to set up and start the Kubernetes cluster.

8. Install kubectl - Also along with EKSCTL we need to install Kubectl so that we can view the deployments and services

9. Install eksctl - Now we need to install eksctl so that we can set up and start the Kubernetes cluster without using AWS UI 

10. Add docker hub and GITHUB credentials - As we need to clone the github repo and push the docker image to docker hub we need to store credentials of github and docker inside Jenkins.

11. Jenkins script for stages - Once we are done all the above steps we are going to write the Jenkins pipeline scripts for all the stages
How to Render HTML string in a React component ?
Tags: react, html, javascript
Published: 2021-08-03 12:09:47

In this tutorial we will see how to render HTML string in a React component. 

Most of the rich text editor for react uses html for the formatting. So the data in the text editor is saved as string.
```javascript
"<p>some dummy <span>data</span></p>"
```

We cannot directly render this string, html tags will also get treated as raw string.

The easiest solution for this is to use **dangerouslySetInnerHTML**.

```javascript
<div dangerouslySetInnerHTML={{ __html: "<p>some data </p>" }} />
```
by using dangerouslySetInnerHTML, entire html in the string is preserved.
Other alternative would be to use a [html-react-parser](https://github.com/remarkablemark/html-react-parser) library.


Like this post?
Our Twitter : [@job_pick](https://twitter.com/job_pick) 
Our website : [jobpick.in](https://jobpick.in/)
Today's Daily Humor For Devs - Daily Developer Jokes
Tags: jokes, dailydeveloperjokes
Published: 2021-08-03 12:00:22

---
title: "Today's Daily Humor For Devs - Daily Developer Jokes"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
published: true
tags: #jokes, #dailydeveloperjokes
---

Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one.

![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e12597371ee1.png)

---

For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes).

### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too!

_This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit._

<!--
Joke text:
___Q:___ Why did the programmer come home crying?"

___A:___ His friends were always boolean him.
 -->
Presto Stantest Private Limited

Tags: testinginstruments
Published: 2021-08-03 11:38:28

PRESTO Redefining the Art of Quality Testing and India’s Premier Testing Instruments Manufacturers With an industry experience of over 38 years and National Award-Winning testing instruments manufacturing company and more than three decades, over 13000+ customers worldwide have used our products which are an epitome of Quality, Reliability and Accuracy.
Visit here: https://www.prestogroup.com
java.io.FileNotFoundException: Cannot find the schema file in the assets folder
Published: 2021-08-03 11:28:18

I am trying to test room database migration on robolectric . Robolectric version used 4.4. I am facing java.io.FileNotFoundException: Cannot find the schema file in the assets folder. Make sure to include the exported json schemas in your test assert inputs. See https://developer.android.com/training/data-storage/room/migrating-db-versions#export-schema for details

2021-08-03T17:50:07.733+0530 [DEBUG] [TestEventLogger]         at androidx.room.testing.MigrationTestHelper.loadSchema(MigrationTestHelper.java:320)
2021-08-03T17:50:07.733+0530 [DEBUG] [TestEventLogger]         at androidx.room.testing.MigrationTestHelper.createDatabase(MigrationTestHelper.java:152)
2021-08-03T17:50:07.733+0530 [DEBUG] [TestEventLogger]         at com.excelfore.esync.agent.test.PREH2_1259.sequence(PREH2_1259.java:64)
2021-08-03T17:50:07.733+0530 [DEBUG] [TestEventLogger]         at com.excelfore.esync.agent.test.support.TestBase.lambda$runTestSequence$8(TestBase.java:433)


Eventhough 1.json file present .

build.gradle :

javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/build/schemas".toString()]
}
}

sourceSets {
release.assets.srcDirs += files("$projectDir/build/schemas".toString())
}

testImplementation "androidx.room:room-testing:2.2.6"

Unit test code:

private static final String TEST_DB = "migration-test";

MigrationTestHelper helper = new MigrationTestHelper(InstrumentationRegistry.getInstrumentation(), ld + (MyDatabase.class.getCanonicalName()));
SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 1);

// Prepare for the next version.
db.close();

// Re-open the database with version 2 and provide
// MIGRATION_1_2 as the migration process.
db = helper.runMigrationsAndValidate(TEST_DB, 2, true, MyDatabase.MIGRATION_1_2);
Input needed 💬 Would  you want to do point-and-click API routing?
Tags: react, webdev, watercooler, startup
Published: 2021-08-03 11:16:47

We want to enable devs to start their backend in just a few clicks without any coding. Creating the API routing with point-and-click, consume large number of plug and play services, and have it live. Think of AppWrite/supabase 2.0.

If you are a front-end who doesn't want to deal with the backend for smaller projects, comment thoughts below or let me know if I can reach out for a quick (5 min) demo, and brief talk about your feedback (10 min) on Discord/GoogleMeets. It would be much appreciated as we are trying to validate the idea!
Object Detection on  WEB Real-Time 
Tags: javascript, deeplearning, datascience, machinelearning
Published: 2021-08-03 11:15:03

Object Detection cannot only be done with OpenCV but it can be integrated into the web for those that are into deep learning and have experience with web development, here is an Object Detection system which can detect object in real-time in Videos, Images and Web Cam, though will be adding updates to improve it performance and features, kindly check it out and give me feedback on it for improvement, the site consumes memory(GPU) because Tensorflow.js by default uses WebGL so for better experience it is better to use a PC, thanks 
link: https://j-od.netlify.app