teleren/devto huggingface dataset:
Exploring Data Security and Encryption in PostgreSQL
Tags: apache, postgres, opensource, database
Published: 2023-08-06 11:52:29

Welcome to the 12th article of my blog series.

## Introduction
Data security is crucial, and PostgreSQL, an open-source relational database management system, offers a number of features to guarantee reliable data encryption and protection. In order to protect sensitive data. In this blog I will discuss data security and encryption.

## Authentication and Authorization:
PostgreSQL offers a strong authentication system that supports various techniques, such as password-based and certificate-based authentication, among others. Database access and permissions are managed through user roles, while access control lists (ACLs) provide a granular level of security by enabling control down to specific table columns. With these robust security features, PostgreSQL ensures secure and controlled access to databases and their associated objects, making it a reliable choice for safeguarding sensitive data.

## Data Encryption
Data stored on disc is kept secured. In the event that physical storage is compromised, this safeguards data from unauthorized access.

## SSL/TLS Encryption
PostgreSQL incorporates SSL/TLS encryption to establish secure communication between clients and the database server. By employing this encryption, PostgreSQL protects against potential data interception and eavesdropping during data transmission, ensuring the confidentiality and integrity of sensitive information.

## Encryption at Rest
PostgreSQL offers encryption at rest, which allows data stored on disk to be encrypted. This feature ensures that even if someone gains physical access to the database files, they cannot access the data without the decryption key. PostgreSQL utilizes various encryption techniques, such as AES (Advanced Encryption Standard), to implement this security measure effectively. This safeguard provides an additional layer of protection, bolstering data security and confidentiality within the database system.

## Key Management
Secure key management is necessary for effective encryption. By connecting with other key management systems or using built-in procedures, PostgreSQL offers alternatives for maintaining encryption keys. As a result, security is improved because encryption keys are held apart from encrypted data.
Day 4 of writing code
Published: 2023-08-06 11:50:47

The registration form challenge is complete!

These challenges are getting lengthier and more difficult by the minute lol
The challenge incorporated new elements, attributes and properties in CSS.

A little tip when starting a new html/css document. Always remember to that in each CSS document to reference my style sheet to my HTML document.

<link rel="stylesheet" href="styles.css">

In summary I have highlighted a few steps included in creating the form:

Add a form element in order to action a form-data
The method attribute specifies how to send form-data to the URL specified in the action attribute. 

To create form-like lines, we add the fieldset element 
In order to name each fieldset, we have to add label elements and add the desired text. 
As label elements are inline by default, they are all displayed side by side on the same line, making their text hard to read. To make them appear on separate lines, add display: block to the label element, and add a margin of 0.5rem 0, to separate them from each other.

To create black boxes within the form we should add an input element within our label element.
We should use the `for` and `id` attributes to connect the label and input elements. E.g
<label for="first-name">Enter Your First Name: <input id="first-name" /></label>

For accessibility, best practices link the input elements and label elements by adding ids 
`For` attributes will be added to the label
`id` attributes will be added to the input

I have noticed that I haven’t gotten accustomed to memorising the different properties E.g to align text I must write `text-align` instead of just `text`. It is going to take a lot of practice before I grow comfortable remembering these little things. In order to facilitate the memory of these properties I will add them to a document list and test myself.

Overall, I have learned how to create a fully functioning interactive form with answer boxes and submit buttons.

If you are also taking the freecode camp challenges let me know your thoughts and what have you learnt so far.
How you properly test your React hook methods
Tags: react, hooks, testing
Published: 2023-08-06 11:55:12

---
title: How you properly test your React hook methods
published: true
date: 2023-08-06 11:19:11 UTC
tags: react,hooks,testing
canonical_url: https://krzysztofzuraw.com/blog/2023/test-react-hooks-methods/
---

If you are using [React Hooks testing library](https://react-hooks-testing-library.com) to test your hooks remember to wrap hooks methods in the [`act`](https://react-hooks-testing-library.com/reference/api#act).

For example, if you try to run the test below:

```tsx
import { renderHook } from "@testing-library/react-hooks";

test("test login", () => {
  const { result } = renderHook(() => useAuth());

  result.login();

  expect(result.user).toEqual({ token: "token", user: "Tom Smith" });
});
```

You will get this error message:

```
Warning: An update to TestComponent inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
    at TestComponent ()
    at Suspense
    at ErrorBoundary ()
```

To fix this you need to wrap the `result.login` call with the `act`:

```diff
-import { renderHook } from "@testing-library/react-hooks";
+import { renderHook, act } from "@testing-library/react-hooks";

test("test login", () => {
  const { result } = renderHook(() => useAuth());

- result.login();
+ act(() => {
+     result.login();
+ });

  expect(result.user).toEqual({ token: "token", user: "Tom Smith" });
});
```
Efficient Data Generation in Laravel: Leveraging JSON Files && Laravel Factory for Your Database
Tags: webdev, beginners, tutorial, laravel
Published: 2023-08-06 11:16:00

Hello! Generating dummy or fake data for testing purposes is a common need in software development, and Laravel provides several ways to achieve this. Let's explore some of the methods commonly used in Laravel to generate test data:
1. Using a JSON file to store dummy data, you can follow these steps:
- Create a folder named "data" inside the "database" folder of your Laravel project.

Inside the "data" folder, create a file named "category.json" and add the following JSON data to it:

```
[
    {
        "id": 1,
        "name": "Electronics"
    },
    {
        "id": 2,
        "name": "Clothing"
    },
    {
        "id": 3,
        "name": "Books"
    }
]

```

This JSON data represents a list of categories with their respective IDs and names.

Next, you can read the JSON data from the file and use it in your Laravel application. For example, you can use the DatabaseSeeder.php

```
<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        //get the data
        $data = File::get('database/data/category.json');
        //convert to array, of the asscociative kind
        $categories= collect(json_decode($data, true));
        $categories->each(function($category){
            DB::table('category')->insert([
                'category_name'=>$category['name'],
                'category_id'=>$category['id']
            ]);
        });
    }
}

```

2. Using faker
Laravel comes with the Faker library by default, which allows you to create fake data like names, addresses, emails, and more.

- create a factory for a post modal

`php artisan make:factory PostFactory`

- In the PostFactory

```
class PostFactory extends Factory
{
 public function definition(): array
    {
        $title = fake()->unique()->sentence();
        $slug = Str::slug($title);
        return [
            'title'=>$title,
            'slug'=>$slug,
            'description'=>fake()->paragraph(9, true),
            'category'=>Category::inRandomOrder()->value('category_id'),
        ];
    }
}
```


Now, in the DatabaseSeeder.php,

```
class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        //create 20 rows in the table
        Post::factory()->count(20)->create();
    }
}
```

Now, what if we want a relationship to build as well for the post. For instance, where an author has many posts, and we want a fake data for that as well??
Next.js, Tailwind CSS and Shadcn-ui template
Tags: nextjs, tailwindcss, react, webdev
Published: 2023-08-06 11:15:42

In my previous [post](https://dev.to/hunchodotdev/nextjs-boilerplate-24bh), I introduced **Kaminari**, a Next.js and Tailwind CSS template. 

I have since updated it to use shadcn-ui and now has **dark mode**. 

Here are a few demo images:

![Kaminari light mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dsi067ng54f1c9p8vxuy.png)


![Kaminari dark mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mwdnppwf2q5oo6anlag3.png)

It is configured with:

- Next.js 13 (with the new `app` directory 🤯)
- Tailwind CSS 3 ✨
- shadcn-ui
- Dark mode 🌒
- TypeScript 👍
- Prettier 🦋
- Eslint 👌
 
Make sure to check out the below links and drop a star if you do not mind!

[GitHub Repo](https://github.com/lucky-chap/kaminari)
[Live Demo](https://kaminari.vercel.app)
Bash Completion for kubectl
Tags: bash, ubuntu, completion
Published: 2023-08-06 11:00:00



## Introduction
Bash is an `sh-compatible` command language interpreter that executes commands read from the standard input or from a file. 
Bash can run most shell scripts without modification. 

`bash-completion` is a collection of shell functions that take advantage of the programmable completion feature of bash on Ubuntu Linux.

**How to add bash auto completion in Ubuntu Linux**
The procedure is as follows to add `bash completion` in `Ubuntu`:

Open the terminal 
Refresh package database on `Ubuntu` by running:

```
sudo apt update
```
Get info about the `bash-completion` package:

```
apt info bash-completion
```
Install `bash-completion` package on `Ubuntu` by running:

```
sudo apt install bash-completion
```
Log out and log in to verify that `bash auto completion` in `Ubuntu Linux` working properly.


**How to test programmable completion for Bash**
Installer placed a shell script called `/etc/profile.d/bash_completion.sh`. 
You can view it with help of cat command:

```
cat /etc/profile.d/bash_completion.sh
```

You can add `/etc/profile.d/bash_completion.sh` to your `~/.bashrc` file as follows:

```
## source it from ~/.bashrc or ~/.bash_profile ##
echo "source /etc/profile.d/bash_completion.sh" >> ~/.bashrc
 
## Another example Check and load it from ~/.bashrc or ~/.bash_profile ##
grep -wq '^source /etc/profile.d/bash_completion.sh' ~/.bashrc || echo 'source /etc/profile.d/bash_completion.sh'>>~/.bashrc
```

I will recommend after reading this post read the bash man page using the `man` command or `help` command:

```
man bash
help complete
```

## Enable Kubectl Bash Completion

The bash completion script of kubectl can be generated with the following command:

```
kubectl completion bash
```

The first way can be achieved through the adding `~/.bashrc`:
Type the command in your command line tool, reload the bash shell and you are done.

```
echo ‘source <(kubectl completion bash)’ >>~/.bashrc
```

![First - User way](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mmqx2753u625b01c8y8v.png)

The second way is to adding access the system
In this mode, type command in your terminal

```
kubectl completion bash | sudo tee /etc/bash_completion.d /kubectl > /dev/null
```

![Second System way](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/blqvxdchkje1cacr4pow.png)


Good Luck
🔁 Importance of "continue" in Solving String Reversal with Vowels 🔁
Tags: java, python, javascript, programming
Published: 2023-08-06 10:43:49

In this post, I'll demonstrate how the "continue" keyword in Java can greatly simplify and optimize the process of reversing only the vowels in a given string. Let's dive into the solution and see how this powerful keyword enhances the efficiency of the code.

Given a string `s`, we need to reverse only the vowels ('a', 'e', 'i', 'o', 'u'), regardless of their case, while leaving the non-vowel characters in their original positions.

Example 1:
Input: "hello"
Output: "holle"

Example 2:
Input: "leetcode"
Output: "leotcede"

🔍 The Problem:
```java
public static String reverseVowels(String s) {
    StringBuilder sbs = new StringBuilder(s);
    String vowels = "aeiou";
    int leftPointer = 0;
    int rightPointer = sbs.length()-1;
    while (leftPointer < rightPointer) {
        if (!vowels.contains(Character.toString(sbs.charAt(leftPointer)).toLowerCase())) {
            leftPointer++;
            continue; // Skip to the next iteration if not a vowel
        }
        if (!vowels.contains(Character.toString(sbs.charAt(rightPointer)).toLowerCase())) {
            rightPointer--;
            continue; // Skip to the next iteration if not a vowel
        }
        // Swap the vowels found at leftPointer and rightPointer
        Character rightCharacter = sbs.charAt(rightPointer);
        Character leftCharacter = sbs.charAt(leftPointer);
        sbs.setCharAt(leftPointer++, rightCharacter);
        sbs.setCharAt(rightPointer--, leftCharacter);
    }
    return sbs.toString();
}
```

🚀 The Solution:
In the above code, we use `two pointers`, `leftPointer` and `rightPointer`, to traverse the string from the start and end simultaneously. Whenever we encounter a non-vowel character, we skip to the next iteration using the "continue" keyword. This means that if a vowel is not found at a particular position, the pointers will advance to the next position without performing any unnecessary operations.

💡 Key Takeaways:
1. **Efficient Pointer Movement**: By utilizing "continue", we ensure that the pointers move swiftly and only focus on vowels, without repeatedly processing non-vowel characters.

2. **Improved Time Complexity**: The efficient movement of pointers leads to a reduction in the overall time complexity of the algorithm, making it faster and more optimal.

3. **Simplified Logic**: The "continue" statement simplifies the code logic by eliminating the need for nested conditionals and flag variables, resulting in cleaner and more readable code.

So, the next time you're dealing with scenarios where you need to skip certain elements while traversing a data structure, remember the power of "continue" and how it can significantly enhance your code's performance and maintainability. Happy coding! 🚀
Open Source Contribution
Published: 2023-08-06 10:43:02

- Open Source lies the spirit of collaboration. Developers from diverse backgrounds come together to contribute their expertise, exchange ideas, and work towards common goals.

- The heart and soul of Open Source lies within its vibrant community. Developers, users, and enthusiasts come together in forums, conferences, and online platforms to share ideas and celebrate their achievements.

## why Contribute to Open Source?

> - Make a Positive Impact
> - Collaborate with a Global Community
> - Enhance Your Portfolio
> - Strengthen the Ecosystem

## How to Contribute?
You can make both Code and non-code contributions based on your field of interest

_**Code Contribution**_

You can take various approaches while making a code contribution.

1. _**Issues**_

    a. find/verify bugs
    b. suggest ideas

2. _**Changes via PRs**_

    a. fix bugs
    b. refactor code
    c. create features

3. _**Reviewing Pull Requests**_

    a. test changes
    b. make suggestions

_**Non-code contributions**_

Code is a very small part of Open Source, You can contribute to:

   1. make suggestions
   2. make tutorials for beginners
   3. Spread awareness
   4. answer questions in the community
   5. Designing the User Interface
   6. Translating the language of the documentation


## Conclusion:
Open Source is not limited to Code and non-code, You can start anytime and the best time is now.

## See You Guys Next Time, Keep Building......
GitHub Contributors JavaScript Library Documentation
Tags: githubapi, simple, html, extensions
Published: 2023-08-06 10:17:01


The GitHub Contributors JavaScript library provides an easy way to display a list of contributors for a GitHub repository on your website. The library offers various display modes, including grid, slideshow, and list. This document will guide you through the usage and features of the library.

Getting Started
To get started, you need to include the GitHub Contributors library in your HTML document. You can import the library using the following script tag:


```html
<script src="https://bashamega.github.io/scripts/cdn/libs/js/contributingjs/index.js"></script>
```
Usage
The GitHub Contributors library requires a container element in your HTML to display the contributors. You can use the following code as a template:


```html
<div id="contributors" data-githuburl="https://github.com/username/repo" data-type="grid" data-imgprofile="true" data-link="true"></div>

<script src="https://bashamega.github.io/scripts/cdn/libs/js/contributingjs/index.js"></script>
```
Replace "https://github.com/username/repo" with the URL of the GitHub repository you want to fetch contributors from. The attributes data-type, data-imgprofile, and data-link control the display and behavior of the contributors' list.

JavaScript API
The GitHub Contributors library offers a JavaScript API that allows you to programmatically fetch and use contributor data. You can use the following function to fetch contributor data:

```javascript

const contributors = GITHUBFETCH("https://github.com/username/repo");
Replace "https://github.com/username/repo" with the URL of the GitHub repository.
```

Display Modes
## Grid Mode
Grid mode displays contributors' avatars and usernames in a grid layout. Each contributor container is clickable and opens the contributor's GitHub profile in a new tab.

## Slideshow Mode
Slideshow mode presents contributors' avatars and usernames in a slideshow format. The slideshow automatically transitions between contributors at a defined interval. Navigation dots allow manual selection of contributors.

## List Mode
List mode shows contributors' avatars and usernames in a vertical list. Each contributor container is clickable and opens the contributor's GitHub profile in a new tab.


## Error Handling
The library incorporates error handling to display an error message in case of issues with fetching or displaying contributors' data.

## Conclusion
The GitHub Contributors JavaScript library simplifies the process of fetching and displaying contributors' data from GitHub repositories. It offers multiple display modes and customization options, making it easy to integrate contributors' information into your website. Just remember to include the library script and configure the container element attributes according to your needs.
Type Safety Made Easy for Beginners: How to Effortlessly Achieve It with tRPC
Tags: typescript, webdev, trpc, tutorial
Published: 2023-08-06 09:48:57


---
title: "Type Safety Made Easy for Beginners: How to Effortlessly Achieve It with tRPC"
published: true
description: "A step-by-step guide to using tRPC and TypeScript for creating type-safe APIs. Perfect for beginners looking to enhance their web development skills."
tags: ["typescript", "webdev", "trpc", "tutorial"]
---


## Table of Contents
1. [Introduction](#introduction)
2. [What Is tRPC?](#what-is-trpc)
3. [Strengths of Combining TypeScript and tRPC](#strengths-of-combining-typescript-and-trpc)
4. [A Basic Use Case for tRPC](#a-basic-use-case-for-trpc)
5. [Real Code Examples](#real-code-examples)
6. [Conclusion](#conclusion)

## Introduction
Type safety in API development is a crucial aspect. By combining tRPC with TypeScript, even beginners can easily create type-safe APIs. This post will guide you through the basics of tRPC to real code examples.

## What Is tRPC?
tRPC is a tool for sharing type information between the server and client. In this section, we’ll cover an overview and the benefits of tRPC.

### Type Safety
It detects type errors at compile time, reducing runtime errors.

### Strengths of Combining TypeScript and tRPC
Pairing TypeScript with tRPC makes it even more powerful. In this section, we’ll explore the reasons and advantages of this combination.

### A Basic Use Case for tRPC
Here, we will explain a common use case of collecting visitor information on a website using tRPC as an example.

### Real Code Examples

### Server-Side Code

```typescript
import { createTRPCRouter } from '@trpc/server';

const router = createTRPCRouter()
  .query('getUser', {
    resolve() {
      return { id: 1, name: 'Bilbo' };
    },
  });

// Example of integration with Express
import express from 'express';
import { inferAsyncReturnType } from '@trpc/server';
import { z } from 'zod';

type Context = inferAsyncReturnType<typeof createContext>;

const createContext = async ({ req, res }: express.Request) => ({ req, res });
const app = express();
app.use('/trpc', trpcExpress.createExpressMiddleware({ router, createContext }));
```

### Client-Side Code

```typescript
import { createTRPCClient } from '@trpc/client';

const trpc = createTRPCClient({
  url: '/trpc',
});

// Example of using the getUser query
const user = await trpc.query('getUser');
console.log(user.id, user.name); // 1, 'Bilbo'
```

### Conclusion
tRPC is a powerful tool that even beginners can use to effortlessly achieve type-safe API development. Through this article, you’ve learned the basics of tRPC and understood how to apply it in real projects.

Feel free to try tRPC in your projects and experience its robust type safety features!