teleren/devto huggingface dataset:
✨React State Management: UseState vs UseReducer
Tags: react, webdev, javascript, typescript
Published: 2023-01-13 09:48:38

In React, **useState** and **useReducer** are two hooks that are used to manage state in a functional component. Both hooks allow you to update state and re-render your component, but they have different use cases and trade-offs.

### useState

**useState** is a Hook that allows you to store a single piece of state in your component. It is easy to use and understand, making it a good choice for small and simple state management tasks.

To use **useState**, you need to call the Hook in your component and provide an initial value. The Hook will return an array with two elements, the first being the current value of the state, and the second being a function to update the state.

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

In the example above, we are using **useState** to store a piece of state called **name**, with an initial value of "Ahmed Murtaza". The variable **name** contains the current value of the state, and the variable **setName** is a function that can be used to update the state.

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

In the example above, we are using the **name** state variable as the value of an input field, and using the **setName** function to update the state when the input field value changes.

### useReducer

**useReducer** is a Hook that allows you to store multiple pieces of state and perform more complex state updates. It is more powerful than **useState**, but also more complex to use and understand, making it a better choice _for larger and more complex state management tasks_.

To use **useReducer**, you need to call the Hook in your component and provide a reducer function and an initial state. The Hook will return an array with two elements, the first being the current state, and the second being a function to dispatch actions to the reducer.

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

In the example above, we are using **useReducer** to store multiple pieces of state in an object called **state**, with an initial value of **{ name: "Ahmed Murtaza", age: 29 }**. The variable **state** contains the current state, and the variable **dispatch** is a function that can be used to dispatch actions to the reducer.

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

In the example above, we are using the **state.name** state variable as the value of an input field, and using the **dispatch** function to update the state when the input field value changes.

## Conclusion
In conclusion, **useState** and **useReducer** are both very useful Hooks in React. It's more personal choice as well as other factors i.e performance and complexity, which we can consider picking the most suitable hook.
Longest Path With Different Adjacent Characters
Tags: javascript, leetcode
Published: 2023-01-13 09:45:05

[Longest Path With Different Adjacent Characters](https://leetcode.com/problems/longest-path-with-different-adjacent-characters/)

```js
/**
 * @param {number[]} parent
 * @param {string} s
 * @return {number}
 */
var longestPath = function(parent, s) {
     let n = parent.length;
  let ans = 1;
  let distance = new Array(n).fill(0);
  let adj = [];
  for (let i = 0; i < n; i++) {
    adj[i] = new Array();
  }

  for (let i = 1; i < n; i++) {
    adj[parent[i]].push(i);
  }
  console.log(adj);
  const getLongestPath = (source) => {
    distance[source] = 1;

    for (let node of adj[source].values()) {
      getLongestPath(node);
      if (s[source] !== s[node]) {
        ans = Math.max(ans, distance[source] + distance[node]);
        distance[source] = Math.max(
          distance[source],
          distance[node] + 1
        );
      }
    }
  };

  getLongestPath(0);
  return ans;
};

```
How we solved Gnarly bug with React table + useGlobalFilter + useRowSelect
Tags: reacttable, react, typescript, webdev
Published: 2023-01-13 09:42:30



## Application
- We have react table showing data related to customers 
- We have external filters, to filter out customer based on a selected filter criteria


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



## Usage which cause issue
- Whenever the master checkbox is checked, we get the list of selected indices from the react table. 
- The selected indices are an array of strings like ["0", "1"..]
- We parse the string to number and then iterate over given customers and filter the customer which match the indices given us
- This was working fine till the global filter came in to play.


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



## With Global filter
- Lets say we have filter which filters the customers based on the age

```
let customers = [
  {
    name: "name1",
    age: 60,
  },
  {
    name: "name2",
    age: 20
  }
]
```
- We have picked the age-group [0-20]
- Since the external data has changed the globalFilter function is invoked and after the filter is applied the result would be
```
customers = [
  {
    name: "name2",
    age: 20
  }
]
```



Now if we select the master-checkbox of the react table, the selected indices returned is ["1"] not ["0"], this minor details caught us off guard. Meaning the selected customers is always based on the original data set which is fed to the react table. 

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


Code sandbox link for the above code - https://codesandbox.io/s/unruffled-dubinsky-lrxixo?file=/src/App.js
NEED help - how to rewrite URL in react js (vite js)
Tags: react
Published: 2023-01-13 09:29:42

HI EVERYONE,
I'm stuck from last few days can anyone tell me how to rewrite URL in react js (vite js) or using javascript. I want to render one HTML page via url like www.something/portal/home/article.html but my backend team wants to hide this url and wants mw to show a dummy url or rewrite like this www.something/home/category/sub-catefory/article
This thing is working in some other project of DOTNET core but i have to implement this in react js. 
Please help me if someone have any solution....
Things to do After Custom Mobile App Development
Tags: android, ios, mobile, testing
Published: 2023-01-13 09:21:19

After custom mobile app development, it is important to thoroughly **test the app** for any bugs or errors. This includes functional testing, usability testing, and performance testing to ensure that the app is working as intended and is user-friendly.

**Optimizing the app** for performance and speed is also crucial. This includes reducing the app's memory usage, minimizing the number of background processes, and compressing images and other media. Additionally, it is important to ensure that the app is compatible with different devices and screen sizes. This includes testing the app on various devices and ensuring that the app's layout and functionality adapts to different screen sizes.

**Security** is a crucial aspect of mobile app development, so it is important to implement measures to protect user data. This includes encrypting sensitive data, implementing authentication and authorization mechanisms, and regularly updating the app to fix any security vulnerabilities.

**Integrating analytics** is also important to track user engagement and app usage. This allows developers to understand how users are interacting with the app and identify areas where the app can be improved.

Creating **detailed documentation** for the app and its features is also important. This includes user manuals, technical documentation, and release notes. This makes it easier for developers to understand the app's structure and features, and for users to understand how to use the app.

After the app is developed and tested, it should be published on the appropriate **app stores** (iOS, Android, etc.). Before publishing, it's important to monitor and respond to user feedback and reviews. This can help identify areas where the app needs improvement and also help the app to improve its ranking on the app store.

Continuous **maintenance and updates** are important to fix bugs, add new features, and improve performance. It's also important to promote the app through various marketing channels to increase its visibility and attract more users.

To know more about it: http://bitly.ws/yT5X
Packed my First Game out of UE5, BUT.....
Tags: gamedev, programming
Published: 2023-01-13 09:12:49

I am facing an issue. I packed my game with minor warnings and no errors and now the exe file is not opening at all !

When I tried to Launch the game from the editor using, "Launch the game in this windows device" option, Then I got an error and it didn't launch ! The error kinda looks like this:

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

Any Ideas on How to deal with this ??
Using Thirdweb and Hardhat to create and deploy a dApp on the Goerli testnet.
Tags: thirdweb, hardhat, goerli, web3
Published: 2023-01-13 09:10:31

## **Technologies**

- Thirdweb: A tool for creating, deploying, and managing dApps on the Ethereum blockchain
- Hardhat: A development environment for Ethereum smart contract development

## **Steps**

- First, we need to create a new contract using Thirdweb. Run this command in your terminal: **`npx thirdweb@latest create --contract`**.
- Next, we need to install the dotenv package to manage our environment variables. Run this command: **`npm install dotenv`**.
- We will also need to get our private key from MetaMask and the endpoint from **[https://www.ankr.com/rpc/eth/eth_goerli/](https://www.ankr.com/rpc/eth/eth_goerli/)**.
- In the hardhat.config.js file, add the following code to connect to the Goerli testnet and use your private key:

```jsx
defaultNetwork: 'goerli',
networks: {
hardhat: {},
goerli: {
url: '[https://rpc.ankr.com/eth_goerli](https://rpc.ankr.com/eth_goerli)',
accounts: [0x${process. env.PRIVATE_KEY}]
}
},
```

- Now we can deploy our contract by running the command **`npm run deploy`**.
- Once the deployment is successful, you will see a link to deploy your contracts on Thirdweb. Open the link and follow the instructions to deploy your contract.
- For the client-side of the application, we will create a new app using Thirdweb. Run this command: **`npx thirdweb@latest create --app`**.
- Select the app name, EVM, and JavaScript as the preferred stack.
- Now we will install React Router DOM and check our build so far by running **`npm install react-router-dom`** and **`npm run dev`** respectively.
- Next, delete the src folder and create a new one. Inside the new src folder, create an index.js file and an App.js file.
- Use the React functional component file (RAFCE) snippet to create the App component.
- Convert the index.js file to main.jsx and App.js to App.jsx
- To add styling, we will install and configure Tailwind CSS with Vite. Run these commands:

```jsx
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
```

- In the tailwind.config.cjs file, add the desired theme, and extend the font family and box shadow.
- In the postcss.config.js file, add the tailwindcss and autoprefixer plugins.
- In the index.css file, import the tailwindcss base, components, and utilities.
- Finally, run **`npm run dev`** in the terminal and your dApp should be up and running.

That's it! You have successfully created and deployed a dApp using Thirdweb and Hardhat. With this setup, you can easily create, deploy and test your dApps on the Goerli testnet. Remember that this is just a basic setup and can be further customized to suit your specific needs. Happy coding!
Angular JS Training in Chennai
Tags: beginners, webdev, programming, angular
Published: 2023-01-13 09:05:22

Learn a new skill!!! Learn AngularJS at IntelliMindz **[AngularJS Training in Chennai](https://intellimindz.com/angular-js-training-in-chennai/)** with experienced instructors. IntelliMindz AngularJS course in Chennai covers all basic concepts of front-end web development with AngularJS. The Angular JS course demonstrates the purpose of abstraction and how to use the necessary abstractions to develop applications including modules, controllers, services, and directives. After completing your Angular JS training in Chennai, you will be ready to build powerful web applications. Enroll in  Angular JS courses in Chennai and learn Angular JS to build dynamic and powerful mobile and web applications. Join the course quickly to learn more about Angular JS.
Spread operator in JavaScript VS Python.
Tags: python, javascript, tutorial
Published: 2023-01-13 09:00:47

The **JavaScript** spread operator(...) becoming popular in programming as it is used for expanding iterable objects into function arguments, array literals, or other object literals.

Simply saying, spread operator can be used as an unpacking tools which expands the _iterables_ into _individual elements_

On the other hand, Python too contains an alternative for `Spread operator` that allows the iterables unpacking.

Now we will see it in some of the examples shown- 

## Array Literals

**In JS**
```js
const name = ['Aditya', 'Shivam', 'Yash'];
 const newname = ['Sahil', ...name, 'Niraj']; //spreading name in newname

 console.log(newname);

//Output:['Sahil', 'Aditya', 'Shivam', 'Yash', 'Niraj']
```
Similarly,
**In Python**
```python
name = ['Aditya', 'Shivam', 'Yash']
newname = ['Sahil', *name, 'Niraj']# unpacking name in newname

print(newname)

#Output: ['Sahil', 'Aditya', 'Shivam', 'Yash', 'Niraj']
```

As we can see, we achieved the same result in Python as we got using the spread operator in JS.

## Function Arguments

**In JS**
```js
function add(a,b){
    return a+b;
}
const nums = [20,30];

console.log(add(...nums));//spreading nums while passing argument to a function

//Output: 50
```

Similarly,
**In Python**
```python
def add(a,b):
    return a+b
nums = [20,30]
print(add(*nums)#unpacking nums list while passing it to the add method
```

Here we used the approach to get the similar output as we got in JS using spread operator.

## Object Literals

**In JS**
```js
const person = {
    name : 'Aditya',
    age : '23',
    occupation : 'Developer',
    height:'170 cm'
}

console.log({...person,location : 'India'})

//Output: {name: 'Aditya', age: '23', occupation: 'Developer', height: '170 cm', location: 'India'}
```
Similarly, in Python we can use the double asterisk operator (`**`)

**In Python**
```python
person = {
    'name' : 'Aditya',
    'age' : '23',
    'occupation' : 'Developer',
    'height' : '170 cm'
}

print({**person, 'location':'India'})

//Output: {'name': 'Aditya', 'age': '23', 'occupation': 'Developer', 'height': '170 cm', 'location': 'India'}
```
As we can see, we needed `**person` to unpack the keyword arguments. Whereas, single asterisk operator `*nums` is used for iterable objects.

For more, follow me on [Github](https://github.com/extinctsion), [LinkedIn](https://www.linkedin.com/in/aditya-sharma123/)
2246. Longest Path With Different Adjacent Characters
Tags: java, 100daysofcode, problemoftheday, leetcode
Published: 2023-01-13 08:42:24

**Problem Statement:**

You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.

You are also given a string s of length n, where s[i] is the character assigned to node i.

Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.

 
**Example 1:**
**Input:** parent = [-1,0,0,1,1,2], s = "abacbe"
**Output:** 3
**Explanation:** The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.
It can be proven that there is no longer path that satisfies the conditions.
 
**Example 2:**
**Input:** parent = [-1,0,0,0], s = "aabc"
**Output:** 3
**Explanation:** The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.
 

**Constraints:**

- n == parent.length == s.length
- 1 <= n <= 105
- 0 <= parent[i] <= n - 1 for all i >= 1
- parent[0] == -1
- parent represents a valid tree.
- s consists of only lowercase English letters.

**Solution:**

**Code:**
```
public int longestPath(int[] parent, String s) {
    final int n = parent.length;
    List<Integer>[] graph = new List[n];
    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();
    for (int i = 1; i < n; ++i)
      graph[parent[i]].add(i);
    longestPathDownFrom(graph, 0, s);
    return ans;
  }
  private int ans = 0;
  private int longestPathDownFrom(List<Integer>[] graph, int u, final String s) 
  {
    int max1 = 0;
    int max2 = 0;
    for (final int v : graph[u]) 
    {
      final int res = longestPathDownFrom(graph, v, s);
      if (s.charAt(u) == s.charAt(v))
        continue;
      if (res > max1)
      {
        max2 = max1;
        max1 = res;
      } else if (res > max2) 
      {
        max2 = res;
      }
    }
    ans = Math.max(ans, 1 + max1 + max2); 
    return 1 + max1; 
    }
```
Today's Fun Joke For Developers - Daily Developer Jokes
Tags: jokes, dailydeveloperjokes, watercooler
Published: 2023-01-13 08:00:16

---
title: "Today's Fun Joke For Developers - 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, #watercooler
---

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/5e1258bb6df5f.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 spider do on the computer?

___A:___ Made a website!
 -->
2. Do have a good law department
Tags: itlaw, dataprivacy, itdepartment, productivity
Published: 2023-01-13 08:15:06

An unresponsive or non-existing law department can be one of the biggest blockers for IT.

IT and data are highly linked with the law. Law involves data privacy, procurement, contracts, and ownership.

Uncertainty about the law is a blocker of new initiatives and means that organizations get stuck and are not able to move forward.

## Common questions that a law department should be able to answer relatively quickly are:

- Are we allowed to use the cloud?
- Are we allowed to use this vendor?
- What data can we store?
- Should we have a DPA with this vendor?
- Can we start this new project?

## Part of the series: 52 dos and don’ts on how to get things done by the IT department

I've created a list of 52 dos and don’ts that can make your work with IT much more productive and enjoyable!

These dos and don’ts are not about managing an IT department, but about how you can get things done by the IT department.

A new dos and don’ts every week in 2023

### Original:
```
https://datamaverick.co/blog/52-dos-and-donts-on-how-to-get-things-done-by-the-it-department/2-do-have-good-law-department
```
XCP-NG Center issue on Window: Your saved settings appear to be corrupt
Published: 2023-01-13 08:07:25

Error :"Your saved settings appear to be corrupt. Revert Changes to C:\Users\(userprofile)\AppData\Roaming\XCP-ng\XenCenterMain.exe_Url_zgy2ft4zhzkcejgr02qwwlngl4rqizyf\20.4.1.33" or delete the file to return to deafult values

`FIX: delete the file C:\Users\(userprofile)\AppData\Local\XCP-ng\XenCenterMain.exe_Url_zgy2ft4zhzkcejgr02qwwlngl4rqizyf\20.4.1.33
`
https://www.youtube.com/watch?v=jFv88VIE9GM
Best Practices for Writing Clean, Efficient Code
Tags: cleancode, beginners, tutorial, productivity
Published: 2023-01-13 07:59:52


As a programmer, one of the most important skills you can develop is the ability to write clean, efficient code. Not only will this make your code easier to understand and maintain, but it can also lead to better performance and fewer bugs. In this article, we’ll explore some of the best practices for writing clean, efficient code.

1. Use clear and consistent naming conventions

One of the most important things you can do to make your code more readable and easy to understand is to use clear and consistent naming conventions. This means choosing variable and function names that accurately describe their purpose and using the same naming conventions throughout your codebase. This will make it much easier for others to understand and work with your code.

2. Keep your functions small and focused

Another key practice for writing clean, efficient code is to keep your functions small and focused. This means breaking your code into smaller, more manageable chunks that each perform a specific task. By doing this, you’ll make it easier to understand and test your code, and you’ll be less likely to introduce bugs.

3. Use comments and documentation

Even though you should strive to write code that is easy to understand, sometimes it’s still necessary to add comments and documentation. This can be especially helpful when working with complex or unfamiliar code, or when working on a team with other developers. Comments and documentation can help to explain the purpose and behavior of your code, which can save time and reduce the risk of errors.

4. Use appropriate data types and structures

Choosing the right data types and structures is essential for writing clean, efficient code. For example, using arrays instead of lists when working with large data sets can lead to better performance. Similarly, using a hash table instead of a list for searching can also improve performance. By selecting the right data types and structures, you can optimize your code to run faster and take up less memory.

5. Optimize your code

Finally, one of the most important best practices for writing clean, efficient code is to optimize it. This means looking for ways to make your code run faster and take up less memory. This can be done by removing unnecessary code, using more efficient algorithms, and making use of built-in libraries and functions.

Writing clean, efficient code takes practice and attention to detail. By following these best practices, you can improve the quality of your code and make it easier to understand, maintain, and optimize.


This Article includes:

- Best practices
- Clean code
- Efficient code
- Programming
- Code optimization
- Naming conventions
- Functions
- Comments and documentation
- Data types and structures
- Code readability
- Code maintainability
- Code performance