teleren/devto huggingface dataset:
comandos GIT más utilizados
Tags: git, codenewbie, programming, spanish
Published: 2023-11-15 18:14:14

Aunque hay cientos de comandos diferentes de Git, hay unos pocos que se utilizan con más frecuencia, entre ellos:

**git config**: Este comando se utiliza para establecer la configuración específica de usuario o de repositorio. Puedes configurar tu nombre de usuario, dirección de correo electrónico, colores de interfaz, entre otras opciones.

```bash
$ git config --global user.name "Tu Nombre"
$ git config --global user.email "tu@email.com"
```

**git clone**: Este comando se utiliza para clonar un repositorio existente en un nuevo directorio. Descarga una copia de un repositorio remoto, incluidos todos los historiales y ramas.

```bash
$ git clone <URL_del_repositorio>
```

**git init**: Este comando se utiliza para iniciar un nuevo repositorio Git. Crea un nuevo directorio y configura los archivos de control de versiones de Git.

```bash
$ git init
```

**git status**: Muestra el estado actual del repositorio. Te dice qué archivos han cambiado, están pendientes de ser confirmados o no están siendo rastreados por Git.

```bash
$ git status
```

**git push**: Este comando se utiliza para enviar los cambios locales al repositorio remoto. 

```bash
$ git push <nombre_remoto> <rama_local>
```

**git add**: Agrega cambios al área de preparación (staging area). Permite seleccionar qué cambios se incluirán en la próxima confirmación.

```bash
$ git add <nombre_archivo>
```

**git commit**: Registra los cambios confirmados en el repositorio. Crea un punto de control con un mensaje que describe los cambios realizados.

```bash
$ git commit -m "Mensaje descriptivo"
```

**git branch**: Muestra, crea o borra ramas. También se puede usar para cambiar entre ramas.

```bash
$ git branch                    # Muestra las ramas
$ git branch <nombre_rama>      # Crea una nueva rama
$ git branch -d <nombre_rama>   # Borra una rama
```

Estos son comandos básicos y muy utilizados en Git. Cada uno de ellos tiene opciones adicionales que puedes explorar en la documentación oficial de Git o mediante la ayuda integrada (`git help <comando>`).
Developing a group video calling web-app AGAIN!
Tags: webdev, learning, react, webrtc
Published: 2023-11-15 18:08:01

Approximately a year ago, I developed "Sonic Meet," a group video chat web application as part of a college project. At that time, I was new in React and development in general. Still, I managed to achieve what I aim for, and I was proud of the achievements. Reflecting on those early days, I can openly admit to the learning curve, the missteps, and the occasional shortcuts taken.

Now, let's jump to today, where my strong desire to learn is driving me to explore complex things like WebRTC and sockets for Sonic Meet V2. This journey isn't just about adding new stuff; it's also about admitting my past mistakes and using them as steps to grow personally and professionally.

This project isn't just about making a software or a product. It's like an ongoing adventure where I'm discovering more about myself and getting better at what I do. I'd love for you to be a part of this journey, following my updates on social media and reading interesting blog posts on Dev.to and my website. Let's learn and grow together!

Connect with me:

Sonic Meet v1 Repo: [GitHub Repository](https://github.com/sahilverma-dev/sonic-meet)
Sonic Meet v2 Repo: [GitHub Repository](https://github.com/sahilverma-dev/sonic-meet-v2)
GitHub: [sahilverma-dev](https://github.com/sahilverma-dev/)
Twitter (𝕏): [sahilverma_dev](https://twitter.com/sahilverma_dev)
LinkedIn: [sahilverma-dev](https://www.linkedin.com/in/sahilverma-dev/)
My website: [sahilverma.dev](https://sahilverma.dev/)
PostgreSQL vs SQL Server
Published: 2023-11-15 18:02:51

People frequently contrast SQL and PostgreSQL to decide which is preferable for their data engineering project. The most crucial thing to keep in mind is that there isn’t a single database that will be a suitable fit for every project requirement, therefore it’s necessary to know which option will be most effective for your particular use case. So, in order to help you better grasp the differences between SQL and PostgreSQL and determine which is most appropriate for your needs, this blog compares PostgreSQL and SQL Server on basic level.

**What is SQL Server?**
SQL Server is a top RDBMS built on top of SQL and created by Microsoft. It is used to organize and store data for a variety of organizational use cases, including business intelligence, transaction processing, data analytics, and machine learning services. Without having to duplicate data storage in a database, SQL Server’s row-based table structure enables you to link relevant data components from other tables.

**What is PostgreSQL?**
The PostgreSQL License governs the use of PostgreSQL, an open source object-relational database management system. It features complex SQL capabilities, such as foreign keys, sub-queries, and triggers, and supports both relational (SQL) and non-relational (JSON) data types. Additionally, PostgreSQL is quite expandable, enabling you to create unique functions and construct data types.

Here are some of the main factors on the basis of which both can be compared.

**Platform Support:**

**PostgreSQL** is an open source platform that works with the majority of the top operating systems. Numerous operating systems, including Linux, macOS, Windows, BSD, and Solaris, are capable of hosting it. It can also be set up on Kubernetes or Docker containers.
However, **SQL Server** only supports Microsoft Windows, Microsoft Server, and Linux as operating systems.

**RDBMS vs. ORDBMS:**

PostgreSQL is an ORDBMS which means that, similar to Object-Oriented programming languages, objects, classes, and inheritance are supported by PostgreSQL. It can handle novel data formats such as video, audio, and image files.
RDBMS like SQL Server is based on the relational model of data and is well-suited for handling traditional application activities like data processing and management.

**Syntax and language:**

Both SQL Server and PostgreSQL implement their own dialects of the SQL language in addition to using the mainstream SQL query language.

Transact-SQL, sometimes known as T-SQL, is the language used by SQL Server. It offers all the same capability as SQL and includes a number of exclusive programming extensions. It is limited, offering support for Java, JavaScript (Node.js), C#, C++, PHP, Python, and Ruby only.
In PostgreSQL, you may combine SQL with its own procedural language, PL/pgSQL, which enables you to add control structures to SQL as well as functions and trigger operations. It also supports Python, PHP, Perl, Tcl, Net, C, C++, Delphi, Java, JavaScript (Node.js), and more.

Apache-Age:-https://age.apache.org/
GitHub:-https://github.com/apache/age
How to Make OpenAI API to Return JSON
Tags: openai, ai, javascript, howto
Published: 2023-11-15 18:02:06

During OpenAI's dev day, one of the [major announcements](https://openai.com/blog/function-calling-and-other-api-updates) was the ability to receive a JSON from the chat completion API. However, there aren't a few clear examples of how to do this as most examples focus on function calls.

Our objective is straightforward: given a query, we want to receive an answer in JSON format.

How can we achieve this?

There are three crucial steps.

### Modify your prompt

Your prompt must explicitly specify that the response should be in JSON format and you need to define the structure of the JSON object.

```
Given this work history, what's the overall years of experience?
Work history includes start and end date (or present), title, and company name.
If the end date is "Present", use the current date. Today is November 2023.
Return the answer in JSON format with the field "experienceInMonths"
and value as a number.
```
Pay attention to the last sentence of the prompt.

### Pass response_format

When calling the API, specify the response_format.

```jsx
const res = await this.openAI.chat.completions.create({
  model: 'gpt-3.5-turbo-1106',
  temperature: 0.0,
  top_p: 1,
  frequency_penalty: 0,
  presence_penalty: 0,
  response_format: {
    type: 'json_object', // specify the format
  },
  messages: [
    { role: 'system', content: systemPrompt },
    { role: 'user', content: workHistory },
  ],
});

```

It's crucial to modify the prompt as well. Just changing the response type to JSON might result in a JSON of an arbitrary structure.

See this comment from the OpenAI API:

```markdown
**Important:** when using JSON mode, you **must** also instruct the model to
produce JSON yourself via a system or user message. Without this, the model may
generate an unending stream of whitespace until the generation reaches the token
limit, resulting in increased latency and the appearance of a "stuck" request.
Also note that the message content may be partially cut off if
`finish_reason="length"`, which indicates the generation exceeded `max_tokens`
or the conversation exceeded the max context length.

```

### Parse JSON response

Once we receive the response, the content is still text (string type), but we can now parse it as JSON.

```jsx
const content: string = get(res, 'choices[0].message.content');
try {
  return JSON.parse(content)['experienceInMonths'];
} catch (error) {
  this.logger.warn('Calculating total experience for a member did not work');
  return -1;
}

```

It's good practice to wrap JSON.parse in a try...catch statement in case we receive an invalid JSON structure.

You can find a [playground example here](https://platform.openai.com/playground/p/JP5k7UGrVtfbZAk8RyIkgEgi?mode=chat).
TERRAFORM COMANDOS BASICOS
Tags: terraform, aws, azure, gcp
Published: 2023-11-15 17:54:04

**terraform version**

```
$ terraform version
Terraform v1.0.2
```

**terraform init**

```
$ terraform init
```

También puede cambiar los detalles del backend usando la opcion -backend-config. -reconfigure reconfigurará el backend, ignorando cualquier configuración guardada.

```
$ terraform init -backend-config=PATH/TO/CONFIGURATION_FILE -reconfigure
```

**terraform plan**

Verificará los archivos de configuración (básicamente todos los archivos en el directorio) y le mostrará los elementos o cambios que se van a realizar en la infraestructura o los recursos de destino

```
$ terraform plan
```

Opcionalmente, puede guardar el plan en un archivo

```
$ terraform plan -out plan.out
```

**terraform apply**

apply hará la operación real en los recursos de infraestructura. apply mostrará el plan y ejecutara las acciones en detalle.

```
$ terraform apply
```

apply le pedirá su confirmación para proceder con los cambios. Puede utilizar -auto-approve para la confirmación automática.

```
$ terraform apply -auto-approve
```

Puede usar -target la opción para apuntar a recursos, módulos o colecciones de recursos específicos.

```
$ terraform apply -target="aws_ec2_object.objects"
```

Puede pasar diferentes variables o archivos de variables.

```
$ terraform plan -var="instancetype=t2.medium"
$ terraform plan -var-file="dev.tfvars

$ terraform apply -var="instancetype=t2.medium"
$ terraform apply -var-file="dev.tfvars
```

**terraform destroy**

destroy eliminará todos los recursos pero con confirmación.

```
$ terraform destroy
```

Puede crear un plan de eliminación como se muestra a continuación.

```
$ terraform plan –destroy
```

Usa el -target para destruir un recurso específico.

```
$ terraform destroy -target="aws_ec2_object.objects"
```

**terraform validate**

Puede verificar la sintaxis y validar la configuración usando validate.

```
$ terraform validate
Success! The configuration is valid.
```

**terraform providers**

Puede ver los proveedores en uso por los módulos y configuraciones en sus archivos de Terraform.

```
$ terraform providers

Providers required by configuration:
.
└── provider[registry.terraform.io/hashicorp/gcs]
```

**terraform fmt**

Reescribe todos los archivos de configuración de Terraform a un formato canónico con la sangría y el estilo adecuado. (Los archivos JSON (.tf.json o .tfvars.json) no se modifican).

```
$ terraform fmt
```

**Que sigue**

- https://www.terraform.io/cli/commands
- https://acloudguru.com/blog/engineering/the-ultimate-terraform-cheatsheet
- https://k21academy.com/terraform-iac/terraform-cheat-sheet/
Unleashing Graph Analytics with Cloud Express
Published: 2023-11-15 17:52:25

In the era of big data, understanding and analyzing complex data relationships becomes a critical part of business success. To meet this need, Bitnine Global Inc., a leading company in Graph database R&D, has launched a cutting-edge cloud-based graph visualization solution called AG Cloud Express.

AG Cloud Express, a free online database service based on AgensGraph, was launched in response to the growing demand for cloud services across the globe. It is Bitnine's calculated response to the expanding market demands for cloud services as well as the rise in demand for those services globally.

The ultimate goal of AG Cloud Express is to make graph analysis more accessible to anyone. It is intended to be easily used by all users, regardless of their level of technical expertise. This dedication to user accessibility exemplifies Bitnine's mission to provide the accessibility and affordability of advanced data analytics for all.

One of the standout features of AG Cloud Express is its advanced graph visualization capabilities. Users can explore their data in a graph format, which can often reveal insights that would be hard to spot in more traditional data views. Graph visualization can help users to understand complex relationships between entities and identify patterns that may otherwise remain hidden.

**Conclusion**
In summary, AG Cloud Express represents a significant step forward in the field of cloud-based graph analytics. By offering a free, accessible platform based on the powerful AgensGraph technology, Bitnine is making it easier than ever for users to harness the power of graph analytics and unlock the insights hidden in their data. Whether you're a seasoned data scientist or a curious beginner, AG Cloud Express provides a valuable tool for exploring and understanding complex data relationships.

Apache-Age:-https://age.apache.org/
GitHub:-https://github.com/apache/age
Day 16 Final Year Project Work and DBMS
Published: 2023-11-15 17:40:39

Yah I started DBMS today, just revision. I had a couple of hard conversations between the placement coordinator and my father. I revised my placement strategy to focus more on aptitude, DBMS and CN/OS. 


I will do OOPS and DBMS in 2 days each. Cool. A lot of work ahead, challenging work BUT I will take on this challenge and get it done
The State of Serverless GPU Part -2
Tags: serverless, gpu, machinelearning, llm
Published: 2023-11-15 17:30:00

In the evolving landscape of AI Infrastructure, Serverless GPUs have been a game changer. Six months on [from our last guide,](https://news.ycombinator.com/item?id=35738072) which sparked multiple discussions & created more awareness about the space, we've returned with fresh insights on the state of "True Serverless" offerings and I am here sharing performance benchmark & cost effectiveness analysis for [Llama 2-7Bn](https://huggingface.co/meta-llama/Llama-2-7b-hf) & [Stable Diffusion 2-1](https://huggingface.co/meta-llama/Llama-2-7b-hf) model.  

📊 **Performance Testing Methodology:** We put the spotlight on popular serverless GPU contenders: Runpod, Replicate, Inferless, and Hugging Face Inference Endpoints, specifically testing for:

**1. Cold Starts:** Varied across platforms. Latency minus inference time, represents the delay due to initializing a dormant Serverless function.

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

**2. Variability:** We don't just trust one-off results; we test over 5 days to ensure stability. We observed differences in consistency.   

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

**3. Autoscaling:** Simulated traffic peaks to assess how well platforms scale under pressure ,we tried the simulation on what happens when we receive 200 requests with a concurrency of 5. Not all platforms could manage linear scaling efficiently, leading to varied latencies under load.   

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

**4. Decoding Serverless Pricing:**

4.1 We modeled a scenario where you process 1,000 documents daily with the Llama 2 7Bn model. Here's the TL;DR on costs:

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

4.2 For the image processing (stable diffusion) use case, only the number of processed items and cold start times differ. Instead of 1,000 documents, we're considering 1,000 images daily.

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

**🔮 Overall Insights:** The serverless GPU sector is advancing, notably in reducing cold-start times and improving cost efficiency. However, the best choice depends on specific use cases. While AWS Lambda is a leader in general serverless solutions, specialized tasks, particularly those GPU-intensive, may find better options elsewhere.

**_Detailed Blog link:_** https://www.inferless.com/learn/the-state-of-serverless-gpus-part-2

This analysis aims at shedding light on the serverless GPU arena. We welcome feedback and aim for precision in our findings.
Maximum Element After Decreasing and Rearranging
Tags: java, algorithms
Published: 2023-11-15 17:26:53

You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:

    The value of the first element in arr must be 1.
    The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x.

There are 2 types of operations that you can perform any number of times:

    Decrease the value of any element of arr to a smaller positive integer.
    Rearrange the elements of arr to be in any order.

Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.

 

Example 1:

Input: arr = [2,2,1,2,1]
Output: 2
Explanation: 
We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1].
The largest element in arr is 2.

```java
class Solution {
    public int maximumElementAfterDecrementingAndRearranging(int[] arr) {
        Arrays.sort(arr);
        arr[0] = 1;
        
        for(int i = 1; i < arr.length; i++){
            if(arr[i] - arr[i-1] > 1){
                arr[i] = arr[i-1] + 1;
            }
        }
        return arr[arr.length-1];
    }
}
```

Reference : https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/
🏆 Open Source Heroes
Tags: opensource, showdev
Published: 2023-11-15 17:25:00

Hey there 👋

Open Source Heroes is a new platform to explore the open source ecosystem data and trends: https://opensource-heroes.com

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

You can find different kind of lists, rankings and collections:

- Top [Contributors](https://opensource-heroes.com/contributors): with filters by language and/or country
- Top [Users](https://opensource-heroes.com/developers)/[Organizations](https://opensource-heroes.com/organizations) rankings
- Top [Repositories](https://opensource-heroes.com/repositories)
- Reviews (like Google Reviews or Truspilot, but for OSS projects)
- [Trending](https://opensource-heroes.com/discover): most starred repos by language and different date ranges (30 days, 90 days, ...)
- [Awesome](https://opensource-heroes.com/awesome) lists: with extra info like stars, last update and license
- Embeddable stars history for each repo
- [Country/city stats](https://opensource-heroes.com/countries): top contributors, cities with more open source contributors, top rank for each language, compare with other countries
- "Made in": a page for each country with the Top 100 repos (also filterable by language, so you can filter out things like: Top 100 Python projects from Spain: https://opensource-heroes.com/made-in/spain?language=Python)

Hope you like the platform! Any constructive 🙏 feedback is really appreciated. We want to build a platform that allows everybody to easily explore the open source world! 

Under the hood, the system is built ⚙️ with: Rails, PostgreSQL, Redis, Meilisearch and Turbo/Hotwire. And of course the GitHub API, from where we fetch all this data. 

Happy exploring!
Mejores prácticas para optimizar el rendimiento de aplicaciones web: Estrategias probadas
Published: 2023-11-15 17:10:53

En el mundo del desarrollo web, el rendimiento de las aplicaciones es crucial para ofrecer una experiencia excepcional a los usuarios. En este artículo, compartiré estrategias probadas y consejos prácticos para optimizar el rendimiento de las aplicaciones web. Estas técnicas no solo mejorarán la velocidad de carga, sino que también mejorarán la experiencia del usuario.
Optimización de imágenes y recursos estáticos: Exploraremos técnicas para reducir el tamaño de las imágenes y archivos estáticos sin comprometer la calidad, utilizando formatos eficientes y herramientas de compresión.

1. Optimización de imágenes y recursos estáticos:

La optimización de imágenes es crucial para mejorar el rendimiento. Exploraremos técnicas como la compresión sin pérdida utilizando herramientas como TinyPNG o ImageOptim. También discutiremos la selección de formatos de imagen adecuados (como WebP o AVIF) para maximizar la calidad con el menor tamaño de archivo posible.

Además, abordaremos la importancia de la entrega de recursos estáticos a través de CDNs (Content Delivery Networks) para reducir la latencia y mejorar los tiempos de carga.

2. Caché y almacenamiento local:

Explicaremos cómo implementar estrategias de almacenamiento en caché tanto en el lado del cliente como en el servidor. Esto incluirá el uso de encabezados de caché HTTP para permitir una mayor duración de caché para recursos estáticos y la utilización de almacenamiento local en el navegador para almacenar datos que pueden ser accedidos rápidamente.

3. Minificación y concatenación de archivos:

Detallaremos los beneficios de minificar y combinar archivos CSS y JavaScript para reducir el número de solicitudes HTTP. Mostraremos ejemplos de herramientas como Webpack o Gulp que automatizan este proceso, así como técnicas para evitar problemas comunes que pueden surgir al combinar archivos.En esta página puedes encontrar un buen ejemplo de minificación de contenido [trashtucada.es](https://trashtucada.es/)

4. Carga diferida y asincrónica:

Abordaremos cómo implementar la carga diferida de recursos no críticos, como imágenes que están fuera del viewport inicial o scripts que no son necesarios para la renderización inicial. Además, explicaremos la carga asincrónica de recursos mediante atributos como async y defer en las etiquetas de script.

5. Monitoreo y ajuste continuo:

Resaltaremos la importancia de utilizar herramientas de monitoreo como Google Lighthouse o GTmetrix para evaluar el rendimiento y la usabilidad de la aplicación. Explicaremos cómo interpretar los resultados y realizar ajustes basados en las métricas obtenidas para mejorar continuamente el rendimiento.

Optimizar el rendimiento de las aplicaciones web es una tarea continua. Al implementar estas estrategias y realizar ajustes iterativos, podrás ofrecer aplicaciones más rápidas y eficientes para tus usuarios, mejorando así la satisfacción y el compromiso.