teleren/devto huggingface dataset:
How to call method on browser resize in react
Tags: react, reactnative, javascript, tutorial
Published: 2022-02-03 22:05:33

Sometimes, we have to do some functionality on browser resize in react. In this tutorial we will learn how to call method on browser resize in react. And we can do this in functional or class component.

## Window Resize in Functional Component using React Hooks
To do this we can define a custom Hook that listens to the window resize event. Use the code given below.

```react
import React, { useLayoutEffect, useState } from 'react';

function useWindowSize() {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;
}

function ShowWindowDimensions(props) {
  const [width, height] = useWindowSize();
  return <span>Window size: {width} x {height}</span>;
}
```

We can now use **useWindowSize** as function by exporting it using export default function **useWindowSize** . We can also use **useWindowSize** as hooks in other functional components. **[useLayoutEffect ](https://reactjs.org/docs/hooks-reference.html#uselayouteffect)** it is like as **useEffect** . But It is called synchronously after all DOM mutations.

## Window Resize in Class Component

Here we are using **[componentDidMount ](https://reactjs.org/docs/state-and-lifecycle.html)** method which is a part of React-Lifecyle. It is called after the component is rendered or when our component got updated. Using componentDidMount we can execute the React code when the component is already placed in the DOM.

```react
import React from 'react';

class ShowWindowDimensions extends React.Component {
  state = { width: 0, height: 0 };
  render() {
    return <span>Window size: {this.state.width} x {this.state.height}</span>;
  }
  updateDimensions = () => {
    this.setState({ width: window.innerWidth, height: window.innerHeight });
  };
  componentDidMount() {
    window.addEventListener('resize', this.updateDimensions);
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.updateDimensions);
  }
}
```

That's it. Please support and like to motivate me to write more.

For More Tutorials Please visit my website [readymadecode](https://www.w3courses.org/tutorials/).

Thanks
Happy Coding :)
Working with GeoIP APIs and IP Addresses
Published: 2022-01-31 03:29:20

# Introduction

Hey everyone! We're going to continue looking at Web Components, from the perspective of a Front End Developer. Today, we're examining a project where we study how we can find someone's geolocation from their IP Address. 


# GeoIP API
First, let's take a look at the GeoIP API. Check out [this link](https://freegeoip.app/json/) to see an example of this at work.

![GeoIP API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ccqztzq84p2gngvporwo.png)

Here we see that our constructor for our API is linking back to the GeoIP API, which enables our APIs to work together.

# IP Fast API
We now move to the IP Fast API.

![IP Fast API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4py3j4yjnno3smtfu4uu.png)

The `async updateUserIP()` automatically updates the IP, with the `fetch()` function grabbing an IP through the GeoIP API, and once the response is confirmed to be okay, the data comes back to us in the form of safe JSON data.

Then, we can pull out the necessary information from the JSON data, the IP, and then the corresponding city and country. Finally, a composite attribute, called location, is created.

# Utilizing Both APIs

![Both APIs being used together](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/15qljdcb13b6chqqerre.png)

Finally, we can proceed to utilizing both APIs together, as seen in this image. What this code accomplishes is that it pulls the location from the GeoIP API, and then gathers data from the IP Fast API, and then outputs it in the render function.


![Render Method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vhm9uzaq65v5442gh0ux.png)

Finally, the render method takes the information and searches it and pulls up the necessary wikipedia queries.
Git command tips: git amend
Tags: git
Published: 2022-02-03 21:35:20

A very powerful yet maybe not so common git command is the **amend** command.

Consider the following scenario, you have a task to create a label to show current date. You create this and commit and your git tree looks something like this now:

```
5152417 (HEAD -> feature/add-date-label, origin/master, master) Added date field
936442a Added assets
…
```

Now you noticed that your date label is showing:

```
Feb 3, 2022 at 10:05 PM
```

But the requirement was to show it in the following format:

```
yyyy-MM-dd HH:mm
```

You update this and commit again and your git tree looks like this now:
```
283b5d0 (HEAD -> feature/add-date-label, origin/master, master) Added right formatting to date field
5152417 Added date field
936442a Added assets
…
```

This does work, but you could do it in a much cleaner way without creating a new commit with the use of the **amend** command. So try this command instead:

```
git add . && git commit --amend --no-edit && git push --force
```

After running above command you will instead of creating a new commit, you will amend it to the current commit. Your git tree looks like this now after the amend:

```
84hv801 (HEAD -> feature/add-date-label, origin/master, master) Added date field
936442a Added assets
…
```

The following will happen:

1. You will get a new commit id for you latest commit
2. You will not create a new commit, instead you will amend the latest commit

Hope you found this useful!
Why I wanted to start coding
Published: 2022-02-03 20:54:52

I started coding back in high school as a thing I thought always sounded cool so I picked as on of my classes for my senior year. After about 2 weeks I started to really enjoy the class and start to appreciate how structure or the blue prints of things. After high school I took a break and started working and after about a year I realized that my passion was coding and decided to pick it back up. I aspire to eventually end up working for a big company such as Google, Sony or Epic Games.
Hash strings to INT using Java
Tags: java, coldfusion, cfml
Published: 2022-02-03 20:24:56

I'm not sure where I previously learned about the Java `hashCode()` method for strings, but it enabled us to quickly assign a unique-ish numerical hash from a textual product configuration and enabled us to search, group & report data where it would have been very difficult otherwise.

The hashCode() method works in Adobe ColdFusion 8-2021. I also tested it using CFTry.com and Railo + Lucee4 worked, but Lucee5 didn't return anything so I'm not sure if it works or not.

Here's the gist:
https://gist.github.com/JamoCA/e94b1100932db2c02b18eb11afc56079

{% gist https://gist.github.com/JamoCA/e94b1100932db2c02b18eb11afc56079 %}
Paracetamol.js💊| #43: Explica este código JavaScript
Tags: javascript, beginners, webdev, spanish
Published: 2022-02-03 20:24:04

## **Explica este código JavaScript**

```js
function sayHi(name) {
  return `Hi there, ${name}`
}

console.log(sayHi())
```


-     A: `Hi there`
-     B: `Hi there, undefined`
-     C: `Hi there, null`
-     D: `ReferenceError`

Respuesta en el primer comentario.

---
CLI Applications Tips & Tricks – Run the command in background
Tags: programming
Published: 2022-02-03 20:24:03

<!-- wp:paragraph -->
<p>Sometimes commands takes too much time to finish. And during its running process, your terminal should always be online! If you close your terminal or you lose your internet connection, process will interrupt. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To avoid this problem, there are many different approaches. If your command takes too much time and you afraid it gets terminated because of "you", you can use <code><strong>nohup</strong></code> to run command in background. </p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"bash"} -->
<pre class="wp-block-syntaxhighlighter-code">nohup php artisan command:name &amp;</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>It will run the command in background and you can close your connection. When you run the command, you'll see such message:</p>
<!-- /wp:paragraph -->

```bash
nohup: ignoring input and appending output to 'nohup.out'
```

<!-- wp:paragraph -->
<p>This means, all output will be stored under <code>nohup.out</code> file. You can tail it while your command is running. <code>tail -f nohup.out</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I prefer to save logs in specific folder and file. </p>
<!-- /wp:paragraph -->

```bash
nohup php artisan command:name &> /path/to/your/specific/file.log &amp;
```
CLI Applications Tips & Tricks – Lock the command
Tags: programming
Published: 2022-02-03 20:21:37

<!-- wp:paragraph -->
<p>Locking the command is basically a "double run prevention". </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Assume that you have a hourly email command and you're sending e-mails to users one by one. If the command doesn't finish until next hour, you may send multiple e-mails to some users. Or your colleague can try to start same command after you run it.</p>
<!-- /wp:paragraph -->

```php
// RUN A:
$users = User::where('hourly_email_sent', false)->get();
// On above query, 10.000 users have been found. 
// The command started and already processed 8.000 users in one hour. There are 2.000 users remaining.
// If you start command again, you'll send 2 emails for remaining 2.000 users. Because a command is already running and you started another one.

// RUN B:
$users = User::where('hourly_email_sent', false)->get();
// On above query 2000+ users have been found.
// RUN A and RUN B can contain same users!
```

<!-- wp:paragraph -->
<p>I generally prefer to put a value to cache and check it before actually running the command. Here's an example:</p>
<!-- /wp:paragraph -->

```php
<?php

$cacheLockKey = 'command_name';
if (Cache::has($cacheLockKey)) 
{
    $this->output->writeln('Another process is already running. Exiting...');

    return 1;
}

Cache::put($cacheLockKey, date('Y-m-d H:i:s'));

// do some logic

Cache::forget($cacheLockKey);

return 0;
```

<!-- wp:paragraph -->
<p>This simple control will prevent you to run a command twice with mistake. It's easy, isn't it?</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="downsides-with-putting-lock-into-cache">Downsides with putting lock into cache</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You can use database or file storage too. I didn't get trouble just because I'm using cache, but of course you can get problems somehow. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If cache gets flushed for all values, your cache key will also be removed. You have to protect your "lock" until command is really finished.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you have multiple servers, you have to make sure all servers are using same cache storage. </p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="failure-case">Failure Case</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>If the command fails for a reason, you have to be sure cache key was removed.  Otherwise command won't start again. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can handle this situation manually, but if you're running command on cronjob, your next run may not be able to succeed.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This failure case of course depends whatever you want from a job.  </p>
<!-- /wp:paragraph -->
CLI Applications Tips & Tricks - dry-run
Tags: programming
Published: 2022-02-03 20:13:40

<!-- wp:paragraph -->
<p>Testing command line applications is not easy. <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Dry_run_(testing)" data-type="URL" data-id="https://en.wikipedia.org/wiki/Dry_run_(testing)" target="_blank">Dry Run</a>, is a testing process usually used for command line applications. Also it allows you to simulate what will happen when you run the command. </p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>It's like running "SELECT" statement on SQL before running DELETE/UPDATE statements and see which records will be affected.</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>I'm going to share an example use case. Assume that you have a command which deletes unused files from your S3 bucket. </p>
<!-- /wp:paragraph -->

```php
<?php

$files = File::all();

$this->output->writeln('There are '.count($files).' file to be checked');

foreach ($files as $file) {
    if (!$this->fileService->isFileInUse($file)) {
        $this->fileService->deleteFile($file);
        $this->output->writeln('File has been deleted from storage: file_id_'.$file->id);
    }
}
```

<!-- wp:paragraph -->
<p>This command is a bit risky! If there is an unexpected behavior on <code>isFileInUse</code> method, then we can delete wrong files. I prefer to simulate data before actually running these kind of commands. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So <code>--dry-run</code> option is with us! </p>
<!-- /wp:paragraph -->

```php
<?php

// In Laravel, we use `option` method to get an option.
$dryRun = $this->option('dry-run');

$files = File::all();

$this->output->writeln('There are '.count($files).' file to be checked');

foreach ($files as $file) {
    if (!$this->fileService->isFileInUse($file)) {
        if ($dryRun) {
            $this->output->writeln('File will be deleted from storage: file_id_'.$file->id. ' URL: '.$file->url);
            continue;
        }

        $this->fileService->deleteFile($file);
        $this->output->writeln('File has been deleted from storage: file_id_'.$file->id);
    }
}
```

```bash
php artisan s3:delete-unused-files --dry-run
```

<!-- wp:paragraph -->
<p>Simple! We're just passing <code>--dry-run</code> option to command line and it's telling us which files will be deleted. In the example, I've also added the url to output. You can add whatever you want to make spot-check. If everything seems good, you can run actual command without dry-run. </p>
<!-- /wp:paragraph -->
Factorial of a large Number
Tags: java, programming, dsa
Published: 2022-02-03 20:08:28

Given an integer N, find its factorial.

Example 1:
Input: N = 5
Output: 120
_Explanation : 5! = 1*2*3*4*5 = 120_

Example 2:
Input: N = 10
Output: 3628800
_Explanation :
10! = 1*2*3*4*5*6*7*8*9*10 = 3628800_

To solve this question click here:(https://practice.geeksforgeeks.org/problems/factorials-of-large-numbers2508/1#);

Asked in companies like **Adobe**, **BrowserStack**, **MakeMyTrip**, **Microsoft**, **Philips**, **Samsung**

It is a **MEDIUM LEVEL** question, you must have calculated factorial of a number. But this question is a bit different, in this we have to calculate factorial of a **large number**.

Factorial of large numbers cannot be stored in `int` or `long` or `long long`. So in this case we use ArrayList or LinkedList to solve the question.

**JAVA CODE**
```
static ArrayList<Integer> factorial(int N){
        //code here
        ArrayList<Integer> res=new ArrayList<>();
        res.add(0,1); //adding 1 in the arraylist
        int size=1;
        int carry=0,val=2;
        
        while(val<=N)
        {
            for(int i=size-1;i>=0;i--)
            {
                int temp=res.get(i)*val + carry;
                //store the last digit at index and add remaining to carry
                res.set(i,temp%10);
                //update carry
                carry=temp/10;
            }
            while(carry!=0)
            {
                res.add(0,carry%10);
                carry=carry/10;
                size++;
            }
            val++;
           
        }
        return res;
    }
```
Sharing excess food with OSS and React
Tags: opensource, contributorswanted, react
Published: 2022-02-03 19:56:40

Last week's Open Source Friday featured Ryan McHenry from Sharing Excess project. [Sharing Excess](https://app.sharingexcess.com/), a non profit based in West Philly, and working on converting the surplus (5 million pounds) food that is often thrown out or goes to waste in one way or another and delivering that to local nonprofits and food pantries. 

They are approaching this problem in a unique way using open source using React to managing the operations in a PWA. 

The non-profit ecosystem in the USA is a $390 billion ([based on 2016 numbers](https://independentsector.org/about/the-charitable-sector/#:~:text=The%20nonprofit%20sector%20%E2%80%93%2010%20percent,2.7%20percent%20increase%20from%202015.)), but despite number operations and technical help can be lacking in the web interactions. 

If you are interested in joining the cause through open source contributions, consider reaching out and checking out their issues and discord.

{% github sharingexcess/rescue %}

_If you are looking for a list of more projects looking for contribution, check out our [Open Source Friday repo recommendations](https://github.com/stars/bdougie/lists/open-source-friday)._

{% twitter https://twitter.com/bdougieYO/status/1487056598178533378?s=20&t=i352YP9HqU-M98-8_JYmHw %}
Understanding React Components
Tags: javascript, java, react
Published: 2022-02-03 19:25:19

Components in React let you split the page into independent and reusable parts.

Let's visualize this by taking a look at the diagram below.



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

Notice that the page can be split into multiple parts.
Each of these "parts" is a **component**.
The heading is a component, the "new question" button is a component, and the search bar is its component.
This makes organizing the page leaps and bounds easier, but even more importantly, components allow us as developers to separate concerns from one another.

> **Separation of concerns** is a programming principle that states that each concern should be separated into individual pieces.
For example, in the diagram above, the "new question" button (2) should be clicked if a user wanted to add a new question, whereas the search bar (3) would be used if the user wanted to search existing questions.

## **Functional Components**

In React, there are two types of components that you can use: **Functional Components** and **Class Components.**

A functional component is a simple JavaScript function.

```
function Hello() {
  return <h1>Hello world.</h1>
}
```
The code above defined a functional component called **Hello**, which returns a simple React element.

## **Rendering Components**
 
We need to create the corresponding <u>JSX</u> element to display the component.
For example, for our user-defined component **Hello**:

```
const el = <Hello />;
```
Now, we can use our user-defined element and render it on the page:

```
function Hello() {
  return <h1>Hello world.</h1>
}
const el = <Hello />;
ReactDom.reader(
el,
document.getElementById('root')
);

```

> **Remember, all component names need to start with a capital letter.**

 

## **Class Components**

**Class components are typically used when there are more advanced user interactions, like forms, and animations.**

All class components need to extend the **React.Component** class.

```
class Hello extends React.Component {
 render() {
   return <h1>Hello world.</h1>;
}
}
  
```
Class components need to have a **render** method, which is in charge of telling what the page should show.
Deploying your files to the server on Save
Tags: webdev, programming, tutorial, php
Published: 2022-02-03 19:22:21

Once you have your files ready to share with the world, your next step is to deploy them, which is a fancy way of saying "lets save these files on a server so other people can access them". Here I'll go through a few different options of accomplishing this:

##Uploading the file to the server using cPanel
The most common way for new web developers to push their files to the server is using the file manager built into cPanel. This allows you to select which files to upload. While this is reliable, it's a very manual process to upload new files or overwrite files when something changes.

##FTP
FTP stands for **File Transfer Protocol**, and it is a way for your computer to make a connection to the server, allowing you to upload, overwrite, and delete files on a remote server. For all the below methods, you will first want to setup an FTP login in your cPanel by going to Files -> FTP Accounts. Create a new FTP account and store the username and password, you will need these to setup the FTP client below.

####FTP using PHPStorm
In PHPStorm, under Preferences -> Deployment -> Add, you can setup an FTP connection to the server. 

- For type you can use FTP

- Host should be your domain name, port 21

- Enter the username and password you setup on cPanel
Next, under the Mappings tab, you can setup the local path and deployment path. If you want files uploaded to the root of your server, you can just use "/" for Deployment path.
If you are working on a subfolder of your website (like mywebsiteblog.com/blog) then you can set the deployment path for /blog to have all the files in your folder pushed to that subfolder.

- Back to PHPStorm Preferences -> Deployment -> Options, I like to set the Upload changed files automatically to the server to "On Explicit Save", which gives you the Save to deploy functionality.

######FTP using [FileZilla](https://www.hostwinds.com/tutorials/connect-site-filezilla-cpanel)/[CyberDuck](https://support.cpanel.net/hc/en-us/articles/1500012655121-How-to-configure-CyberDuck-on-MacOS-to-connect-to-a-cPanel-FTP-account)
An honorable mention here, these FTP clients allow you to more easily sync files between the server and your computer than the cPanel file manager, but still take some manual work.

##SSH
The modern more secure way to connect to a server, there is a solid tutorial for setting up SSH [here](https://www.digitalocean.com/community/tutorials/how-to-use-visual-studio-code-for-remote-development-via-the-remote-ssh-plugin)

##Using Git
New platforms like Vercel and Netlify allow you to select a git repository, and whenever a commit is pushed to the main branch, it automatically builds the new files, then copies the build folder to the server.
Day 5 of 100DaysOfCode
Tags: 100daysofcode, todayilearned, python, challenge
Published: 2022-02-03 19:18:47

## Day 5 of 100 Days of Code

Here can you find what I learned (& published) today.

### What I published / coded / updated today?
* Day 5 started with fix 5 security vulnerabilities 2 github repositories, I published my first python libary to PyPi:  https://pypi.org/project/simple-amari.py/ the Python libary is for amaribot API (The amaribot is a discord bot), the documentation is coming soon. I learned today some new python experience too.
* The day 5 ended with the blog post here. ;)
Internal Dev Team 🎭
Tags: career, discuss
Published: 2022-02-03 19:00:33

It's been said that working for a large company with an internal team could be quite a high risk, I have been in this position in the past, working for a huge org with a < 10 Dev strong Dev team who where trying to form, at the same time, contractors from large well known agencies where really running the show, we where beholden to them but at the same time being told that this was our stack.

1 year after I sensed danger and left, the team was dismantled.

I wonder if an internal Dev team really works in this sort of context, can an org outgrow it's dev team, or attempt to form one to save money, only for it to fail in comparison to scale?

Have you ever been here, or seen it work, let me know 🙂