teleren/devto huggingface dataset:
Lessons from open-source: Use nested functions for logic encapsulation and separation of concerns.
Tags: javascript, nextjs, node, react
Published: 2024-03-06 23:10:21

This lesson is picked from [@next/mdx package](https://github.com/vercel/next.js/blob/canary/packages/next-mdx/mdx-rs-loader.js). In this article, you will learn how next.js source code applies encapsulation and separation of concerns with nested functions in @next/mdx package.

![Compile nested inside createFormatAwareProcessors function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hbi0cxabrg53b57bm02x.png)

`createFormatAwareProcessors` returns an object with two properties `extnames`, `compile`.

![compile](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oah28e1y0zy0zzh80x1d.png)

`compile` here is a function that encapsulates processing logic.

> If you are looking to practice next.js, checkout my website: https://tthroo.com/

You could have just let `createFormatAwareProcessors` do the processing logic but, context and proximity matter when you write functions and to decide what they (functions) should return. This is why you have 'extnames' property returned by `createFormatAwareProcessors` along with 'compile'.

By returning a function (compile), the external code using this processor can decide when to call it. It provides a level of abstraction, allowing the external code to control when and how the compilation should occur, giving more flexibility and control.

This design choice makes your code more modular and allows for better organization and reuse of the processing logic.

## Conclusion:

You can encapsulate logic in a nested function (function within a function). To have more control over triggering a logic, you can simply return this function along with other properties in the object.

The following is a snippet from nextjs source code, an object returned by `createFormatAwareProcessors`:

```
return {
  extnames:
  compileOptions.format === 'md'
  ? mdExtensions
  : compileOptions.format === 'mdx'
  ? mdxExtensions
  : mdExtensions.concat(mdxExtensions),
  compile,
}
```

I just admire the fact that the `compile` function is used to encapsulate logic and to create separation of concerns because you might want to put certain logic processing on hold until you reach/meet some criteria.
Terraform Code Repository: Monolith or Microservice Approach
Tags: azure, devops, terraform, community
Published: 2024-03-06 23:07:42

Greetings to my fellow Technology Advocates and Specialists.

In this Session, I will explain __Terraform code repository structure: Monolith vs Microservice.__

| __SPECIAL NOTE:-__ |
| --------- |
| I thank @pwd9000 and @anandarbone for collaborating. Though I am publishing this Article, but both of them have the equal rights to republish and repost. |

| __CODE REPOSITORY:-__ |
| --------- |
| {% github arindam0310018/06-Mar-2024-DevOps__Terraform-Code-Repo-Monolith-Microservice %} |

| __CONSIDERATIONS:-__ |
| --------- |
| For the purpose of this article, I/We have considered below:- |

| __#__ | __CATEGORY__ | __VALUE__ |
| --------- | --------- | --------- |
| 1. | Cloud Platform | __Azure__ |
| 2. | Devops Platform | __Azure Devops__ |
| 3. | Source control | __Azure Git__ |
| 4. | Pipelines | __Azure Devops Pipelines__ |
| 5. | IaC  | __Terraform__ |
| 6. | Code Structure | __Modules Based__ | 

| What is Monolith based code repository in Terraform ? |
| --------- |
| 1. In simple terms, it means one repository under Azure DevOps Project with multiple folders. |
| 2. Each folder contains Terraform Module per Azure Service. |
| 3. Reference screenshot follows below:- |
| ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3e8ydzgzchqr94etinwy.jpg) |

| __Monolith based code repository problem statements:-__ |
| --------- |
| 1. Each time the Pipeline runs, it checks out all codes. | 
| 2. Pipeline execution time increases gradually. |
| 3. Size of the artifacts increases gradually . |
| 4. Avoid Human Error while contributing. |

| What is Microservice based code repository in Terraform ? |
| --------- |
| 1. In simple terms, it means multiple repositories under Azure DevOps Project. |
| 2. Each repository contains Terraform Module per Azure Service. | 
| 3. Reference screenshot follows below:- |
| ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b39p6ktnenjqlpvqffys.jpg) |

All the above identified problem statements in Monolith Code Repository is resolved with Microservice based code repository.

| __Mitigating Monolith based code repository problem statements with Microservice based code repository:-__ |
| --------- |
| 1. Each time the Pipeline runs, it checks out only the relevant repositories. | 
| 2. Pipeline execution is fast/not impacted because it checks out only the relevant repositories. |
| 3. Size of the artifacts is way small and the increase is not even noticed because it checks out only the relevant repositories |
| 4. Chances of Human Error is on the lower side since contributor works on specific repositories. |

__Hope You Enjoyed the Session!!!__

__Stay Safe | Keep Learning | Spread Knowledge__
La importancia del archivo composer.lock en PHP
Tags: laravel, php, composer
Published: 2024-03-06 23:05:55

En el vasto ecosistema del desarrollo de software, especialmente en el ámbito de las aplicaciones PHP, hay una serie de herramientas y prácticas que son esenciales para garantizar la estabilidad y la consistencia del código. Una de estas herramientas fundamentales es el archivo composer.lock, que desempeña un papel crucial en la gestión de las dependencias de un proyecto PHP. En este artículo, exploraremos qué es exactamente el archivo composer.lock y por qué es tan importante en el desarrollo de aplicaciones PHP modernas.

[clic aquí ver el artículo completo](https://angelcruz.dev/post/importancia-composer-lock-php?utm_source=devto)
Modelando um banco de dados - Para um sistema de empréstimo de computadores
Tags: database, documentation, braziliandevs
Published: 2024-03-06 22:43:32

olá, nesse artigo você verá um pouco sobre modelagem de banco de dados e sua implementação em app real.

## Por que modelar?

Primeiramente idealmente antes de implementar qualquer solução deve existir um momento de reflexão sobre ela, sobre as possibilidades e a partir dessa reflexão desenhar um solução -- Documentar -- só depois ir implementa com a solução já descrita.

## Descrevendo o contexto

Na faculdade uma das atividades que temos de banco de dados é pegar uma descrição de um sistema e a partir dessa descrição modelar um banco de dados, aqui antes de modelar descreverei o sistema.

### - Descrição

_O sistema tem o foco em empréstimo de computador, devem ser armazenados os dados de alunos, computadores, disciplina e empréstimo.
Dos alunos tem que deve ser guardado o número de matricula, nome do aluno e disciplina da qual faz parte, da maquina deve ser guardado o número de tombamento, da disciplina deve ser armazenado um identificador, o nome da disciplina, a hora de inicio e a hora de fim, do empréstimo dever armazenado o aluno, a máquina, a disciplina, a hora de empréstimo e a hora de devolução. 
Os alunos podem fazer parte de uma ou mais disciplinas ao mesmo tempo._


## DER - Diagrama entidade-relacionamento

Uma das formas de representar os dados é como diagrama entidade-relacionamento.

Considerando a descrição o diagrama fica assim:

obs: considerei chamar os computadores de "machine" para deixar mais geral. Tendo em vista que esse sistema pode ser usado para controlar outros tipos de dispositivo.


![diagrama de entidade de relacionamento](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c87fbvevjtl2vgvmm6dh.png)


Onde temos três entidades e dois relacionamentos.

Entidades: Student, Subject, Machine

Relações:

Student com Subject -> is enrroled in
Student com Machine -> to loan

A partir do DER é possível criar as tabelas.

## Convertendo DER para modelo relacional

Ok, temos o DER, sabemos quais são as entidades as relações e as cardinalidades, agora é necessário converter para o modelo relacional que é usado por banco de dados relacionais.

As entidades naturalmente são convertidas para tabelas e relações muitos para muitos também se tornam tabelas ficando assim:


![imagem do modelo recional](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/18kbbz4jepoaxj1cv938.png)


obs: 
PK = chave primaria (primary key)
FK = chave estrangeira (foreign key)
First Day With Ruby!
Tags: webdev, github, ruby, html
Published: 2024-03-06 22:37:50

Hello, world!

Today I had my first ruby lesson. I created a webpage with the use of GitHub and Render!

Feel free to check out the site [here](https://hello-world-57gc.onrender.com) or for a look at the repository click [here](https://github.com/MayaS1111/hello-world)!

-Maya
Snowpal Backend as a Service: API Product Suite
Published: 2024-03-06 22:31:35

This video provides an introduction to Snowpal APIs and an overview of their API suite. It explains the different documentation formats available and emphasizes the APIs as building blocks for developers. The video then dives into the details of each API, including Building Blocks, Project Management, Content Management, Classroom, Conversation, Status, Custom Attribution, and Access Control. It concludes by discussing the licensing and implementation options and highlighting the extensive documentation and resources available for developers.

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

## Takeaways

- Snowpal offers a suite of APIs that serve as building blocks for developers to quickly build applications without reinventing the wheel.
- The APIs cover various functionalities such as project management, content management, classroom management, conversations, status updates, custom attribution, and access control.
- Snowpal provides different documentation formats, including Postman collections and developer documentation, to cater to the needs of both development and product teams.
- Developers can choose from multiple licensing and implementation options, including subscription-based licensing and integrating the APIs into their own infrastructure.

## Chapters

00:00 Introduction to Snowpal APIs

02:00 Overview of Snowpal API Suite

03:28 Different Documentation Formats

04:33 APIs as Building Blocks

05:29 Building Blocks API

07:12 Project Management API

08:31 Content Management API

10:06 Classroom API

10:52 Conversation API

11:59 Status API

13:06 Custom Attribution API

14:06 Access Control API

17:19 Licensing and Implementation

19:49 Extensive Documentation and Resources

## Video

{% embed https://youtu.be/UYRMmlx46lw %}

## Transcript

https://products.snowpal.com/api/v1/file/8ac8363f-f40d-451b-afa7-ac0101b4eb6b.pdf
Screen resumes in minutes
Tags: recruiting, ai, llm, discuss
Published: 2024-03-06 22:13:48

I worked for a largish startup (140+ people) , and the biggest pain point I personally experienced when recruiting was the sheer volume of resumes I had to sift through. Between career fairs and online applications, at one point we had 3000+ applications for 4 SWE positions. The engineering team was still fairly small (30 people) and very selective, so we would usually manually look for certain schools, a master's degree, interesting personal projects etc.

Unfortunately, at the scale we were at, it was virtually impossible to properly examine every resume. I was thinking about what would have helped me. I'm personally **very against** "resume ranking" because I think it can be extremely biased, but I do think resume filtering is helpful, especially for roles with more defined criteria. I built a quick tool to test this (https://distoresumes.streamlit.app/), and I'd love to hear thoughts / opinions.
Pro{gramadores}, pro{ductivos} y pro{crastinadores}.
Tags: csharp, latam, productividad, programador
Published: 2024-03-06 21:45:32

A las 08:30 de la mañana, Manuel el programador, se sienta frente a su estación de trabajo magnífica, bañado por luces de neón y abrazado por una silla hiperbólica, que como gorda enamorada lo abraza cálida y mullidamente. 

Manuel, se acomoda sus audífonos Coolmaster importados con calefacción y en su monitor amoled ultrawide con relación de aspecto 21:9, abre Youtube... teclea en su armatoste mecánico el nombre de alguna tecnología de frontend, con no más de dos meses de lanzada y comienza un periplo muy común hoy día y poco productivo, en que como conejo, salta entre 12 video tutoriales de los que solo ve un minuto, antes de ver algunos reels chistosos, para reírse un poquito, porque no todo es trabajo; recuerda completar dos horas de capítulos en Crunchyroll y aterriza en Notion, donde por supuesto... un hombre de su altura intelectual organiza sus ideas.

Manuel abre 10 pestañas de youtube con tutoriales de 14 horas cada uno del canal de FreeCodeCamp, después de los cuales, seguro alcanza la iluminación o lo llama Bill Gates para ofrecerle trabajo. 

A las 06:00pm Manuel no vio ninguno de los videos que dejó cargando, no abrió ni una vez Jira, no completó ninguna de sus tareas.

A las 6:15pm justo antes de estirarse adolorido por pasar tanto tiempo "trabajando", recibe un mail de su jefe... Manuel, esta botado por falta de productividad.
Learnt Next.JS in 1 week!! and here is GenAI Chat
Tags: webdev, javascript, programming, openai
Published: 2024-03-06 21:19:18

[GenAi Chat Repo Link](https://github.com/SP4RKiOP/genai-chatbot)
Hello, fellow developers! I'm excited to introduce GenAI Chat, a cutting-edge AI chatbot that's been designed to surpass the functionality of ChatGPT, offering a seamless conversational experience. But what sets GenAI Chat apart? Let's dive in!

🌟 Features

- AI-Powered Chatbot: Utilizes advanced AI models for generating contextually relevant responses.
- Semantic Services: Enhances understanding and context in conversations.
- Kernel Memory Implementation: A key feature under development to improve chatbot memory and context retention.
- Localhost LLM Support: Planned enhancement to work with locally hosted language models.

🛠️ Technologies Used

- **Backend**: .NET ASP Core Web API, LLM, Semantic Kernel, SignalR, WebSocket, MySQL, Azure OpenAI Models.
- **Frontend**: Next.js, TypeScript, Tailwind CSS.

📚 Why GenAI Chat?

While the project strives to be a perfect open-source clone of ChatGPT, it acknowledges the challenge of replicating the UI design and user experience perfectly. The project is driven by the desire to explore and understand the capabilities of AI chatbots, with a particular focus on semantic services and kernel memory implementation.

📣 Share the Love

If you find GenAI Chat useful, please give it a star on GitHub and share it with your network! Your support helps us continue to improve and expand the project.
How to begin web development.!
Tags: webdev, javascript, beginners, programming
Published: 2024-03-06 20:17:28

I wanted to start web development but I get mixed reviews on where to start. Some say start with CSS and then JavaScript. Some say HTML is just enough.
I am a first year engineering student in electronics and communication. There is no need of web development in my course but I would like to learn it for freelancing.
How to undo a git push
Published: 2024-03-06 20:10:25

Programmers, even the best, can make mistakes. They might upload unfinished code online by accident, to the wrong place, or even share private info.

**Mistake made:** Pushed unwanted code online

**Solution:** Use the `git reset` command to remove the unwanted changes

1. Use `git log` to view your commit history and find the bad commit (like a rewind button for your code history).
2. Run `git reset --soft <commit-hash>` to point your branch back to a specific commit.

**Two ways to "undo" a pushed commit:**

- `git reset --soft`**:** Keeps your changes and adds them to be committed later.
- `git reset --hard`**:** Completely removes the changes from your code.

**Pushing the fix (optional):**

After "undoing" the mistake, you can push the changes again using `git push --hard`. **Be careful!** This rewrites history online, so only do this if everyone agrees.
Reset IDs postgresql database - snippet
Tags: postgres, python, database, sql
Published: 2024-03-06 20:09:53

I created a copy of a database so i can mutate the data and try things out. I was getting an error on insert.

```
sqlalchemy.exc.IntegrityError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely)
(psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "customers_pkey"
DETAIL: Key (id)=(14) already exists.

[SQL: INSERT INTO customers (user_id, first_name, last_name, email, phone_number) VALUES (%(user_id)s, %(first_name)s, %(last_name)s, %(email)s, %(phone_number)s) RETURNING customers.id]
[parameters: {'user_id': 1, 'first_name': 'myname', 'last_name': '', 'email': 'myemail', 'phone_number': ''}]
(Background on this error at: https://sqlalche.me/e/14/gkpj)
```

Here is a snippet that helped me out.

```
DO $$
DECLARE
    l_table RECORD;
    column_exists BOOLEAN;
BEGIN
    FOR l_table IN SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name != 'alembic_version'
    LOOP
        -- Check if 'id' column exists in the table
        SELECT EXISTS (
            SELECT FROM information_schema.columns 
            WHERE table_schema = 'public' 
            AND table_name = l_table.table_name 
            AND column_name = 'id'
        ) INTO column_exists;

        -- Log the table name and whether the 'id' column exists
        RAISE NOTICE 'Processing table: %, ID column exists: %', l_table.table_name, column_exists;

        -- If 'id' column exists, set the sequence value and log the action
        IF column_exists THEN
            EXECUTE FORMAT('SELECT setval(pg_catalog.quote_ident(''%s_id_seq''), COALESCE(MAX(id), 1)) FROM %I', l_table.table_name, l_table.table_name);
            RAISE NOTICE 'Sequence set for table: %', l_table.table_name;
        ELSE
            RAISE NOTICE 'No ID column for table: %', l_table.table_name;
        END IF;
    END LOOP;
END;
$$;
```
Admin processes - The Twelve Factor App Methodology
Tags: beginners, tutorial, cloud, architecture
Published: 2024-03-06 20:00:00

Welcome to the final installment of our exploration of the Twelve Factors in Software Development. In Factor 12, we'll delve into the concept of Admin Processes. This factor highlights the importance of running administrative tasks as one-off processes and how it contributes to maintaining a healthy and efficient production environment.

## Admin Processes: Run Admin/Management Tasks as One-Off Processes
The Admin Processes factor advocates for treating administrative or management tasks as separate, one-off processes rather than bundling them with the main application. This approach ensures better isolation, security, and maintainability of tasks related to database migrations, data imports, or other administrative activities.

## Why It Matters
Admin processes often involve tasks that are not part of the regular application runtime but are crucial for maintaining the system. By running these tasks as separate processes, you reduce the risk of interfering with the main application's performance, enhance security, and ensure a clean separation of concerns.

## How to Implement
Identify tasks that are administrative in nature, such as database migrations, data imports, or configuration updates. Create standalone scripts or executables for these tasks, ensuring they can be executed independently of the main application. Trigger these admin processes as needed, either manually or through automation tools.

## Example in Action
Consider a scenario where you need to perform a database migration for your application. Instead of embedding the migration logic within the application code, create a separate script or command specifically for this task.

```bash
# Example of running a database migration on a Laravel app
php artisan migrate
```

By following the Admin Processes factor, you ensure that administrative tasks are executed in an isolated manner, minimizing the impact on the main application and contributing to a more maintainable and secure system.

## Woo-ho!

Congratulations! You've now explored all Twelve Factors that guide the development of modern, cloud-native applications. Implementing these factors can help you build applications that are scalable, maintainable, and well-suited for cloud environments.

Thank you for joining me on this journey through the Twelve Factors! If you have any further questions or topics you'd like to explore, feel free to ask. Happy coding!
Using Postgres with Docker on a Mac
Tags: postgres, apple, docker, ios
Published: 2024-03-06 19:39:39

When running PostgreSQL in a Docker container for testing or local development purposes, you can sometimes run into an issue where the postgres server on the host takes precedence over the postgres server running in the container.

You will see an error like "Role 'postgres' does not exist" when you try to connect to the server if that is the case.

This can happen when you run `postgresql` as a service through [Homebrew](https://brew.sh/).

The solution is to check which processes are running on port 5432, stop the service and then clean up any remaining processes:

```shell
brew services stop postgresql
lsof -i :5432
kill -9 <pid>
```

Here's what the output will look like:

```
% brew services stop postgresql
Stopping `postgresql@14`... (might take a while)
==> Successfully stopped `postgresql@14` (label: homebrew.mxcl.postgresql@14)

% lsof -i :5432
COMMAND     PID    USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
postgres    664 rudolfo    8u  IPv6 0xda1da9a9441be1cf      0t0  TCP localhost:postgresql (LISTEN)
postgres    664 rudolfo    9u  IPv4 0xda1da9a47826a65f      0t0  TCP localhost:postgresql (LISTEN)
com.docke 44908 rudolfo  244u  IPv6 0xda1da9a47921f1cf      0t0  TCP *:postgresql (LISTEN)

% kill -9 664

% lsof -i :5432
COMMAND     PID    USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
com.docke 44908 rudolfo  244u  IPv6 0xda1da9a47921f1cf      0t0  TCP *:postgresql (LISTEN)
```

After that, any connection to `localhost:5432` will be to the postgres server running within the Docker container.

[This article was helpful in understanding the underlying issue: "How to Fix the “Role ‘Postgres’ Does Not Exist” Error When Deploying PostgreSQL Docker Container"](https://medium.com/@chunkang.wong94/how-to-fix-the-role-postgres-does-not-exist-error-when-deploying-postgresql-docker-container-430e903b97fd#:~:text=ChunKang%20Wong%20%7C%20Medium-,How%20to%20Fix%20the%20%E2%80%9CRole%20'Postgres'%20Does%20Not%20Exist,When%20Deploying%20PostgreSQL%20Docker%20Container&text=TL%3B%20DR%3A%20First%20check%20port,command%20sudo%20kill%20%5Bpid%5D%20.)

Another option is to [map the published Docker ports to a higher port range](https://docs.docker.com/network/#published-ports) to avoid this issue:

```sh
docker run -it --rm -p 15432:5432 postgres:16
```

<small>Cover image by <a href="https://unsplash.com/@hdbernd?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Bernd 📷 Dittrich</a> on <a href="https://unsplash.com/photos/blue-and-yellow-plastic-crates-psf4UVSTgCY?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a></small>