teleren/devto huggingface dataset:
@PostConstruct and @PreDestroy in Spring
Tags: spring, java, postconstruct, predestroy
Published: 2020-10-06 03:24:35

@PostConstruct adds behavior at startup (after all dependency injection, constructors, and setters) and @PreDestroy adds behavior at shutdown (prior to destroying the bean instance, when a configurable application context is closed and if application shuts down normally. Not called for prototype beans). The annotated methods can have any visibility but must take no parameters and only return void.

```java
@PostConstruct
void populateCache() {
  ...
}

@PreDestroy 
void flushCache() {
  ...
}
```

Alternatively, the @Bean annotation has the initMethod and destroyMethod options:

```java
@Bean(initMethod="populateCache", destroyMethod="flushCache")
public Repository repository() {
  ...
}

```
Laravel 8 Ajax Form Submit with Validation
Published: 2020-10-06 03:22:42


Laravel 8 ajax form submit with validation. In this post, i will show from scratch on how to submit form using ajax and validate form data before insert into database.

In this post example, i will create laravel ajax contact form and submit form data using ajax without page reload. As well as validate form data before submit using jQuery validation library.

Note that, in laravel 8, the ajax code will submit form without reloading page laravel 8. If form data successfully validate and insert into database, it will shows success message.

### Laravel 8 Ajax Form Submit with Validation

Step 1 – Install Laravel 8 Application
Step 2 – Configuring Database using Env File
Step 3 – Create Model & Migration File For Contact Form
Step 4 – Create Routes
Step 5 – Creating Controller
Step 6 – Create Blade File For Contact Form
Step 7 – Start Development Server
Step 8 – Run Laravel 8 Ajax Form Submit with Validation App On Browser

[https://laratutorials.com/form-submit-using-ajax-in-laravel-8-with-validation/](https://laratutorials.com/form-submit-using-ajax-in-laravel-8-with-validation/ "https://laratutorials.com/form-submit-using-ajax-in-laravel-8-with-validation/")
Form Validation using jQuery in Laravel 8
Published: 2020-10-06 03:21:18


jQuery form validation in laravel 8. In this simple example post, i will show from scratch on how to use jQuery validation in laravel 8.

In this post example, i will create product add form and validate form data before submit using jQuery validation library. And as well as before store into database.


### Form Validation using jQuery in Laravel 8

Step 1 – Install Laravel 8 Application
Step 2 – Configuring Database using Env File
Step 3 – Create Model & Migration File For Product Add Form
Step 4 – Create Routes
Step 5 – Creating Controller
Step 6 – Create Blade File For Product Add Form
Step 7 – Start Development Server
Step 8 – Run Laravel 8 jQuery Form Validation App On Browser
[https://laratutorials.com/laravel-8-jquery-validation-tutorial-example/](https://laratutorials.com/laravel-8-jquery-validation-tutorial-example/ "https://laratutorials.com/laravel-8-jquery-validation-tutorial-example/")
Google v2 ReCAPTCHA In Laravel 8
Published: 2020-10-06 03:20:04


In this post, i will use google recaptcha package that name anhskohbo/no-captcha. And i will create contact us form. And will integrate google v2 recaptcha with contact us form in laravel 8 version.

Note that – Google ReCAPTCHA v2 validate form submission in laravel application. So, in this post, i will show how to integrate google ReCAPTCHA with laravel forms.


### How to Use Google Recaptcha in Laravel 8

Step 1 – Install Laravel 8 Application
Step 2 – Configuring Database using Env File
Step 3 – Install Google Recaptcha Package (anhskohbo/no-captcha)
Step 4 – Create Model & Migration File For Contact Us Form
Step 5 – Create Routes
Step 6 – Creating Controller
Step 7 – Create Blade File For Contact Us Form
Step 8 – Start Development Server
Step 9 – Run Laravel 8 Google V2 Recaptcha Validation App On Browser

[https://laratutorials.com/laravel-8-form-google-v2-recaptcha-validation/](https://laratutorials.com/laravel-8-form-google-v2-recaptcha-validation/ "https://laratutorials.com/laravel-8-form-google-v2-recaptcha-validation/")
Ngrok Intro
Published: 2020-10-06 03:15:58

In developing an app where I needed to have a public URL on the web, I came across Ngrok. Ngrok is a useful utility, which provides a publicly accessible web URL to any locally hosted application. In my case, a nodejs web app. It also has authentication for secure tunnel access.

 As the official site states, you can: 
- Run personal cloud services from your home
- Demo websites without deploying
- Build webhook consumers on your dev machine
- Test mobile apps connected to your locally running backend
- Stable addresses for your connected devices that are deployed in the field

**How it Works**
1. Run the local app, so that it can be accessed at your localhost.  Example: http://localhost:3000

2. Now with ngrok executable (available for different platforms like Mac, Windows, etc.) initiate a tunnel to the localhost on the desired port. We will see this detail in the upcoming sections.

3. Once ngrok sets up the tunnel, it provides a web-accessible URL.

4. Now share the publicly accessible url with the end-users who would hit the locally hosted application.
End users hit the web URL on the internet.

5. When the request arrives at the ngrok server (As the URL is in a subdomain of ngrok.com the requests will initially land to ngrok server), and it will resolve the URL to the app that it needs to tunnel to.

6. Ngrok forwards the request to the tunnel created in Step 2.

7. The forwarded request connects to the locally hosted app.

**Installation**

1. Create a free account on Ngrok to get an auth token for your account.

2. Download client library depending on your operating system.

3. Unzip the downloaded package.

4. Update the ngrok configuration file with your auth token by running `./ngrok authtoken {your-auth-token}` command on the terminal/command prompt.

5. After auth token gets updated, start the tunnel for your locally hosted applications.

6. Run `./ngrok http 80` command to start the tunnel on port 80 for localhost. An application running on this port is accessible through the tunneled https URL.

There are more features that you can do with Ngrok that you can read about on their official site.

**References**
- https://ngrok.com/docs
- https://www.softwaretestinghelp.com/ngrok-introduction/
- https://www.npmjs.com/package/ngrok
Javascript Closures - A Quick Digest
Tags: beginners, javascript
Published: 2020-10-06 03:11:55

A while ago during a mock technical interview I was asked to explain closures. At first, I thought I knew the answer: "Closures are functions that returns another function". But when I tried to explain it a bit further, I realized that I didn't really understand them. Fortunately my interviewer was very cool about it and went over them briefly with me. Afterwards I went back to basics and read articles, documentation, and watched some Youtube videos to get a better grasp of the topic.

## So What Are Closures?
In JavaScript, a closure is the combination of a function and its surrounding scope (lexical environment) within which the function was declared. In fact, a closure is created every time a function is declared. With the help of closures, functions can have local (private) variables that can be accessed even after the parent function was invoked and closed.

Let's take a look at a simple example:
```javascript
function outer() { // parent function
  const message = "Hello"; // local variable

  function inner() { // child function
    return message;
  }

  return inner;
}

const greeting = outer();

greeting() // will return a message "Hello"
```
We have a `message` variable inside the `outer` function. It is a local variable and cannot be accessed outside the parent function. By declaring the `inner` function within the parent function, `inner` has access to all local variables in its surrounding scope, which in this case is the `message` variable in `outer`.

When we assign function `outer` to the variable `greeting`, a few things happen:

1. `outer` function runs once and returns child function `inner`;
2. `outer` function closes itself
3. `greeting` variable became function declaration, and now has access to the closure `inner` and the `message` variable.

Now that `greeting` function became a function declaration, it can be invoked, and the returned result will be a message from the `outer` function.

This might seem a bit weird because in some programming languages, local variables within a function only exists for just the duration of the function's execution. But not in JavaScript. In Javascript, functions create closures with all surrounding environment, like variables that are in scope, at the moment they are created.

The `greeting` function has a reference to the function `inner`. The latter was created during the `outer` function execution and holds its environment, in which the variable `message` exists.
Taskord Changelog - Oct 6
Tags: opensource, productivity, changelog, showdev
Published: 2020-10-06 02:24:57

Welcome to **Taskord Changelog** 📜, This is a weekly post where we share what we shipped to [Taskord](https://taskord.com) this week.

Visit Taskord: https://taskord.com

**This week on Taskord**

- Design Improvements, more curved edges

![Screenshot 2020-10-05 082219](https://dev-to-uploads.s3.amazonaws.com/i/urui4cq005lsxl14igl7.png) 

- Block Disposable emails to fight spam users

![Screenshot 2020-10-05 082331](https://dev-to-uploads.s3.amazonaws.com/i/cywp7g0qypue3ywef3af.png)

- Hidden Task for moderators to hide a task from the public 

![Screenshot 2020-10-05 082425](https://dev-to-uploads.s3.amazonaws.com/i/sv80fi4s9w0dwql4rnv2.png) 

- New Sponsors Page

![Screenshot (18)](https://dev-to-uploads.s3.amazonaws.com/i/qezxer1lvltu4ojlerix.png) 

- Improved Dark mode by reducing color complexity and using native Bootstrap colors

![Screenshot (19)](https://dev-to-uploads.s3.amazonaws.com/i/3i0mwefxqxln15i6ne4u.png) 

- Personal Access Token to access our GraphQL API

![Screenshot (20)](https://dev-to-uploads.s3.amazonaws.com/i/ql299je75xqz6qeae1zx.png) 

- Repo link support for products, currently GitHub, GitLab and Bitbucket links are supported

![Screenshot (21)](https://dev-to-uploads.s3.amazonaws.com/i/0on5ztrl0cg0h9jmvza9.png)

- Dynamic favicons for a website link in product and user's social section
- Improved Font Awesome speed

Make sure to signup today! https://taskord.com/register

### Thanks 🙏

For providing constant feedback and feature requests!

{% user filiptronicek %}

Happy shipping ❤️
Creating users ID
Tags: log
Published: 2020-10-06 01:54:53

Fix duplicated user IDs when adding a new one right before delete the last user.

❌Wasn't working like this
```JS
const id = Number(data.users.length + 1)
```
It happens that when you delete a user before the last, and create a new user, the new user gets the same id as the last. Making two users to have the same ID.

✔So i made it like this:
```JS
let id = 1
    const lastMember = data.users[data.users.length - 1]

    if (lastUser) {
        id = lastUser.id + 1
    }
```

Of course that is far from the best way to create unique user IDs, since we have node uniqid and other node packages. But it was made to be simple, just to get used with the language as i get better in logic and solve problems without an out of the box solution.
meh.com scrapper in 3 lines ;)
Tags: codenewbie, script, json, hacktoberfest
Published: 2020-10-06 01:47:20

<i>
export PATH=/usr/local/bin:$PATH
curl -s "https://meh.com/feed.json" | jq '.items[0].title' 
curl -s "https://meh.com/feed.json" |jq '.items[0].url' 
</i>
Now if you have a json path, and installed jq tool, you can technically scape any site right from the shell!
Save value to localstorage - Magento 2
Tags: magento2
Published: 2020-10-06 01:04:47

Recently came across a requirement where url parameter value should be saved in localstorage 

Let's say the url is test.com/abc=123 and the localstorage name is 'abc_local'.


Path: app/code/Vendor/Module/view/frontend/web/js/tracking.js

The following will check all the parameters availabe in the URL and select only the required via getUrlParams() method.
```
require([
    'jquery'
], function($){
    var page_url = window.location.href;
    var abc_val;

    var getUrlParams = function getUrlParameter(page_url) {
        var url = window.location.search.substring(1),
            params = page_url.split('&'),
            param_name,
            i;
        for (i = 0; i < page_url.length; i++) {
            param_name = page_url[i].split('=');

            if (param_name[0] === page_url) {
                return param_name[1] === undefined ? true : decodeURIComponent(param_name[1]);
            }
        }
    };

    abc_val = getUrlParams('abc');
    localStorage.setItem('abc_local', abc_val);
});
```

The newest way to save this seems to be the following
```
require([
    'jquery'
], function($){
    var searchParams = new URLSearchParams(window.location.search)
    var abc_val = searchParams.get('abc');
    localStorage.setItem('abc_local', abc_val);
});
```
How to write multiple queries in mongoose?
Tags: help, mongodb, node
Published: 2020-10-06 01:00:01

I have written this query but it is not correct.
```javascript
router.get("/product/:name", function(req, res){
Product.findById(req.params.name).populate("reviews").exec(function(err, foundProduct){
    if(err){
        console.log(err);
    }
    else{
        foundProduct.aggregate([{"$lookup": {"from": "reviews", "localField": "reviews", "foreignField": "_id", "as": "reviews"}}, {"$unwind": "$reviews"}, {"$group": {"_id": null, "ratingAvg": {"$avg": "$reviews.rating"}}}], function(err, result){
        if(err){
            console.log(err);
        }
        else{
            result.forEach(function(element){
                var rate = Math.round(element.ratingAvg);
                foundProduct.updateOne({avgRating: rate});
                res.render("product", {product: foundProduct});
            });
        }
    })
    }
})
})
```
Here is what I want:

Find the product with that id
populate the reviews in the product model associated with that product id
calculate the average rating by taking all the ratings associated with that product id
as the default avgRating in the product model is zero, so update the avgRating with the average rating calculated in the previous step.
now render the foundProduct which contains the updated avgRating.

Here is the product model:
```javascript
var productSchema = new mongoose.Schema({
category: String,
name: String,
price: Number,
image: String,
description: String,
stock: Number,
avgRating: {type: Number, default: 0},
reviews: [
    {
        type: mongoose.Schema.Types.ObjectID, ref: 'Review'
    }
]
})
```
Phonics ESL - English sounds review tool
Tags: showdev, react, javascript, webdev
Published: 2020-10-06 00:56:42

Just finished a small React project and I'm hoping to get some feedback here on Dev! I built this to improve my React skills and to try out TailwindCSS.

Check it out [here](https://yougotwill.github.io/phonics-esl/).
See the source code [here](https://github.com/yougotwill/phonics-esl).

The tool is based around [Jolly phonics](http://jollyreading.com/introduction-to-jolly-phonics/) which is a great English education book series that I use in my day job. The idea behind this project is for people to be easily able to review English phonics on any smart device.

Let me know what you think in the comments!

**Mobile**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/l6cgduhvrq8qkinx6i2p.jpg)


Cover Photo by [Jerry Wang](https://unsplash.com/@jerry_318)
Scrape client-side rendered HTML content with JavaScript
Tags: node, javascript, tutorial
Published: 2020-10-06 00:52:13

In a previous tutorial I wrote about [scraping server-side rendered HTML content](https://www.w3collective.com/scrape-sever-side-content-javascript/). Many modern websites however are rendered client-side so a different approach to scraping them is required.

Enter [Puppeteer](https://pptr.dev/) a Node.js library for running a headless Chrome browser. This allows us to scrape content from a URL after it has been rendered as it would in a standard browser.

Before beginning you’ll need to have [Node.js](https://nodejs.org/) installed.

Let’s get started by creating a project folder, initialising the project and installing the required dependencies by running the following commands in a terminal:

```
mkdir scraper
cd scraper
npm init -y
npm install puppeteer cheerio
```
 
`cheerio` – is an implementation of core jQuery designed specifically for the server. It make’s selecting elements from the DOM easier as we can use the familiar jQuery syntax.

Next create a new file called scrape.js and load in the dependencies:

```javascript
const puppeteer = require("puppeteer");
const cheerio = require("cheerio");
const fs = require("fs");
```

`fs` – Is a Node.js module that enables interacting with the file system which we’ll use to save the scraped data into a JSON file.

Then add a `getData()` function that will launch a browser using Puppeteer, fetch the contents of a URL and call a `processData()` function that’ll process the page content:

```javascript
async function getData() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto("https://www.reddit.com/r/webdev/");
  const data = await page.content();
  await browser.close();  
  processData(data);
}
getData();
```

With the page content scraped let’s setup the `processData()` function. Here we use cheerio to select only the content we require (username, post title and number of votes):

```javascript
function processData(data) {
  console.log("Processing Data...");
  const $ = cheerio.load(data);
  const posts = [];
  $(".Post").each(function () {
    posts.push({
      user: $("._2tbHP6ZydRpjI44J3syuqC", this).text(),
      title: $("._eYtD2XCVieq6emjKBH3m", this).text(),
      votes: $("._1E9mcoVn4MYnuBQSVDt1gC", this).first().text(),
    });
  });
  fs.writeFileSync("data.json", JSON.stringify(posts));
  console.log("Complete");
}
```

This code loops through each of the `.Post` elements, grabs the data we specified (Reddit doesn’t use human readable class names hence the long strings of random characters), and pushes it to a `posts` array.

Once each of the posts has been processed a `data.json` file is created using `fs.writeFileSync`. You can now run the script using `node scrape.js`. It’ll take a little while to complete, once finished browse to the project folder and you’ll see the data.json file complete with data.
¿Qué es lo mas esencial para alguien que quiere iniciar como Frontend Developer?
Published: 2020-10-06 00:43:49

---
title: ¿Qué es lo mas esencial para alguien que quiere iniciar como Frontend Developer?
published: true
description: Las guerras de los frameworks nos distraen y se nos olvida cuales son las bases que debemos tener en cuenta como Frontend Developers. 
tags: 
//cover_image: https://direct_url_to_image.jpg
---

Esta respuesta suele parecer obvia para muchas personas, pero estamos en un punto donde considero que la "guerra" de Frameworks no debe continuar, he visto como se pelean por un framework tal cual como hinchas de un equipo de fútbol, y sí, es un poco absurdo pero es real.

El hecho de generar estas "peleas" Angular vs React vs Vue vs Svelte vs [Inserte framework de moda] hace daño a la hora de iniciarce como Frontend Developer, ya que hace que el desarrollador trate de aprender primero el framework antes de las bases y esto genera problemas al futuro al dev. 

Pero ¿cuáles son las bases del Frontend?
Antes de comenzar y hablar de cualquier lenguaje que debe aprender el Frontend, lo esencial es que entendamos varios puntos:

•¿Cómo funcionan los navegadores?
•¿Qué es HTTP?
•¿Qué es un dominio?
•¿Qué es un hosting?

Esta es una base que debe enteder muy bien cualquier desarrollador web. 
La base de todo Frtontend Dev, es HTML, CSS y Javascript, antes de aprender un framework esto es lo primero que debe estudiar cada desarrollador, porque estas también son las bases de cada framework. 

### HTML
• Aprender lo básico
•Escribir HTML Semántico
•Entender los formularios
•Convecciones y buenas prácticas. 

### CSS
• Aprender lo básico y buenas prácticas
•Crear layouts
•Entender sobre Flex Box, Positions, CSS Grid, 
•Responsive Design y Media Queries

### Javascript
• Sintaxys y conocimientos básicos
• Aprender a manipular el DOM
•Hacer llamados a Apis 
• Ecma Script 6 y programación funcional

Agreguémosle un Plus mas, y es que como Frontend también debemos tener en cuenta varios conceptos básicos sobre diseño. 


Estos son algunos puntos sobre HTML, CSS y Javascript, claramente el aprendizaje es más extenso, pero aquí es donde debe empezar cada desarrollador que quiere ser Frontend y es lo que cada Frontend Dev debe reforzar si no quiere depender de ningún framework.
Mygeolocate: Free GPS map Update
Tags: gps, map, update
Published: 2020-10-03 11:14:06

GPS, which stands for Global Positioning System, is the only system today able to show you your exact position on the Earth anytime, in any weather, anywhere. Ground stations, located worldwide, continuously monitor them. 

The satellites transmit signals that can be detected by anyone with a GPS receiver. Using the receiver, you can determine your location with great precision. GPS is one of history’s most exciting and revolutionary developments, and new uses for it are constantly being discovered.

We, at Mygeolocate, are going to help you from the very beginning till the very end. We will let you know even the very basic and fundamental knowledge about the GPS system and more. We are an independent third party GPS Customer Service provider and have years of experience in resolving the various GPS issues.

The <a href="https://mygeolocate.com/"> GPS map update support </a> is described as a system of radio-emitting & receiving satellites, GPS map gives the real-time location/ position and also, keeping the device up to date.

Dial us at MyGeolocate +1(855) 386-1126 to get in touch with experts
How to get the first child of a parent DOM element in JavaScript?
Tags: javascript
Published: 2020-10-06 00:00:00

---
  title: How to get the first child of a parent DOM element in JavaScript?
  published: true
  tags: JavaScript
  date: Tue Oct 06 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/get-first-child-element-dom-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-9dd6888a64c86745a55847f4a5e04a59.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/get-first-child-element-dom-javascript)
  
To get the first child of a parent element, you can use the `firstElementChild` property in the DOM element in JavaScript.

Let's say we have a parent element `div` and three `paragragh` tags inside it like this,

```html
<div id="container">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
</div>
```

Now let's get the first `paragraph` element from the `div` tag.

To get the first `paragragh` element, first we have to get a reference to the `div` tag and then use the `firstElementChild` property like this,

```javascript
// get refernece to tht div tag
const div = document.querySelector("#container");

// ge the first child element
const firstChild = div.firstElementChild;

console.dir(firstChild); // first p tag properties and methods
```

See this example live in [JSBin](https://jsbin.com/bexaticoha/edit?html,js,console).

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

---