teleren/devto huggingface dataset:
GraphQL Files in Next.js
Tags: graphql, nextjs, typescript, react
Published: 2022-09-27 04:20:50

## Introduction
Next.js allows for utilizing a GraphQL API but its implementation may be less clear based on documentation, tutorials, or other resources found online. Most such resources (using Apollo) will make use of a query string in the component, such as:

```TypeScript
const GET_MISSIONS = gql`
  query missions {
    launchesPast {
      mission_name
    }
  }
`;

function Missions() {
  const { loading, error, data } = useQuery(GET_MISSIONS);
}
```

While this is not incorrect, such an implementation loses the benefits of an IDE which can format, lint, etc the query because it is wrapped in a JavaScript string. Instead, we want to take full advantage of separating GraphQL calls into distinct files such as `.graphql` or `.gql` as we would `.md` for markdown or `.json` for JSON content.

## Next.js and Webpack
In order to use `.graphql` files in Next.js, we have to configure the webpack configuration Next.js provides. In order to do so, create or edit the `next.config.js` file at the root level of your Next.js application:

```TypeScript
module.exports = {
  webpack: (config, options) {
    config.module.rules.push({
      test: /\.(graphql|gql)/,
      exclude: /node_modules/,
      loader: "graphql-tag/loader"
    });

    return config;
  }
};
```

What the code above does is tell the webpack configuration of Next.js to parse `.graphql` or `.gql` files through the `graphql-tag` loader. In order for this to work, install `graphql` at the root level of the application.

```Bash
npm install graphql-tag
```

Now we can refactor the previous component to make use of the new filetype.

```TypeScript
import { missions } from 'queries/mission.graphql';

function Component() {
  const { loading, error, data } = useQuery(missions);
}
```

In our new `.graphql` file, we can list each query which are exported and can be used in components.

```TypeScript
query missions {
  launchesPast {
    title
    author
  }
}
```

## Next.js and TypeScript
If using TypeScript with Next.js, you may find the new import will result in TypeScript warning that no modules or type declarations are found.

```Bash
Cannot find module 'queries/mission.graphql' or its corresponding type declarations.ts
```

To resolve this, we will need to create a custom type definition. If you don't already have custom types, create a `@types` folder at the root level of your application with a `graphql.d.ts` file. In this new file, declare the corresponding module.

```TypeScript
declare module '*.graphql'
```

If using `.gql` files, create a `gql.d.ts` file with `declare module '*.gql'` written inside.

## Conclusion
Next.js is a powerful framework that allows for a GraphQL API and harnessing the power of utilizing separate GraphQL files for queries just requires a few changes to configurations as mentioned above. A full working example can be found in the repo [richardtorres314/graphql-files](https://github.com/richardtorres314/graphql-files).
Create your team on HackSquad and win SWAG! 🤯
Tags: javascript, webdev, hacktoberfest, beginners
Published: 2022-09-27 12:54:13

Hi Community!

With the fantastic atmosphere of Hacktoberfest, we have decided to create Hacksquad.
Hacksquad is here to enhance your Swag, meet with more community members and participate in workshops from our great sponsors.

If you haven't heard about HackSquad feel free to go to the first post of the series.
And register here:
https://www.hacksquad.dev

I have opened the building a team option 🚀
But if you haven't, now it's the time to create or join a team! (yes, you can also join a random team)
So just enter here: https://www.hacksquad.dev/myteam

I can also help you find a team over Twitter, tweet us and I will retweet you using this link: https://discord.novu.co/tweet


![Let's do it](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n0nunv9o3ntlprgbwvmx.gif)

What's next?
- I will clarify the rules for a valid contribution
- I will let you know about some fantastic live events happening during the month (if you want to learn something specific, just write on the general channel, and I will try to find a speaker for it!)

Love ❤️
How to make vertically scrollable in CSS
Tags: css, html, webdev
Published: 2022-09-27 12:47:03

In order for the scroll to appear, you need to limit its `height` by adding height or `max-height` properties.

```css
.scroll-area {
  overflow-y: auto;
  max-height: 400px;
}
```

If you do not add this, your block will stretch to the entire height.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9uxdd7z2ccnh9belnkua.png)
My Mistake as an Android Developer, which I do not want others to make
Tags: android, software
Published: 2022-09-27 12:25:17

The journey of becoming an Android Development started in the year 2017, after two years of graduating from Nigeria University. Before graduating from University have been thinking of a way to make a living, knowing the high unemployment rate in my country. I first thought of learning hand work, but after I searched the internet, I learned about software development. As God will have it, I have the privilege to visit a brother of mine living in Dubai. My brother gave me a small laptop, and with an uninterrupted power supply and internet, then I started learning how to code. 

Firstly, I started with HTML and CSS, Query, and then PHP for the backend. I built two to three personal websites with this knowledge. After seven months, I left Dubai for Nigeria because of NYSC. NYSC means National Youth Service Corps, through which Nigerian graduate serve their Fatherland. During my service year, I decided to learn Android Development, and I started with learning Java programming language, which was the official Google language for developing Android apps. And there was an app that has been wishing to build with the knowledge I acquired, I built the app, and it is doing well on the google play store. Instead of looking for experience by getting a job as Android Developer, I keep working on my project. In addition, since the android version of the app was a success, people clamored for the iOS version, and I was able to build it within a month. With the android version, the app has more than one hundred thousand downloads on google play, while the iOS version was a paid version. 

Through the android version, I was making almost $300 a month, while through the iOS version, I was making $100 a month. And my income through this app has been steady for many months. Hitherto, someone filed a copyright claim for some of the audio I used in the app for both the android and iOS versions of the apps. Consequently, both the android and iOS versions of the apps were removed from the google play store and App Store. But for almost a year now have been trying to get a job in tech, and think the reason why am unable to get any of it was my lack of experience in android app development. Below, we look at the two things we believe every software engineer should know.

1. As you are learning software development, continue applying for a job, even though you might have a project you want to build. If you eventually get a job, after coming back from the job, you can work on your personal project.

2. Join an online group that is related to what you are learning. Hence, there are many people out there that already know more than you, no matter how many years you might have been learning.

In conclusion, don't only work on your personal project, but also look for experience. Thank you for reading. Please look out for more publications from me.
Mobile App Development Trends in 2022
Tags: mobile, app, development, webdev
Published: 2022-09-27 12:21:46

[Technology products](https://www.incepteo.com/blog/mobile-app-development-trends-in-2022/) are susceptible to change every year as customer habits and demands transform. Businesses must remain up to date with changes in technology to ensure that their web and mobile app products are working and still delivering results
Typescript customized Function handler for exceptions with Node.js and Express.js
Tags: javascript, webdev, programming, typescript
Published: 2022-09-27 12:10:19

## Hi, Devs!

First of all, step one is to build the function handler for exceptions, it is necessary because when you use the **throw** the application's is going to broke, so when you use the try/catch scope and into catch we could use the method below to get the exception.

/middlewares/ErrorHandler.ts
```js
import { NextFunction, Request, Response } from 'express';

class ErrorHandler {

    public static handle(error: Error, _req: Request, res: Response, next: NextFunction) {
        res.status(500).json({ message: error.message });
        next()
    }
}

export { ErrorHandler }
```

Let's create the app.ts:

/src/app.ts

```js
import express from 'express';
import { ErrorHandler } from './middlewares/ErrorHandler';
import { NextFunction, Request, Response } from 'express';

const app = express();
app.use(express.json());
app.post('/handler', (req: Request, res: Request, next: NextFunction) => {
try{
  if(req.body.number < 0)
    throw new Error('Negative number!');
}catch(error: any) {
 next(error)
}
});
app.use(ErrorHandler.handle); // necessary to be the last middleware to get the exception.

export default app;
```

Let' create server.ts file to start the API:

```js
import app from './app';

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => 
     console.log(`Running server on port: ${PORT}`));
})
```

If you pass a negative number for the body request you'll receive an exception and it will treat with the customized handler because the last middleware (ErrorHandler) will get it.

**That's all!**

**Contacts**
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca
How to participate in hacktoberfest 2022
Tags: hacktoberfest, hacktoberfest2022, opensource, programming
Published: 2022-09-27 12:01:54

## Introduction

Want to contribute to Open-source? Month of contribution is here. Hacktoberfest is back with a whole new version. Don't know how to participate? Want to contribute to open-source community? Want to learn by contributing? Want to earn swags from contributions? Let me tell you how you can take part in this October-festival for coders.


## Steps

1. Navigate to [hacktoberfest](https://hacktoberfest.com/) portal.

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

2. Click on Registerations now open button below.


3. Chose how to login to this contest. I'm chosing Github.

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

4. Asking for some more info, which I've to give.

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

5. Select the additional details asked in the form.

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

6. At last, agreeing to terms and conditions & click on Register button.

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

7. At last, below image is taken from your github profile, so put some great picture ahead. This marks the confirmation that you've registered for Hacktoberfest 2022.

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

8. This marks my current progress. You need to do atleast 4 PRs & it should be merged.

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


All the best for HacktoberFest 2022. Keep contributing to Open-Source.


[Keep Hacking] 
"Follow me on [GitHub](https://github.com/nitinkumar30/) too."
"Visit my [Portfolio](https://nitin-kr.onrender.com/) also."
console.log() shortcut in VS code
Published: 2022-09-27 11:55:09

**_FIRST WAY_**

- vs code open kore
- ctrl + shift + p press korte hobe
- snippets likhe search dite hobe
- erpor j language e dorkar, oi language select kore, amader configure korte hobe.

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


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



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

```javascript
{
	"Console.log": {
		"prefix": "clg",
		"body": "console.log($1);",
		"description": "Console Log"
	}
}
```



---
--- 
---

**_ANOTHER WAY_**

- first step:

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

- second step (click the red mark like the image)

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

- third step (write 11 to 18no. line of code)

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

- code 

```javascript
// Place your key bindings in this file to override the defaultsauto[]
[
    {
        "key": "ctrl+r",
        "command": "code-runner.run"
    },
    {
        "key": "ctrl+alt+n",
        "command": "-code-runner.run"
    },
    {
        "key": "ctrl+shift+l",
        "command": "editor.action.insertSnippet",
        "when": "editorTextFocus",
        "args": {
            "snippet": "console.log(`${TM_SELECTED_TEXT}$1`$2);"
        }
    }
]
```
How to Install Vue CLI on Ubuntu 22.04 - HostnExtra
Tags: javascript, vue, ubuntu, linux
Published: 2022-09-27 11:46:52

In this article, we’ll explain how to install Vue CLI on Ubuntu 22.04.

Vue.js is an open-source model-view-viewmodel front end JavaScript framework. This article will guide you the installation process and creating hello world first project.

#### Prerequisites
A Ubuntu 22.04 installed dedicated server or KVM VPS.
A root user access or normal user with administrative privileges.

#### [Install Vue CLI on Ubuntu 22.04](https://www.hostnextra.com/kb/how-to-install-vue-cli-on-ubuntu-22-04/)

####1 - User management

Add user

`# adduser <user name>`

It will ask you to enter the password for the new user.

Add user in sudo group

`# usermod -aG sudo block`

Login with new user

`# su - <username>`

#### 2 - Keep the server up to date

`$ sudo apt update -y`

####3 - Download NodeJS

Download latest stable release of NodeJS.

`$ sudo curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -`

####4 - Install NodeJS

Next, install the NodeJS using following command:

`$ sudo apt-get install -y nodejs`

####5 - Verify the installation

`$ node -v && npm -v`

Output:

> v18.9.0
> 8.19.1

####6. Install Vue CLI

Following command will install Vue CLI.

`$ sudo npm install -g @vue/cli`

Verify the installation:

`$ vue --version`

Output:

> @vue/cli 5.0.8

####7. Create Vue project

`$ vue create hello-world`

You will be prompted to pick a preset. You can either choose the default preset which comes with a basic Babel + ESLint setup, or select "Manually select features" to pick the features you need.

> Output:
> Vue CLI v5.0.8`
> ? Please pick a preset: (Use arrow keys)
> ❯ Default ([Vue 2] babel, eslint)
> Default (Vue 3 Preview) ([Vue 3] babel, eslint)
> Manually select features

Successfully created project hello-world.
Get started with the following commands:

`$ cd hello-world
$ sudo npm run serve`

Output:

> App running at:
> - Local: http://localhost:8080/
> - Network: http://192.168.0.106:8080/
> Note that the development build is not optimized.
> To create a production build, run npm run build.

Navigate to your browser and open http://[server_IP]:8080.


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

That’s it. The installation has been completed.

In this article, we have seen how to install Vue CLI on Ubuntu 22.04.
Fruit Into Baskets
Tags: javascript, leetcode
Published: 2022-09-27 11:42:11

```js
var totalFruit = function (fruits) {
  let map = new Map();
  let max = 0;
  let tempArray = [];
  let end = 0;
  let array = fruits;
  let k = 2; // as total fruits is two you can have at a time


  while (array.length > end) {
    const nextChar = array[end];

    if (map.size < k && !map.has(nextChar)) {
      map.set(nextChar, 1);

      end++;
      tempArray.push(nextChar);
    } else if (map.size <= k && map.has(nextChar)) {
      map.set(nextChar, map.get(nextChar) + 1);

      end++;
      tempArray.push(nextChar);
    } else if (map.size === k && !map.has(nextChar)) {
      while (map.size === k) {
        // save the current
        if (tempArray.length > max) {
          max = tempArray.length;
        }

        let startValue = tempArray.shift();
        map.set(startValue, map.get(startValue) - 1);
        if (map.get(startValue) === 0) {
          map.delete(startValue);
        }
      }
    }
  }
  return max > tempArray.length ? max : tempArray.length;
};

console.log(totalFruit([1, 1, 1, 1, 1, 1, 1, 3, 2, 1]));
console.log(totalFruit([1, 2, 1], 2));
console.log(totalFruit([1, 2, 3, 2, 2]));
console.log(totalFruit([0, 1, 2, 2]));


```
Collecting Data into Database Automatically
Published: 2022-09-27 11:40:50

### Import Necessary Libraries

```
import pandas as pd
import sqlite3
import os
```
### Get Data From Excel File

```
def GetData(filename):
    # excel settings
    try:
        df = pd.read_excel(filename)
        return df
    except:
        print('File Not Readed Filename: ' , filename)
        pass
    # csv settings
    try:
        df = pd.read_csv(filename, delimiter=',')
        return df
    except:
        print('File Not Readed Filename: ' , filename)
        pass
    else:
        df = pd.read_csv(filename, delimiter=';')
        return df
    finally:
        print('CSV File Added!: ', filename)
```
### Write Database Code

```
def RecordSql(dataframe, filename):
    filename = str(filename).lower().strip().replace(' ', '_')
    conn = sqlite3.connect('collector_database.db')
    try:
        dataframe.to_sql(filename, conn)
        print('Table Added: ', filename)
    except:
        pass
    conn.close()
    return
```
### Run Code

```
if __name__ == '__main__':
    currdir = os.getcwd()
    for filepath in os.listdir(currdir):
        filename, ext = os.path.splitext(filepath)
        if ext in ['.xlsx', '.xls', '.csv']:
            print(filepath)
            data = GetData(filepath)
            RecordSql(data, filename)
```
Add Tailwind CSS in the Quasar 2 and Vue 3 project — Simple steps
Published: 2022-09-27 10:11:18


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

###### (Image Source — https://stackdiary.com/vue-ui-components-kits/)

.
.
Quasar Framework is a great UI framework that provides lots of ready-to-use components which are well tested on the web, iPad, mobile, and all devices.

By adding Tailwind CSS, you can build website UI within minutes. Quasar+Tailwind CSS will definitely help you increase front-end development speed!

In 90% of cases, if you install tailwind using the default command, it won’t work, I am sharing steps that worked for me after lots of trial and error.

Create Quasar Project and install Tailwind CSS and it’s dependencies:

```
quasar create quasar-tailwind-project
cd quasar-tailwind-project
npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
```

Add tailwindcss in the plugins section to .postcssrc.js like below

```
module.exports = {
     plugins: [
       require('tailwindcss')
     ]
}
```

Add tailwindcss imports to src/css/app.scss

```
@tailwind base;
@tailwind components;
@tailwind utilities;
```

Now you are ready to use Tailwind CSS in your Quasar Project, just use code from their official documentation.
send form to email
Tags: html, webdev, email, programming
Published: 2022-09-27 11:27:29

When you create your next website just remember you don't have to program every feature you need.

If you want a quick way to get your HTML contact form submissions.

With just a few lines of HTML code. You can create a contact form for your website , that will send the form data to an email.

```
<form action="https://fabform.io/f/{form-id}" method="post">
 <label for="email">Your Email</label>
 <input name="email" type="email">
 <button type="submit">Submit</button> 
</form>

```

You just need to create a free account on the [static website forms] backend fabform.io

Read more about it here.

[Here is how to [send form to email](https://fabform.io/a/send-form-to-email)
CLI: Backing up and restoring file modification times
Tags: linux, tutorial, devops, programming
Published: 2022-09-27 11:08:13


I recently needed to keep the exact file modification times as a part of a git repository. Since git doesn't support such functionality out of the box, I used a simple combination of `find` and `touch` commands as a part of the pre-commit hook.

Here are two versions of this approach, one with the `stat` command, and the other one with just the combination of `find` and `touch`.

## 1st version (stat)

```
find . -type f -exec stat -c 'touch -d "%y" "%n"' {} \; > restore_mtimes
```

Explanation:
  - Using the `find` command, we're recursively iterating over all files (-type f) in all subdirectories, starting from the current directory (`.`)
  - for each file, we're executing (-exec flag) the `stat ...` command (The string `{}` is replaced by the current file name)
  - we're using the formatted output of `stat` command (-c flag) to generate `touch -d "%y" "%n"` lines as a part of our restore script ("%y" is modification time, "%n" is file name).
  - we're redirecting the whole output of the `find` command to the `restore_mtimes` file

The resulting `restore_mtimes` file looks something like this:
```
touch -d "2022-09-26 15:55:10.127898032 +0200" "./f2"
touch -d "2022-09-26 15:55:11.651909078 +0200" "./f3"
touch -d "2022-09-26 15:55:06.751873534 +0200" "./f1"
```

You can execute this file to restore the original modification times (either by making it executable with `chmod +x restore_mtimes` or sourcing it directly with `. restore_mtimes`).

## 2nd version (find & touch)

Since we only need the file modification time, we could optimize things by removing the unnecessary call to the `stat` command, and simply use the modification time provided by `find` command:
```
find . -type f -printf 'touch -d "%t" "%p"\n' > restore_mtimes
```

- "%t" is modification time, "%p" is file name
- unlike with `stat -c`, we also need to explicitly add a newline character at the end


The time format returned by find is a bit different (but it should be also parsed correctly by `touch`):
```
touch -d "Mon Sep 26 15:55:10.1278980320 2022" "./f2"
touch -d "Mon Sep 26 15:55:11.6519090780 2022" "./f3"
touch -d "Mon Sep 26 15:55:06.7518735340 2022" "./f1"
```

---

Alternatives and additional things to consider:

## VCS commit times

One alternative to backing up file modification times is reusing the last commit time from your versioning control system, e.g.: <a href="/restoring-file-mtimes-with-git">restoring file mtimes with git</a>.

## touch --no-create

In cases where you're planning to restore the modification times to a tree where some files may be deleted, it may be useful to add the `--no-create` flag (which will prevent `touch` from creating any new files).

        
<hr><small>
Note: This is a snapshot of the wiki page from the <a href="https://betterways.dev">BetterWays.dev wiki</a>, you can find the latest, better formatted version here: <a href="https://betterways.dev/cli-backing-up-and-restoring-file-modification-times">betterways.dev/cli-backing-up-and-restoring-file-modification-times</a>.
</small>