teleren/devto huggingface dataset:
What is throttling in JavaScript?
Tags: javascript, webdev, beginners, programming
Published: 2022-06-30 07:27:00

---
canonical_url: https://blog.aamchora.space/what-is-throttling-in-javascript
---

Again a jargonish word, but let me demystify it for you.

![let me help you](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rz7pwdqvr8e25wa9sig9.gif)
 

It's nothing but a simple technique we use to prevent unnecessary function calls to improve app's performance.


Unlike [Debouncing](https://dev.to/aamchora/what-is-debouncing-in-javascript-21om), here we block a function call for a particular time if it's been executed recently. Or we could also say that throttling ensures a function call regularly at a fixed rate.


Let's look at the below example,

```html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Throttling</title>
    </head>
    <body>
        <button class="btn">Click here</button>
        <script src="index.js"></script>
    </body>
</html>
```


```js
let count = 0;
function submitData(query){
   // some api call
   console.log("result",count++)
}

document.querySelector(".btn").addEventListener("click",()=>{
submitData();
})
```

![first example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/noojew5jtc2l6uxtze68.png)
 

In the above example, if you click 10 times in 2000ms, Function will be called 10 times, as you can clearly see in the above example. 

It's a very expensive operation, and as dev, our job is to make operations as cheap as possible. 

Let's see how throttling helps us to make these operations cheaper.


```js
function throttle(fn,delay){
  let last = 0;
 /*  
here ...args is optional I've used this in case, if you 
want to pass some parameters you can use ...args
*/ 
  return (...args)=>{
    const now = new Date().getTime();
    if(now - last < delay){
      return;
    }
   last = now;
   return fn(...args)
  }

}

const magicFunction = throttle(submitData,1000);

let count = 0;
function submitData(){
   // some api call
   console.log("result",count++)
}

document.querySelector(".btn").addEventListener("click",magicFunction);
 ```

![second](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/owa67zg0804zmsp8ko7e.png)

Now, if you click 10 times in 2000ms, Function will be called 2 times only, as you can see in the code. We have blocked the function call for 1000ms.

_That's how we can implement the **throttling technique** to **improve our app's performance**_

---


_**follow me for more such blog posts.**
Let me know if this blog was helpful._

[Twitter](https://twitter.com/AamChora) || [Linkedin](https://www.linkedin.com/in/hemendrakhatik/)
should i update my redux code with the new version?
Tags: frontend, redux, reouter, legacy
Published: 2022-06-30 07:24:41

I have started my application two years ago. when I started I use the versions of React router and redux that were available at that time. now there are new versions of them and my code that uses redux and router become legacy code. now should I update my code or keep it.

in another world, with every new version of a package or library should I update my code.

when should I update my legacy code?
The Best MultCloud Alternatives
Tags: alternative, multcloud, storage
Published: 2022-06-30 07:18:27

MultCloud may be the most well-known cloud storage manager. Still, many cloud-to-cloud services offer powerful functionality and intuitive interfaces. Moving content between accounts by downloading and reuploading is tedious and not practical for clouds with a lot of content. 

The top MultCloud alternatives featured all have free versions that let users test the interface and basic functionality. Take advantage of free trials to try different software and find the one that offers security, convenience, and support across platforms.

Let's talk about one is the best multcloud alternatives - CloudMounter.
Cloudmounter is an app that allows you to mount all of your cloud storage accounts as local drives. Instead of syncing your content from your hard drive, Cloudmounter connects you directly to your cloud accounts. 

You can read more about other multcloud alternatives in this article:
https://cloudmounter.net/multcloud-alternative/
Functions in Python with examples.
Tags: beginners, programming, python, functions
Published: 2022-06-30 07:09:37

**1.Introduction**
A function is a set of specified code in which we given some input and the machine  do some computation and gives us the output. Function helps in writing the same code again and again and we can get numerous out once a function is defined. The data is passed in parameters.

**Syntax**
Function is defined with the keyword ’def’ Followed by a variable name and ended with a colon’:’.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r2zgqa3fn93x5wuyl809.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qi964cstkx2kv35uzcs4.png)  
**Calling of a function**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ykeyraslphmlkaq80apx.png)
In above example we called a function by its variable name and assigned a value to a.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fy0klilhp4wvqknnfkxq.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zdmerx2zqfe33vhdbvvj.png) 
In above example we added to value entered by user as many times the user want and we did not have to write the same code again and again because of function.     
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ibu514bh9huw6kbws8z7.png) 
**Types of functions**
There are two types of functions:
1.Built-in functions
2.User defined functions
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/orbbg4ibujrrakoza4od.png)

**Common examples of built-in functions**
1.print( ) function.
2.type( ) function.
3.input( ) function, etc.

**User defined function**
Functions which are defined by ourselves to perform some specified task are called user defined functions. They make code easy to understand by the user.
Tailwind CSS: Cheat Sheet (Chrome Extension)
Tags: tailwindcss, css, chrome, webdev
Published: 2022-06-30 07:08:31

Are you new to Tailwind CSS or maybe you’re returning to give it a second try? In any case, having quick access to the Tailwind CSS cheat sheet is a fundamental part of working with the framework. Everyone knows Tailwind CSS has a peculiar syntax.

The two most popular cheat sheets are either [the official documentation](https://tailwindcss.com/docs/installation) from Tailwind Labs or the [custom-built reference](https://tailwindcomponents.com/cheatsheet/) by Tailwind Components. And now, thanks to [Shahid Shaikh](https://github.com/shahidshaikhs), you can also get the Tailwind CSS cheat sheet as a Chrome extension.

You can get it directly from the [Google Web Store](https://chrome.google.com/webstore/detail/tailwind-cheat-sheet-exte/jmggagicdeomaenmjjlphbamdaeojcol) or visit the [GitHub](https://github.com/shahidshaikhs/Tailwind-Cheat-Sheet-Chrome-Extension) project page.

_All the references are taken from the Tailwind Components page._

Once you install the extension, you can click on the icon in your extension bar and have quick access to various classes and their associated properties. For each property, there’s also a link to the official docs page in case you need additional details. There is a search feature also.

So, for example, if you need a quick reference to all the available `place-items` properties, you can just search for that and click to copy to the clipboard.

The project is open-source, so feel free to contribute. I think the search feature could use a little bit of fine-tuning, as I found quite a few overlaps when searching for classes. And, it would probably be nice if someone could port this over for Mozilla users, too.
How to redirect from server side in HTMX
Tags: htmx, django, flask, fastapi
Published: 2022-06-30 06:15:40

---
title: How to redirect from server side in HTMX
published: true
description: HTMX works like Ajax request but in this blog post I have explained a way to redirect the user from server side.
tags: htmx, django, flask, fastapi
# cover_image: https://rajasimon.io/blog/htmx-server-side-redirect/banner.png
# Use a ratio of 100:42 for best results.
---

Advantage of using HTMX is it feels like snappy. Since I am a backend developer in Python I have used HTMX in Django and Flask. But you can also use this in any server side frameworks including Ruby on Rails and ExpressJS. Or anything that server HTML from the server can use HTMX.

When I was developing the application I come across this problem. I need to redirect the user from server side to different page. But HTMX is making Ajax request on the front and getting response from the backend to change the HTML on the run. So to make this happen HTMX support headers. It will scan for `HX-Redirect` header present in the response headers if it is then it will make the redirect.

In this blog I’m going to explain this concept in details you can use this in your backend framework.

Click this [link](https://rajasimon.io/blog/htmx-server-side-redirect/) to view full article. Originally published on [Raja Simon's blog](https://rajasimon.io/blog/htmx-server-side-redirect/)
OverTheWire- Bandit 0 to 5
Tags: linux, beginners
Published: 2022-06-30 05:48:37

Note:- don't forget to logout before moving to next level
**Level0**
Question:-The goal of this level is for you to log into the game using SSH. The host to which you need to connect is bandit.labs.overthewire.org, on port 2220. The username is bandit0 and the password is bandit0.
Answer:-`ssh bandit0@bandit.labs.overthewire.org -p 2220`
**Level0 -> Level1**
Question:-The password for the next level is stored in a file called readme located in the home directory. Use this password to log into bandit1 using SSH. Whenever you find a password for a level, use SSH (on port 2220) to log into that level and continue the game.
Answer:-
```
ls
cat readme
ssh bandit1@bandit.labs.overthewire.org -p 2220
```
**Level1 -> Level2**
Question:-The password for the next level is stored in a file called - located in the home directory.
Answer:-
```
cat ./-
ssh bandit2@bandit.labs.overthewire.org -p 2220
```
**Level2 —> Level3**
Question:-The password for the next level is stored in a file called spaces in this filename located in the home directory.
Answer:-
```
cat spaces\ in\ this\ filename
ssh bandit3@bandit.labs.overthewire.org -p 2220
```
**Level3 —> Level4**
Question:-The password for the next level is stored in a hidden file in the inhere directory.
Answer:-
```
ls -a
ls -a
cat .hidden
ssh bandit4@bandit.labs.overthewire.org -p 2220

```
**Level4 —> Level5**
Question:-The password for the next level is stored in the only human-readable file in the inhere.
Answer:-
```
ls -a
ls -a
file -/*
ssh bandit5@bandit.labs.overthewire.org -p 2220
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h9nwwhtonyxtcpxyx3op.png)
704. Leetcode Solution cpp
Tags: cpp
Published: 2022-06-30 05:41:35

```
class Solution {
public:
    int bSearch(vector<int>& nums, int target, int start, int end){
        if(end < start) return -1;
        int mid = (start+end)/2;
        // cout << mid << endl;
        if(nums[mid] == target){
            return mid;
        }else if(target < nums[mid]){
            return bSearch(nums, target, start, mid-1);
        }else{
            return bSearch(nums, target, mid+1, end);
        }
    }
    
    int search(vector<int>& nums, int target) {
        return bSearch(nums, target, 0, nums.size()-1);
    }
};
```
278. Leetcode Solution in CPP
Tags: cpp
Published: 2022-06-30 05:39:10

```
bool isBadVersion(int version);

class Solution {
 public:
  int firstBadVersion(int n) {
    int l = 1;
    int r = n;

    while (l < r) {
      const int m = l + (r - l) / 2;
      if (isBadVersion(m))
        r = m;
      else
        l = m + 1;
    }

    return l;
  }
};

```
FastAPI Streaming Response
Tags: python, fastapi, webdev, async
Published: 2022-06-30 05:24:31

## What is a streaming response?
**Streaming Response** basically stream the data. So, how this happen?? Let's say you have a good amount of data. For example, 10MB text data. How you will send data through API? You might get timeout, other network issues for downloading the such a data from server. So, Streaming response come in first place to resolve the issue.

## How it works?
It's really simple. Think how your downloader works, chunk by chunk. So, the Streaming response is. Your 10MB will be downloaded chunk by chunk. In the technical language we call it multipart.

## Streaming Response in FastAPI
```python
from typing import Generator
from starlette.responses import StreamingResponse
from fastapi import status, HTTPException

# A simple method to open the file and get the data
def get_data_from_file(file_path: str) -> Generator:
    with open(file=file_path, mode="rb") as file_like:
        yield file_like.read()

# Now response the API
async def get_image_file(path: str):
    try:
        file_contents = get_image_from_file(file_path=path)
        response = StreamingResponse(
            content=file_contents,
            status_code=status.HTTP_200_OK,
            media_type="text/html",
        )
        return response
    except FileNotFoundError:
        raise HTTPException(detail="File not found.", status_code=status.HTTP_404_NOT_FOUND)
```
You just use the function `get_image_file` and you'll get your desired Streaming response.  

## Why I am writing about it?
Because there is a twist about it. Starlette(The mother of FastAPI) encountered a bug about async generator. To working around the issue in FastAPI it created another issue. When you use sync generator for serving file or stream the response it because really slow.
[Bug link here](https://github.com/encode/starlette/issues/793).

**Moral of the story** We should use the async generator for serving/streaming the API. Implementation is here,
```python
from typing import Generator

# Just use the async function you already have. :)
async def get_data_from_file(file_path: str) -> Generator:
    with open(file=file_path, mode="rb") as file_like:
        yield file_like.read()

```

That's it. Now I am good to go.
Customizing Columns Using Templates in Angular Gantt Chart
Tags: webdev, angular
Published: 2022-06-30 05:21:24

Learn how easily you can customize the column headers and data in the Angular [Gantt Chart](https://www.syncfusion.com/angular-ui-components/angular-gantt-chart) component using templates. In this video, the custom toolbar buttons Quick Filter and Clear Filter are rendered, along with predefined toolbar items Expand All and Collapse All. 

**Product overview**: https://www.syncfusion.com/angular-ui-components/angular-gantt-chart

**Download the example from GitHub**: https://github.com/SyncfusionExamples/customizing-columns-using-templates-in-angular-gantt-chart

{% youtube ZVwZAE0Uu7g %}
Two things I find difficult
Tags: programming, webdev, embedded, datascience
Published: 2022-06-30 04:39:24


In web development:
- synchronizing state between frontend and backend
- distributing state inside a frontend application

In embedded software:
- getting the LED to blink at the right speed
- I2C

In software architecture:
- communicating with people who don't think in systems
- getting team buy-in while keeping a coherent vision

In data science:
- cleaning and indexing CSV files
- recognizing and explaining the 800 ways data can lie

When learning:
- finding the right balance between practice and theory
- making up exercises when none exist

(titile image: wolfgangfoto - CC)
React js & material UI
Published: 2022-06-30 04:08:58

**1. Link**

```
**Parent component**
import { Link } from 'react-router-dom'

<Link
                              to={{
                                pathname: "/dashboard/selectmapsubjctefaculaty",
                                state: { row }
                              }}
                            >
                              <Button
                                size='small'
                                className='mr-1 fullWidth'
                                color="secondary"
                                variant='contained'
                                sx={{ width: "100%", p: "0.1em", borderRadius: "2px" }}
                              >Assign Faculty</Button></Link>

**Child component**

import { useLocation } from 'react-router-dom/cjs/react-router-dom.min'

 const location = useLocation()

  let subject = location.state.row

```

**2. MUI Autocomplete**

```
import { Autocomplete, Box, TextField } from '@mui/material'
import React, { Fragment, useState } from 'react'
import styled from '@emotion/styled';

 const _handleInputChange = (e, data) => {
    if (e.target.value.length > 3) {
      GET_SEARCH_STUDENT(e.target.value)
    }
  }
  const _handleChnage = async (e, value) => {
    let res = await GET_STUDENT_DETAILS(value?.id)
    setStudentDetails(res)
  }
  const _handleAddFee = () => {
    setAddFeeType(!AddFeeType)
  }

  <Autocomplete
        sx={{ boxShadow: 4 }}
        id="auto-com"
        options={searchStudent}
        renderInput={params => (
          <StyledInputBase {...params} label="Search student" />
        )}
        getOptionLabel={option => `${option?.firstname} ${option?.lastname} ${option?.phone}`}
        style={{ boxShadow: 3 }}
        onChange={(e, newvalue) => {
          _handleChnage(e, newvalue)
        }}
        onInputChange={handleInputChange}
      />


```
Apply Agile to the Family
Tags: agile, productivity, webdev, discuss
Published: 2022-06-30 03:52:10

Although I have [recently criticized some aspects of Agile](https://leanpub.com/rethinkingagile), it does some things very well.

1. It creates a sense of mission across a variety of roles within a team.

2. It provides frequent opportunities to evaluate work in progress and pivot as needed.

3. It emphasizes small wins that can add up to a larger purpose.

To put it another way, we can break the Agile methodology into several components:

1. There is a team with multiple roles.

2. The team works together towards a mission within their distinct, yet sometimes overlapping goals.

3. The team has tasks on its mission.

4. The team tracks its tasks and evaluates periodically as tasks are being done.

The principles of Agile may be applied across any organization that also has a team with a mission comprised of a multitude of tasks and roles within that mission.

The family is such an organization.

We don't always think of it in this way, but the family is a mini government, a mini organization, a mini team.

Families do well to have a concrete mission. They should have aims as to what they should produce and how they may contribute to larger society for good--and how they can accomplish such things in a way that builds every member up.

Members of a family have distinct skills, experience, strengths, interests, callings, roles, and responsibilities. Yet, they are contributing to a shared mission.

Putting it all together, a family is a team with many roles found within it. A family may have a mission and small wins (tasks) to accomplish that mission, delegating work across the variety of members.

Therefore, why can't an Agile methodology be applied to a family?

Here's what it could look like:

- Write out your family mission
- Aggregate current tasks and projects that are a part of that mission
- Make these tasks and projects deliverables that are small but important wins 
- Distribute the work across the team
- Take time to check in on progress, see how things are going, discuss any difficulties, pivot as needed, and reflect to commend each other for what has gone well, yet still working on areas of improvement

For my family, which right now is only comprised of my wife and our not-even-one-year-old, we have formed a long term mission.

While the long term mission is something we always think about and prepare for in the background, we pursue it until it changes.

Each year, we set aside goals for what we would like to accomplish, to be intentional about.

Every month, we set aside some projects that can help us towards some of our goals.

Every week, we jot down some projects we can work on as well as the everyday life type of work.

At the start of each week, we review how the past week went, discuss our plans for the new week, and record an action items, making those action items tasks for the week.

Rinse and repeat.

Have you tried applying Agile to your family?
462. Leetcode solution in CPP
Tags: cpp
Published: 2022-06-30 03:42:48

```
class Solution {
 public:
  int minMoves2(vector<int>& nums) {
    const int n = nums.size();
    nth_element(begin(nums), begin(nums) + n / 2, end(nums));
    const int median = nums[n / 2];
    return accumulate(begin(nums), end(nums), 0,
                      [&](int a, int b) { return a + abs(b - median); });
  }
};




```
How to create turn off icon in linux?
Tags: systems, linux, vietnameseblogs
Published: 2022-06-30 03:32:56

Hi, I'm Tuan. Today I will create shutdown icon for linux operating system.

- you are in a hurry, want to shutdown quickly on ubuntu complicated shutdown operations, type the command that makes you uncomfortable. Let's learn about creating shutdown icon.
I will help you to create a turn off icon for ubuntu. You can only install the icon on your computer screen. To create the icon, it must go through the following steps:

1. Create a file named turn-off.desktop using terminal cat > turn-off.desktop

2. Turn on write file mode and write the command line:
`[Desktop Entry]
Version=x.y
Name=Shut down icon
Comment = create by Tuan Tran 
Exec=/sbin/shutdown -Ph now
Icon=/usr/share/icons/Humanity/places/16/folder_home.svg
Terminal=false
Type=Application
Categories=Utility;Application;`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/djram1ihf7pqbvnq6zqn.png) 
3. Left click enable properties and go to permission tab allow executing file as program
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o2zixcrxc9et92jjwbpy.png) 
4. Right click allow lauching and here is the result:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7jtl4qp0hjy85z4ztaz0.png)
So you are done creating the shutdown icon. good luck!
C#: How to mock HttpContext methods such as ForbidAsync?
Tags: csharp, mock, httpcontext
Published: 2022-06-30 03:17:57

When writing unit test, we need to mock "HttpContext" methods such as ForbidAsync, SignInAsync, etc.

As these methods are extension method, we need to know which actual method to mock.

# Unit Test

This is the code I use to test "ForbidAsync".

```csharp
Mock<IAuthenticationService> mockedIAuthenticationService = new();
mockedIAuthenticationService
    .Setup(x => x.ForbidAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()))
    .Returns(Task.FromResult((object)true));
Mock<IServiceProvider> mockedIServiceProvider = new();
mockedIServiceProvider
    .Setup(x => x.GetService(typeof(IAuthenticationService)))
    .Returns(mockedIAuthenticationService.Object);
Mock<HttpContext> mockedHttpContext = new Mock<HttpContext>();
mockedHttpContext.Setup(x => x.RequestServices).Returns(mockedIServiceProvider.Object);
```
# Where does it come from?

[AuthenticationHttpContextExtensions](https://github.com/dotnet/aspnetcore/blob/main/src/Http/Authentication.Abstractions/src/AuthenticationHttpContextExtensions.cs) indicates it comes from IAuthenticationService, which is obtained via ``context.RequestServices.GetService<IAuthenticationService>()``.

So I just need to mock IServiceProvider and IServiceProvider.

Hope this helps me again in the future.