teleren/devto huggingface dataset:
My First AWS EC2 Project: Hosting a Static Website
Published: 2024-07-13 16:17:13

Are you looking to break into cloud computing? Let me share my recent experience setting up a static website on Amazon Web Services (AWS) using an EC2 instance. This project was a great introduction to cloud infrastructure and helped me gain hands-on experience with AWS.

Getting Started with EC2

First, I logged into the AWS console and searched for EC2. After navigating to the Instances section, I clicked "Create Instance." For this project, I chose a Linux server with a t3.micro instance type—perfect for learning as it's part of the AWS Free Tier.

Setting Up the Instance

Once my instance was running, I clicked on the instance ID to access its information page. The next step was connecting to the instance via SSH. I used Git Bash, ensuring I was in the same directory as my downloaded key pair (.pem) file.

To connect, I ran these commands:
```
chmod 400 keyparfilename.pem
ssh -i keyparfilename.pem ubuntu@ec2-public-IP-address.AWSareaID.compute.amazonaws.com
```

Installing Necessary Software

After successfully connecting, I switched to root access with `sudo su -`. Then, I installed and started Nginx:

```
apt install nginx -y
systemctl start nginx
systemctl enable nginx
```

I also installed unzip to help with unpacking the website files:

```
apt install unzip
```

Deploying the Website

Next, I downloaded and unzipped the website files:

```
curl "name-of-zipped-file" -o "preferred-file-name.zip"
unzip preferred-file-name.zip
```

Finally, I copied all the files to the Nginx web directory:

```
cp -r * /var/www/html/
```

Viewing the Result

With everything set up, I copied the public IP address from the AWS console and pasted it into a web browser. Voila! My website was live.

Challenges and Learnings

While the process seems straightforward now, I encountered a few hiccups along the way. Understanding the EC2 dashboard took some time, and I initially struggled with SSH connections. However, careful reading of AWS documentation, Youtube videos, our slack channel and some troubleshooting helped me overcome these obstacles.

This project taught me valuable lessons about cloud infrastructure, Linux command line, and web servers. It's amazing to see how quickly you can deploy a website using cloud services!

If you're looking to start your cloud computing journey, I highly recommend trying out a similar project. It's a great way to get hands-on experience and build your confidence in working with AWS.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ztacp51z78fy8zyk9mip.png)
Screenshot of the Hosted Website
Website template accessed from : https://www.tooplate.com/view/2135-mini-finance
🚀 How to Start a Discord Bot Using Node.js with Google Bard API 🤖
Tags: discord, node, bot
Published: 2024-07-13 16:20:33

## Prerequisites

1. **Node.js** installed.
2. **Discord account** with a server.
3. **Google Cloud account** with Bard API access.

## Step 1: Set Up Your Project

1. **Create a New Directory:**

   ```bash
   mkdir discord-bot-bard
   cd discord-bot-bard
   ```

2. **Initialize a Node.js Project:**

   ```bash
   npm init -y
   ```

3. **Install Required Packages:**

   ```bash
   npm install discord.js axios dotenv
   ```

## Step 2: Create Your Discord Bot

1. **Create a New Bot Application:**
   - Go to the [Discord Developer Portal](https://discord.com/developers/applications).
   - Create a new application.
   - Add a bot under the "Bot" tab.

2. **Get Your Bot Token:**
   - Copy your bot token from the "Bot" tab.

3. **Invite Your Bot to Your Server:**
   - Go to the "OAuth2" tab and generate an invite URL with necessary permissions.
   - Invite your bot using the generated URL.

## Step 3: Integrate Google Bard API

1. **Set Up Google Cloud Project:**
   - Create a new project in the [Google Cloud Console](https://console.cloud.google.com/).
   - Enable the Bard API.
   - Create an API key.

2. **Store Your API Keys:**

   Create a `.env` file:

   ```env
   DISCORD_TOKEN=your-discord-bot-token
   BARD_API_KEY=your-google-bard-api-key
   ```

## Step 4: Write Your Bot Code

Create an `index.js` file and add the following code:

```javascript
require('dotenv').config();
const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');

const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });

client.once('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', async (message) => {
  if (message.author.bot) return;

  if (message.content.startsWith('!bard')) {
    const query = message.content.replace('!bard', '').trim();

    if (!query) {
      message.channel.send('Please provide a prompt for Bard.');
      return;
    }

    try {
      const response = await axios.post(
        'https://bard.googleapis.com/v1/creations:generate',
        { prompt: query },
        {
          headers: {
            'Authorization': `Bearer ${process.env.BARD_API_KEY}`,
            'Content-Type': 'application/json',
          },
        }
      );

      const bardResponse = response.data.response;
      message.channel.send(bardResponse);
    } catch (error) {
      console.error('Error fetching Bard response:', error);
      message.channel.send('Sorry, I could not fetch a response from Bard.');
    }
  }
});

client.login(process.env.DISCORD_TOKEN);
```

## Step 5: Run Your Bot

Run your bot with:

```bash
node index.js
```

## 🎉 Conclusion

Your Discord bot is now online and ready to generate creative content using the Google Bard API! Have fun interacting with it and expanding its features. Happy coding! 💻✨
LLNL Hackathon: Chat GPT, GraphRAG, & Vector DataBase Pipeline with LangChain
Published: 2024-07-13 16:50:50

###Overview
Created an **LLM Pipeline** using **LangChain**, **GraphRAG**, and Vector Databases for the data secure local instance of ChatGPT(LivChat) at Lawrence Livermore National Labs(LLNL) to allow users access to LLNL-specific information through LivChat.The LLM Pipeline creates clearance level-dependent indexes of Knowledge Graphs and Vector Databases, and queries both to synthesize a response for the user.

##Step By Step Process
Lawrence Livermore National Labs(LLNL) has a local instance of ChatGPT 3.5 & 4o(LivChat) on site to minimize sensitive data risks that arise when user queries are sent off site to OpenAI(ChatGPT), Microsoft(Copilot), etc. We proposed an improvement to the local model to **allow users to be able to ask this local ChatGPT instance questions that require internal LLNL knowledge** that OpenAI doesn't have access to when training ChatGPT. The improvement consists of using **LangChain**🦜🔗 to provide a method for LivChat to query clearance level specific data from Knowledge Graphs using GraphRAG, and a Vector Database using Pinecone, to then have LivChat read both queries and synthesize a response for the user. A flow chart of the overall process is shown below. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wcqgra1xcebsa9uf7okx.png)
O que é Design system e por que usar
Tags: designsystem, braziliandevs
Published: 2024-07-13 18:45:16

---
title: O que é Design system e por que usar
published: true
description: Entenda o que é um Design System e suas vantagens
tags: designsystem, braziliandevs
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2024-07-13 16:38 +0000
---

## O que é um design system?

Design system é uma biblioteca que é usada para organizar o tema de uma aplicação, incluindo suas variações. Ele contém os componentes mais comuns, como botões, entrada de texto e barra de navegação. Define as cores a serem usadas, desde cores primarias a terciárias, usadas em destaques, estados do sistema (erro/sucesso por exemplo) etc, também define diferentes usos de texto, como títulos. Além disso, inclui variações de tema (claro/noturno), assim como fontes e espaçamentos.

## Exemplo

Aqui temos um exemplo de um design system simplificado, contendo algumas variações de fontes, cores e componentes, como botão e input. Nesse caso, as fontes poderiam ter usos diversos como títulos, corpo de texto, legendas etc, podendo isso ser indicado no design system. Já as cores são de acordo com o uso, como a cor principal, aqui chamada de primária, que é usada nos lugares de destaque como em botão de ação, tela de inicialização (splash) etc, temos cores relacionadas ao estado da aplicação, como aqui demonstrado com a cor para erro, onde poderia ter também sucesso e neutro, variando de acordo com a necessidade. 

![Exemplo de um design system no figma, mostrando variações de fontes, cores, botão e input](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uhtqgq6xtbs4848cjobx.png)

## Pontos ao considerar se irá ou não ter um design system

Ter um design system resulta em uma centralização dos componentes, permitindo reusar em diferentes aplicações, gerando assim uma padronização e facilitando a manutenção, uma vez que ao atualizar em um local irá refletir nos demais.

Mas como nem tudo são flores, ao decidir criar e usar um design system têm-se um maior esforço inicial, tanto para decidir o que irá compor como para criar os componentes e suas variações. 

## Considerações finais

Ter ou não um design system depende da necessidade de sua aplicação, precisando assim avaliar os prós e contras caso a caso. Em aplicações que trabalhei e que tinham um design system foi bastante útil, como ao criar templates já agiliza por ter alguns componentes pré-definidos e em casos de mudança de marca, facilita a retafotação por não precisar ir em cada componente alterar manualmente.
Understanding Dependencies in Node.js Projects
Tags: webdev, beginners, basic, javascript
Published: 2024-07-13 17:27:48



# Understanding Dependencies in Node.js Projects

When working on a Node.js project, managing dependencies is a crucial aspect that ensures your project runs smoothly. Dependencies are the libraries or packages your project needs to function. There are two main types of dependencies you should be aware of: devDependencies and normal dependencies.

## Types of Dependencies

### DevDependencies

These are the packages required only during the development phase. They are not needed in the production environment. For example, tools like parcel, webpack, or babel, which help in building or bundling your project, are usually listed as devDependencies.

Here's an example of how to define a devDependency in your `package.json` file:

```json
"devDependencies": {
  "parcel": "^2.8.3"
}
```

### Normal Dependencies

These are the packages that your project needs in both development and production environments. Examples include frameworks like React, libraries for making HTTP requests, or any other code that your application relies on to run.

## Understanding Versioning Symbols

In the `package.json` file, you might notice symbols like `^` or `~` before the version numbers. These symbols are used to specify version ranges:

- **Caret (`^`)**: This symbol allows updates to minor versions. For example, `"parcel": "^2.8.3"` means any version from `2.8.3` to less than `3.0.0` is acceptable.
  
- **Tilde (`~`)**: This symbol allows updates to patch versions. For example, `"parcel": "~2.8.3"` means any version from `2.8.3` to less than `2.9.0` is acceptable.

## package.json and package-lock.json

Both `package.json` and `package-lock.json` are essential for managing dependencies in a Node.js project, but they serve different purposes:

- **package.json**: This file lists the dependencies your project needs and can include version ranges (`^` or `~`).

- **package-lock.json**: This file locks down the exact versions of each dependency, ensuring that every time you or someone else installs the project, the same versions are used.

## Understanding the Configuration and Node Modules

The `package.json` file can be seen as part of your project's configuration, specifying which packages are needed and their respective versions. The `node_modules` folder is like a database where all these packages are installed.

## Transitive Dependencies

Dependencies can have their own dependencies, creating a chain known as transitive dependencies. For example, Parcel might depend on other packages, and those packages might depend on even more packages. This chain is automatically managed for you, ensuring that all necessary packages are installed.

---

I hope this gives you a clearer understanding of how dependencies work in Node.js projects. Managing these correctly ensures your project runs efficiently and as expected, both during development and in production.
Introducing WeedX.io: A Comprehensive Platform for the Cannabis Industry
Tags: weedx, cannabis
Published: 2024-07-13 17:49:18

Hello Dev.to community,

I'm excited to share with you our latest project at Selnox Infotech Pvt Ltd - [WeedX.io](https://weedx.io) . 🚀

What is WeedX.io?

WeedX.io is a robust platform designed to cater to the diverse needs of the cannabis industry. Our goal is to streamline the connection between dispensaries, delivery services, and customers, all in one place.

Key Features:

Dispensary Listing:  Find local dispensaries with ease. 
Delivery Listing: Discover delivery services in your area.
Brand Listing: Explore various cannabis brands and their products.
Order Placement: Customers can place orders for delivery or pick-up.
Location-Based Services: Get personalized recommendations based on your location.

 Our Journey

At [Selnox Infotech](https://selnox.com/), we are committed to leveraging technology to simplify and enhance the cannabis business ecosystem. WeedX.io represents our vision of creating a seamless experience for both businesses and consumers in the cannabis industry.

Get Involved

We'd love to hear your thoughts and feedback on WeedX.io. If you're interested in learning more or have any questions, feel free to comment below or reach out to us directly.

Thank you for your support!

Best regards,  
sandeep kourav  
Founder & CEO, Selnox Infotech Pvt Ltd

---

Feel free to check out WeedX.io at [https://weedx.io](https://weedx.io) and explore what we have to offer!
Introducing Cannabaze: Your Ultimate POS System for the Cannabis Industry
Published: 2024-07-13 17:58:07

In the rapidly evolving cannabis industry, efficient and reliable management solutions are crucial for success. Enter [Cannabaze](https://cannabaze.com/), the ultimate Point of Sale (POS) system designed specifically for the cannabis business. Whether you’re running a dispensary, delivery service, or brand, Cannabaze is your go-to solution for streamlined operations and enhanced customer experiences.

Why Choose Cannabaze?
Tailored for the Cannabis Industry
Cannabaze is not just another POS system. It's built with the unique needs of the cannabis industry in mind. From compliance with regulatory requirements to managing inventory and sales, Cannabaze has you covered.

Seamless Integration
Integrate Cannabaze with your existing systems and workflows effortlessly. Whether you're using WeedX.io for dispensary listings or delivery services, Cannabaze syncs seamlessly to provide a unified and efficient operational experience.

Comprehensive Inventory Management
Stay on top of your stock with Cannabaze’s robust inventory management features. Track products in real-time, manage suppliers, and ensure you never run out of your best-selling items.

Enhanced Customer Experience
Cannabaze enables you to provide a superior customer experience with quick and easy transactions. Our user-friendly interface ensures that your staff can focus on what matters most – serving your customers.

Advanced Reporting and Analytics
Make informed business decisions with Cannabaze’s advanced reporting and analytics. Gain insights into sales trends, customer preferences, and inventory turnover to optimize your operations and increase profitability.

Secure and Compliant
Cannabaze prioritizes security and compliance. Our system is designed to meet the stringent regulatory requirements of the cannabis industry, ensuring that your business remains compliant while protecting sensitive customer data.

24/7 Support
Our dedicated support team is available around the clock to assist you with any issues or questions. We’re committed to ensuring that your Cannabaze experience is smooth and trouble-free.

Transform Your Cannabis Business with Cannabaze
In an industry where efficiency and reliability are key, Cannabaze stands out as the ultimate POS system. Simplify your operations, enhance your customer service, and grow your business with the power of Cannabaze. Join the ranks of successful cannabis businesses that trust Cannabaze for their point-of-sale needs.

Ready to take your cannabis business to the next level? Discover the Cannabaze difference today!
O que é DTO? Por que usar?
Tags: webdev, java, solidprinciples, dto
Published: 2024-07-13 18:13:35

Olá pessoal, sou Jean e vim trazer um artigo sobre DTO. Aqui é apenas a teoria e não terá código prático. Espero que aproveitem!

## Introdução

DTO, ou "Objeto de Transferência de Dados" (do inglês, Data Transfer Object), como o nome sugere, é um objeto utilizado para enviar e receber dados. Normalmente é utilizado no backend de aplicações mais estruturadas.

## Mas por que usar DTO?

DTO é uma forma de simplificar e separar, proporcionando vários benefícios como:

1. **Encapsulamento**: Baseado na arquitetura limpa (clean architecture) e nos princípios SOLID, é uma maneira de agrupar/limitar dados para melhor organização e separação da lógica de negócios e outras camadas.
   
2. **Redução de Acoplamento**: Com a redução do acoplamento, há um melhor controle na manutenção e escalabilidade do código, além de possibilitar testes e outros tipos de manipulação.

3. **Segurança e Controle**: Ao separar e controlar melhor os dados, é possível implementar validadores, sistemas de segurança ou validação, e reduzir vazamentos de informações sensíveis.

4. **Desempenho**: Embora em alguns casos não haja melhoria direta, o uso de DTOs permite melhor controle e redução de dados desnecessários, resultando em pacotes de rede menores e potencialmente melhorando a performance.

5. **Facilidade de Testes**: Ao isolar partes do sistema, é possível simular cenários (mock), realizar testes isolados, e ter melhor visibilidade do fluxo de dados.

## Como utilizá-lo?

Existem várias formas de implementação, e aqui estão alguns exemplos em diferentes linguagens:

1. **JavaScript**: [DTOs in JavaScript](https://dev.to/tareksalem/dtos-in-javascript-118p)
2. **TypeScript**: [Simplifying DTO Management in Express.js with Class Transformer](https://dev.to/mdmostafizurrahaman/simplifying-dto-management-in-expressjs-with-class-transformer-56mh)
3. **Rust** (reddit): [Are DTOs and Entities the Right Way?](https://www.reddit.com/r/rust/comments/174o3ph/are_dtos_and_entities_the_right_way/)

## Quando utilizar DTO?

Listarei alguns contextos para explicar por que utilizar DTO:

- **Aplicações de web service**: Melhor controle do fluxo de dados para receber e retornar informações, estabelecendo um contrato claro entre cliente e servidor.
  
- **Sistemas distribuídos**: Em arquiteturas de microserviços e APIs, é benéfico para controlar e obter uma visão melhor do sistema, além de reduzir a latência devido à diminuição do tráfego de rede.

## Conclusão

O DTO é uma excelente forma de organizar, separar, otimizar, testar e realizar diversas outras tarefas dentro de uma aplicação. O conceito é semelhante ao do GRPC, que também utiliza uma estrutura bem definida. Enfim, espero que tenham gostado.
How the internet works
Tags: internet
Published: 2024-07-13 18:28:43

## What is internet
The internet in a lay man terms can be perceive as a network of cables that runs through out the world and this cables are the means in which computers from different locations can communicate with each other, the computers can be any form of device from a server to a laptop or even smartphones, at a very basic level, computers can communicate with each other by connecting via cables.

![Two computers linked together](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/77bkq2s8bjygwetb5rfk.png)

The solution in the picture above can be optimised with the use of a router (routers are computers that ensure a message sent from one computer find it way to the target computer). Instead of connecting each computer to one another via a cable, they are all connected to the router and when a computer sends a message out to another computer it goes through the router which will figure out the computer the message is meant for and deliver it.

![Ten computers with a router](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uvuxtpnpshdwigz913mj.png)

### How does this local network communicate with other network outside
Internet Service Provider (ISP is a company that manages some special routers that are all linked together and can also access other ISPs' routers) helps connect our local network via a modem through the ISP router to get to our destination network.

![Full internet stack](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a3wude5fj1rbcq6q5acc.png)

### Finding a computer
Each computer can be identified by an internet protocol address (IP address) which is how a message sent from one computer can travel through the cables and find the right computer the message is meant for. The IP address is an address made of a series of four numbers separated by dots, for example: `192.0.2.172` but because the IP address are not easy to remember for humans, each IP address is given a domain name that is easily readable and can be remembered easily. Take a user for example on a laptop trying to access the google server, the google server IP address `142.250.190.78` (this can change in the future) can be type in a browser the google server will respond with the google search page.

If this article is helpful, consider liking, sharing, and following me; connect with me on [Twitter](https://x.com/Jideotetic) and [Linkedin](https://www.linkedin.com/in/jideotetic).
Happy coding.