teleren/devto huggingface dataset:
Debouncing, and web performance
Tags: javascript, react, webdev, html
Published: 2021-03-22 07:13:34

Debouncing is a important when you are making a scalable web product and going to JavaScript interview.

**Introduction** 

Debouncing, is an important practice which is used very often by web developers to improve the performance of browser. 

Debounce methods do not execute when invoked. Instead, they wait for a predetermined time before executing. If the same method is called again, the previous is cancelled and the timer restarts.

**Example**
Consider the example in this the function associated to the button will be called 2 sec after the button is pressed. No matter how many times you press is continuously it will be executed once. 
{% codepen https://codepen.io/amansingh1020/pen/RwKbRBz %}

**Let us understand the code**

```js
function debounce(func, wait, immediate) {
  var timeout;

  return function executedFunction() {
    var context = this;
    var args = arguments;
	    
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };

    var callNow = immediate && !timeout;
	
    clearTimeout(timeout);

    timeout = setTimeout(later, wait);
	
    if (callNow) func.apply(context, args);
  };
};
```

Here the debounce function takes three argument 
1. The function which needs to be executed.
2. The wait time.
3. do you want to invoke this immediately (optional).

## we can also implement this in react very easily with help of `lodash`

Consider someone is building a search application making an api call after every key stroke. consider this example with help of debouncing you can visualize the difference between events fired.

{% codepen https://codepen.io/amansingh1020/pen/BapBzQB %}

**Let's understand the code**

```js
 onSearchItemWithDebounce = debounce((query) => {
    this.setState({
      queryWithDebounce: query
    }, () => {
      //Do Stuff after state is updated.
      console.log('search with Debounce: ', this.state.queryWithDebounce);
    })
    this.setState({eventsFiredDebounce : this.state.eventsFiredDebounce+ 1})
  }, WAIT_TIME);
```

`**Note : debounce is imported from lodash**`

Thanks for Bearing,
I will be writing articles explaining each hook provided by react in upcoming articles please follow to stay connected.
Typescript - Tips & Tricks - Type Guard
Tags: typescript, webdev
Published: 2021-03-22 07:13:17

There are some cases, where we need to detect the type of the object to get the correct implementation of our method.
Let me show you a case
```ts
type Square = {
  size: number;
};

type Rectangle = {
  with: number;
  height: number;
};

type Circle = {
  radius: number;
};

type Shape = Square | Rectangle | Circle;

const area = (shape: Shape) => {
  if ("size" in shape) return shape.size * shape.size;
  if ("with" in shape) return shape.with * shape.height;
  if ("radius" in shape) return shape.radius * 2 * Math.PI;
};
```
In this case, in the area method, we need to detect the type of the shape to return the correct result.
Here we detect the type of the shape in the if condition but typescript permits us to create a special function that identifies if a type is of a specific type or not.
These functions are created to have Type Guards that help the compiler, the intellisense, and us to understand the correct type of the object.
To show you this function in action, the previous example can be rewritten in this way.
```ts
Square = {
  size: number;
};

type Rectangle = {
  with: number;
  height: number;
};

type Circle = {
  radius: number;
};

type Shape = Square | Rectangle | Circle;

function isSquare(shape: Shape): shape is Square {
  return "size" in shape;
}

function isRectangle(shape: Shape): shape is Rectangle {
  return "with" in shape;
}

function isCircle(shape: Shape): shape is Circle {
  return "radius" in shape;
}

const area = (shape: Shape) => {
  if (isSquare(shape)) return shape.size * shape.size;
  if (isRectangle(shape)) return shape.with * shape.height;
  if (isCircle(shape)) return shape.radius * 2 * Math.PI;
};
```
As you can see, the methods: isSquare, isRectangle, and isCircle get a shape as parameter and return a boolean value. If the result is true the shape parameter corresponds to the type indicated to the right of the is keyword, otherwise, it corresponds to another type.

I hope this feature will help you in the future and improve the reading of your code.

It's all Guy!
See you soon!
Solidity Principles
Tags: solidity, smartcontracts, blockchain, ethereum
Published: 2021-03-22 09:09:07

---
title: Solidity Principles
published: true
date: 2021-03-22 06:59:41 UTC
tags: solidity,smartcontracts,blockchain,ethereum
canonical_url: https://medium.com/coinmonks/solidity-principles-f3adb7289085
---

[![](https://cdn-images-1.medium.com/max/600/0*JJsN4KUuwBRwI0yv.png)](https://medium.com/coinmonks/solidity-principles-f3adb7289085?source=rss----721b17443fd5---4)

Solidity is the programming language of Ethereum. Like Bitcoin’s scripting language, which allows conditional financial transactions to be…

[Continue reading on Coinmonks »](https://medium.com/coinmonks/solidity-principles-f3adb7289085?source=rss----721b17443fd5---4)
How to create NFT Contracts on VeChain (quick)
Tags: vechain, nft, blockchain, openzeppelin
Published: 2021-03-22 09:09:38

---
title: How to create NFT Contracts on VeChain (quick)
published: true
date: 2021-03-22 06:59:13 UTC
tags: vechain,nft,blockchain,openzeppelin
canonical_url: https://medium.com/coinmonks/how-to-create-nft-contracts-on-vechain-quick-e9fd0003a4a4
---

[![](https://cdn-images-1.medium.com/max/1280/1*tBW3m1oekOP27XV2lW5exg.jpeg)](https://medium.com/coinmonks/how-to-create-nft-contracts-on-vechain-quick-e9fd0003a4a4?source=rss----721b17443fd5---4)

A quick tutorial to create NFT Contracts using templates

[Continue reading on Coinmonks »](https://medium.com/coinmonks/how-to-create-nft-contracts-on-vechain-quick-e9fd0003a4a4?source=rss----721b17443fd5---4)
Java/ Merge Multiple Excel Documents into a Single Document 
Published: 2021-03-22 06:57:37

In daily work, to facilitate the doucment management, we can merge multiple Files into a Single File. Today, this article will introduce how to merge multiple Excel documents into a single document using Java. 

**1# You need to import the jar dependency of a free Java Excel API**
**Method 1:** Download the [free API](https://www.e-iceblue.com/Download/xls-for-java-free.html) (Free Spire.XLS for Java) and unzip it, then add the Spire.Xls.jar file to your project as dependency.

**Method 2:** Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
```xml
<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>3.9.1</version>
    </dependency>
</dependencies>
```

**2# A screenshot of two Excel documents that need to be merged**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hvs3usn7ib8wkjpzb4kv.png)


**3# Relevant code snippet**
```java
import com.spire.xls.*;
import com.spire.xls.core.IWorksheet;

public class MergeExcels {
    public static void main(String[] args){
        //The input Excel files
        String[] inputFiles = new String[]{"Data1.xlsx","sample3.xlsx"};

        //Create a new workbook
        Workbook newBook = new Workbook();
        //Clear all worksheets
        newBook.getWorksheets().clear();

        //Create another workbook
        Workbook tempBook = new Workbook();

        //Loop through the Excel files, copy worksheets in each Excel file into the new workbook
        for (String file : inputFiles)
        {
            tempBook.loadFromFile(file);
            for (Object sheet : (Iterable)tempBook.getWorksheets())
            {
                newBook.getWorksheets().addCopy((IWorksheet) sheet, WorksheetCopyType.CopyAll);
            }
        }

        //Save the result file
        newBook.saveToFile("MergeFiles.xlsx", ExcelVersion.Version2013);
    }
}
```

**4# A screenshot of the generated document**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/77jlwn4i82w1wvnopwwb.jpg)
The Cloud Resume Challenge (series): Part 6 - Deploying & Configuring CloudFront
Tags: devops, cloud, serverless, aws
Published: 2021-03-22 06:54:04

---
title: The Cloud Resume Challenge (series): Part 6 - Deploying & Configuring CloudFront
published: true
tags: devops, cloud, serverless, aws
series: Cloud Resume Challenge
---

This is the sixth episode in a series on the cloud resume challenge series. 

{% youtube TQz67rZbGbw %}

If you’ve not heard of the cloud resume challenge, it’s a free challenge that you can take to build a resume using cloud tech.

It’s a great starting point for beginners or those new to the cloud. But… it’s definitely not for the faint of heart.

The challenge is tough and requires you to learn lots of different aspects of the cloud from CDN's to CI pipelines. The best way to learn any technology is by getting hands-on and using it in anger. 

The point of this YouTube series is to provide some extra structure and guidance to the challenge for those daring to attempt it!

But it's not about giving you all the answers, just some prompts, and some ideas to push you in the right direction. 

So... if you're thinking of getting into the cloud, do you dare take on the cloud resume challenge? 😁

---

If you’re interested in Cloud I write a monthly [newsletter for Cloud Software Engineers](https://newsletter.thedevcoach.co.uk). I spend the month digging around the internet for the best cloud engineering content and provide a monthly summary. I read every article I share, and I focus on fundamentals as much as possible.
Quick Cheat Sheet for AWS Amplify
Tags: aws, amplify, development, serverless
Published: 2021-03-22 06:44:01

AWS Amplify is a set of tools and services that can be used together or on their own, to help front-end web and mobile developers build scalable full stack applications, powered by AWS. With Amplify, you can configure app backends and connect your app in minutes, deploy static web apps in a few clicks, and easily manage app content outside the AWS console.

Amplify supports popular web frameworks including JavaScript, React, Angular, Vue, Next.js, and mobile platforms including Android, iOS, React Native, Ionic, Flutter. Get to market faster with AWS Amplify.

Sharing here quick cheat sheet of Amplify CLI commands.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fr3ai59iyv1xxgewpr8f.jpeg)

Visit https://docs.amplify.aws/ for more information
3 Turn Cacho Game in Python
Tags: python, gamedev
Published: 2021-03-22 06:40:38

Cacho is a Bolivian dice game. There are many variants of the game, but in for this project, it was selected the simplest version. 

This game is intended to emulate this dice game in a short computer game. In the code, we can select the amount of players (1 to 4), and each player will be able to throw dice (a total of 5). The objective is to score the most points in the Cacho dashboard. 

The dashboard consist of a total of 11 squares, 6 of them represent the face value of a dice. While the others have a special condition, that is require to meet to get the points. 

In this game the players will be able to choose the dice they want to throw, and which square which they want to select to earn the most points. 

The project is hosted in this GitHub link :
https://github.com/japp2510/Cacho.git
JAMstack with NuxtJS Content & Forestry = 🚀
Tags: vue, cms, netlify, nuxt
Published: 2021-03-22 06:36:12



## JAMstack
 
I'm a JAMstack lover. It's easy, fast (like, really fast!), high performance, and cheap, thanks to providers such as Netlify. 

For my last side project  [Tuto.dev](tuto.dev), I wanted something simple to create & maintain the Frontend. I'm a fanboy of **VueJS**, so the choice of  [NuxtJS Content](https://content.nuxtjs.org/) was a no-brainer for me. NuxtJS Content lets you create Markdown files under a folder called 'content' and  then use 
`<nuxt-content>` **to populate your page with the content from the Markdown file**. Yeah, it's *that* simple : 

```html
<template>
  <article>
    <h1>{{ page.title }}</h1>
    <nuxt-content :document="page" />
  </article>
</template>

<script>
export default {
  async asyncData ({ $content }) {
    const page = await $content('home').fetch()

    return {
      page
    }
  }
}
</script>
```

## The CMS 

Now that I have the Frontend ready, I wanted to create, edit & manage those Markdown files.

I've tested tons of Headless CMS like Sanity & Strapi. They are all great, but they don't fit my needs. I required something more basic! A way to edit my .md files from my content folder and push them into my GitHub repo to trigger a new build from Netlify. Nothing more.

So I've tried another solution at first:  [Obsidian](https://obsidian.md/). Obsidian is a text editor on steroids; if you're looking for a Notion alternative, you should give it a try. 
Plus, you can install plugins made by the community, making it easier to create and maintain your work. And there is an Obsidian [plugin](https://github.com/denolehov/obsidian-git) made by Denis Olehov that Push the markdown files every x minutes. Remarkable! 

It worked great, but media management was painful: your .md files are in a /content folder when your media files are in the /assets or /static folder. So every time I add an image into a folder, I had to remember the relative path and then add it into Obsidian ... boring.

## Forestry 🌲

And then, someone shared with me another CMS I was not aware of :  [Forestry.io](https://forestry.io/) 

When I first saw the website headline "Headless CMS that commits" I was excited like it was Christmas.
It was exactly what I was looking for! To summarize, Forestry is a CMS that can create & edit Markdown files and push them into your Repo when you save them. 

![Oversimplified Diagram of NuxtJS with Forestry](https://cdn.hashnode.com/res/hashnode/image/upload/v1616347087167/AgMAM3srI.png)

Forestry is by far the most simplistic CMS I've ever used. But don't get me wrong: **simplicity doesn't imply limited functionalities!** Forestry is also a really powerful tool when it comes to media management and Front-Matter editing. 

With the [Front-Matter block](https://forestry.io/docs/editing/front-matter/), we can add and manipulate metadata from our Markdown file and then create an API by [fetching those metadata into NuxtJS](https://content.nuxtjs.org/fetching). 

Yup, we can create an API with our Markdown files. When I first saw that, my mind was blown 🤯
Rainbow Webpage
Tags: javascript
Published: 2021-03-22 06:27:46

> Want To Add A Hidden Feature In Your Webpage For Users to Discover? Do This:  

#### Rainbow Webpage

```javascript
var i = 0; // Define varible "i"
setInterval(function(){
  document.body.style.filter = `hue-rotate(${i}deg)`; // Set Hue Of Page To i
  if(i == 360){ 
    i = 0; // Set i to 0
  } else{
    i = i + 2; // Change i by 2
  }
}, 60);
```



enjoy!
Generate API Docs for Django Rest Framework
Tags: python, django, api, documentation
Published: 2021-03-22 06:20:33

In this blog, I will show you how to generate the documentation of your Django API in 2 min. Let's start, 

There are many tools available to generate the docs for REST API but I prefer something simple and lucid. 

For this example, I have created the `snippet` model with following settings,

`models.py` file,

```python
from django.db import models

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
```

`serializer.py` file,

```python
from rest_framework import serializers
from .models import Snippet

class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = '__all__'
```

`views.py` file,

```python
from rest_framework import viewsets
from .models import Snippet
from .serializer import SnippetSerializer

class SnippetViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

```

Let's provide the URL endpoint for our API documentation,

```python
from .views import SnippetViewSet
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from rest_framework.documentation import include_docs_urls

router = DefaultRouter()
router.register(r'snippet', SnippetViewSet)

urlpatterns = [
    path('api/', include(router.urls)),
    path('docs/', include_docs_urls(title='Snippet API'))
]
```

> **Note** that the doc-strings provided in the `views.py` file will be used for our documentation so please provide as much information as you can.

Now your API documentation can be found in http://localhost:8000/docs.

Happy coding!

### Reference

1. [Build a RESTAPI using nested serializers in Django-Rest-Framework: medium](https://medium.com/@gurupratap.matharu/build-a-restapi-using-nested-serializers-in-django-rest-framework-c0f6a31fd865#)
Laravel VS NodeJS — Which One Is The Better Choice?
Tags: laravel, node, mobile, devops
Published: 2021-03-22 06:16:14

Coding can create problems at times, and technology is evolving to address this fundamental issue. Various web frameworks have started gaining ground among the developer’s community with a promise to make the development process simple and straightforward for developers. However, two robust and advanced frameworks [Laravel](https://www.suriainternational.com/laravel-development-company/) and NodeJS have marked their presence through their set of unique features to solve a particular development problem.

As reliable and developer-friendly frameworks, both Laravel and NodeJS have contributed to reducing development time and ensuring a smooth transition from the development to the production phase. Therefore, it is difficult to compare these frameworks and find out which one is better. However, in this blog, we will attempt to show their characteristics to enable you to find the most suitable web development framework for your upcoming project.

Before moving forward, let’s get an introduction to Laravel and NodeJS.

Laravel- Versatile PHP Framework

It is a simple to understand, open-source framework that follows MVC (Model-View-Controller) design pattern. It uses existing components from other available frameworks for building customized web applications. [Laravel-based web apps](https://www.suriainternational.com/our-work/) are more organized and reliable.

Laravel has many features that can be easily integrated with the key components of other PHP frameworks including CodeIgniter, Yii, and other programming languages like Ruby on Rails. [Laravel development company](https://www.suriainternational.com/laravel-development-company/) can make a safe and user-friendly website in a short time using features of Laravel like template engine, MVC architecture support, and database migration system.

Read More:https://www.suriainternational.com/laravel-vs-nodejs/
Chrome devtools capture full page
Tags: chrome, devlive
Published: 2021-03-22 06:04:41

Chrome finally launched an excellent way to capture a whole page in version 89.

We could always take screenshots by using the [Chrome Screenshot functions](https://daily-dev-tips.com/posts/chrome-screenshot-specific-element/).

However, in version 89, the modified right-click element inspector allows us to capture a screenshot from the inspector.

![Chrome screenshot specific element](https://cdn.hashnode.com/res/hashnode/image/upload/v1615960345609/Qaig2z9Ga.gif)

## How to take a screenshot in Chrome

So with this new version, you can simply open up the developer tools.

> Mac Cmd + Shift + C or Windows: Ctrl + Shift + C.

Now open the element inspector, right-click any element and click the "Capture node screenshots" button.

> Pro tip: If you use this on the body tag, you'll get your whole website.

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
JavaScript with Run Options
Tags: javascript
Published: 2021-03-22 05:55:05

> Run Code In JavaScript With options like:
* Use Unchangeable variables:

```javascript
var options = {
  UseConstants: "true"
}
var JavaScriptCode = `
var js = "JavaScript";
console.log(js);
js = "wow";
// Cannot Change Value
` // JavaScript Code That will be affected with options

if(options.UseConstants){
	var u = URL.createObjectURL(new Blob([JavaScriptCode.replaceAll("var", "const")], {type: "application/javascript"}));
	
	var script = document.createElement("script");
	document.head.appendChild(script);
	script.src = u;
	script.defer = "";
}

// Gives Error: Assignment to constant variable.
/*
Code After Change:
const js = "JavaScript";
console.log(js);
js = "wow";
// Cannot Change Value
*/

```
Day 8 of 100 days of SwiftUI
Published: 2021-03-22 05:54:08

Day 8 of HackingWithSwift's 100 days of SwiftUI. Today I learnt about Structs.

Structs in Swift are used to define your own custom data types. Structs can have variables, constants, and functions. Variables and constants in Structs are known as properties while functions are known as Methods. Structs in Swift can be written like so.
```
 struct Person {
   var name: String
   var nationality : String
   var level: Int

   func checkLevel() -> Bool {
       if level > 9000 {
         print("It's over 9000!")
       } else {
         print("hmmmmm.... not bad.")
       }
   }
}

let sanmi = Person(name: "sanmi", nationality: "Nigerian", level: 9001)
sanmi.checkLevel()
```
The code above defines a structure(struct) with three variables and one method. Methods are pretty much functions inside a struct. There are two noticeable differences between methods and functions.
* Methods have access to properties defined in a struct. You can see in the `checkLevel` method, we are checking to see if the `level` property is above 9000.
* There are two kinds of methods in Swift. Mutating methods and non-mutating methods. Mutating methods are used when you want to change a properties value. Mutating method are simply marked as mutating.
```
 struct Engine {
   var name: String
   var speed : Int = 150

   mutating func upgrade() {
     speed += 50
   }
}

let engine = Engine(name: "Tron")
engine.upgrade()
```
Properties in Swift have this really cool feature called property observers. Properties observers let you run a piece of code before and after the property changes. Property observers are very simple to use in swift. 

```
 struct Engine {
   var name: String
   var speed : Int = 150
        didSet {
            print("Engine speed was changed to \(speed)")
        }
        willSet {
            print("Engine speed is about to be  changed")
        }

   mutating func upgrade() {
     speed += 50
   }
}

let engine = Engine(name: "Tron")
engine.upgrade()
```


If you are interested in taking the challenge, you can find it at https://www.hackingwithswift.com/100/swiftui
See you tomorrow ;)
Looking at logrotate in debian and timers in general.
Published: 2021-03-22 05:33:22

---
title: Looking at logrotate in debian and timers in general.
published: true
description: We look into logrotate on Debian and figure out how timers actually work with a system with cron installed and configured. This was a bit of a gotcha for me, so hopefully, this will help you when you configure logrotate and want to use the timers in Debian to set a correct time.
tags:
cover_image: https://i.ytimg.com/vi/_5xMkIMyEX4/maxresdefault.jpg
---

{% youtube _5xMkIMyEX4 %}

We look into logrotate on Debian and figure out how timers actually work with a system with cron installed and configured. This was a bit of a gotcha for me, so hopefully, this will help you when you configure logrotate and want to use the timers in Debian to set a correct time.