teleren/devto huggingface dataset:
10 more Rules that will help you write secure, scalable and adaptable programs
Tags: programming, beginners, devjournal, systems
Published: 2023-06-15 01:31:00

Everybody in this country should learn to program a computer because it teaches you how to think. - Steve Jobs

10 more Rules that will help you write secure, scalable and adaptable programs:


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


## 1. Use Commodity Systems:
Use small, inexpensive systems where possible. Build your systems to be capable of relying on commodity hardware and don't get caught in the trap of using high-margin, high-end servers.


## 2. Scale out your data centers:
Design your systems to have three or more live data centers to reduce overall cost, increase availability, and implement disaster recovery.


## 3. Design to leverage the cloud:
Make use of third-party cloud environments for temporary demands. Design your application to service some requests from a third-party cloud when demand exceeds a certain peak level.


## 4. Use databases appropriately:
Use relational databases when you need ACID properties to maintain relationships between your data. For other data storage needs consider more appropriate tools.


## 5. Firewalls, firewalls everywhere!
Use firewalls only when they significantly reduce risk and recognize that they cause issues with scalability and availability. Employ firewalls for critical PII, PCI compliance, and so on.


## 6. Actively use log files:
Use your application’s log files to diagnose and prevent problems. Make good use of your log files, and you will have fewer production issues with your system.


## 7. Don't check your work:
Never read what you just wrote for the purpose of validation. Store data in a local or distributed cache if it is required for operations in the near future.


## 8. Stop redirecting traffic:
Avoid redirects when possible; use the right method when they are necessary. If you must have them, consider server configurations instead of HTML or other code-based solutions.


## 9. Relax temporal constraints:
Alleviate temporal constraints in your system whenever possible. The difficulty in scaling systems with temporal constraints is significant because of the ACID properties of most RDBMSs.


## 10. Leverage content delivery networks:
CDNs are a fast and simple way to offset the spikiness of traffic as well as traffic growth in general. Make sure you perform a cost-benefit analysis and monitor the CDN usage.


First 10 rules:
https://dev.to/pragyanatvade/10-rules-that-will-help-you-build-secure-scalable-and-adaptable-applications-46pi


Thanks for reading this.

If you have an idea and want to build your product around it, schedule a call with [me](https://calendly.com/pragyanatvade).

If you want to learn more about DevOps and Backend space, [follow me](https://dev.to/pragyanatvade).

If you want to connect, reach out to me on [Twitter](https://twitter.com/pragyanatvade) and [LinkedIn](https://www.linkedin.com/in/pragyanatvade/).
Add Particles.js to Your Squarespace Site
Tags: squarespace, particlesjs, animation, javascript
Published: 2023-06-15 00:35:56

## Particles.js background on Squarespace

[Particles.js](https://vincentgarreau.com/particles.js/) is a lightweight plugin that adds motion and interaction to your Squarespace site. You can set up a Particles.js background on your site in five steps:

1. Upload the Javascript file
2. Inject Particles.js and Javascript file into the header
4. Add CSS styles
5. Add custom code-block with target div

Let's go through each of steps.

------------------

### Upload the Javascript file

First you should upload this file to your Squarespace site: https://github.com/michaelsynan/squarespace-files/blob/main/floatingMO.js

The technique uses the [Mutation Observer](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) API to make sure the necessary script doesn't load until its target div has been rendered. To upload a file to Squarespace you need to go to "pages" -> new page -> "link" -> gear icon -> "file" -> "upload file" (I know its a little unintuitive). Note the link address, which is "/s/floatingMO.js" in this case. 


### Inject Javascript into your Squarespace site

To inject your new Javascript file you need to go to "settings" -> "developer tools" -> "code injection", then place the following code in the header (remember to check your javasript file link): 

```
<script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
<script src="/s/floatingMO.js"></script>
```

### Add CSS Styles
"design" -> "custom CSS"

```
#particles-js-wrapper {
    position: fixed;
    width: 100%;
    height: 100vh;
    top: 0;
    left: 0;
    background-color: #000;
    z-index: -1;
}

#particles-js {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 0;
}

#particles-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: red;
    z-index: 1;
}
```

### Add Custom Code Block

Go to the editor in your Squarespace site and add the following code block: 
```
<div id="particles-js-wrapper">
    <div id="particles-js"></div>
</div>
```
It's important to note that the code above targets the div "#particles-js" - if you want to change this you should update the JavaScript GitHub file linked to above. 

If you just want to play around with Particles.js outside of Squarespace, you can check out my CodePen [here](https://codepen.io/michaelsynan/pen/bGmLawL). Feel free to fork it and post your Pens below - I'll be sure to like and reply. 

Enjoy and feel free to reach out if you have any questions!
Mastering Express.js Commands
Tags: express, javascript, database, webdev
Published: 2023-06-15 00:27:00

## Comprehensive Guide

**introduction:**

Express.js is a popular web application framework that simplifies building reliable and scalable web applications for Node.js. As a developer working with Express.js, it is important to familiarize yourself with the various commands and utilities it offers to increase your productivity. In this article, we'll explore a set of Express.js commands that allow you to efficiently manage routing, middleware, and application configuration.


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

**Setup and Installation:**

- Install Express.js: npm install Express
- Create an Express application: const Express = require('Express'); const program = express();
- Start server: app.listen(port, () => { console.log('Server started on port ' + port); });

**Route:**

- Set main path: app.get('/', (req, res) => { res.send('Hello, World!'); });
- Route parameters: app.get('/users/:id', (req, res) => { const userId = req.params.id; /*...*/ });
- Handle Controllers: app.get('/users', getUsers);

**Middleware:**

- Run the middleware: app.use(middleware);
- Body analysis: app.use(Express.json()); and app.use (Express.urlencoded ({extended: true}));
- Login request: app.use ((req, res, next) => { console.log('Request:',req.method,req.url); next(); });

**Error handling:**

- Handle errors with middleware: app.use ((error, req, res, next) => {/*...*/});
- private Error handler: app.use((error, req, res, next) => { /*...*/ res.status(500).json({error: 'Something went wrong.'});}) ;

**Static files:**

- Serve a static file: app.use(Express.static('public'));
- Define static file directory: app.use('/assets', Express.static('public/assets'));

**Template Engine:**
Set the template engine (eg EJS): app.set('view engine', 'ejs');
Render: res.render( 'index', { title: 'Home' });

**Middleware Library:**

- Express.js provides a variety of middleware libraries that can be easily integrated into your application:
- Body-manager: Build npm body-manager
- Cookie-parser: Install npm cookie-parser
- Cask: Install npm shell
- Morgan: npm build morgan

**additional services:**

- HTTP methods other than GET: app.post(), app.put(), app.delete(), etc.
- Route group: app.use('/api', router);
- Validate paramol parameters: Use libraries like express-validator or custom validation functions.
- Redirect: res.redirect('/new-location');
**The results:**
Express.js Command Node.js. form the core of building a powerful web application with This comprehensive guide provides an overview of the essential commands for building an Express.js application, routing, middleware, error handling, static file portions, working with the template engine, and using additional utilities. By mastering these commands, you'll be equipped to build responsive and scalable web applications using Express.js.
Python Terminal Tic-Tac-Toe Game
Tags: python, beginners, terminal, codecademy
Published: 2023-06-15 00:25:12

_My First Portfolio Project on Codecademy_

**Welcome to my first blog post as a coder!**

Today, I want to share with you my first portfolio project which I completed as part of my Computer Science career path on [Codecademy](https://dev.to/codecademy). The project challenged me to post my code on GitHub and write a blog post to share my project. 

The goal of this project was to create a terminal program using the coding tools I have learned so far. I chose to make a two-player Tic-Tac-Toe game.
![picture from computer terminal that says tic-tac-toe](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m175hwkogv0vzxjrd8nh.png)
In the future, I have ideas to improve the program to include the option to play against the computer.

I had a lot of fun developing this program and I learned a lot. I hope you enjoy it!

[https://github.com/lanesummer/Portfolio-Project---Python-Terminal-Game](https://github.com/lanesummer/Portfolio-Project---Python-Terminal-Game)

**Update June 28, 2023:**
I decided to create version2 by refactoring and changing some functionality of the original. Version2 is more readable and easier to maintain. Both the original (tic_tac_toe.py) and the new version (tic_tac_toe_version2.py) can be found in the GitHub link above.
How to Resolve the "__dirname is not defined in ES module scope" Error in JavaScript
Tags: node, javascript
Published: 2023-06-15 00:21:16

`__dirname` is a Node. js-specific variable that is used to obtain the name of the directory from a given file path. This variable is specific to the CommonJS module system used in Node.js before ECMAScript (ES) modules. Now that ES modules are the standard, there is a different approach to handling modules and file paths. 

To resolve this issue, we can use the `import.meta.url` property to obtain the directory name:

```
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

```

This code converts `import.meta.url` into a file path using the `{ fileURLToPath }` function from the `url` module and then extracts the directory name using the `{ dirname }` function from the `path` module.

This solution should address the problem. Do you have any alternative approaches for resolving this? Feel free to share your suggestions in the comments.
Running and Connecting to Postgres Using Docker Compose
Tags: beginners, docker, postgres
Published: 2023-06-19 23:15:51

---
title: Running and Connecting to Postgres Using Docker Compose
published: true
date: 2023-06-15 00:00:00 UTC
tags: [ "beginners", "docker", "postgres", "postgresql" ]
canonical_url: https://webbureaucrat.gitlab.io/articles/running-and-connecting-to-postgres-using-docker-compose/
---

Setting up a new development environment from scratch can feel like a slog. This is a quick copy-paste recipe for getting up and running quickly with Postgres in `docker compose`.

### Start with a .env file

At the very least, we know we will need a `POSTGRES_PASSWORD` environment variable, and our .env file doesn't rely on any other files, so it's a good place to start.

I personally am not crazy about hiding files by beginning them with periods, so I'm going to call my file _database.env_.

_database.env_

```bash
POSTGRES_USER=postgres_user
POSTGRES_PASSWORD=postgres_password
POSTGRES_DB=postgres_database
```

It goes without saying, but this is for _local development_. Sensitive information for any database you intend to stand up for a while should be treated better than this. Use stronger passwords, and don't publish them in a blog post on the Internet, etc., etc.

### Create database scripts

This section is more or less the "Draw the rest of the owl" portion of this article. The idea here is to create whatever database scripts--tables, stored procedures, etc--in _./database/docker-entrypoint-initdb.d_. Any _.sql_ or compressed _.sql_ file in this folder will be run by the database at startup. (Other file extensions are supported. See [the official documentation](https://hub.docker.com/_/postgres/) for more.)

### Create a _docker-compose.yml_ file

Now we're ready to get started with our docker compose file. There's no magic here--we're just exposing our ports, referencing our _database.env_ file, and feeding in our scripts from our scripts directory.

_docker-compose.yml_

```yaml
version: "3.8"
services:
  database:
    env_file: "database.env"
    image: postgres:latest
    ports:
      - "5432:5432"
    volumes:
     - ./database/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
```

You should now be able to run this with `docker compose up`.

### Connecting to a locally-running Postgres container

With that compose file running, we can connect via SSH like so:

```bash
docker compose exec database bash
```

Note that "database" is the identifier chosen in the _docker-compose.yml_.

Lastly, we can run psql from within the container to run commands directly inside the container. Use the values from your _database.env_ file.

```bash
psql --dbname postgres_database --host localhost --username postgres_user
```

This can be shortened to:

```bash
psql -d postgres_database -h localhost -U postgres_user
```

From here, you can run Postgres queries against your database.

### Wrapping up

Starting with a blank sheet of paper can be kind of daunting, so writing (and having) basic tutorials like this to lay out some basic first steps to be a good motivational and organizational tool. I hope this has been helpful.
Dremio and Apache Iceberg: New Hope or Data Hype!?
Tags: database, datascience, bigdata, architecture
Published: 2023-06-14 23:59:26

Hello Everyone,

I started to look at the market and saw a growing use of Apache Iceberg, an amazing data format totally open-source and maintained and used by a huge community. With this opportunity I observed a very common architecture of using Iceberg with the Dremio solution, I summarized these and other points in a post on Medium.

To know more:

https://jlgjosue.medium.com/dremio-and-apache-iceberg-new-hope-or-data-hype-8b4594efdf89

Thanks for reading; share this post! :)
[PT-BR] - Entenda CORS e saiba lidar com os erros!
Tags: webdev, programming, security, help
Published: 2023-06-14 23:35:24

Cross-Origin Resource Sharing ou simplesmente CORS para os mais intímos, é um padrão de segurança que permite que um determinado site, a partir de uma URL, solicite dados de outra URL ou API.
 
Se você é um desenvolvedor front-end, provavemente já se deparou com a seguinte frustante mensagem no seu console em algum momento da vida:

![Console com cors error, que assola à todos os programadores](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kl82npn9q2krxnc2mj7w.png)

Isso acontece porque os navegadores, por padrão, implementam um politica de origem como parte de modelo de segurança. Essa política permite que os websites acessem e requisitem imagens e dados da mesma URL, mas bloqueia qualquer coisa que provenha de fontes externas, a menos que algumas condições expecíficas e pré-definidas sejam atigindas. 

Quando o navegador faz uma requisição, ele adiciona por padrão um cabeçalho de origem (header) à mensagem. Se a request atingir um servidor com a mesma origem, o navegador permitirá a conexão. No entanto, se a solicitação for para uma URL diferente, então é conhecida como uma **cross-origin request**.  

Quando enviando a resposta do servidor, vai ser adicionado o "Access-control-allow-origin" no header, o valor do cabeçalho precisa ser correspondente com a origin header na request, ou também pode ser uma (*) que permite qualquer entrada ou qualquer URL. 

![Access control origin igual ao caminho de origem](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3gsc193l71mwoxzhfb7s.png)

Caso os valores sejam diferentes, o navegador impedirá o compartilhamento dos dados com o cliente, resultando no erro mostrado acima. 

![You shall not pass gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mcipkkx6l360i4e6h2k0.gif)

**Como lidar com problemas de CORS?**

Se você estiver vivenciando um erro de CORS agora, debugar é bastante simples, basta abrir a guia do navegador, inspecionar e ir para a guia "Network" (Rede). Encontre a response dos dados/request(API) e procure pelo header de **Access-control-allow-origin**.

![Response header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fyrqtjr0qzl1wphr5zow.png)

Se por ventura esse cabeçalho não existir, significa que você precisa habilitar **CORS** em seu servidor (isso pode ser feito utilizando uma biblioteca NPM, como o [NPM cors](https://www.npmjs.com/package/cors) caso esteja utilizando Express).

```
const express = require('express')
const cors = require('cors')
const app = express()
 
app.use(cors())
 
app.get('/', (req, res) => {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})
 
app.listen(80, () => {
  console.log('CORS-enabled web server listening on port 80')
})
```
Se por acaso esse header existir e a URL for diferente do seu website/request, você precisará ajustá-lo para corresponder à sua URL e caminho, ou permitir * (Que permite qualquer acesso, mas tome muito cuidado com essa decisão, se tratando de um produto em PROD!), lembrando que tudo isso pode e é configurado através do seu servidor ou backend.
Shadcn UI pros and cons
Tags: webdev, react, tailwindcss, javascript
Published: 2023-06-14 23:29:11

Shadcn UI provides components to copy and paste into your app. It's built with Radix UI and Tailwind CSS.

It's been a couple of weeks using Shadcn UI. So, I would like to share my thoughts on it. Like other frameworks, it has pros and cons. Some of them are mentioned below.

## Pros

- Copy and paste components directly to your app.
- Built with Radix UI and Tailwind CSS.
- Good design.
- Light/Dark mode out of the box.
- Automatic CLI installation.
- Well integrated with Next.js 13 (app directory).
- Full accessibility out of the box.
- Full type safety with Zod.
- It's open source.

and more

## Cons

- Issues with intellisense. It shows autocomplete from Radix UI too.
![Intellisense issue](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lc657l2t78dr0g85fkl.png)
- Difficulty in changing colors. It's very confusing to change colors on it.
![How the colors look like](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5qer22vf5b49d7ywiucp.png)


## Some feature requests I would like to make 🥳

### Ability to change naming convention

Add an option (while installing) for changing the file convention like PascalCase, camelCase, or spinal-case. As people like me usually use PascalCase for components.

### Ability to change colors with CLI

It can handle automatic color generation. (e.g. https://www.tailwindshades.com)
test number 2 api fetch
Published: 2023-06-14 23:09:07

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
this is just test blog
Published: 2023-06-14 23:06:55

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
How to Create a Kubernetes Cluster on AWS
Tags: kubernetes, devops, programming, aws
Published: 2023-06-14 22:47:50

If you are considering a managed Kubernetes solution, running Kubernetes on AWS is about as good as it gets.

Thanks to technologies like Amazon Fargate and the vast outreach of Amazon’s cloud computing infrastructure, the Elastic Kubernetes Service, or EKS, can offer a truly distributed environment where your applications can run and scale.

With Amazon EKS the scalability is outstanding and the upgrade process is smooth. The tight integration with other AWS services that you get by running Kubernetes with AWS is also a huge bonus.

Now, the **easiest way to get started with EKS** is to use the command-line utilities that include:
⁣
-[AWS-CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) to interact with your AWS account,⁣
-[eksctl](https://docs.aws.amazon.com/eks/latest/userguide/eksctl.html) to create, manage and delete EKS clusters,⁣
-[kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html) to interact with the Kubernetes Cluster itself.⁣
-[docker](https://docs.docker.com/get-docker/) to create and containerize your application.⁣
-[Docker Hub](https://hub.docker.com/) accounts to host your Docker images (free tier will work)⁣
⁣
These are the requirements you need on your local computer:
✅Setting Up AWS CLI⁣
✅Creating and Deleting an EKS Cluster using Fargate⁣


![Amazon EKS Architecture ClickIT](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bp3a2spsqqong5czenea.jpeg)



**How to deploy a Kubernetes cluster on Amazon EKS?**

Check out the full tutorial here: https://www.clickittech.com/devops/kubernetes-on-aws/?utm_source=devto&utm_medium=referal&utm_campaign=dev-blogs&utm_term=dev-june-2023&utm_content=copy
Day 1 open source contribution.
Published: 2023-06-14 22:20:45

Today I started my journey as an open-source contributor, After thinking about a lot of projects, and where to start I came across an article Which was a guide to "Open Source contribution". After reading that only advice I took to just start So I decided I start django I went to Django's open-source guide and started step by step beginners guide, and then I realized, how important testing for a bigger project is the first thing they taught me how to install test dependencies and run test 

This is the no. of test- Ran 16410 tests in 387.508s 
// This section is only for geek 🥹
(E indicates that an error was raised during a test, and F indicates that a test’s assertions failed. Both of these are considered to be test failures. Meanwhile, x and s indicated expected failures and skipped tests, respectively. Dots indicate passing tests.)OK (skipped=1315, expected failures=5)