teleren/devto huggingface dataset:
React Custom Hooks (useDebounce)
Tags: react, reacthooks, customhooks
Published: 2023-08-07 18:03:59

## INTRO
Hello World! 👋
Today's custom hook is `useDebounce`. In this post we will discuss what is debounce method, how to develop through custom hooks and javascript.


## USAGE
Debounce is one of the important concept in JavaScript. Debounce function helps to wait certain amount of time before running again. It is very helpful to reduce the frequent calls (renders) of the function. So that the program efficient will increase.
`For example` If we want to call api with search option, every time we call onchage method then the api will also call so it causes many api calls. It effects on application performance. 

To overcome this problem We have to limit the state update every time we state change, Debounce method will helps to reduce this state update limit.

There are two ways to write the debounce method, one is by the react hooks and second one is by using pure javascript.

## CODE

**HOOK**

```javascript
import { useState, useEffect } from 'react'

export const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
    useEffect(() => {
        const handler = setTimeout(() => {
            setDebouncedValue(value);
        }, delay);

        return () => {
            clearTimeout(handler);
        };
    }, [value, milliSeconds]);

    return debouncedValue;
};
```

**HELPER**
```javascript
export function helperDebounce(fn, delay) {
    delay = delay || 400
    let timer;
    return function () {
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn(...args);
        }, delay);
    };
}
```

## USE CASE
**HOOK USE CASE**
```javascript
import React, { useEffect, useState } from "react";
import { useDebounce } from "../../hooks/useDebounce";

function App() {
  const [value, setValue] = useState("");
  const debonceValue = useDebounce(value, 500);
  useEffect(() => {
    console.log(debonceValue);
  }, [debonceValue]);
  return (
    <>
      <input
        type="text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        placeholder="with hook debounce"
      />
      {debonceValue}
    </>
  );
}

export default App;

```

**HELPER USE CASE**
```javascript
import React, { useState } from "react";
import { helperDebounce } from "../../helpers/helperDebounce";

function App() {
  const [value, setValue] = useState("");

  const handleChange = helperDebounce((e) => {
    setValue(e.target.value);
  }, 500);
  console.log(value);
  return (
    <>
      <input
        type="text"
        onChange={(e) => handleChange(e)}
        placeholder="with helper debounce"
      />{" "}
      {value}
    </>
  );
}

export default App;

```

## OUTPUT

![debounce hook output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8daw9pn1gcckiofdi9k4.gif)
Build Chess game with Pygame
Tags: beginners, programming, tutorial, python
Published: 2023-08-07 17:54:37

Today, I'm excited to share my recent project where I took on the challenge of building a fully functional chess game using Python and the Pygame library. 

**If you want to checkout the full code Here is the GitHub [link](https://github.com/Sadeedpv/pygame_chess)**

If you want to play the game, all you have to do is type the following command on the terminal:
```
python main.py
```


> Feel free to mention any potential issues with the code or better ways to implement them in the comments, as I am relatively 
new to the `pygame` library.


### Here are some explanations of the code:

* The `pygame` library is used to create the graphics and handle the user input.
* The `chessboard` is a 2D list that represents the chessboard. Each element of the list is a string that represents the piece that is on that square.
* The `draw_board()` function draws the chessboard on the screen.
* The `handleClick()` function handles the logic for when the user clicks on a square on the chessboard.
* The `get_moves()` function returns a list of all the possible 
moves for a given piece.

### Features I would love to add

> In real chess, you win by checkmating the king; except here, you have to capture the king to win the game. 

There are some features I would love to add to this game like:
* King side and Queen side Castling
* En passant (If you don't know En passant, please Google)
* Ability to play against the AI

That being said, I am happy to share my experience with you. Chess is a very complex game and writing code for chess can get really messy in no time.
I'm joining Astro full time!
Tags: astro, opensource, webdev, javascript
Published: 2023-08-07 17:43:01


After spending a couple of years at [vBridge Cloud](https://www.vbridge.eu), I'm leaving the company. I've worked at vBridge as a software engineer eversince I graduated.

I had an amazing time there and learned a lot from each and every colleague. Thanks guys! For everything.

![Picture of the vBridge team](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ap8vp0zmkxeic3zt9szk.jpeg)

Now, it's time for a new adventure! I'm joining the DX-team at [Astro](https://astro.build) full-time! I'm so excited to be able to work on Astro full-time and help shape the future of web development!

After being nominated and selected as a maintainer for the project, this always felt like one of the next steps. You can read [the blogpost about becoming a maintainer here](https://www.elian.codes/blog/23-04-12-becoming-an-astro-maintainer/)

After being invited and flying out to Copenhagen to attend the first ever Astro meetup, where I met so many faces behind Astro, I knew that I wanted to stay involved with the project and help out where I could.

| ![Picture of the Astro meetup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqck1frgh2cn8fmoy229.jpg) | ![Picture of the Astro 3 displayed on a screen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gd33y4ocegzibig97h4r.jpg) |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |

## Team DX - Astro

The DX-team at Astro is something I've always resonated with. They are responsible for communication, welcoming new people and help them get started with Astro, keeping documentation updated and so much more!

One of my major tasks, will be the community! (In other words, you guys!)

Ranging from the weekly community calls, helping the support squad and reviewing and helping you guys make PRs!

(If you're interested in joining the Astro community, [join us on Discord](https://astro.build/chat))

Astro has given me so much, ranging from opportunities to travel the world, making new friends and learning so much about open source!

![A picture of Elian presenting Astro at JSWorld](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/90w79469q6lkxbv6kts3.jpg)

Let's change the future of web applications!

Interested to see what I'm doing? Follow me here:

- GitHub: [@ElianCodes](https://github.com/eliancodes)
- Twitter: [@eliancodes](https://twitter.com/eliancodes)
- Mastodon: [@eliancodes](https://webtoo.ls/@eliancodes)
Log Share: Enhance Collaboration and Streamline Troubleshooting
Tags: webdev, softwaredevelopment, bugmanagement, logmanagment
Published: 2023-08-07 17:42:04

[ClearInsights](https://clearinsights.io/logging/) [Log Share](https://clearinsights.io/blog/clearinsights-log-share-enhance-collaboration-and-streamline-troubleshooting/) is a revolutionary feature that streamlines collaboration and troubleshooting. By securely [sharing logs](https://clearinsights.io/blog/clearinsights-log-share-enhance-collaboration-and-streamline-troubleshooting/) with partner companies, teams can resolve issues faster and gain deeper insights for data-driven decisions. The customizable access control ensures data privacy and enhanced efficiency in log management. Embrace [ClearInsights](https://clearinsights.io/logging/) Log Share for optimized workflows and seamless cross-team collaboration.
Using Sinatra Filters
Published: 2023-08-07 17:29:52

######Sinatra filters are special methods invoked for each individual request and evaluated in the same context as the routes. They provide an efficient way to organize logic and make variables available across multiple routes. There are two types of filters, `before` and `after`, named for when they are executed in relation to a particular request.

 

The `before` filter's use cases include authentication, logging, and the declaration of instance variables that should be available to all or a several routes **within the same request-response cycle**. This is an important distinction! Variables declared inside a `before` filter will be initialized before each request and made available to all the routes that follow in that particular cycle. This behavior is different from regular instance variables declared in the body of the application, which can retain their value across different requests.

Here is a hypothetical example, showcasing the use of `before` in a version of the Umbrella app that implements user authentication.
```ruby
before do 
	# Redirect to login route if user not authenticated
	unless session[:user_id] 
		redirect to('/login') 
	end  
	
	# Log the request 
	logger.info "Request: #{request.request_method} #{request.path} Params: #{params.inspect}"

	# Pre-process some data from the request to make it available to the routes
	if params[:data] 
		@user_coordinates = get_coordinates(params.fetch("user_location")) 
	end
end

# Helper method to retrieve user's location coordinates from Google Maps' API
def  get_coordinates(user_location) 
	# Make a request to Google Map's API and process response to get the specific coordinates
	user_coordinates
end
```


 

The `after` filter has access to a similar context as `before`. However, as its name implies, it is invoked _after_ the route block is finished. (Although I have not had the opportunity to use this filter within my applications, I am including the example below for documentation purposes.) Here is another hypothetical example. The filter is used to ensure that the response's `Content-Type` header is appropriately set to `application/json` before sending it back to the client.

```ruby
get '/route' do 
	body({ message:  'This is an endpoint!' }.to_json) 
end 

get '/another_route' do 
	body({ data:  'This is another endpoint!' }.to_json) 
end 

after do 
	response['Content-Type'] = 'application/json'  
end
```



 

Lastly, a couple interesting aspects about filters:

1) Multiple `before` and `after` filters can be defined in the same application. They can be placed before or after the routes they affect, but **the order in which they are defined determines the order in which they will be executed**.

2) Sinatra filters (like routes) can optionally accept patterns and conditions. In those cases, filters will be evaluated only when the request's path matches the specified pattern. Here is an example from Sinatra's [documentation](https://rubydoc.info/gems/sinatra#filters):
```ruby
# Any request whose path begins with '/protected/' will require authentication
before '/protected/*' do
	authenticate!
end
```
Views and more
Published: 2023-08-07 16:42:43

To incorporate Ruby and HTML together in a page, Sinatra provides a folder called views, where you can put .erb files. These files are primarily HTML but you can add erb tags to inject some Ruby, which your browser will read as the HTML the Ruby code snippets represent. This is a great way to put logic or variables directly into your HTML templates.

If you have code that will be repeated in various templates, this can be placed in the folder layout.erb. The code from the other erb files will appear where you place the `<%= yield %>` tag.

Putting `{ :layout => false }` in the app.rb file for a specific route will turn off the layout for that particular view, or you can override the layout with a different one using `{ :layout => :other_layout }`.

use :variable in your path to create a dynamic variable. The variable params allows us to get those in the form of a hash.

We also learned about the importance of automated tests. They're super helpful when refactoring code to make sure that the functionality of the original has been maintained, and can test a number of user inputs automatically. While writing the code for these tests takes some time, possibly longer than writing the code that will be tested itself, it is a great time investment as it ensures functional code over time and over changes to the codebase.
Intro to Python: Day 7 - Private Methods in Python
Tags: python, programming, beginners, oop
Published: 2023-08-07 16:27:36

*Hi there 👋 I'm a New York City based web developer documenting my journey with React, React Native, and Python for all to see. Please follow my dev.to profile or [my twitter](https://twitter.com/stonestwebdev) for updates and feel free to reach out if you have questions. Thanks for your support!*

This brief post follows my [last three posts](https://dev.to/jwhubert91) which discussed encapsulation vs abstraction and private variables in Python.

In Python, we can prevent other developers from calling certain methods that we want to have private by naming the method with a double-underscore in front just like a private variable.

ex:

```python
class SomeClass:
    def __init__(self):
        self.public_variable = 0
        self.__private_variable = 0

    def my_public_method(self):
        return self.public_variable

    def __my_private_method(self):
        return self.public_variable
```

In the example above, we create a `SomeClass` class and define the constructor function to set one public and one private variable on each instance, set to 0.

We then define two methods- one public method called, cleverly, `my_public_method`, and one private method called `__my_private_method`. Naming the latter method using the double-underline syntax prevents other programmers from calling the private method on any instance of the class. This allows us to use the method while within the class, but not on each instance.

This can further help with encapsulation when you are working with data you either want private or that you simply don't want exposed for use on each instance.

**If you like projects like this and want to stay up to date with more, check out my Twitter [@stonestwebdev](https://twitter.com/stonestwebdev), I follow back! See you tomorrow for another project.**
How I messed up my systemd logs in NixOS and how I fixed it.
Published: 2023-08-07 16:21:00

NixOS is an amazing distro, like, imagine configuring all your system stuff, containers, services, programs, development environments and so on using a consistent language. This is not the future but actually the present.

Even though NixOS modules can do validation of inputs and scenarios such as not allowing you to have both pipewire and pulseaudio in the same system, because it's known that it will conflict with each other, there are stuff that modules can't predict, and at the end of the day modules are made by humans and humans do make mistakes even though there is a lot of code review happening on nixpkgs.

This case is very unlikely to be treated by a module because it's more like a runtime issue.

Systemd-journald grants access to users to view their service logs using ACLs, that are basically an extension to what chmod does. Root and the systemd-logs have write access to the logs and the final user only has the privilege to read them using a special annotation. The problem is that my zfs filesystem wasn't allowing this annotation to be saved because zfs doesn't support saving these ACLs by default. For it to save you have to set the `acltype` attribute to `posixacl` using `zfs set`. I did know about this when I built the partition scheme for this system but I missed a small little thing: It was mounting that dataset on the wrong location: `/var/journal` instead of `/var/log/journal`.

To fix this, first I stopped the journal using `systemctl stop systemd-journald` so it would not try to write to that location. Second, I moved `/var/log/journal` to `/var/log/journal.old` then created an empty folder on that location so I can remount that dataset that was mounted on the wrong place to `/var/log/journal`. After that I copied using rsync from `/var/log/journal.old` to `/var/log/journal`, fixed the ACLs using `sudo setfacl u:lucasew:r 97e3b5a7928145bdb0d45bc645b5c20e/user-1000*` (you will have to change it to your own user and user id) and then tested running `journalctl --user -r`. Stuff then appeared nicely so it's fixed. Finally I ran `systemctl start systemd-journald` to start the journal service again and [changed in my `hardware-configuration.nix`](https://github.com/lucasew/nixcfg/commit/17e75862c4e4eeaabfb7e717fed8cd0e19342e74) so the next time it will mount that dataset correctly.
What Makes 0L Network Different?
Published: 2023-08-07 16:16:16

What is 0L Network?
0L Network is layer 1 blockchain protocol that is open, permissionless and Community governed. An open source fork of Diem originally developed by Meta (formerly Facebook) and uses the Move programming language which is designed to be extremely safe in adversarial environments. 

Most block chains are indebted to early venture capital investors, founders who control the majority of coins and validators. 0L network has no venture capital investors, all the growth comes from the community working and reinvesting in the network. Validators and Community members contribute to community wallets which are used for continued improvements of the network and ecosystem.

Community 
The 0L Network was designed to reward the workers, the builders, and the community. Community members can assist with many aspects of the network and are rewarded with 0L gas tokens. Tokens are distributed from a Community wallet funded by the validators. Community wallets are managed by independent organizations and used to fund technical and non-techical missions.

Governance is done by the community, all members can participate in any aspect of the development and decision making process of the chain. Not since Bitcoin has there been a blockchain as decentralized, open and permissionless as 0L Network.

Slow Wallets
Slow Wallets are a unique feature of the 0L Network. Slow Wallets are coded with limits on withdrawals per blockchain epoch. Slow wallets could also be used as a specific function such as automated payments, escrow accounts, etc. The slow wallets create additional security appointing all the validators to be observers of the wallet.

The slow wallets also prevent any potential “whales” from dumping on the market, potentially creating more stability for the chain. All validator’s wallets are slow wallets as well, so although some may appear to be “whales” their coins are locked for years.

The Move Language
0L Network used the Move language for smart contracts. The Move language is gaining in popularity due to the inherent safety features in the code. Built-in formal verification is a huge advantage of Move and will be the standard for autonomous financial systems. 




Favorable use in a strict Regulatory environment
The 0L Network is one of only a few block chains positioned to be well accepted by regulatory agencies worldwide. Take all the best aspects of Bitcoin and put them in a modern blockchain with fast, cost efficient, and adaptable use cases and you have the 0L Network.

Aptos Compatibility
With version 7 upgrade the 0L Network will be compatible with the Aptos Network, another fork of Diem. With dozens of developers already developing Apps for Aptos these developers will also find a great opportunity on the 0L Network.

The Most Loved Block Chain
The 0L Network is destined to be the most loved block chain. With no venture capitalist, decentralization on par with Bitcoin, and fast cost efficient transactions, businesses and end users will flock to the 0L Network.
Encontre os melhores scripts PHP e temas wordpress
Published: 2023-08-07 16:12:15

Encontre os melhores Script php scripts e sistemas em geral, temos vários Script, Sistemas Web Completos, temas para wordpress,templates html e aplicativos para android e IOS.Sistemas e Scripts PHP & MYSQL Prontos, Site Imobiliária, Sistemas Delivery Entregas, Loja Virtual, Ecommerce, Gestão de escolas, pedidos online,Plataformas SAAS  e muito mais...

https://www.codemobile.net/
Question: new tech or old tech on a portfolio?
Tags: career, discuss, interview, portfolio
Published: 2023-08-07 16:03:13

If you are a hiring manager, which looks better on a portfolio something written in new tech or old tech?

Besides my passion projects, I've been wanting to write something that would look nice on a portfolio (maybe an issue tracker?). My first thought was Astro, but maybe Ruby on Rails would be good too.

Thoughts?
Turbocharge suas publicações: Os Melhores Editores Markdown Online!
Published: 2023-08-07 16:00:00

## Visão geral  
Os editores de markdown são ferramentas melhorar e aumentar sua produtividade na hora de criar uma boa publicação, este post vai te mostrar alguns ótimos editores de markdown online.

## [Stackedit.io](https://stackedit.io/)

 - Decidi colocar este site em primeiro por ser muito facil de usar e por conter uma interface muito "clean", inclusive estou utilizando-o para criar esta publicação
![Imagem da pagina incial do stackedit.io](https://i.imgur.com/2q9j4dg.png)

## [Readme.so](https://readme.so/)
- Decidi colocar este site em segundo pois é um pouco mais complicado de utilizar porém possui uma organização incrivel, após aprender a utilizar, você vai sentir facilidade em e se organizar ao criar suas publicações
![Imagem da pagina incial do Readme.so](https://i.imgur.com/IoQWGBj.png)

## [Onlinemarkdowneditor.dev](https://onlinemarkdowneditor.dev/)
- Este site é otímo para quem quer criar suas publicações de forma facil e intuitiva, você consegue editar suas tabelas, referencias, entre outras, de forma descomplicada.
![Imagem da pagina inicial do Onlinemarkdowneditor](https://i.imgur.com/1gSLMzZ.png)
Sorting values in a List with the sort() Method in Python.
Tags: webdev, python, opensource, development
Published: 2023-08-07 15:46:33

Definition : is the the systematic arrangement of values or data in a list in a particular Order or format.
In python  number  of values or lists of strings can be sorted with the  sort() method.For example  enter the following into interactive shell:


```
>>> numbers = [1,-2,3,10,80,-4,30,4,8]
>>> numbers.sort()
>>> numbers
>>> numbers = [1,-2,3,10,80,-4,30,4,8]
>>> numbers.sort()
>>> numbers
[-4, -2, 1, 3, 4, 8, 10, 30, 80]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
>>> 
```
Inclusion
There are three things to note when using sort(),First the sort() method sorts  the list in place,Second you cannot sort  lists that have  both number  values and string values in them,since python  doesn't know how to  compare these values.
Third , sort() uses “ASCIIbetical order” rather than actual alphabetical order for sorting strings. This means uppercase letters come before lower-case letters. Therefore, the lowercase a is sorted so that it comes after the uppercase Z.
JS Challenge: Reverse the characters of each word in a string
Tags: javascript, javascripttips, jschallenge, oneliners
Published: 2023-08-07 15:41:32

---
title: JS Challenge: Reverse the characters of each word in a string
published: true
description: 
tags: javascript, javascripttips, js, jschallenge, oneliners
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-08-07 13:44 +0000
---

The solution is to create an array of the characters in the string by using the `split()` function, reverse the array and then join the characters back into a string using `join()` function.

```js
str = 'Once upon a time there was clean fresh air';
str.split(' ').map(word => 
  word.split('').reverse().join('')
).join(' ');

//To reverse the order of words in the string too

str.split(' ').map(word => 
  word.split('').reverse().join('')
).reverse().join(' ');

```