teleren/devto huggingface dataset:
How to setup Prisma with your local PostgreSQL
Published: 2023-07-12 05:40:46

This is my memo when I tried t3 app with PostgreSQL for the first time.

Pre-requirements: install postgresql
OS: macOS

 1. psql postgres to enter postgres

 2. Create an user with `CREATEDB` permission: `CREATE ROLE <username> WITH LOGIN PASSWORD '<password>' CREATEDB;`

 3. go to your app’s root folder

 4. make sure the provide is ‘postgresql’ at prisma/prisma.schema
```
    datasource db {
        provider = "postgresql"
        url      = env("DATABASE_URL")
    }
```
5. Database url has the following structure: postgresql://username:password@localhost:5432/database-name 
⚠️ If you don’t use the default port number, replace from 5432 to yours.

6. `npx prisma migrate dev --name initial`

Special thanks: [https://www.codementor.io/@engineerapart/getting-started-with-postgresql-on-mac-osx-are8jcopb](https://www.codementor.io/@engineerapart/getting-started-with-postgresql-on-mac-osx-are8jcopb)
Microsoft provides training on Microsoft Azure Fundamentals: Understanding Cloud Concepts
Published: 2023-07-12 05:24:33


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


This learning path helps you prepare for Exam AZ-900: [Microsoft Azure](https://learn.microsoft.com/) Fundamentals.

This publication aims to call on young student programmers to visit [Microsoft Learn](https://learn.microsoft.com/) in order to take advantage of the opportunity offered by Microsoft to learn several technologies and acquire a solid foundation to advance in our career as programmers.
Prerequisites
Basic knowledge of IT terms and concepts

A. **Describe cloud computing**
This module introduces cloud computing. It covers things like cloud concepts, deployment models, and understanding shared responsibility in the cloud.
Learning objectives
Upon completion of this module, you will be able to:
Define cloud computing.
Describe the shared responsibility model.
Define cloud models, including public, private, and hybrid.
Identify appropriate use cases for each cloud model.
Describe the consumption-based model.
Compare cloud pricing models.
Want to learn more?
Click on [Microsoft Learn](https://learn.microsoft.com/) and if there are any questions, feel free to leave a comment.
ActionAI: Call local functions using OpenAI function calling
Tags: openai, chatgpt, python
Published: 2023-07-12 05:24:06

ActionAI is a small wrapper around Openai's function calling. It works by auto-generating json schemas for your Python functions.

## Repo 

{% embed https://github.com/amalshaji/actionai %}

## Usage

Install the package,

```bash
pip install actionai
```

Now define a new function,

```python
def get_current_weather(location: str, unit: str = "fahrenheit"):
    """Function to get current weather for the given location"""
    weather_info = {
        "location": location,
        "temperature": "72",
        "unit": unit,
        "forecast": ["sunny", "windy"],
    }
    return weather_info
```

Function parameters must be typed and must have a docstring. The docstring is used as the function description for openai, and typed parameters are used for autogenerating json schema(using [pydantic](https://pydantic.dev))

Now, register your functions and start asking questions

```python
import actionai

action = actionai.ActionAI()
action.register(get_current_weather)

response = action.prompt("What is the current weather in the north pole?")

print(response["choices"][0]["message"]["content"])
# The current weather at the North Pole is 72°F. It is sunny and windy.
```

The chat completion API will decide if a function call must be made for the query and send it in response. ActionAI calls the function and returns the response to the model, which completes the conversation. 

### Adding context

Sometimes, you don't want to populate certain parameters yourself(via the program). You can make use of context here. 

```python
def list_todos(user: str):
    """Function to list all todos"""
    return todos[user]

action = actionai.ActionAI(context={"user": "jason"})
```

The context variables are skipped when creating json schema, and the values are inserted when calling the function. 

## Demo

Demo running the [todo example](https://github.com/amalshaji/actionai/blob/main/examples/todo.py)

[Demo](https://raw.githubusercontent.com/amalshaji/actionai/main/examples/demo.svg)
Using ClamAV with .Net Core
Published: 2023-07-12 05:04:54

**Introduction**:
In this article, we'll explore how to scan files for viruses using the ClamAV REST API in a .NET Core application. We'll leverage Docker to run the ClamAV service and utilize the System.Net.Http.HttpClient library for making HTTP requests.

**Prerequisites**:
Before getting started, ensure the following requirements are met:

Dotnet Core is installed on your machine.
Docker Desktop or Docker Engine is installed and running.
Pull the ClamAV REST API Docker image by following the instructions in the [clamav-rest GitHub repository](https://github.com/ajilach/clamav-rest).

**FileModel Class**:
To represent the file we want to scan, we'll create a FileModel class with the following properties:

```
public class FileModel
 {
     public string FileName { get; set; }
     public byte[] FileBytes { get; set; }
     public string FileContentType { get; set; }
 }
```

1. **Sending the File for Scanning:**
To send a file for scanning, follow these steps:

Get the file you want to scan as a byte array. You can use the File.ReadAllBytes method to read the file contents.

```
FileModel fileModel = new FileModel
{
    FileName = "example.txt",
    FileBytes = File.ReadAllBytes("path/to/file"),
    FileContentType = "text/plain"
};
```

2. **Create a ByteArrayContent using the file bytes:**

```
var contentByte = new ByteArrayContent(fileModel.FileBytes);

```

3. **Create a `MultipartFormDataContent` and add the ByteArrayContent to it:**

```
var multiContent = new MultipartFormDataContent
{
    { contentByte, "file", fileModel.FileName }
};
```

Sending the Request:
Once we have the file prepared, we can send a request to the ClamAV scanner using the `HttpClient` class:

```
using (var httpClient = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        var fileContent = new ByteArrayContent(fileModel.FileBytes);
        content.Add(fileContent, "file", fileModel.FileName);

        var response = httpClient.PostAsync("http://localhost:9000/scan", content).Result;
        if (response.IsSuccessStatusCode)
        {
            var responseContent = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(responseContent);
        }
        else
        {
            Console.WriteLine("File request did not complete: " + response.StatusCode);
        }
    }
}
```

**Conclusion**:
In this article, we've covered the process of scanning files using the ClamAV REST API in a .NET Core application. By leveraging Docker to run the ClamAV service and utilizing the `HttpClient` library, we can easily integrate virus scanning capabilities into our applications.

Remember to handle exceptions and implement error handling according to your application's requirements. This will ensure a robust and reliable file scanning process.
Javascript Polyfill Array.shuffle #6
Tags: javascript, programming, tutorial, polyfill
Published: 2023-07-12 04:35:29

**This problem was asked by Tencent.**

## How would you implement a shuffle() ?

Shuffle the array, it may be [1, 3, 2, 4], but it should modify the array inline to generate a randomly picked permutation at the same probability.

**Example**

```
[1, 2, 3, 4].shuffle()
```

**Solution**

```

if (!Array.prototype.shuffle) {
  Array.prototype.shuffle = function shuffle() {
    let i = this.length - 1;
    while (i) {
      const j = Math.floor(Math.random() * (i + 1));
      [this[i], this[j]] = [this[j], this[i]];
      i--;
    }
    return this;
  };
}

```

This works by:

- Checking if Array.prototype.shuffle() already exists
- If not, adding a shuffle() method to the Array prototype
- The shuffle() method:
- Loops from the array length down to 0
- Picks a random index between 0 and i
- Swaps the current element (i) with the random element (j)
- This shuffling procedure is performed in place on the array
- The shuffled array is returned

**This polyfill implements a simple shuffle algorithm to randomly rearrange the elements of an array.**
Torrent problem
Tags: torrent
Published: 2023-07-12 04:34:27

guys who used torrent in South Korea. cause mine is so slow. what can I do to improve its speed. pls guys help me.

парни, которые использовали торрент в Южной Корее. Потому что мой такой медленный. что я могу сделать, чтобы улучшить его скорость. Пожалуйста, ребята, помогите мне.
Australian State of Origin Rugby 2023 Live
Published: 2023-07-12 04:00:54

Australian State of Origin 2023 live
New South Wales vs Queensland Live 
📺GO LIVE➡@streamsrugbytv
📺GO LIVE➡@streamsrugbytv

#Rugby 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2sfxpx0jcthrep4avk4l.png)
Local Storage
Published: 2023-07-12 03:56:45

## The blog is about how to used local storage?
Initially  I don't have any idea about  how local storage work? how to use local storage? Then Onkar dada  told me to read MDN of local storage.I read it and also watched one video on youtube.
        
## About Local Storage.
Local storage is one of the web storage API in which data is store in the form of key value pairs or we can say it is object of strings.In local storage we can store minimum 10MB data but it is not fixed varying with different different browsers.The key point about local storage is- data is still present in local storage even if user close the window or restart the browser or even shut down the system.Means user can store data in local storage as long as user wants.
With the help of following methods we can perform operations on local storage.

**setItem**-This is function which take two parameters one is key and another is value.This function  will add key value pairs in local storage or update key's value if key already exists.
Ex.`localStorage.setItem("name","harry");`

**getItem**-With the help of getItem function we can fetch key's value by passing key to the function.If key is not present in local storage then it will return null.
Ex.`localStorage.getItem("name");`

**removeItem**-This function takes parameter as key if key is exists then it will remove key along with value.
Ex.`localStorage.removeItem("name");`
 
**clear**-This function is used to remove all key value pairs from local storage.
Ex.`localStorage.clear();`

---
After understanding all above concepts then I started with assignment which was based on local storage.
I used two components.First is about to store the key value pair in localStorage and second is about to access key's value from local storage and import both components in main App component.

In first components I added two inputs and one button.
First input is for key and another is for value and used onChange events on each input.
when user enter key and value then state will get updated.
And onclick of button key value pairs will store in local storage.
display one alert msg here I used toastify which makes alert message attractive and also looks nice.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yr4fm6uyl05fn9oqol1q.png)
In second component I used one input and one button.
Input is for key. Here also used onChange event to update state when use enter key.Onclick of button display one alert msg of key's value if key exist in local storage else show alert of 'Please enter valid key'.

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

At the end I used one icon which is for to clear local storage.
onClick of icon display alert msg of 'local storage cleared...'

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rvoelwm5aiziwbmx7bbh.png) 
[Live link](https://codesandbox.io/s/local-storage-3tgm69?file=/src/components/SaveToLocalStorage.jsx)
Gum code
Tags: cssadventures, gumcodeconfusion, oops, codinggonewrong
Published: 2023-07-12 03:54:53

Just when I thought my CSS was a gum code disaster, it surprisingly worked like a charm! 🎉 But my attempts to fix it using the code interpreter resulted in an even stickier mess of gum code. Back to the drawing board! 😅
TIL how to use CodeSpaces
Tags: github, virtualmachine, webdev, beginners
Published: 2023-07-12 03:52:43

I have grown quite accustomed to having spend a significant amount of time setting up a machine for each new coding environment.  And yet, no matter how many times I do it, I always seem to run into at least one difficulty that takes a while to debug, every time!

And then, of course, there's also the matter of deploying all of the different small projects I create.  Again, a frequent source of frustration!

Today, as part of the pre-apprentice Tech Prep programmed offered by Discovery Partners Institute, I learned how to use GitHub CodeSpaces and Pages.  Both of these are valuable tools to hit the ground running when learning a new language! 

I am excited to see what else I learn as part of this program.
04 - Foreign Data Wrappers
Tags: beginners, tutorial, programming, apacheage
Published: 2023-07-12 03:39:18

## Foreign Data Wrappers

The PostgreSQL addition known as Foreign Data Wrappers (FDWs) enables the database to communicate with external data sources as if they were standard PostgreSQL tables. FDWs offer a way to access and query information held in distant databases or other non-database sources, such files, online services, or other DMSs.

An external data source can be connected to and tables or views that reflect the remote data defined when a Foreign Data Wrapper is installed and configured in PostgreSQL. Regular SQL commands may be used to query, join with local tables, and alter these virtual tables, which are referred to as foreign tables.

## FDWs Crucial role in query processing

When using remote data sources, Foreign Data Wrappers (FDWs) are essential to PostgreSQL query processing. 

![Images-of-images](https://res.cloudinary.com/practicaldev/image/fetch/s--JdFZobuv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oyjw0qaatc01b3v49jph.png)
How FDWs affect query processing is as follows:

**Query Planning:** The PostgreSQL query optimizer examines the query and creates an execution plan during query planning. While FDWs are present, the optimizer takes their capabilities and statistics into account while choosing the most effective plan.

**Query Execution:** To get the required data from the remote source while running a query using FDWs, the PostgreSQL execution engine communicates with the FDW. The FDW manages communication with the outside system and gives the execution engine the necessary data.

**Data Retrieval:** The FDW translates the activities that should be performed on the remote data source based on the query that was executed against the foreign table. In order to process the necessary data, it transmits it to the PostgreSQL execution engine.

**Parallel Query Execution:** PostgreSQL allows for the parallel execution of queries, and FDWs may use this feature when appropriate. In order to speed up data retrieval, PostgreSQL can split the query burden among many processes if the FDW and the remote data source enable parallel execution.

**Data Integration and Joins:** FDWs make it possible to seamlessly combine local PostgreSQL data with distant data. The query optimizer can make join operations between foreign tables and local tables more efficient by using the FDW's cost estimation and available information.

## Closing Remarks

FDWs offer an expandable and adaptable method for incorporating external data sources into PostgreSQL's query processing. FDWs offer effective query planning and execution by utilizing statistics, join capabilities, and pushdown optimization. This allows for easy access to remote data while maximizing speed.
03 - Query Processing
Tags: programming, beginners, tutorial, apacheage
Published: 2023-07-12 03:28:21

## What is Query processing?

In PostgreSQL, the set of operations carried out by the database engine to carry out a SQL query and deliver the appropriate results is referred to as query processing. It involves a number of steps, such as query execution, query optimization, and query parsing.

**Query Parsing**: The SQL query must first be parsed and its syntax checked. The query's structure is examined by the parser to make sure it complies with the standards of the SQL language. The parser will issue an error and stop processing the query if there are any syntax mistakes.

**Query Rewriting:** The next phase is query rewriting after the query has been correctly processed. The query is subject to a number of changes by PostgreSQL to make it simpler and more effective. This entails enlarging views, resolving aliases, and simplifying difficult statements.

**Query Optimization:** PostgreSQL's query optimizer examines the rewritten query, creates an execution plan, and executes the plan. In an effort to reduce the total execution cost, the optimizer compares several methods for accessing the data, joining tables, and applying filters. It employs a variety of methods to calculate the cost of alternative execution strategies while taking data distribution statistics into account.

**Execution Plan Generation:** PostgreSQL produces an execution plan based on the optimizer's analysis. The query's execution is outlined in the execution plan in great detail, step by step. The sequence in which tables are accessed, join strategies, and any extra actions like sorting or aggregation are all specified.

**Query Execution:** The actual execution of the query in accordance with the produced execution plan is the last stage. The execution engine receives data from the disk, does any required actions, such as filtering or sorting, and then provides the user or program with the result set.

## Closing Remarks

PostgreSQL uses a number of techniques and algorithms to improve query processing, including the use of indexes, caching, and parallel processing. The objective is to efficiently provide query results while reducing resource utilization and response time.

It's important to note that PostgreSQL's query processing is an intricate and flexible process. Administrators can fine-tune the execution plans for certain workloads or queries by using the configuration settings and tuning tools the database offers.
AWS Glue in Terraform
Tags: terraform, awsglue, etl, python
Published: 2023-07-12 03:11:20

Hey all!

in this post I would like to go over an implementation of module in Terraform.

**AWS Glue** is a full ETL or ELT service, which provides connection to/from various sources. For example, MySQL to S3. And while you create a connection between these two you can add any transformations you want. This can be using code or no-code approach. The best thing is that Glue is a full-blown service which makes the development easy with Glue Notebook, where you can directly test your job.

I had hard time finding in Terraform the right module which combines creating an AWS Crawler, AWS Glue catalog as well as AWS Glue Job.
This example creates all these in one single block. Use case can be simple leading files from CSV processing it, and publishing to DB for other tables.

In order to use a terraform module simply initialize this GitHub Repo: [aws-terraform-glue-db-crawler](https://github.com/Luk3rson/aws-terraform-glue-db-crawler)

```
module "glue" {
  source                = "github.com/Luk3rson/aws-terraform-glue-db-crawler"
  create                = terraform.workspace == "dev" ? true : false
  glue_database_name    = "call-statistics"
  name_prefix           = "main-application-name"
  job_name              = "first-job"
  s3_target_bucket_name = "et-test-bucket"
  s3_database_location  = "${local.s3_database_location}/${local.glue_database_name}/${local.glue_table}"
  target_path           = "data/csv-table"
  glue_script_path      = "etl_scripts/etl-csv-to-dynamoDB.py"
  kms_key               = "1234abcd-12ab-34cd-56ef-1234567890ab"

  # Job
  worker_type           = "G.1X"
  number_of_workers     = "2"
  glue_version          = "3.0"
  execution_class       = "FLEX"
  default_arguments = {
    "--TempDir"             = "s3://etl-test-bucket/temp_dir/"
    "--class"               = "GlueApp"
    "--encryption-type"     = "sse-s3"
    "--job-language"        = "python"
    "--job-bookmark-option" = "job-bookmark-enable"
  }
}
```

Hope this module is helpful and it will speed up your work pushing development work to production!
How to Create Component Library Like Material UI or Mantine UI?
Tags: library, component, mantine, materialui
Published: 2023-07-12 02:08:40

Creating a robust and reusable component library is a fundamental aspect of modern web development. If you've ever wondered how to develop component libraries like Material UI or Mantine UI from scratch, you're in the right place. In this article, we will delve into the essential steps for creating your own component library. So, let's embark on this journey!

<a id="1"></a>
## 📜 Table of Content
- [📜 Table of Content](#1)
- [🛠️ Techs & Pre-Knowledge](#2)
- [🔭 Project Description](#3)
- [👟 Init NPM Project](#4)
- [⚙️ Configure Typescript](#5)
- [🧱 Create Components](#6)
- [⛑️ Build](#7)

---

<a id="2"></a>
## 🛠️ Techs & Pre-Knowledge

In this tutorial, we will be utilizing the following technologies:

- React.js
- TypeScript
- NPM
- esbuild
- Storybook
- GitHub

Throughout this tutorial, we assume that you already possess a basic understanding of the following concepts. If you are unfamiliar with any of them, please refer to articles covering the topics below:

- Basic React.js
- Basic TypeScript
- Basic GitHub
- Basic NPM

---

<a id="3"></a>
## 🔭 Project Description

So, in this project, we will create a component library called `cool-components` that includes customizable components. To keep things simple, we will focus on creating just one component: the Button! Users will be able to adjust the color, variant, and size of the Button. Curious about how? Let's dive in!

Note: If you would like to see the final result of this project, please visit the following link.

---

<a id="4"></a>
## 👟 Init NPM Project

<a id="5"></a>
## ⚙️ Configure Typescript

<a id="6"></a>
## 🧱 Create Components

<a id="7"></a>
## ⛑️ Build

<a id="8"></a>
## 🚀 Publish into NPM

<a id="9"></a>
## 🤖 (Optional) Automate Publish Using Github

<a id="10"></a>
## 📚 (Optional) Add StoryBook
Writing a contract when the work is already done?
Tags: freelance, webdev, discuss, help
Published: 2023-07-12 02:06:16

I suppose this is a bit of a weird question, but I couldn't find anything pertaining to my situation.

My wife works for a preschool and childcare, and she was put in charge of scheduling for the staff. In order to do that, she had to calculate the teacher-student ratio (it differs depending on a child's age) for each classroom. I was horrified to learn that this was all done with pencil and paper, so I wrote a web app to assist with this.

When the web app was complete -- and my wife had been using it for several weeks -- she presented it to the director of the facility. The director was impressed with it, and (some weeks later) had me attend a staff meeting to present it in proper form to the entire staff.

Now that the app is done, and has not been in need of any debugging or any kind of maintenance, really, the director informed my wife that she wants to pay me for the work. I certainly didn't keep track of the number of hours I put into it; it was a labor of love, literally: I love my wife and saw a way in which I could make her job a little less stressful. I can guess, but a guess is all it would be.

So as to my question. I have found plenty of templates for web development service agreements, but how do I write one when the work has already been done?