teleren/devto huggingface dataset:
Third argument in setTimeout()
Tags: javascript, settimeout
Published: 2020-03-02 09:30:27

#Introduction
This is about the third argument in setTimeout function.

As we know, setTimeout allows us to run a function once after the interval of time.
This is the general syntax,
```javascript
let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)
```
In day to day usage, we use setTimeout() like this:
```javascript
function greeting(){
 alert('hey!!')
}
setTimeout(greeting,1000);
```
Let's see how we can pass the third argument
```javascript
function greeting(arg1, arg2){
 console.log(arg1,arg2)
}
setTimeout(greeting,1000,"Hi", "There");
//output: Hi There
```

Instead of string we can pass an array, object, etc.
```javascript
function greeting(arr){
 console.log(arr);
}
const arr = [1,2,3,4]
setTimeout(greeting,1000,arr);
//output:  (4) [1, 2, 3, 4]


function greeting(person){
 console.log(person);
}
const person = {name:"abc", age: 21}
setTimeout(greeting,1000,person);
//output: {name: "abc", age: 21}
```
That's how you can make use of the third argument.
Cheers !!!
Selectors explained: Translate CSS Selectors into plain English
Tags: beginners, css
Published: 2020-03-02 09:17:11

---
title: Selectors explained: Translate CSS Selectors into plain English
published: true
description: An online tool to translate CSS Selectors into plain English
tags: beginner, css
---

CSS selectors are used to select [HTML elements](https://dev.to/ziizium/html-elements-and-tags-4gdi) on a web page. There are different type of selectors some of which are:

* Attribute Selectors
* Descendant Selectors
* Class Selectors
* ID Selectors

The list above is inconclusive. For more information about CSS selectors please refer to [my post on CSS Selectors](https://dev.to/ziizium/css-selectors-1ch3).

Depending on your coding style CSS selectors can get really complex and unless you have a good understanding about them you might need someone or something to explain it to you.

When you find someone to sit you down and explain the quirks of CSS selectors to you congratulations! However, there is an online tool that can be of help.

###__Selectors explained: An online tool__

[Selectors explained](https://kittygiraudel.github.io/selectors-explained/) is an online tool by [Hugo Riraudel](https://https://hugogiraudel.com/)

He announced the tool on Twitter late last month (February 24, 2020):

{% twitter 1231861909001056256 %}

The tool is useful and it tries it's best to explain the provided selectors. However, it's currently in _alpha_ and it has some limitations:


{% twitter 1232197976841433088 %}

The tool can be used alongside [specificity calculator by Keegan Street](https://specificity.keegan.st).

_Have fun!_

_Updated July 16, 2021: Updated the link to the selectors explained tool thanks to a comment by @unclejustin_
Adding an Exchange Rate Display to the PlashServer
Tags: svelte, plash, background
Published: 2020-03-02 09:08:28

I’m one of those people that love to control what’s on the background of my computer. I’ve used many widget tools to perform these tasks, but they all left me as under developed, hacky at times, and not as easy to use as I would like. That’s most likely because I never took the time to really get into their code structures. But, when you create your own thing, then you know it very well.

When the [Plash](https://sindresorhus.com/plash) program came out for the macOS, I jump right onto it. It allows you to put any website, whether a local file system one or one served on the net, as your background. That directly inspired me to create a [Svelte](https://svelte.dev) based background webpage for Plash.

I have a full tutorial series on my [personal blog site](http://customct.com/#/blog/plashserver-series). The [first tutorial](http://www.customct.com/#/tutorials/plashserver/plashserversetup) takes you through the building of the basic framework and getting everything running with Plash. The initial widgets are a circular time display with the actual time under it.

My latest tutorial is [an Exchange Rate widget](http://www.customct.com/#/tutorials/plashserver/exchangewidget). This widget will show the current exchange rate for whatever currency your interested in seeing. Since it’s a widget, you can add it onto your screen as many times as you like. This tutorial really shows how to make use of promises in the Svelte framework.

This series assumes you know very little about Svelte. I am trying to use it as a way to get more people interested in Svelte framework and know how to use if for their needs. I think it makes a great playground to learn Svelte.

I would love to see your comments on this series. All code is located on my [GitHub repository for the PlashServer](https://github.com/raguay/SveltePlashServer). Fork it, expand it, and send me some pull requests. It would be a lot of fun to have a community contributing to this project.
Change the password visibility after certain time
Tags: javascript, html, css
Published: 2020-03-02 08:57:33

Hello World! This is Nehemiah. Recently, I've started working on a web page designing project, which actually deals with the password management system. User has to access a server by entering it's (newly updated) password in DB. In the first html page, server name and IP address will be asked. Once the user enters the proper details, the respective password will be displayed on the Screen. Here is the main concern. Once the password is visible on the screen, it should get automatically invisible after 1 minute. I've tried doing it by using timestamp function. But unable to achieve the same. Could anybody help me with the same?
You are not "Alone"
Published: 2020-03-02 08:54:13

Are you a developer who...
➡ Got stuck solving an easy programming problem?
➡ Wrote a code more than 100 lines and when compiled got more than 1000 errors?
➡ Can't figure out solutions quickly?
➡ Didn't code for a week and forgot how to print hello world in the console?
➡ Get depressed when you can't solve any programming problem?
➡ Got overwhelmed when you first opened your IDE?
➡ Get's scared by bigger codes?
➡ Think himself not good enough for programming?
➡ Often think programming is not for you?
➡ Can't find out solutions for the problems in Google?
➡ Often think of quitting programming?
➡ Regularly gets frustrated for not writing good enough codes?

Then great! Cause you are not alone. Do you remember the first cuts you got while learning to walk(probably you won't)? And the day when you almost got drowned in the water when first tried swimming without help? After all those years, look at yourself now. You can walk, you can run, you can swim. Just like that, the problems mentioned above are the baby steps of programming. 

I am pretty sure all the professional developers have faced multiple of them. And more importantly, they are facing this kind of problem every day. But the thing is they are used to it. This is just a part of programming. 

So, the next time you face this kind of problem just remember that you are not alone. And if others can solve it why can't you? You need to survive the whole run to get the ultimate reward.

(Did I missed any problems that you faced when you just got started? Comment it below.)
Deploy "The EventBridge Circuit Breaker" pattern today (AWS API Gateway, Lambda, EventBridge, DynamoDB)
Tags: aws, serverless, architecture, tutorial
Published: 2020-03-02 08:36:31

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dfkcyw8e4tvd0blvpkt7.PNG)

This is a pattern adapted from "The Circuit Breaker" by Jeremy Daly. I used EventBridge to route service call failures to a lambda that inserts them into DynamoDB with a 60 second Lifespan. Then when consumers call the API Gateway to call our external service we check if the number of errors in the last 60 seconds is above our threshold. If it is, we instantly error saving lambda execution costs and user time.


The pattern is here:
https://github.com/cdk-patterns/serverless/blob/master/the-eventbridge-circuit-breaker/README.md

This pattern is available in Python/TypeScript AWS CDK versions but also each version has the native CloudFormation checked in as template.yaml.
Higher Order Functions from scratch - Functional JS
Tags: javascript, functional
Published: 2020-03-02 08:26:38

## Why Functional Programming
**Functions** are first class objects in JavaScript that means functions can be treated as objects as well, functions can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.
```js
function greet() { 
console.log(`Hello ${greet.person}, how are you !`)
}
greet.person = 'Mohit'  // using fn as object
greet() // prints Hello Mohit, how are you !
```
Functional Programming pattern makes *asynchronicity* possible in JS , functions are invoked when *()* is present after variable containing function definition. What if we don't want to run a function immediately but after some delay like *setTimeout* which takes in two parameters - a callback function and other is delay in ms. This type of function is called **Higher Order Function**, which is a function that takes in a function as an argument or returns a function. This pattern gives rise to concept of **Closures** which is the most powerful concept in JS.

## Inbuilt High Order Functions in Arrays

JS provides us with many higher order functions like *map*,*reduc*,*filter*,*sort* ... , this allows functions composition possible which helps us in writing cleaner and maintainable code. 

Let's see how we can create few *Higher Order* functions from scratch :

#### Map method from scratch

**Array.prototype.map** -
The map() method creates a new array by calling the callback function provided as an argument on every element in the input array. 


```js
Array.prototype.map2 = function(fn) {
    let result = [];
    for (let i = 0, l = this.length; i < l; i++) {
        result.push(fn(this[i]))
    };
    return result;
}
const arr = [1,2,3];
const mulBy2 = (ele) => ele*2;
console.log(arr.map(mulBy2)) // [2,4,6]
console.log(arr.map2(mulBy2)) // [2,4,6]
```
#### Filter method form scratch
**Array.protoype.filter** - 
The filter() method creates a new array with all elements that pass the test provided by the callback function.

```js
Array.prototype.filter2 = function(fn) {
    let result = [];
    for (let i=0,l=this.length;i<l;i++) {
        fn(this[i]) && result.push(this[i])
    };
    return result;
}
const arr1 = [1,2,3,5,8];
const getOddNos = (ele) => ele%2 !== 0;
console.log(arr1.filter(getOddNos))  // [1,3,5]
console.log(arr1.filter2(getOddNos)) // [1,3,5]

```
####  Reduce method form scratch
**Array.prototype.reduce** -
The reduce method executes the callback function on each member of the calling array which results in a single output value. The reduce method accepts two parameters: 1) The reducer function (callback), 2) and an optional initialValue.

```js
 Array.prototype.reduce2 = function(fn, acculumator) {
    for (let i = 0, l = this.length; i < l; i++) {
        acculumator = fn(acculumator, this[i])
    };
    return acculumator;
}
const arr2 = [1,2,3,4,5];
const sumSeries = (acculumator,currentValue) => acculumator+currentValue;
console.log(arr2.reduce(sumSeries,0)); // 15
console.log(arr2.reduce2(sumSeries,0)); // 15
```
My path to becoming a software developer
Published: 2020-02-25 21:54:09

I have applied for several jobs with no response from any and still got no replies for the interviews I attended. I was really confused in the early weeks of 2019 before I came across the Code Plateau application through Facebook for Software Development and Digital Skill training. I applied reluctantly thinking it is going to be allocated to only indigenes since it is organized by Plateau State Government.
To my surprise after some months, I received a message inviting me to an interview. I attended the interview and was selected to participate in the training. Boom! We started like play, I chose FRONT-END Web developer.
When we started, I thought there was going to be a monthly stipend of at least 25,000 Naira per person for transportation and data, and a laptop for each person. All my assumption was wrong because none of this happened except in Local Governments like Kanke where laptops were given to their own indigenes. Also, we were told that we would meet with the Governor for the inauguration of the program but this did not happen. At some point, I got discouraged and I almost give up. I had thought that I was going to resign from my teaching job once we started the training so that I could focus since my teaching job was not paying as much as I expected, but after we started and had spent two months in the training, I couldn’t resign because there was no hope of getting any monthly stipends from Code Plateau and I have a family to cater for. I am a married man with one kid, so resigning from my teaching job will not be a good option. My school proprietor did cooperate at all (I work in a private secondary school). He only gave the option of me resigning or I’d have to stop the Code Plateau training.

I thought of the whole thing for about two days and came up with the idea of self-learning. Since I had known the basics which is very important, I then came up with a plan of attending classes twice a week (that means I would dodge school without anyone knowing to avoid my appointment being terminated).
Code Plateau training looks promising because there are a lot of opportunities out there which I can see but the challenge of transportation, data, and a good laptop is not to be left out because all these are needed to make one focus.
Some people that started with us gave up after two months and some got an appointment for work. But to be honest, I have never regretted my decision to continue even with all the challenges at hands, and to the glory of God, I can boldly say I am now on my right path and a path of greatness because I can see a brighter and great future before me now.
Highlight of my present skills through the Code Plateau Initiative program are HTML, CSS, JavaScript, Uikits, Bootstrap, React.
Dark mode with CSS
Tags: dark, css, opensource
Published: 2020-03-02 08:19:30

My eyes hurt a lot when I stare at a bright screen with light mode so I  use [Dark Reader](https://darkreader.org/) but prefer the website native support for dark mode. 

Since https://remotework.jp/ went live a couple of weeks ago, I wanted to add the dark mode to it. Luckily, CSS supports the media query `prefers-color-scheme` which checks the user's default mode for light/dark and add CSS specific to each case.

So I went on and added this simple piece of CSS and no Javascript needed for this change!

```css 
body {
  @media (prefers-color-scheme: dark) {
    color: #515151;
    background-color: #000;
  }
  @media (prefers-color-scheme: light) {
    color: #515151;
    background-color: #fff;
  }
}
```

Et voilà! Dark mode easily supported... 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/h703ujf9cp6txbhtujp4.png)

And light mode still there.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bziq3ls7jsyfllw4emm4.png)

For further reading and better styling structure of your whole website/app, I suggest reading this [post](https://nandovieira.com/supporting-dark-mode-in-web-content).
Binary Search Tree: Insert, Find, and Validate
Tags: javascript, computerscience
Published: 2020-03-02 07:29:14

Trees can have nodes that can have unlimited number of children of any value. Binary search tree is a tree data structure with more constraints.

## Constraints

* Every node can have at most two children
* Node to left needs to have value less than parent
* Node to right needs to have value greater than parent

### Binary Tree

Binary search tree is not the same as a Binary tree. Binary trees have nodes that can have at most two children, but there is no restriction on its left value being less than the parent or the right value being more than the parent.

## Node

```javascript
class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}
```

## Insert

```javascript
class Node {
  // ...

  insert(data) {
    const newNode = new Node(data);
    const isLeft = newNode.value < this.data;

    if (this.left && isLeft) {
      return this.left.insert(data);
    }

    if (this.right && !isLeft) {
      return this.right.insert(data);
    }

    if (isLeft) {
      this.left = newNode;
    } else {
      this.right = newNode;
    }
  }
}

```

## Find

```javascript
class Node {
  // ...

  find(data) {
    const isLeft = data < this.data;

    if (data === this.data) {
      return this;
    }

    if (this.left && isLeft) {
      return this.left.find(data);
    }

    if (this.right && !isLeft) {
      return this.right.find(data);
    }

    return null;
  }
}

```

## Validate

```javascript
function validateBST(node, min = null, max = null) {
  if (max && node.data > max) {
    return false;
  }
  
  if (min && node.data < min) {
    return false;
  }

  if (node.left) {
    return validateBST(node.left, min, node.value);
  }

  if (node.right) {
    return validateBST(node.right, node.value, max);
  }

  return true;
}

```
Tree: Breadth-first and Depth-first
Tags: javascript, computerscience
Published: 2020-03-02 07:28:19

A tree is a data structure with nodes. There are many different types of trees but all trees use collection of nodes to store data. Let's create a `Node` and `Tree` class and traverse the tree breadth-first and depth-first.


## Node

A node has two properties: data and children of nodes.

```javascript
class Node {
  constructor(data) {
    this.data = data;
    this.children = [];
  }
}
```

## Tree

A tree has reference to a root node.

```javascript
class Tree {
  constructor() {
    this.root = null;
  }
}
```

## Traversal

The starting point is always the same, but there are many ways to traverse the tree from the same starting point.

### Breadth-first

Breadth-first traversal goes through each level. It will not move on to the next level unless everyone in the current level has been visited.

1. Put root of the tree in an array.
2. While there are elements in this array, take out the very first element and PUSH all of its children into the back of the array.


```javascript
class Tree {
  // ...

  traverseBreadthFirst(lambda) {
    if (!this.root) {
      return;
    }

    const nodeArray = [this.root];

    while (nodeArray.length) {
      const firstElement = nodeArray.shift();

      lambda(firstElement);

      nodeArr.push(...firstElement.children)
    }
  }
}
```

### Depth-first

Depth-first traverses into a deeper level if possible until it can go no longer. Once it cannot go any deeper, it backtraces to the last parent node in which all of its children have not been explored yet.

1. Put the root of the tree in an array.
2. While there are elements in this array, take out the very first element and UNSHIFT all of its children into the front of the array.


```javascript
class Tree {
  // ...

  traverseDepthFirst(lambda) {
    if (!this.root) {
      return;
    }

    const nodeArray = [this.root];

    while (nodeArray.length) {
      const firstElement = nodeArray.shift();

      lambda(firstElement);

      nodeArr.unshift(...firstElement.children);
    }
  }
}
```
React Hooks notes
Tags: javascript, react, notes
Published: 2020-03-02 07:20:14

Hooks are new additions to react in 16.8.0

Hooks are basically a JavaScript functions

They let you hook(application business logic) into react state and lifecycle features from function components.

Hooks can only be used inside function components, 

Hooks make FCs state rich.

You can create your own hooks

Without hooks today Its difficult to share state-full logic in a class based component, which is made easy.
Laravel Merge PDFs
Published: 2020-05-07 23:51:37

---
title: Laravel Merge PDFs
published: true
date: 2020-03-02 07:14:02 UTC
tags: 
canonical_url: https://dcblog.dev/laravel-merge-pdfs
---

 ![Laravel Merge PDFs](https://dcblog.dev/assets/images/blog/laravel-framework/laravel-merge-pdfs.png) 

Ever needed to merge multiple PDF's together? It's a common need. In this tutorial, I'll cover how to do merge multiple pdf's together in Laravel.

First, we need a package called [**lara-pdf-merger**](https://github.com/deltaaskii/lara-pdf-merger) Install it with composer:

```php
composer require daltcore/lara-pdf-merger
```

Next, create import the namespace:

```php
use LynX39\LaraPdfMerger\Facades\PdfMerger;
```

Create a new instance:

```php
$pdfMerger = PDFMerger::init();
```

Add PDF to be merged:

```php
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/1.pdf'), 'all');
```

Do this for each PDF to be merged.

```php
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/1.pdf'), 'all');
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/2.pdf'), 'all');
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/3.pdf'), 'all');
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/4.pdf'), 'all');
```

Next, call a merge method to perform the merge.

```php
$pdfMerger->merge();
```

Next, save the PDF to disk

```php
$pdfMerger->save(public_path('quotes/001.pdf'), "file");
```

## Putting this all together:

```php
$pdfMerger = PDFMerger::init(); //Initialize the merger
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/1.pdf'), 'all');
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/2.pdf'), 'all');
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/3.pdf'), 'all');
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/4.pdf'), 'all');
$pdfMerger->merge();
$pdfMerger->save(public_path('quotes/001.pdf'), "file");
```

## Generate a PDF and merge with existing

You may want to generate new PDF and merge that in with existing PDFs.

Let's install Laravel [DOMPDF](https://github.com/barryvdh/laravel-dompdf) to make a new PDF. Install with composer:

```php
composer require barryvdh/laravel-dompdf
```

Import PDF:

```php
use PDF;
```

Create a new PDF, load a view file (quotes/pdf.blade.php) for the contents of the PDF and save to a quotes folder and use the filename quote-001.pdf

```php
$filename = "quote-001.pdf";
$pdf = PDF::loadView('quotes.pdf', ['quote' => $data]);
$pdf->save('quotes/'.$filename);
```

Now, this can be merged using the same technique above.

```php
$filename = "quote-001.pdf";
$pdf = PDF::loadView('quotes/pdf', ['quote' => $record]);
$pdf->save('quotes/'.$filename);

$pdfMerger = PDFMerger::init(); //Initialize the merger
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/1.pdf'), 'all');
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/2.pdf'), 'all');
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/3.pdf'), 'all');
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/4.pdf'), 'all');
$pdfMerger->addPDF(public_path('quotes/'.$filename), 'all');
$pdfMerger->addPDF(base_path('Modules/Quotes/pages/5.pdf'), 'all');
$pdfMerger->merge();
$pdfMerger->save(public_path('quotes/quote-001.pdf'), "file");
```