teleren/devto huggingface dataset:
An introduction to custom React hooks
Tags: react, javascript
Published: 2022-09-08 08:33:31

As someone who's written React for several years now, it took me far too long to discover the joy of custom hooks - in fact it took me over 3 years! In this post, I'm going to show you how to take advantage of one of React's most powerful features.

## What even is a hook?

A hook is quite simply a function which lets you _hook_ into React's rendering lifecycle. Let's briefly look at the most common hook `useState`:

```tsx
const [state, setState] = useState(0)
```

As you can see, `useState` _hooks_ into React and provides an interface for managing state - it's entirely abstracted away the complexity that would otherwise be associated with it.

When we think of hooks as reusable abstractions, it makes them easier to reason about. As a component is reusable markup, a hook is just reusable logic!

I like to refer to React's built-in hooks as _atomic_ - in that we typically use and combine them to build our own custom ones.

## Our first custom hook

Let's build a basic custom hook to manage the state of a toggleable component (modal, dropdown, etc):

<small>useToggle.ts</small>
```tsx
import { useState } from "react";

function useToggle(initial = false) {
  const [state, setState] = useState(initial);

  return [
    state,
    {
      open: () => setState(true),
      close: () => setState(false),
      toggle: () => setState((state) => !state)
    }
  ] as const;
}

export default useToggle;
```

> Quick tip: using `as const` on our return value tells TypeScript to infer the type as a readonly tuple instead of a union type array! 😁

In this example, all we've done is _wrap_ the use state hook with some logic that would otherwise pollute a component - look how easy it is to implement:

<small>App.tsx</small>
```tsx
function App() {
  const [state, { open, close, toggle }] = useToggle();

  return (
    <div className="App">
      <button onClick={open}>Open</button>
      <button onClick={close}>Close</button>
      <button onClick={toggle}>Toggle</button>
      {state && <div>Hello!</div>}
    </div>
  );
}
```

...and that's it! I hope that after seeing this you can start to see how you might implement other hooks - try `useQueue` and `useStack`.

In a future post I'll detail how to implement some more complicated behaviour, and some common design patterns for handling refs, external data and more.
Parts &amp; accessories - Page 1 - Always Armed
Tags: programming, node
Published: 2022-09-08 08:24:17

1.What are the different types of gun parts?

Weapons. It is an area that has been under public scrutiny in recent times. So it’s fair enough to say that the topic should be discussed. If want to get specific, then the topic is going to be about guns. 

Gun is a basic weapon in the hierarchy of high-grade weapons. It classifies as a broad category itself. There are multiple types of guns available for everyone. There are multiple methods of categorizing guns.

It is not a single entity. It is made of many [Gun Parts](https://alwaysarmed.com/parts/). Certain parts are mandatory while other parts work as add-ons. All the mandatory parts are required to manufacture a working gun.

We are going to discuss the AR-15 gun and its parts here. Our priority includes mandatory parts. These are mentioned below:
1.Barrel
2.Bolt carrier group
3.Lower receiver parts (Lower parts)
4.Upper receiver parts (Upper parts)
5.Gas system length.

All of these parts need to be selected according to the basic requirement behind building an AR-15. Next, we have all the different parts and accessories that are added to it to build a full-functioning weapon:
1.Cleaning tools
2.Stocks and Grips
3.Bolt Carrier Groups
4.Calibre Conversion Kits
5.Charging Handles
6.Grips
7.Muzzle Devices
8.Stocks Triggers
9.Magazines
10.Stripped Upper.

These parts are also necessary for the system to function. But these can be selected with a little bit of leeway. Also when it comes to accessories, selecting the ones that are relevant and appropriate to the purpose turns out beneficial. Always. [Complete Pistol Kits](https://alwaysarmed.com/)
Looping through objects in javascript
Tags: javascript, react, node, angular
Published: 2022-09-08 08:14:15

In this post I will explain you the various methods to loop through objects in javascript programming language.


## for . . . in 

- This approach  is used to loop through the keys of an object
- By looping through the keys, you can get the value using object[key]

```javascript
const object = {
  name: "Dhanush",
  language:"js"
}

for(const key in object){
  const value = object[key]
  console.log("Key: ",key)
  console.log("Value: ",value)
}

// Key: name
// Value: Dhanush
// Key: language
// Value: js

``` 

## Object.keys()

- The keys method of the Object constructor returns an array of the keys in an object
- With the array of keys you can then loop through the array using any array approaches.
- You can get the value fo the objects key also using object[key]


```javascript
const object = {
  name: "Dhanush",
  language:"js"
}
const keys = Object.keys(object)
// ['name', 'language']
keys.forEach(function(key){
  const value = object[key]
  console.log("Key: ",key)
  console.log("Value: ",value)
})

// Key: name
// Value: Dhanush
// Key: language
// Value: js
``` 

## Object.values()

- The values method returns an array of the values in an object ( opposite to keys method )
- With the array got you can loop through them using any array functionality
- You can use a key to get a value directly but you cannot use a value to get a key directly


```javascript
const object = {
  name: "Dhanush",
  language:"js"
}
const values = Object.values(object)
// ['Dhanush', 'js']
values.forEach(function(value){
  console.log(value)
})

// Dhanush
// js
``` 

## Object.entries() 

- The entries method returns an array of subarrays where each subarray has two items, the first one being the key and the second one being the value
- Unlike the keys and values method, entries returns the keys and values of an object in subarrays.
- Then you can access them using the index.


```javascript
const object = {
  name: "Dhanush",
  language:"js"
}
const entries = Object.entries(object)
// [
//   ['name', 'Dhanush'],
//   ['language', 'js'],
// ]
entries.forEach(function(entry){
  const key = entry[0]
  const value = entry[1]
  console.log("Key: ",key)
  console.log("Value: ",value)
  
console.log(value)
})

// Key: name
// Value: Dhanush
// Key: language
// Value: js
``` 

Twitter post 👇

{% twitter 1567196752536535041 %}

Thanks for reading 🙏 

Hope you liked this post, If you have any questions please feel free to reach out to me via [Twitter](https://twitter.com/Dhanush_Nehru/)

Leave a like & follow for more ✌️
Today's Daily Humor For Devs - Daily Developer Jokes
Tags: jokes, dailydeveloperjokes
Published: 2022-09-08 08:00:10

---
title: "Today's Daily Humor For Devs - Daily Developer Jokes"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
published: true
tags: #jokes, #dailydeveloperjokes
---

Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one.

![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e125933e8609.png)

---

For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes).

### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too!

_This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit._

<!--
Joke text:
___Q:___ What did the fruit basket say to the developer?

___A:___ I hope you're ready for some pear programming!
 -->
Failing is better than not trying
Tags: watercooler, beginners
Published: 2022-09-08 07:47:22

I've wanted to optimize my website even more for the longest time.
Every weekend I try to dedicate some time to see where I can optimize it even more.

This weekend it was all around CSS loading.
It's already pretty optimized, and there were only two items I could think of.

- Page by page loads
- Preloading stylesheets

## Page by page loads

Unfortunately, this is not supported with Tailwind in Astro as we get one generic output CSS.
For my website, it doesn't make the biggest difference as the post pages only have a couple of lines of extra CSS compared to the homepage.

However, still looking at how I can optimize what's used even more.

**Conclusion**: Nothing to optimize for a quick win. More research is needed.

## Preloading stylesheets

I wasn't sure if this one would help, but we could declare the main stylesheet as important by adding a `rel="preload"` link.
This would indicate that the page should try and fetch this with the most priority.

It sounded easy to try out, but it took a lot of research and trying out things.

I went over the Astro docs and found out you can load the stylesheets as a plain URL by appending a `?url` parameter.

Then, we can load it directly like this:

```js
---
import stylesUrl from '../styles/main.css?url';
---
<link rel="preload" href={stylesUrl} as="style">
<link rel="stylesheet" href={stylesUrl}>
```

The dev version worked perfectly, but then I tried outputting this as a build, and I noticed it base64 encoded the whole CSS file.

It is documented in the docs this can happen, and we have to disable this Vite config.
I added the following to my `astro.config.mjs` file:

```js
export default defineConfig({
  vite: {
    build: {
      assetsInlineLimit: 0,
    },
  },
});
```

I reran my build output and ended up with a compiled CSS like this:

```css
@tailwind base;
@tailwind components;
@tailwind utilities;
.some-of-my-custom-css {
  // ...
}
```

Ugh, not really what I wanted as our Tailwind is not processed now.

I took one of my existing build compiled CSS files for option three and put them in my project.

> Note: My CSS doesn't ever change, so that it could be a viable option.

I changed my imports to load this CSS file, and voila, it worked!

Eagerly I went to try my tests again to see how fast it was loading.
To my disappointment, it went backward. It now took another 2ms longer to load the first byte.

And thus, back to the drawing board with CSS optimizations.

## Conclusion

Sometimes you might have put a lot of work into something that does not work as you expected.

It's totally fine, and it happens to everyone.
At least you learned something, and you tried it out.

I generally don't write as much about my failed experiments, but I thought it might help other people not to feel bad when something doesn't work on the first try.

### 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)
Reading time calculator tool
Tags: programming, javascript, webdev
Published: 2022-09-08 07:28:15

Search engines are shifting focus from long form content to short form content. Some examples:
1. Featured snippets (short form answers)
2. Reading labels in search (Experimental Time to read badge by Google) to let user decide to read long form article or short form article. 
Seeing lot of youtube videos too suggesting the same.

So in order to have better rankings at search, it's important to estimate the total time taken to read a blog post. 
To calculate that, developed a free tool to estimate the total reading time (including images). 

Here is the [Reading time calculator](https://tipseason.com/reading-time-calculator) tool. 

Looking for feedback on the tool and want to know your thoughts if any other features are missing. Thanks in advance.
2402. Leetcode Solution in CPP
Tags: cpp
Published: 2022-09-08 07:25:03

```
using LL  = long long;
using PLI = pair<LL,int>;
class Solution {
public:
    int mostBooked(int n, vector<vector<int>>& meetings) 
    {
        priority_queue<PLI, vector<PLI>, greater<>>busy;
        priority_queue<int, vector<int>, greater<>>free;
        for (int i=0; i<n; i++)        
            free.push(i);
        
                
        sort(meetings.begin(), meetings.end());                
        vector<LL>count(n);        
        
        for (int i=0; i<meetings.size(); i++)            
        {
            LL start = meetings[i][0];
            LL end = meetings[i][1];
            
            while (!busy.empty() && busy.top().first <= start)
            {
                free.push(busy.top().second);
                busy.pop();
            }
            
            if (!free.empty())
            {
                int idx = free.top();
                count[idx]++;                
                free.pop();
                busy.push({end, idx});                                
            }
            else
            {
                auto [time, idx] = busy.top();
                count[idx] += 1;
                busy.pop();
                busy.push({time + end- start, idx});                
            }
    
        }
        
        return max_element(count.begin(), count.end()) - count.begin();
    }
};
```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/meeting-rooms-iii/
I got selected for GitHub Field Day Philippines! 💜
Tags: github, community, womenintech
Published: 2022-09-08 07:16:26

Credits to [ GitHub Field Day Philippines FB Page](https://www.facebook.com/GHFieldDayPH) for the image I used in the cover photo. 

---
Hi! Julia here, a beginner blogger. I just wanted to share this great news. Last September 1, 2022, I received an email stating that I've been selected as one of the attendees of #GHFieldDayPh. 

**What is GitHub Field Day?**

"GitHub Field Day is an unconference for leaders of technical student communities in the Philippines☂️🇵🇭", as described in their official [Facebook Page](https://www.facebook.com/GHFieldDayPH). It is a one day unconference field with educational talks, activities and a lot of fun. It has been happening across the the globe and GitHub Field Day Philippines is the first in South East Asia. 

**What's in store for the attendees?** 

Selected leaders from different parts of the Philippines can connect and learn from each other's challenges in managing their local tech communities. The event is free inclusive of lunch 🍝, snacks 🍔 and some swag ⚡🛍️! 

**Registration Process**

Registration started on July 20, 2022 and ended last August 21, 2022 via google forms. 

**Summary**
I'm indeed grateful for this opportunity to learn, connect and have fun in the unconference. I'm excited to meet the other attendees and make new friends. I'll also make a blog update about what happens on the event.💜
You Need Just 4 Steps to Responsive Design Approach
Tags: webdev, responsive, web, html
Published: 2022-09-08 07:12:47

**step 1:** At first, develop a html structure according to design, just only html (no css).

**step 2:** This only html structure provides you mobile-like small devices' design(check it on dev tool). Put typography, color, padding, margin in the html through css, but do not put any layout style.

**step 3:** Find out break points using dev tool and then use @media query according to that breakpoints. In this step, concentrate on layout. Use `display:flex/grid/block/inline` and other properties into @media query.

**step 4:** Use less number of @media query as much as possible to reduce complexity.
Coding Period GSoC'22 | Week 10 + 11 + 12
Tags: gsoc, javascript, webdev, career
Published: 2022-09-08 07:08:10

I am sharing my progress for Weeks 10 and 11 in this blog.

### Task Completed

By now, we have completed following tasks:
- [Simulator Testing](https://github.com/CircuitVerse/CircuitVerse/tree/master/simulator/spec).
- [Importing and Exporting of CircuitFiles](https://github.com/CircuitVerse/CircuitVerse/tree/master/simulator/src/file).
- [Touch Compatibility](https://github.com/CircuitVerse/CircuitVerse/pull/3236).

![clapping-meme-gif](https://c.tenor.com/Cn6yJ4YTMJgAAAAC/good-job-clapping.gif)

### Week In Review

Completed [Mobile Touch Compatibility](https://github.com/CircuitVerse/CircuitVerse/pull/3236) task for simulator and finally got Pull Request merged in Primary codebase 🎉.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t96kjffc6qijba71604y.png)

Now we can simulate circuits from our mobile or tablet.

![Mobile-view-simulator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ytpbrqfp2qn5byfe0kk9.jpg)


**Pull Requests**

- [Touch compatibility || GSoC'21 + GSoC'22](https://github.com/CircuitVerse/CircuitVerse/pull/3236)
- [hotfix: simulator mobile-UI for smaller devices](https://github.com/CircuitVerse/CircuitVerse/pull/3272)
- [feat: logic to toggle mobile view for simulator](https://github.com/CircuitVerse/CircuitVerse/pull/3268)



### Future Plan

Currently, we are working on Custom Dialog Box task 🚀. Hopefully we will complete Custom Dialog task by next week 🥳.

That's all for now; stay tuned for more updates😉.

**Thank You**
Amazon S3. 6 Essential CLI Commands to better manage S3 Buckets.
Tags: aws, s3, storage, cloudskills
Published: 2022-09-08 06:47:27



Amazon S3 or simple Simple Storage Service is a simple an object storage service offered by Amazon Web Service. With S3, the users can store various type of data (images, texts and or videos) as object in buckets. 

 AWS has a great web interface for creating , deleting and managing S3 buckets but it is nothing compared to the flexibility and the speed that the CLI offers

 The list of CLI Command available is extensive. To lean more and go beyond what I will be converting in this blog post, click [here](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/index.html) 





 Bellow are 6 CLI Commands that any cloud engineer must know when dealing with Amazon S3.

 

---


## 1. The “mb” command Creating a new S3 Bucket.

 This command is used to create new S3 Buckets. Make sure that the bucket name is unique.

>  Aws s3 mb myBucketName

```
aws s3 mb myBucketName
```

## 2. The “ls “command.

 Used to inspect buckets by listing Buckets or the content of Buckets.

>  aws s3 ls 


```
aws s3 myUnikMajicBucket
```

## 3. The “mv” command.

This is used to move things around. From local to S3, from S3 to local as well as between S3 Buckets. 
 People tend to get confused between the “mv” and the “cp” or copy command.  mv is used to move files from location A to location B (The files no longer in location A). When “cp” is used, the file is in both location A and location B.

 > Move files from local to S3
```
aws s3 mv file1_name.txt s3://bucket-name/file2_name.txt_
```


 > Move from S3 to local
```
aws s3 mv s3://bucket_name/file1_name.txt file2_name.txt
```
 
> Move files between S3 Buckets
```
aws s3 mv s3://bucket_name/file1_name.txt s3://bucket2_name /file2_name_2.txt  
```

## 4. The “rb” command

 This is used to delete or remove S3 Buckets.  This will only work if the bucket is empty 


```
aws s3  rb myBucket_name
```

Used to force  delete a bucket along with his contents 

```
aws s3 rb Bucket_name --force  
```


## 5. The “rm “command.


 This is used to delete the content of an S3 bucket.


```
aws s3 rm <s3url_to_the_file>

```

## 6. The “sync “command.

This is used to sync or update files either from local to s3, from s3 to local or  between s3 buckets 

```
aws s3 sync ./local_folder s3"//mybucket_name

```
Background removal on car images - Machine learning project
Tags: python, serverless, machinelearning, keras
Published: 2022-09-08 06:35:40

### Introduction
The goal of this project was to have an algorithm capable of removing the background of a vehicle image automatically with machine learning.

### Technical
This was done with Python using the framework **Keras**, **Tensorflow** and a number of known python libraries like Numpy, Pandas, OpenCV, etc…

The algorithm uses a lot of CPU power to predict and remove the background and by consequence, this raises a scalability issue, it can get very costly to deploy and scale something like this.
So to get something high-performance and scalable, i did a lot of work optimizing the code, packaging, removing useless code all to reduce the size of the end result.

After weeks of hard work, i was able to deploy it in a Serverless environment on Google cloud with Cloud Functions.
So now, i had a ML model that is fast, scalable and almost totally free (1mil operations per month for free).

**Source:**
https://www.ibragim.fr/portfolio/detourage-automatique-voitures-ia/
121 days streak on Leetcode🥳🥳🥳🥳
Tags: leetcode, programming, challenge, chiki1601
Published: 2022-09-08 06:15:53

I completed today 121 days strak on Leetcode.....🥳🥳🥳🥳
I am glad that my consistency is increased...and I become a regular person since 121 days...

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qet0bnfx9aa92jfn9xqa.png)
Keyboard KeyCode Finder
Tags: javascript, webdev, css
Published: 2022-09-08 06:12:00

Hey, Have your ever wondered "what is the keycode of particular key that you are pressing?"
While doing a project or creating a website, Mouse plays the major part. But, Sometimes we need Keyboard too, to make the website or project much responsive and look cool.

To include the keyboard in this JavaScript, One should know the Keycodes of all the keys in the keyboard, which is quite an impossible thing to do. 
 
Here comes my website. By using this, You get the keycode of every key in the keyboard that you pressed. 
There is a _Copy_ button available. You can easily copy the keycode and paste them in your code.
 
**Click the below Link**

[Link🔗](https://keycode-finder-praveenkumarpanchadarla.vercel.app/)
AWS Certified Developer Associate prepare
Tags: 30daysofaws, certifieddeveloperassociate, awsquestions, aws
Published: 2022-09-08 05:07:40

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


Hello Cloud Learners,
I want to go through the topics that are covered in the AWS Certified Developer Exam.

Let's it be a 30-day challenge, another way it can take unlimited time. I will cover essential knowledge parts that would be enough to know on the practice side.

The AWS website has [Exam Preparation Guide](https://d1.awsstatic.com/training-and-certification/docs-dev-associate/AWS-Certified-Developer-Associate_Exam-Guide.pdf)

To pass the exam, you need to know certain services from the 5 domains: Deployment, Security, Development with AWS Services, Refactoring, Monitoring and Troubleshooting

I made some [adjustments to the topics flow](https://romankurnovskii.com/en/docs/aws-certified-developer-associate/#training-plan)

This is how my **roadmap** and the order looks like:

1. AWS Identity and Access Management (IAM)
1. Amazon EC2
1. AWS Elastic Beanstalk
1. AWS Lambda
1. Amazon S3
1. Amazon DynamoDB
1. Amazon ElastiCache
1. Amazon RDS
1. Amazon API Gateway
1. Amazon CloudFront
1. Elastic Load Balancing (ELB)
1. Amazon Kinesis
1. Amazon OpenSearch Service (Amazon Elasticsearch Service)
1. Amazon CloudWatch
1. AWS CloudFormation
1. AWS CodeCommit
1. AWS CodeDeploy
1. AWS CodeBuild
1. AWS CodePipeline
1. Amazon CodeGuru
1. AWS CodeStar
1. AWS CodeArtifact
1. AWS X-Ray
1. AWS Fault Injection Simulator
1. Amazon Elastic Container Registry (Amazon ECR)
1. Amazon Elastic Container Service (Amazon ECS)
1. AWS Fargate
1. Amazon Elastic Kubernetes Services (Amazon EKS)
1. Amazon Cognito
1. AWS Key Management Service (AWS KMS)
1. Amazon EventBridge (Amazon CloudWatch Events)
1. Amazon Simple Notification Service (Amazon SNS)
1. Amazon Simple Queue Service (Amazon SQS)
1. AWS Step Functions

At the same time, I will go through domain related questions. Some of them (most interested) will post here.