teleren/devto huggingface dataset:
Let's Run PHP On Localhost with XAMPP Server
Tags: php, localhost, run, xampp
Published: 2022-08-04 19:19:21

Using xampp is the fastest way to run PHP and MySQL on localhost. It's easy to install and its setup won't be covered in this tutorial. First, just make sure your xampp server is running!

To run PHP with Xampp on localhost you need to do the following:

- Download and install Xampp server
- Make sure it is running

How To Run PHP On Localhost (on YouTube)

[how to run php on localhost video tutorial](https://www.youtube.com/watch?v=PUwRinHHTCo)

How To Run PHP File on Localhost In Chrome, Firefox or Another Browser (your local PC home address without having to upload files via FTP.)

0:00 [How to run PHP File on localhost in Chrome browser on my computer / PC](https://www.youtube.com/watch?v=PUwRinHHTCo)
0:08 [Make sure XAmpp server is installed and already running on your PC](https://youtu.be/PUwRinHHTCo?t=8)
0:30 [Go to C drive and to C:\xampp\htdocs folder (This is Xampp's localhost root folder)](https://youtu.be/PUwRinHHTCo?t=30)
1:05 [Open index.php file you just created in VSCode (Visual Studio Code)](https://youtu.be/PUwRinHHTCo?t=89)
1:54 [Open PHP script file in Chrome browser running on localhost](https://youtu.be/PUwRinHHTCo?t=114)

[how to run PHP on localhost]()
Here goes a new series, Code rant. 05/08/2022
Tags: beginners, productivity, todayilearned, programming
Published: 2022-08-04 19:08:32

# About Me
Honestly, I am one of the greatest procrastinators out there. I have had great ideas and plans that were ruined solely due to procrastination. This series is to document or record my journey. Currently I'm working on my basic coding skills with Go, learning a bit of devops and working on my Flask, React, Node and Svelte skills.
Discussion and Comment of the Week - v13
Tags: bestofdev
Published: 2022-08-04 18:43:29

This weekly roundup highlights what we believe to be the most thoughtful and/or interesting discussion of the week. We're also be highlighting one particularly cool comment in each installment. 🙌

The DEV Community is particularly special because of the kind and thoughtful discussions happening between community members. As such, we want to encourage folks to participate in discussions and reward those who are initiating or taking part in conversations across the community. After all, a community is made possible by the people interacting inside it.

## Discussion of the Week

Congrats to @michaelsalim for writing “I have 218 browser tabs open”

{% embed https://dev.to/michaelsalim/i-have-218-browser-tabs-open-1la9 %}

This hilarious post highlights how far we've come with browser technology. We all find ourselves overwhelmed by tabs and this post shows us the tools we can use to ~~hoard~~ handle them. 

## Comment of the Week

I'd like to reward @goncalorodrigues for their response to @nombrekeff's prompt "[You will not do it later (most likely) - I'm a procrastinator, I know](https://dev.to/nombrekeff/you-will-not-do-it-later-most-likely-im-a-procrastinator-i-know-j2d)"

{% embed https://dev.to/goncalorodrigues/comment/20l64 %}

Reading Keff's post, the saying "Why save for tomorrow what you can do today?" really rings true. Time management is tricky for all of us and the only way we can improve at it is by acknowledging where we slip up. When you feel yourself about to save something for later, ask why.

## What are your picks?

There's loads of great discussions and comments floating about in this community. These are just a few we chose to highlight. 🙂

I urge you all to share your favorite comment and/or discussion of the past week below in the comments. And if you're up for it, give the author an @mention — it'll probably make 'em feel good. 💚
How to make Your Own Hook
Tags: javascript, react, webdev, tutorial
Published: 2022-08-04 18:36:11

## How to make Your Own Hook

### What

***React Hooks*** are simple JavaScript functions that we can use to isolate the reusable part from a functional ***component.***

### How To make Your Own Hook

If you are using the same Function again and again but with different **Names,** you can make a **Hook So that you don’t have to write the same code over and over again.**

**Let’s Take the Example a Simple Input Form.**

 **** 


![React JS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ljqfnh7vo2rrvw5ev46o.png)
  

In this InputForm Component, we are using the **handleChange  Function** Multiple Times with the same **Name.** So we can make a Hook For this Purpose.

**Before Starting making a Hook we have to Think of what are the Re-useable Functions in Input Form.**

**So generally we have ,**

**`1. onSubmit Function: called when the form is submitted`**

 **`2. onChange Function: called when the form is changed`**

 **`3. onReset Function: called inside of the OnSubmit Function`**

**So what our Hook will do, it will takes the Initial Input [Empty string ], set the state using the Initial value , then it will return 3 things** 

- **state**
- **handle Change**
- **handle Submit**

**In the Form of an Array or Object an then we can use it the Component.**
### UseInputForm Hook
![React Hooks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3bd28srs2tcc83zzm7h.png)

##Code
![React JS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j9zuky8wnmzd86hy32dw.png)

Follow For More Such Videos 😊
Hire+Plus! For Employees Here's how I built it (Redux - Company)
Tags: react, webdev, programming, tutorial
Published: 2022-08-04 18:13:00

**Purpose:** The candidate will be able to view a company's profile, and see the jobs they posted.


## Types, Actions and Reducers: Company state

### Types
**inside `app > features > company > companyTypes.ts`**

Data types for a `company`. I have `JobData` imported from diff file, but I'm showing side-by-side for simplicity. 

```json
export type CompanyData = {
 id: string;
 companyName: string;
 companyDescription: string;
 companyUrl: string;
 email: string;
 isHiring: boolean;
 companySize: string;
 jobs: JobData[];
};

export type JobData = {
 id: string;
 companyName: string;
 position: string;
 location: string;
 salary: string;
 datePosted: string;
 jobType: string;
 applyUrl: string;
 description: string;
};

```

---

### Actions
**inside `app > features > company > companySlice.ts`**
setting the initial state for `company` reducer, and call `getCompany` from DB to get a company by `id`. I return the stringifyed version of the `company`.

```javascript
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { getCompanyById } from '../../../utils/firebase/firebase.utils';
import { CompanyData } from './companyTypes';

interface companyState {
 company: CompanyData;
 isLoading: boolean;
}
const initialState: companyState = {
 company: {
   id: '',
   companyName: '',
   companyDescription: '',
   companyUrl: '',
   email: '',
   isHiring: false,
   companySize: '',
   jobs: [],
 },
 isLoading: false,
};

export const getCompany = createAsyncThunk(
 'job/getCompanyById',
 async (id: string) => {
 const company = await getCompanyById(id);
 const [companyObj] = company;
 return JSON.stringify(companyObj);
 }
);

```
---

### Reducers
I handled the response states and set the state accordantly.
On the `.fulfilled` response state, I get this data back, parse it and set it to state.

```javascript
const companySlice = createSlice({
 name: 'job',
 initialState,
 reducers: {},
 extraReducers: (builder) => {
  builder
   .addCase(getCompany.pending, (state, action) => {
     state.isLoading = true;
   })
   .addCase(getCompany.fulfilled, (state, action) => {
     state.isLoading = false;
     state.company = JSON.parse(action.payload);
   })
   .addCase(getCompany.rejected, (state, action) => {
     state.isLoading = false;
     console.log('error with company data', action.error);
   });
 },
});

export default companySlice.reducer;
```

That's all for the company/redux portion of the project, stay tuned!
Javascript Tagalog - Optional Chaining
Tags: javascript, optional, chaining, tagalog
Published: 2022-08-04 18:12:04

**Ano ngaba ang Optional Chaing?**
etong optional chaining ay ginagamit para lang siyang . na nag a-access ng property pero diba minsan nag-cacause ng error kapag yung reference is nullish? dun papasok yung optional chaining para ma return nalang ang "undefined" kesa sa mag cause ng error.

![Javascript Tagalog - Optional Chaining](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jrlci9sbokszdz5kxgv0.PNG)

Magiging useful din to kapag dika sure if ano magiging laman ng property na kinukuha mo para lang siyang guard clause in a sense

---
**More tagalog Javascript Learning Resources:**
https://javascript-methods-in-tagalog.vercel.app/
Looking for a teammate for the Redis Hackathon?
Tags: redishackathon, redis, webdev, database
Published: 2022-08-04 18:12:00

As you know, we announced the [Redis Hackathon on DEV](https://dev.to/devteam/announcing-the-redis-hackathon-on-dev-3248) a few days ago, and we have seen several people searching for teammates. Let's use the comments section below this post to organize that. If you are looking for a teammate, please post in the comment section below. Mention your skills, your idea, language, etc. as well as how many teammates you are looking for and if you are looking for specific skills (languages, frameworks, etc.). Thanks, and happy hacking!
Issues with useEffect
Tags: javascript, beginners, react, performance
Published: 2022-08-04 17:47:02

If you are react dev you surely encounter multiple use cases for useEffect. But let me show how useEffect is tricking you all these times.

You want some function to run when component mounts 

```
useEffect(() => ...fn() )
```
Everything is good here.

But now you want function to run when some specific state value is changed 

```
 const [data, setData] = useState("");
 useEffect(() => {
    console.log("Running useEffect");
  }, [data]);
```

our expectation is that this function will run when data is changed.

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

Check this small example. Here we can see that useEffect callback ran even if I don't change data.
That is because useEffect will run at least once on component mount.

So what is fix here?
We all use this to make some api calls and do some critical work and due to this behaviour of useEffect we can face bugs or performance issue. 

So to run it only when data is changed we can.
```
import { useState, useEffect, useRef } from "react";

export function App() {
  const isMounted = useRef(false);
  const [data, setData] = useState("");
  useEffect(() => {
    if (isMounted.current) {
      console.log("HERE");
    } else {
      isMounted.current = true;
    }
  }, [data]);
  return (
    <div>
      <input
        onChange={(e) => setData(e.target.value)}
        placeholder="First name"
      />
    </div>
  );
}
```
Now in the console you will not see HERE on mount.

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

Notice here we are using useRef specifically so that on re-render value of isMounted persist else with simple js variable it will keep reseting on every mount.

Hit like if you have learned something awesome.
GitLab will be deleting dormant projects
Tags: news, discuss, gitlab, cloud
Published: 2022-08-04 17:41:00

Here's the story:

## [GitLab plans to delete dormant projects in free accounts](https://www.theregister.com/2022/08/04/gitlab_data_retention_policy/)

They plan on saving a quarter in hosting costs by doing this.

I'm curious what the opinions are on this.

_Update: GitLab has modified their approach based on some feedback._
MutableAI - Copilot alt for VS Code
Tags: launch, tooling
Published: 2022-08-04 17:35:35

{%embed https://www.youtube.com/watch?v=x-gKEbgyzCg %}

Hello dev.to, 

We’re MutableAI (YC W22) (https://mutable.ai). Our mission is to reduce the time and cost to create high quality code using AI. We have worked at the full gamut of companies ranging from startups to big tech and have gotten the sense that many of the rote aspects of software development could be made easier, freeing up precious mental energy.

Devs love Copilot, but autocomplete is just one of many ways that AI should make programming easier. We’re taking a more comprehensive approach to developer tooling that bundles Copilot-like autocomplete with documentation, custom AI instruction, and some early refactoring capabilities (Python only) in one extension. We currently support Javascript/Typescript, Python, Go, and Rust, with more coming soon.

In addition to autocomplete, which can be triggered either automatically or manually, we can add documentation to all your methods in a Rust file, or you can ask the AI to insert missing imports in a Python file. In some cases we can get really sophisticated and ask it to program a game from scratch or update your REST interface to accommodate a new data payload.  

We use a combination of AI (e.g. OpenAI codex) and AST transformation / metaprogramming techniques on the backend. We are also working on providing other backend solutions for varying needs, including on-prem deployments.

We soft launched our product with a small cohort of users and want to welcome more of you to our pilot beta. We hope you enjoy the product and look forward to learning from you.

We are currently in an extended free trial phase for early adopters and plan to keep a free tier for solo devs and open source contributors. We also offer a generous discount to startups. For enterprise please reach out to info@mutable.ai 

We want to thank our very earliest users and invite the HN community to try the product installing it via the VS Code marketplace [1] and email us directly with feedback or feature suggestions (support@mutable.ai).

[1] [MutableAI for VS Code](https://marketplace.visualstudio.com/items?itemName=mutable-ai.mutable-ai)
Javascript Tagalog - Ternary Operator
Tags: javascript, tagalog, ternary, filipino
Published: 2022-08-04 16:53:50

**Ano ngaba ang Ternary Operator?**
Yung ternary operator para lang siyang minifed if else statement na may expression output.. i think.. Wag na i over think pa.

---

**Syntax**
`Conditional Statement ? 'output moto if true' : 'output moto if false'`

---

**Paggamit**
![Javascript Tagalog Ternary Operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m6vkmnkue7cgwpd4mdpa.PNG)

---
**Chaining Ternary Operator**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ipg0n7ossoyd2esi2mai.PNG)
as a random javascript developer, suggest ko na wag lagi i chain ang ternary operator tignan niyo naman sobrang baba ng readability points.


---
**More tagalog Javascript Learning Resources:**
https://javascript-methods-in-tagalog.vercel.app/
Test 2
Published: 2022-08-04 16:51:00

- lalalalalala [Link](https://google.com)
- lalalalalala [Link](https://stackoverflow.com/questions/70553760/how-to-style-child-elements-with-vanilla-extract)
- lalalalalala [Link](https://stackoverflow.com/questions/70553760/how-to-style-child-elements-with-vanilla-extract)
- lalalalalala [Link](https://stackoverflow.com/questions/70553760/how-to-style-child-elements-with-vanilla-extract)

[Link](https://stackoverflow.com/questions/70553760/how-to-style-child-elements-with-vanilla-extract)

**Bold**

_Italic_

<u>Underline</u>

~~Strike~~

---

> quote

`docker exec -it asd21138uasd rm -rf`

```markdown
block code
var
var
var
```

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur quis enim sit amet lacus mattis tincidunt. Morbi elementum varius est, et euismod ex luctus a. Etiam pharetra, elit sed cursus gravida, enim ipsum dapibus mi, eget laoreet elit ex a quam. Mauris euismod et elit ornare finibus. Ut ultrices mauris eu nisl tempor finibus. Nulla elementum felis sed justo bibendum, non elementum velit vestibulum. Curabitur sagittis, lacus eget dapibus varius, dui ipsum eleifend eros, et posuere quam metus et quam. Nam non est condimentum, euismod metus ac, rutrum sem. Morbi ornare tortor libero, nec ultrices nunc aliquam in. Aliquam mollis scelerisque varius. Pellentesque in ultrices nibh.

`Lorem Ipsum`

Donec fermentum libero et tortor bibendum bibendum. Mauris nec ullamcorper arcu. Duis metus ante, porta vel pretium in, dapibus et sapien. Aenean rhoncus quam et varius viverra. Proin fringilla sit amet ex ac venenatis. Nam at augue nec sapien convallis facilisis ut nec tellus. Fusce gravida feugiat sagittis. Suspendisse pellentesque elit nisi, vehicula convallis nulla cursus a. In euismod dictum lectus eu facilisis. Sed fringilla turpis a pulvinar dapibus. Cras non est vehicula, aliquet arcu feugiat, pharetra nulla. Praesent in velit congue, tempor neque quis, malesuada purus. Sed metus nisl, commodo auctor ipsum sit amet, consectetur aliquet massa. Sed faucibus `fermentum` ligula, sit amet mattis augue dictum at. Maecenas sodales mattis porta. Donec ultrices gravida tristique.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4tdj2b6vkn3clw15o3va.png)
1. Two Sum - Leetcode Easy
Tags: programming, tutorial, python, career
Published: 2022-08-04 16:41:00

## Problem statement
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.
```
Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
```
```
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
```
## Approach 1
Iterate through the array, select each element and check if there is any other element in the remaining array which when added to the first one gives the target value. It is guaranteed that one such pair exists. So, we need to return their indices.

```python
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)-1):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i,j]
                
        return [-1, -1]
```
**Time complexity** - `O(n^2)` - due to nested for loops.
**Space complexity** - `O(1)`.

## Approach 2
Iterate through the array and check for each element if the required number to sum up to target is already present in the hashmap. If there is one, return an array with both of it's indices. Else, add current item to the hashmap with it's index as value and item as key.

```python
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashMap = {}
        for i in range(len(nums)):
            if target - nums[i] in hashMap: # If present in hashmap
                return [hashMap[target-nums[i]], i]
            else:
                hashMap[nums[i]] = i # Add item as key and index as value into hashmap
                
        return [-1, -1]
```

## Conclusion
Do let me know if I missed any other approach.

Do follow me for more such explanations.
Let's connect on: [Twitter](https://twitter.com/VChiranjeeviAK) [LinkedIn](https://www.linkedin.com/in/chiranjeevi-tirunagari/) [Showwcase](https://www.showwcase.com/vchiranjeeviak)
关于JavaBeans的总结
Published: 2022-08-04 16:40:00

### JavaBeans是什么
JavaBeans就是在Java中， 将数据存放在一处而使用，所对数据进行的处理方式

### 总结特性
- 所有属性为private
- 提供默认构造方法
- 提供getter和setter
- 实现serializable接口
リダイレクトとフォワードの違い
Published: 2022-08-04 16:33:34

#### 从地址栏显示来说
- forward是服务器请求资源,服务器直接访问目标地址的URL，把那个URL的响应内容读取过来,然后把这些内容再发给浏览器。浏览器根本不知道服务器发送的内容从哪里来的，所以它的地址栏还是原来的地址。
- redirect是服务端根据逻辑，发送一个状态码，告诉浏览器重新去请求那个地址。所以地址栏显示的是新的URL。

#### 从数据共享来说
- forward:转发页面和转发到的页面可以共享request里面的数据。
- redirect:不能共享数据。

#### 从运用地方来说
- forward:一般用于用户登陆的时候,根据角色转发到相应的模块。
- redirect:一般用于用户注销登陆时返回主页面和跳转到其它的网站等。

#### 从效率来说
- forward:高
- redirect:低


#### 关于两者的本质区别，有以下几种解释：

##### 解释一　　
一句话，转发是服务器行为，重定向是客户端行为。为什么这样说呢，这就要看两个动作的工作流程：
转发过程：客户浏览器发送http请求——web服务器接受此请求——调用内部的一个方法在容器内部完成请求处理和转发动作——将目标资源。发送给客户；在这里，转发的路径必须是同一个web容器下的url，其不能转向到其他的web路径上去，中间传递的是自己的容器内的request。在客 户浏览器路径栏显示的仍然是其第一次访问的路径，也就是说客户是感觉不到服务器做了转发的。转发行为是浏览器只做了一次访问请求。

重定向过程：客户浏览器发送http请求——web服务器接受后发送302状态码响应及对应新的location给客户浏览器——客户浏览器发现 是302响应，则自动再发送一个新的http请求，请求url是新的location地址——服务器根据此请求寻找资源并发送给客户。在这里 location可以重定向到任意URL，既然是浏览器重新发出了请求，则就没有什么request传递的概念了。在客户浏览器路径栏显示的是其重定向的 路径，客户可以观察到地址的变化的。重定向行为是浏览器做了至少两次的访问请求的。



##### 解释二
重定向，其实是两次request：第一次，客户端request A,服务器响应，并response回来，告诉浏览器，你应该去B。这个时候IE可以看到地址变了，而且历史的回退按钮也亮了。重定向可以访问自己web应用以外的资源。在重定向的过程中，传输的信息会被丢失。

例子：
请求转发是服务器内部把对一个request/response的处理权，移交给另外一个，对于客户端而言，它只知道自己最早请求的那个A，而不知道中间的B，甚至C、D。 传输的信息不会丢失。



##### 解释三
假设你去办理某个执照， 重定向：你先去了A局，A局的人说：“这个事情不归我们管，去B局”，然后，你就从A退了出来，自己乘车去了B局。 转发：你先去了A局，A局看了以后，知道这个事情其实应该B局来管，但是他没有把你退回来，而是让你坐一会儿，自己到后面办公室联系了B的人，让他们办好后，送了过来。
AWS: Identity and Access Management[cheatsheet]
Tags: cloudskills, aws, beginners, solutionsarchitect
Published: 2022-08-04 16:28:00

As I begin my journey studying towards being a devOps engineer, I would like to share what I learn throughout my journey. I am currently studying for the **AWS CLOUD SOLUTIONS ARCHITECT ASSOCIATE EXAM**
In this article, I will share a summary of **IAM & AWS CLI**

**Summary**
-IAM = Identity and Access Management
- Users are people within your organization and they can be grouped[it’s best practice to always assign each member under a group(s). A user can be a member of more than one group.
- Groups can only contain users but not other groups.
- Policies define the permissions of the users.[best practice: use the least privilege principle; simply don’t give more permissions than the user needs]
- Password policy:- you can set up a password policy that ensures higher security for your account.
- Multi-Factor Authentication – MFA
	**. protects your root accounts and IAM users.
	. MFA = password you know + security device you know
	. If a password is stolen or hacked, the account is not compromised.
	.You can use a virtual MFA device[google authenticator, authy} or a U2F Security Key{yubikey by yubico}**

- To access AWS, you have three options:
	**. AWS Management Console{protected by password + MFA}
	  . AWS Command Line Interface(CLI){protected by access keys}
          . AWS Software Development Kit(SDK) – for code {protected by access keys}**
-Access keys are generated through the AWS console
        **. Access Key ID ~= username
	. Secret Access Key ~= password**
- AWS cloudshell is a CLI in the cloud.
- IAM Credentials Report(account level): this is a report that lists all your account’s users and the status of their various credentials.
- IAM Access Advisor(user-level): shows the service permissions granted to a user when those services were last accessed.

**IAM Guidelines and Best Practices**
- Don’t use the root account except for AWS account setup
- One physical user = One AWS user
- Assign users to groups and assign permissions to groups
- Create a strong password policy
- Use and enforce the use of Multi-Factor Authentication(MFA)
- Create and use roles for giving permissions to AWS services
- Use Access Keys for Programmatic Access(CLI/SDK)
- Audit permissions of your account with the IAM credentials report and IAM Access Advisor
- Never share IAM users and Access Keys
How to convert file object to path object in Java?
Tags: java, files, path, exceptionhandling
Published: 2022-08-04 16:11:00

To convert file object to path object we use toPath() function by importing import java.nio.file.Path class.

Below is the syntax.

```
Path path=myObj.toPath();

```
Below is the sample Program to convert File object to Path object.

```
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
class FileExample{
public static void main(String args[]) throws Exception{
	 File myObj = new File("fileExample.txt");
	 Path path=myObj.toPath();
	}
}
```