teleren/devto huggingface dataset:
GraphQL e Node.js: GraphQL e Node.js: Construindo APIs Poderosas
Tags: graphql, javascript, node, webdev
Published: 2024-03-18 19:34:09

## Introdução

GraphQL representa uma abordagem poderosa e flexível para APIs, permitindo que clientes solicitem exatamente os dados de que precisam, diferentemente das APIs REST tradicionais, que retornam dados fixos e pré-definidos. Neste artigo, exploraremos como configurar um servidor GraphQL com Node.js, oferecendo um exemplo prático de como criar e consultar uma API GraphQL.

## Por que GraphQL?

Antes de mergulharmos na implementação, vamos entender as vantagens do GraphQL:

- **Flexibilidade**: Os clientes podem buscar exatamente o que precisam, nem mais, nem menos.
- **Eficiência na Comunicação**: Reduz o over-fetching e under-fetching de dados.
- **Desenvolvimento Rápido**: Facilita a evolução da API sem versões múltiplas.
- **Introspecção**: Possui capacidades de auto-documentação.

## Configurando o Ambiente

Certifique-se de ter o Node.js instalado. Inicie um novo projeto Node.js e instale as dependências necessárias:

```bash
mkdir graphql-api
cd graphql-api
npm init -y
npm install graphql express express-graphql
```

## Criando um Servidor GraphQL

Vamos começar configurando um servidor GraphQL simples com Express e `express-graphql`, um middleware que facilita a criação de um servidor GraphQL.

### Definindo o Schema

Em um arquivo chamado `schema.js`, definimos o schema GraphQL da nossa API:

```javascript
const { buildSchema } = require('graphql');

const schema = buildSchema(`
  type Query {
    message: String
  }
`);

module.exports = schema;
```

### Implementando o Resolver

Os resolvers são responsáveis por retornar os dados para as queries GraphQL. No nosso caso, vamos retornar uma mensagem simples:

```javascript
const root = {
  message: () => 'Hello, GraphQL!',
};

module.exports = root;
```

### Configurando o Servidor Express

Agora, vamos configurar o servidor Express para usar GraphQL:

```javascript
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema');
const root = require('./root');

const app = express();

app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));

app.listen(4000, () => console.log('Servidor rodando em http://localhost:4000/graphql'));
```

## Testando a API

Com o servidor rodando, você pode testar a API acessando `http://localhost:4000/graphql` no navegador. Use o GraphiQL, uma interface gráfica integrada, para executar a seguinte query:

```graphql
{
  message
}
```

Você deverá receber a resposta:

```json
{
  "data": {
    "message": "Hello, GraphQL!"
  }
}
```

## Conclusão

Este exemplo básico demonstra como configurar um servidor GraphQL com Node.js, desde a definição do schema até a implementação dos resolvers. GraphQL oferece uma alternativa robusta e flexível às APIs REST, possibilitando consultas eficientes e específicas que são ideais para aplicações modernas web e mobile. À medida que você expande sua API GraphQL, pode explorar conceitos mais avançados, como mutações, tipos personalizados e integração com bancos de dados.
Embracing the Tech Future: My Transformation Journey with ATLP.
Tags: andela, coding, prince, javascript
Published: 2024-03-18 19:20:28

Two months ago, I embarked on a life-changing journey that accelerated my technical skill set and bolstered my vision of becoming a world-class software engineer: the Andela Technical Leadership Program (ATLP). I first heard about ATLP through a tech community event in Kigali at the end of 2022. As I listened to an alumnus share their story, I was captivated by the intensive, hands-on experience that promised a blend of technical and soft skill development.


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

Joining ATLP wasn't just a decision, but a commitment to my future. I didn't have any coding experience, but I was always eager to dive into the depths of coding and emerge as a disciplined coder and a technical leader. I saw ATLP as the perfect launchpad to turn my passion for technology into a career that could shape the digital landscape of Rwanda and beyond, so I decided to apply to ATLP in September 2023, and after being admitted, I officially started the program on January 22, 2024.

In these fascinating two months, my coding abilities have grown exponentially. HTML and CSS were my gateways into the intricate world of web development, allowing me to craft the structure and aesthetics of web pages with finesse. JavaScript then brought my designs to life, introducing me to the dynamic capabilities of web applications. The real game-changer, however, has been mastering the backend with NodeJS, Express JS, and MongoDB. Testing, documenting, and implementing APIs (using tools like Postman and libraries like Jest, Swagger, and Mocha) was somehow harsh but worth it. Designing server-side logic and managing databases has unveiled the robust architecture that powers our internet. These skills are the building blocks I am using to forge my path as a well-versed full-stack developer.

Once my nine-month tenure at ATLP concludes, my roadmap includes diving into the fintech sector. This industry's blend of finance and technology excites me, and I plan to contribute by developing secure, innovative solutions that can drive economic growth. Additionally, leveraging the apprenticeship program, I aspire to lend my expertise to businesses, further honing my skills in a real-world environment.

To those considering ATLP, step in with an eager mind and a resilient heart. This program is rigorous but rewarding, designed to teach and transform. The landscape of technology is vast and can seem discouraging, but with ATLP as your compass, even if you don't have any previous coding experience, you can navigate it successfully. Pursue excellence, embrace collaboration, and let us innovate for a brighter future.

In conclusion, as I venture through ATLP, I am more convinced than ever that the future is for those who build it. One thing to keep in mind is 

> You didn't get this far to only get this far
. Let's make it one line of code at a time.
Just a simple bash menu
Tags: bash, webdev
Published: 2024-03-18 19:08:03

Hi there 🙂 I now work with so many complex tools on the command line. That's why I developed a shell menu for each tool as a kind of mnemonic. It's super easy to use. I have put the basic script and a few applications for Git and Kubernetes online cause I thought it might be of interest to the community 🤓

https://github.com/nschlimm/EasyKey.shellmenu

I would be happy to hear your opinion, comments and criticism. If you like it, I would of course be very happy about a star on Github 🙂 Ok, so long - Niklas ✌🏻
Combining Nix with Terraform for better DevOps
Tags: terraform, nix, programming
Published: 2024-03-18 19:07:30

An investment in creating the best software in the world will still go to waste if the infrastructure it runs on isn’t well-managed. At Stack Builders, our mission is to push the boundaries of the software industry through quality, pragmatic solutions that bring to life our client's vision, and one way we are doing this is to leverage our training and staff experience with functional programming to make DevOps better.

In that light, we’re thrilled to announce the release of [nixpkgs-terraform](https://github.com/stackbuilders/nixpkgs-terraform/)! This Nix project significantly enhances the flexibility and control of your Terraform environment, making its installation and management declarative and reproducible. This is largely thanks to Nix and its unique capabilities for precisely pinning packages to a version, ensuring its consistency across different environments. Forget about writing documentation on environment setup - just use one of the provided [templates](https://github.com/stackbuilders/nixpkgs-terraform/tree/main/templates) to bootstrap your Terraform installation and get the whole team on the same version with minimal manual intervention.

No need for deep knowledge of Nix either - just keep adding tools to your template of choice to craft a reproducible, declarative, and portable development environment for everyone on the project so that you can focus on what matters.

At Stack Builders, our DevOps/SRE team uses nix-shells to install all of the necessary tooling to work on various Infrastructure-as-Code projects across the board. However, while nix-shells are useful for creating portable development environments, more fine-grained control over the different Terraform versions was lacking. We've taken inspiration from [nixpkgs-python](https://github.com/cachix/nixpkgs-python) and [nixpkgs-ruby](https://github.com/bobvanderlinden/nixpkgs-ruby), and we're grateful for the paths they've paved.

We’ve noticed that some users have been asking about how to use older versions of Terraform in their Nix setups [[1](https://discourse.nixos.org/t/use-a-specific-version-of-terraform-in-a-nix-shell/27880), [2](https://github.com/NixOS/nixpkgs/issues/218617)]. This is an example of the diverse needs of people and the importance of maintaining backward compatibility. We hope that nixpkgs-terraform will be a useful tool for these users.

The design of nixpkgs-terraform follows a bottom-up approach, making it more approachable for newcomers. We hope this will empower everyone to take their Nix experience to the next level!

Looking forward to your feedback and contributions. Happy Nixing!

Don't forget to subscribe to our [newsletter](https://www.stackbuilders.com/blog/).
Just a simple bash menu
Tags: bash
Published: 2024-03-18 19:07:02

Hi there 🙂 I now work with so many complex tools on the command line. That's why I developed my own shell menu for each tool as a kind of mnemonic. It's super easy to use. I have put the basic script and a few applications for Git and Kubernetes online cause I thought it might be of interest to the community 🤓

https://github.com/nschlimm/EasyKey.shellmenu

I would be happy to hear your opinion, comments and criticism. If you like it, I would of course be very happy about a star on Github 🙂 Ok, so long - Niklas ✌🏻
Code for Tic-Tac-Toe: Codecademy Portfolio Project
Published: 2024-03-18 18:58:09

I created a tic-tac-toe game for Codecademy's CS 101 Introduction to Programming. The task was to create a program that can be played with family and friends. The project objectives were as follows:
- Build a terminal program using Python
- Add at least one interactive feature using input()
- Use Git version control
- Use the command line and file navigation
- Write a technical blog post on the project

The program starts with creating a tic-tac-toe board. Each square is given a number 1 through 9. Player 1 can enter a number to place an X in the chosen square. Then the computer places a O in a random square. After each play, the program checks if either player has three in a row. If there is, someone wins. Otherwise, the game continues until all the squares are full and the game ends in a tie. 

The following is a link to the code on GitHub:
https://github.com/mjp286/tic_tac_toe.git

This is a basic code for a simple game, but it was fun to do. It's a good way to practice python. Give it a try and let me know what you think.
Shallow Copy vs. Deep Copy in Javascript
Tags: javascript, shallowcopy, deepcopy, typescript
Published: 2024-03-18 18:57:06

JavaScript is a high-level, dynamically typed client-side scripting language.


- **Shallow Copy** : In JavaScript, a shallow copy refers to creating a new object or array that has an exact copy of the top-level elements of the original object or array.In simple words, a reference variable mainly stores the address of the object which is pointing to the original object or array.

A **shallow copy** can be achieved using the **spread operator (…)** or using **Object.assign()**:

```
const originalObject = { name: 'John', age: 22, hobbies: ['reading', 'painting'] };

// Shallow copy using Object.assign()
const copiedObject = Object.assign({}, originalObject);

// Modifying the copiedObject
copiedObject.name = 'Johnny';
copiedObject.hobbies.push('coding');

console.log(originalObject); // { name: 'John', age: 22, hobbies: ['reading', 'painting', 'coding'] }
console.log(copiedObject); // { name: 'Johnny', age: 22, hobbies: ['reading', 'painting', 'coding'] }
```

- **Deep Copy** : In JavaScript, a deep copy refers to creating a new object or array that is completely independent of the original object or array. It means that all levels of the object or array, including nested objects or arrays, are duplicated, and changes made to the copy will not affect the original.

A **deep copy** can be achieved using **JSON.parse()** + **JSON.stringify()**

```
const originalObject = { name: 'John', age: 22, hobbies: ['reading', 'painting'] };

// Deep copy using JSON.stringify() and JSON.parse()
const copiedObject = JSON.parse(JSON.stringify(originalObject));

// Modifying the copiedObject
copiedObject.name = 'Johnny';
copiedObject.hobbies.push('cooking');

console.log(originalObject); // { name: 'John', age: 22, hobbies: ['reading', 'painting'] }
console.log(copiedObject); // { name: 'Johnny', age: 22, hobbies: ['reading', 'painting', 'cooking'] }

```


**Shallow Copy vs Deep copy**

**Shallow Copy**

-  Shallow copy creates a new object and copies the references of the original object's elements into the new object.
- The new object references the same memory locations as the original object for its elements.
- If any changes are made to the shared elements in the new or original object, the changes will be reflected in both.

**Deep copy**

- Deep copy creates a new object and duplicates all the elements of the original object, including any nested objects or arrays.
- The new object has its own memory locations for all its elements, ensuring that changes made to the copy do not affect the original.


Happy coding!
Blending in with Pure-Blend
Tags: node, javascript, typescript, coding
Published: 2024-03-18 18:47:18

Going for a 1000 walk, floating with 1000 birds, Seeing 1000 things. Now that's blending in 🧬, becoming a part of something.

By far, the underrated package that will take a 1000 👻 years to be discovered. But good it is? That is for you to test out and be impressed!

This post won't be long, I leave the curiosity to you. 🤯

Here is some small feat to know about the package:

- It is really a blend in package for node.js express
- Dedicates itself fully on middleware becoming the middleman
- Simply executes as configured
- Hide all the 🗑 and keeps your code neat

Settle for this **pure-blend**. 100% freshly squeezed package written in typescript, supporting both JavaScript and TypeScript. From the valley of the Node.js and Express technologies. Early wind, that blew so hard, the early bird only had 100 gram of mass and skipped the fattest worm 🤣.

Check the package out from [npm](https://www.npmjs.com/package/pure-blend)

[![NPM](https://nodei.co/npm/pure-blend.png)](https://nodei.co/npm/pure-blend/)

Get ahead of time. Teleport to your Neo Matrix and reduce the workload. 

1000 likes, 1000 types, 1000 more to drop.

I hope you like the package and find it useful. 

Don't forget to do the basics. Like, share, comment and reach out to the Github [Repo](https://github.com/Ethern-Myth/pure-blend) to support and like the project.

As always 🏄‍♂️ out.
BUN
Tags: beginners, programming, tutorial
Published: 2024-03-18 18:41:59

**What is Bun?**

Bun is a next-generation package manager built with simplicity and speed in mind. Bun was created by a company named Oven, but the real mastermind Jarred Sumner created it as a Node.js drop in alternative. Bun employs JavaScriptCore as its JavaScript engine, as opposed to V8 used by Deno and Node.js.

**Key features:**
 Lightweight and Fast:
 Bun prides itself on its lightning-fast performance. Node.js and Deno use Chrome's V8 javascript engine. Bun decided on using Javascript core engine which powers browsers such as safari. Bun itself is written in Zig, a low-level programming language that uses manual memory management and native threading to support multiple computations are happening at the same time. The end result is a lightweight runtime with a reduced memory footprint, faster start-up times, and up to four times the speed of Node.JS and Deno. 

**Dependency Resolution**
 Bun automatically resolves version mismatches and installs the most compatible versions of dependencies, saving developers from headaches. It also helps prevent common dependency conflicts, making it easier to manage your project’s dependencies over time. By reducing the amount of time that developers spend waiting on test suites to run, for instance, you also reduce the time needed to iterate on those tests.

**Centralized Repository**
 Bun maintains a centralized repository of packages, making it easy for developers to discover and install dependencies with a simple command. Bun also employs symlinks, packages for each project are linked to a centralized location. This means that modules occurring or coming later or after projects do not have to be downloaded again.

**Getting Started with Bun:**

Using Bun is straightforward. After installing the Bun CLI, developers can initialize a new project and start managing dependencies with a few simple commands. Here's a quick guide to get started:

**Install Bun:**

npm install -g bun
 
Initialize a new project:

bun init my-project

Install dependencies:

bun install package-name

**Conclusion**

In conclusion, Bun redefines the landscape of package management with its emphasis on speed, simplicity, and reliability. Whether you're a seasoned developer or just starting with programming, Bun empowers you to manage dependencies effortlessly, allowing you to focus on building remarkable software.Give Bun a try today and experience the future of package management!
Video — Deep dive: model merging
Tags: huggingface, deeplearning, llm, transformers
Published: 2024-03-25 20:45:22

---
title: Video — Deep dive: model merging
published: true
date: 2024-03-18 18:25:15 UTC
tags: huggingface,deeplearning,llm,transformers
canonical_url: https://julsimon.medium.com/video-deep-dive-model-merging-44066d5a99a2
---

### Video — Deep dive: model merging

![](https://cdn-images-1.medium.com/max/1024/1*-Za04J6kIWUnzMo2CiYHVA.png)

Model merging is an increasingly popular technique that makes it possible to add or remove capabilities to transformer models, without the need for any additional training.

In this video, we first introduce what model merging is. Then, we discuss different merging algorithms implemented in the mergekit library: model soups, SLERP, Task Arithmetic, TIES, DARE, and Franken-merging.

{% youtube cvOpX75Kz4M %}

**#opensource**  **#ai**
Instalando kernel Linux Zen no Arch Linux com systemd-boot 🧑🏽‍💻
Tags: archlinux, kernel, linuxzen, tutorial
Published: 2024-03-18 18:19:05

O Arch Linux é um sistema altamente modular, pensado para usuários avançados que gostam de customizar ao máximo seu próprio sistema. A liberdade é tamanha que você pode, de maneira oficial e sem muita complicação, alterar qual kernel Linux você quer instalar. Nesse tutorial, ensinarei como instalar e mudar para o kernel para o Linux Zen no seu Arch Linux.


![Pinguim meditando sobre um computador](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7s8j0uhn0vhi2k6xiy8.jpeg)

### Primeiro, o que é o Linux Zen?

O kernel Linux Zen é o resultado de um esforço colaborativo entre entusiastas do mundo Linux para entregar o melhor kernel possível para o dia a dia. Aplica alguns patches do kernel Liquorix, priorizando estabilidade e novidades no suporte de novos hardwares, além da mudança de como os processos são priorizados, além de diminuir a latência (ótimo para quem trabalha com áudio no linux).

### Instalação

A instalação não tem segredo, visto que o pacote `linux-zen` está nos repositórios oficiais do Arch Linux. Para isso, basta abrir o terminal e dar o comando `sudo pacman -S linux-zen linux-zen-headers`.

![Terminal Linux com o comando para instalar o kernel Linux Zen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y178hipne5u32rmtuth9.png)




Após a instalação, você ainda precisa seguir mais alguns passos, pois apenas o pacote foi instalado, precisando habilita-lo para dar boot no novo kernel. Para isso, editaremos um arquivo .conf que está no caminho /boot/loader/entries. No meu caso, possuo apenas uma entrada e usarei ela. Você pode criar uma nova entrada caso queira ficar alternando entre os kernels durante o boot.
Digite `sudo nano /boot/loader/entries/*nome_do_arquivo*.conf`. Você verá uma janela parecida com essa:



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



Para que você ative o Linux Zen, basta adicionar o sufixo "-zen" na linha "linux" e "initrd"

```
title Arch Linux (linux)
linux /vmlinuz-linux-zen
[...]
initrd /initramfs-linux-zen.img
[...]
```

![Arquivo de entrada atualizado para o kernel-zen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lehb9m33r3dakcj5hooa.png)

Como podemos ver, agora o arquivo de entries está configurado para o boot ser no Linux Zen invés do kernel Linux convencional. Para aplicar as configurações, salve o arquivo e execute o comando `sudo bootctl update` e reinicie seu computador. Agora o kernel Linux Zen é o seu kernel padrão.
Question about Node.js and scraping websites
Published: 2024-03-18 18:11:46

Hey everyone,

I'm diving into learning Node.js via Udemy courses and I'm eager to tackle a project.

My aim is to scrape historical sports scores from two distinct websites, save the data into a database, and create an app to view it all seamlessly. I anticipate needing separate logins for each website.

Could someone offer guidance or outline how to approach this?

If the websites [https://plnkgame.com](https://plnkgame.com) lack an API for integration, can scraping still be feasible?

Additionally, are there any particular libraries you suggest I explore for this task?
Devs, let's talk about caching
Tags: webdev
Published: 2024-03-18 18:05:31


Hey Devs...

You may have heard about the word caching, but do you know what **caching** is?

In general, caching is the process of storing copies of files/data in a temporary storage location, so that they can be accessed more quickly.

When developing a web application - caching is implemented on the client-side ( Frontend ), but Why?

Let's understand this via an example: 

`Let's say you have a website with a large number of images. Every time a user visits a page on your website, their browser needs to download these images from your server. This process takes time and slows down the page loading speed.


Now, imagine if you could store these images on the user's device the first time they visit your website. The next time they access the same page, instead of downloading the images again, their browser can retrieve them from the temporary storage location, known as the cache`


This is for just storing an image -- there are multiple occasions when you want to store data and even update whenever needed - For that, you need to implement a robust caching mechanism.

For React -  I can suggest to use [react-query ](https://www.npmjs.com/package/react-query)


Experience devs here, can you suggest some great libraries for implementing the cache mechanism?

DevTip:

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