teleren/devto huggingface dataset:
Easiest way to make Google and Local authentication using Passport.js
Tags: node, passportjs, authentication, javascript
Published: 2023-01-21 10:12:04

To use Passport.js for both Google and local (username and password) authentication in a Node.js application, you will need to:

1. Install the `passport-google-oauth20` and `passport-local` packages by running `npm install passport-google-oauth20 passport-local` in your project's root directory.

2. Create a new Google API Console project and configure it to allow your application to use the Google+ API and generate OAuth 2.0 credentials (client ID and client secret).

3. In your Node.js application, import the `passport-google-oauth20` strategy and configure it with your client ID and client secret. Also import the `passport-local` strategy, and configure it with the appropriate options.

4. Create routes for handling the Google OAuth callback and local login.

5. Initialize Passport.js and use the Google strategy and local strategy for authentication.

6. Add the appropriate links in your application to initiate the authentication process with Google or local login.


Here is an example of how to set up Passport.js for both Google and local authentication in a Node.js application:

```javascript
const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const LocalStrategy = require('passport-local').Strategy;

const app = express();

passport.use(new GoogleStrategy({
    clientID: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET',
    callbackURL: 'http://localhost:3000/auth/google/callback'
  },
  (accessToken, refreshToken, profile, cb) => {
    // Perform any additional verification or user lookup here
    // and return the user object
    return cb(null, profile);
  }
));

passport.use(new LocalStrategy((username, password, cb) => {
    // Perform user lookup or verification here
    // and return the user object
    const user = { id: 1, username: 'user', password: 'password' };
    if (username !== user.username || password !== user.password) {
      return cb(null, false);
    }
    return cb(null, user);
}));

app.get('/auth/google', passport.authenticate('google', { scope: ['profile'] }));

app.get('/auth/google/callback', 
  passport.authenticate('google', { failureRedirect: '/login' }),
  (req, res) => {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

app.post('/login', passport.authenticate('local', { failureRedirect: '/login', successRedirect: '/' }));

app.listen(3000);
```

This is a basic example, you might need to customize this according to your application needs, like adding a user model, using bcrypt to hash passwords, etc.


also checkout the github [repo](https://github.com/muhammadabir64/passport.js-auth)
Translating Code: The Importance of Compilation and Interpretation
Tags: computerscience
Published: 2023-01-21 10:00:00

Have you ever wondered how a computer is able to understand and execute the code you write? The answer lies in the process of compilation and interpretation. Compilation and interpretation are two key methods that are used to translate code written in one programming language into machine-readable code. Understanding these processes is essential for any computer programmer or software developer.

---

## Why is this important?

Compilation and interpretation are important because they allow code written in one programming language to be understood and executed by a computer. Without these processes, code would have to be written in machine-readable languages, which would be much more difficult for humans to understand and write.

## How does this affect other computer science fields?

Compilation and interpretation also play a key role in other computer science fields such as software engineering and computer architecture. In software engineering, understanding how code is translated into machine-readable code is essential for the development and optimization of software. In computer architecture, understanding how code is translated and executed by a computer is essential for the design and optimization of computer systems.

## What is it?

Compilation refers to the process of translating code written in a high-level programming language, such as C++ or Java, into machine-readable code, such as assembly or machine code. This process is typically done by a program called a compiler. For example, when a C++ program is compiled, the C++ code is translated into machine code that can be executed by a computer.

Interpretation, on the other hand, refers to the process of executing code written in a high-level programming language, such as Python or JavaScript, without first translating it into machine-readable code. This process is typically done by a program called an interpreter. For example, when a Python program is run, the Python code is passed through an interpreter that executes it line by line.

---

In conclusion, compilation and interpretation are essential processes that allow code written in high-level programming languages to be understood and executed by computers. These processes not only make it easier for humans to write and understand code, but also play a crucial role in the optimization and development of software and computer systems. Understanding these processes is a must for any computer programmer or software developer, and it can be inspiring and motivating to know how a computer is able to understand and execute the code you write.
Netlify Nextjs Deployment — Page Not Found Issue Solution
Tags: netlify, nextjs, github, actions
Published: 2023-01-21 09:53:08

---
title: Netlify Nextjs Deployment — Page Not Found Issue Solution
published: true
description: Nextjs deployment to netlify was made easy by netlify through github repo. But the issue is it’s not working for all and many of the developers are seeking help on the issue page not found even though deployment was successful.
tags: netlify, nextjs, github, actions
# cover_image: https://www.netlify.com/v3/img/components/solutions-nextjs-og.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-01-21 09:41 +0000
---
![Netlify Nextjs Deployment](https://miro.medium.com/max/1400/1*cvZpb4UX4Jc0_un-HlET0Q.webp)

Nextjs deployment to netlify was made easy by netlify through github repo. But the issue is it’s not working for all and many of the developers are seeking help on the issue page not found even though deployment was successful.

So I’ve made a work around for the issue. Its not a perfect solution but it works.

I have created two repos one is for nextjs code and other is for the build generated files.

I have created an action for the first repository where it builds & exports the code and pushed to second repository.

This second repository is connected to netlify and it serves the generated html files.

This action will be created from the first repository actions tab.
![Github Actions](https://miro.medium.com/max/1400/1*Iu-n-UXy4f7PAE9OnU2kAQ.webp)
Click New workflow and then click set up new workflow yourself.
![Create Workflow](https://miro.medium.com/max/1400/1*tfSS0wOkH37H2zvCZTELmg.webp)
Add below code and commit.
```
name: Build & push to Another Repo
on:
  push:
    branches:
      - main
jobs:
  build:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [16.x]

    steps:
      - uses: actions/checkout@v1
        with:
          fetch-depth: 0
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}
      - name: npm install, build
        run: |
          npm ci
          npm run build && npm run export
        env:
          CI: true
      - name: Publish
        uses: selenehyun/gh-push@master
        env:
          GITHUB_TOKEN: ${{ secrets.API_TOKEN_GITHUB }}
          COMMIT_FILES: out/*
          REPO_FULLNAME: userName/repoName
          BRANCH: main
```
These are the build settings as we are deploying generated html files so no build setting are needed.
![Create Workflow](https://miro.medium.com/max/1400/1*DfCVmkUTpJrIZtRhaCkb-g.webp)
One more change required in the `next.config.js`

Add `target: 'serverless'` in the exports.
```
module.exports = {
  reactStrictMode: true,
  target: 'serverless'
};
```
That’s it. Now when ever you push code to first repo it generates a build and pushes to second repo. And when ever second repo gets a push netlify starts the deploy job and that’s how it works. I know its not the perfect fix but as I said it works.
Mobile Architecture
Tags: flutter, dart, mobile, architecture
Published: 2023-01-21 08:33:23

## Uygulama Katmanları:
**Data Katmanı:** API'lerle etkileşimden sorumlu olan katmandır.
**Domain Katmanı:** Data katmanından gelen verileri dönüştürmekle görevli olan katmandır.
**Business Logic Katmanı:** Uygulama state'ini yöneten katmandır.
**Presentation Katmanı:** UI bileşenlerini state'e göre işleyen katmandır.

`Domain katmanı` ham verileri `business logic` katmanı tarafından tüketilen `domain`'e (etki alanına) özgü modellere dönüştürür.
`Business Logic` katmanı `repository`'nin sağladığı domain modellerinin değişmez durumunu (immutable state) korur ve kullanıcı arayüzünden gelen girdilere tepki verir ve state'e göre değişiklik yapılması gerektiğinde depo ile iletişim kurar.


Her katman doğrudan ilişkili olmayan katmanlar arasındaki etkileşimleri önleyen bir ilişki zincirine sahip olmalıdır.
Örneğin presentation katmanı, data katmanındaki apileri doğrudan çağırmamalı veya bunlarla hiçbir şekilde etkileşimde bulunmamalıdır.

**Yeniden kullanılabilirliği göz önünde bulundurarak oluşturun:**
Bu tavsiye özellikle data katmanı içindir. Data katmanındaki bileşenler, belirli bir ürüne uygulamaya bağlı olmadıkları ve daha geniş topluluğa fayda sağlayabilecekleri için genellikle açık kaynak için mükemmel adaylardır.

Verileri ve domain katmanlarını paketler halinde izole etmek onları diğer uygulamalara aktarmaya veya istenirse pub.dev de yayınlamaya olanak tanır.

Belirli bir model beklemek yerine kodlanmış JSON stringlerini depolamak için genel bir API oluşturabilir böylece bu API diğer domain alanlarında yerel bir depolama API'si olarak kullanılabilir.



**Not: Bu yazı [very-good-flutter-architecture](https://verygood.ventures/blog/very-good-flutter-architecture?utm_source=github&utm_medium=readme&utm_campaign=app_architecture) yazısının özeti niteliğini taşır.**


Kaynak:

https://verygood.ventures/blog/very-good-flutter-architecture?utm_source=github&utm_medium=readme&utm_campaign=app_architecture
Using ChatGPT to talk to my website
Tags: chatgpt, openai, machinelearning, webdev
Published: 2023-01-21 09:48:07

The last 4 weeks, I've literally done nothing that's not related to ChatGPT - But I assume that's true for most of us. A couple of days ago I released a new version of [Aista Magic Cloud](https://aista.com), allowing users to scrape their website(s), or any other website for that matter, to generated training data from the site. This allows me to create a _"custom ChatGPT model"_, where the model should be at least in theory able to answer intelligently according to how you would want it to answer. Basically ...

> This turns your existing website into a custom ChatGPT brain

Examples of use cases I see myself are;

1. Support chat bots for companies
2. Legal advice chat bots on lawyer companies websites
3. Investment advice on investment websites
4. Medical advice on websites for medical companies

But really, I suspect the above is just the tip of the iceberg. In the following video, I am demonstrating how I was able to use it to scrape [Aista.com](https://aista.com) and [docs.aista.com](https://docs.aista.com) to generate a chat prompt that would answer questions roughly 50% correctly. 50% of course is far from good enough, but the system also allows you to continuously improve your models, through human supervision, generating *new* training data, and such iterating over and over again, until you reach close to 100% accuracy.

{% embed https://www.youtube.com/watch?v=MVzzA4OvkwY %}

After a simple 5 minutes long scraping session, the system is already capable of answering questions it had no idea how to answer at [the primary website for ChatGPT](https://chat.openai.com). Not spectacularly good numbers, but I suspect with larger websites, creating more training data, it would result in a higher success ratio. In addition, the _"reinforcement training parts"_ allows for supervising the model's questions and answers, allowing human beings to monitor its questions and answers, and such over time incrementally improve its answers rapidly, by _"sanity checking"_ its questions and answers.

Does anyone here have a great suggestion to a (small) website they want me to scrape? It would need at least some 3,000 to 5,000 high quality training snippets I suspect before it's really good at answering. Comment with a link to a nice website, with good semantic data, not too large preferably, tops some 500 pages in total - And I'll scrape it for you, and create your own ChatGPT chat bot ... ;)
"Magento solutions for customizable, scalable, and profitable eCommerce"
Tags: programming, javascript, devops, design
Published: 2023-01-21 09:42:58

Utilizing Magento business solutions agencies assist businesses in building their portals. Through Magento solutions, companies can adapt to evolving requirements of their business and develop profitable profit models by integrating modules and using solutions to automate processes in business. With our affordable and competitive rates, we will always maintain the quality of our output. We guarantee a higher rate than your expectations, no matter the price. Our team will design the ideal Magento website to suit your company, whatever your [Magento Development Services in USA](https://www.99magento.com/) layout or development needs are. Using our passion, we aim to customize any Magento template to meet your specifications. Our company's Magento web designers have designed various attractive and effective designs that are both useful and pleasing to the eye. Scalability is one of the advantages that are a feature of Magento online shopping carts. Our Magento developer can help you transition when you're a mid-sized company looking to compete with the bigger players. If you own a vast collection of complex and customizable products and want to control your company's eCommerce capabilities, it may be necessary to use a dynamic online interface.
Release whispercppapp 0.1.0: speech recognition GUI app
Tags: openai, flutter, showdev
Published: 2023-01-21 09:41:13

<https://github.com/hogelog/whispercppapp>

whispercppapp is GUI speech recognition app powered by [whisper.cpp
](https://github.com/ggerganov/whisper.cpp).

whispercppapp includes bundled whisper.cpp and ffmpeg binaries, and supports automatic dowload of model files for easy use.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6omz38yvpv9e07e52ua9.png)
Google map how to show city boundaries
Tags: javascript, googlemap, programming, tutorial
Published: 2023-01-21 09:18:25

I recently worked on a project where I had to show city boundaries on a Google Map, and it was not an easy task. However, I was able to figure it out and complete the project successfully. If you're interested, you can check out my article on how to display city boundaries using Google Maps. It goes into detail on the process I followed and the challenges I faced. 

https://richtech.io/google-map-show-the-city-or-any-area-boundaries-on-map/
Create an simple blockchain application using NodeJS & Crypto library
Tags: node, blockchain, crypto, javascript
Published: 2023-01-21 09:17:04

Here is an example of how you can create a simple blockchain application using JavaScript:

- Start by creating a new project directory and initialize it as a Node.js project by running `npm init`.
- Next, you'll need to install a blockchain library for JavaScript. There are several options available such as `crypto-js`, `elliptic`, and `web3.js`. In this example, we'll use `crypto-js`.
```javascript
npm install crypto-js
```

- Create a new file called blockchain.js and import the crypto-js library.
```javascript
const SHA256 = require("crypto-js/sha256");
```

- Create a Block class that will define the structure of each block in the chain. Each block will have an index, a timestamp, data, and the hash of the previous block.
```javascript
class Block {
  constructor(index, timestamp, data, previousHash = '') {
    this.index = index;
    this.timestamp = timestamp;
    this.data = data;
    this.previousHash = previousHash;
    this.hash = this.calculateHash();
  }

  calculateHash() {
    return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();
  }
}
```

- Create a Blockchain class that will manage the chain of blocks. This class will have a chain property that will hold the blocks, and a createBlock method that can be used to add new blocks to the chain.
```javascript
class Blockchain {
  constructor() {
    this.chain = [this.createGenesisBlock()];
  }

  createGenesisBlock() {
    return new Block(0, "01/01/2020", "Genesis block", "0");
  }

  getLatestBlock() {
    return this.chain[this.chain.length - 1];
  }

  createBlock(data) {
    const latestBlock = this.getLatestBlock();
    const newBlock = new Block(latestBlock.index + 1, Date.now(), data, latestBlock.hash);
    this.chain.push(newBlock);
    return newBlock;
  }
}
```

- Finally, create an instance of the Blockchain class and use the createBlock method to add new blocks to the chain.
```javascript
const myChain = new Blockchain();
console.log(myChain.createBlock("First block"));
console.log(myChain.createBlock("Second block"));
console.log(myChain.createBlock("Third block"));
console.log(myChain);
```
```javascript
//output of First block
Block {
  index: 1,
  timestamp: 1674293127385,
  data: 'First block',
  previousHash: '37fdbf3027570c6daca59c93c646bb19bae477f5c070abfe74d9170b313ba0df',
  hash: '6395cf4b7634b587e6fb3e7eb4eab12aff0a6a5a7d798b1122ae75186bcff476'
}
```

Please note that this is just a basic example and is not suitable for production use. In a real-world application, you would need to add more features such as validation of new blocks, consensus mechanism and more.

Also, there are multiple frameworks and libraries built on top of javascript that makes blockchain development more easier such as `Ethereum.js`, `NEM2-SDK`, `Chainpoint `etc.

Checkout the github [repo](https://github.com/muhammadabir64/simple-blockchain-in-node)
3 Best Node Js Project Ideas to Get Quick Job
Tags: javascript, webdev, beginners, programming
Published: 2023-01-21 09:09:10

**Node.js** is a powerful platform for building server-side applications, and it's no surprise that it's in high demand among employers. Whether you're a beginner or an experienced developer, working on a Node.js project is a great way to showcase your skills and increase your chances of landing a job.

Here are the **top 3 Node.js project ideas that will help you get a job**:

## 3 Best Node Js Projects

### A real-time chat application:
Building a real-time chat application with Node.js is a great way to showcase your skills in web sockets, real-time data handling, and user authentication. Employers are always looking for developers who have experience in building real-time applications and can handle the challenges that come with it.

### A RESTful API:
Creating a RESTful API is a great way to showcase your skills in routing, handling different types of requests, and building scalable and maintainable applications. Employers are always looking for developers who can create and maintain APIs that can handle a large number of requests and can be easily integrated into other systems.

### A web scraping tool:
Building a web scraping tool with Node.js is a great way to showcase your skills in web scraping, data extraction, and data manipulation. Employers are always looking for developers who can extract data from websites and can turn it into actionable information that can be used to make business decisions.

These are just a few ideas to get you started, but the possibilities are endless with Node.js. Remember to keep in mind the needs of your potential employer while working on your project and take into account the skills they require to increase your chances of getting a job.
Introducing popular SQL Queries & SQL Naming Convention
Tags: sql, naming, query
Published: 2023-01-21 08:46:36

## Abstract

웹 프로젝트 킥오프 때 가장 많이 고민하고 시간을 소요하는 것이 서비스에 적합하면서 확장성을 가지고 있는 DB Structure Design 이다.

한번 `Production` 환경에 올라가면 수정하기 거의 불가능에 가까운 것이 DB이기 때문에 프로젝트 첫 페이즈일때 실제 데이터 수정이 빈번하게 일어나게 된다.

이때 자주 사용하게 되는 기본 Query 들을 이번 포스팅에서 소개하고자 한다.
사실 부족한 내 기억력을 대비하고자 작성한 나만을 위한 포스팅이다.

---

## Queries

### Database

데이터베이스 생성 및 제거

```sql
/* create */
CREATE DATABASE database_name;

/* remove */
DROP DATABASE database_name;
```

---

### Table

테이블 생성 및 제거

```sql
/* create */
CREATE TABLE table_name (
  /* primary key */
  id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT 'Primary Key',

  /* nullable or not nullable */
  key_name_1 VARCHAR(100) NOT NULL,
  key_name_2 VARCHAR(100) NOT NULL,
  key_name_3 TEXT DEFAULT NULL,

  /* for managing CRUD history */
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Create Time',
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update Time',
  deleted_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Delete Time'
) COMMENT 'Table Description';

/* remove */
DROP TABLE table_name;

/* rename */
ALTER TABLE table_name RENAME new_table_name;
```

테이블 전체 데이터 조회

```sql
SELECT * FROM table_name;
```

---

### Data

데이터 생성 및 수정

```sql
/* create */
INSERT INTO table_name (key_name_1, key_name_1, key_name_1)
VALUES
  ('value_1', 'value_2', 'value_3'),
  ('value_1', 'value_2', 'value_3'),
  ('value_1', 'value_2', 'value_3');

/* change */
ALTER TABLE table_name
CHANGE table_name new_table_name;
```

관계 생성 및 제거

```sql
/* create foreign key */
ALTER TABLE table_name
ADD FOREIGN KEY (table_1_id) REFERENCES table_1(id);

/* remove foreign key */
ALTER TABLE table_name
DROP FOREIGN KEY table_ibfk_1;
```

---

## Naming Convention

### Table

- 테이블 이름은 `Singular`

- 테이블 이름은 `Lowercase`

- `Join Table (Relationship Table)` 이름은 테이블 관계에 따라 `_has_`, `_and_` 사용

  - `todo` 테이블 하위 개념인 `task` 테이블일 경우 `Join Table` 이름은 `todo_has_task`

  - `keyboard` 테이블과 동등 개념인 `mouse` 테이블일 경우 `Join Table` 이름은 `keyboard_and_mouse`

  - `ball` 테이블과 `ball_type` 테이블일 경우 `ball_has_type`

- 테이블에는 무조건 히스토리를 관리

  - `created_at`, `updated_at`, `deleted_at`

---

### Data

- 키 이름은 `snake case`
- `foreign key` 의 경우 관계되는 테이블의 이름을 참조

  - `book` 테이블에 연결할 `foreign key` 는 `book_id` 관계 대상은 `book(id)`

  - `Join Table`의 경우

    - `ball_has_type` 테이블의 경우 `ball` 테이블 `foreign key`는 `ball_id`, `ball_type` 테이블의 `foreign key` 는 `type_id`

- `Boolean` 값은 `is_`로 시작

---

## Conclusion

서문에서 언급한대로 이번글은 부족한 기억력을 보완하고자 쓴 포스팅이기 때문에 따로 언급할만한 내용은 없다.
앞으로 계속 추가 예정...