teleren/devto huggingface dataset:
How to keep clean Ruby on Rails views with the Null Object pattern
Tags: ruby, rails, webdev
Published: 2023-02-22 12:43:10


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

One of the most common errors developers encounter is NoMethodError. It occurs when code is executed according to a script not provided by the programmer.

Junior devs often try to solve this problem in a non optimal way. Let’s look at some examples of bad code:
```ruby
@user = User.find_by(email: "deleted@user.com")
@user.first_name
```
If the user is not in the database or is flagged as “deleted”.
Then we will get an error:
```ruby
undefined method `first_name' for nil:NilClass
```
A very common solution to this problem is this:
```ruby
@user.try(:first_name)
```
Or by using a conditional operator:
```ruby
if @user.exists?
 @user.first_name
end
```
This code doesn’t look very smart. The problem is that this check can occur in different places in the project and it is much more convenient to manage this behavior in one place. In addition, this code violates the Tell-Don’t-Ask principle. The **NullObject** pattern just solves these problems.

## Solution
First, let’s write a **NullObject** for a User type object:

```ruby
class DeletedUser
  def full_name
   "Unknown"
  end

  def address
    "Unknown"
  end
  
  def email
   "Unknown"
  end
  # …
end
```
So now we have an object that we can return when a user is not found:
```ruby
@user = User.find_by(email: "deleted@user.com") || DeletedUser.new
@user.first_name #=> "Unknown"
```
Now we are sure that the object will always respond to the methods we expect it to respond to.
FastDB, a speedy persistent KV store
Tags: go
Published: 2023-02-22 12:22:06

---
title: FastDB, a speedy persistent KV store
published: true
description: Looking for KV speed in Go
tags: go
# cover_image: 
# Use a ratio of 100:42 for best results.
# published_at: 2023-02-22 11:28 +0000
---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d8db3tcbxtw851g9xvwo.png)

## Introduction

I've been using several KV (key-value) store solutions, but was never satisfied with the speed. We all know that the database-part of any application is most of the times the weakest link.

So what if I could make this faster as the fastest one I was using? Would the application that I am working on, benefit a lot? The answer is yes, it does. So now my application runs faster, smoother than before.

## Semi-technical stuff

The fastest key-value store is just a simple map, I think. But that was not enough, because I wanted to be able to use buckets. (Buckets are a kind of a "box" in which you store key-values of the same kind.)

So I made the map like this:
map[string]map[int][]byte

I tried the basics of this against the usual solution and it was faster. But I still had to make a solution where the data would be stored on disk. I saw some AOF (append only file) solution somewhere, but wasn't satisfied with the speed, so I've tweaked that a bit more.

So now, when you open the file, you tell it to synchronise the data to disk every X milliseconds. (I would suggest 100.)

Since this is only a KV-store, there is no backed-in mechanism for sorting the output. Perhaps I will make one later, but for now there is a solution which is quite fast. 

## Example (pseudo code)

Here you can see how to open a database and store data in a bucket "texts".
```
store, _ := fastdb.Open("your.db", 100)

record := &someRecord{ID: 1, UUID: "UUIDtext", Text: "a text"}
recordData, _ := json.Marshal(record)

_ = store.Set("texts", record.ID, recordData)
```

Here you can see how to get data.
```
memData, ok := store.Get("texts", 1)
memRecord := &someRecord{}
_ = json.Unmarshal(memData, &memRecord)
```

## Github link

https://github.com/marcelloh/fastdb
CCNA training in chennai
Published: 2023-02-22 12:20:28

[CCNA training in Chennai](https://www.slainstitute.com/ccna-training-in-chennai) typically covers a wide range of topics, including network fundamentals, network access, IP connectivity, IP services, security fundamentals, automation, and programmability. The training is designed to provide participants with hands-on experience working with Cisco networking equipment and software.
What are the main challenges for developer programs?
Tags: devrel, developermarketing, developerprograms
Published: 2023-02-22 12:05:38

It’s that time of the year again! The time when we run the **[Developer Program Leaders survey](https://survey.developernation.net/name/dpl10?utm_source=devto&utm_medium=DPL_Article&utm_campaign=DPL_Article)** to hear from those who work with developer programs.
It's a community effort!

### The goal? 
To understand the challenges developer program managers face, how they prioritise their resources and activities and offer insights into how they compare against other professionals in the field.
**Interested already? You’ll need ±8 minutes. [Take the survey](https://survey.developernation.net/name/dpl10?utm_source=devto&utm_medium=DPL_Article&utm_campaign=DPL_Article)**
### Who can participate?
We’re looking for professionals who are working in or with developer programs. This includes professionals in the following roles:
- Developer relations practitioner
- Developer marketing practitioner
- Developer product architect/engineer
- Community manager
- VP/director/manager of a developer program
- Analyst / analyst relations / research manager
- Product management
- General marketing (non-developer specific)
- General management (CxO/VP/director/founder)
- …and more

### What do participants gain?

Those who will take the survey will gain:

1.Unlimited access to the survey results with a report that illustrates the highlights and key graphs
2.All findings will be discussed in an interactive session where our research analysts and the DevRelX community will come together to discuss – Are you a DevRelX member? Join our community here!
3.A chance to win exclusive DevRelX swag.
4.You become involved in a collective effort to understand and improve how your peers work and set their strategy

### What types of questions does this survey ask?

- Which regional markets does your strategy target?
- Which resources take most of your budget?
- What are the main challenges for your Developer Relations efforts this year?
- Do you segment your developer audience? How?

### Here are some results from the previous survey wave. 
By responding you will gain access to more insights like these.
Do you want to help professionals elevate their DevRel game? [Have your say](https://survey.developernation.net/name/dpl10?utm_source=devto&utm_medium=DPL_Article&utm_campaign=DPL_Article)! 

![Data graph with  Community sizes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h0oluze05sih5dwc6oh1.png)

![Data graph with Role distribution of professionals in developer programs ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4hguviwgrjly97szghnv.png)

![Data graph with  The importance of community in developer-facing strategy ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sk0hz5tzeodd33vzpvwt.png)
Ferramenta AppGen
Published: 2023-02-22 11:40:45


Appgen (Application Generator) é uma aplicação de linha de comandos que serve para criar aplicações, estruturar o projecto, gerar a base de dados e instruções para executar. 

Alguns frameworks e linguagens têm como filosofia não impor muitos padrões no desenvolvimento de aplicações e deixar a organização do projecto nas mãos do programador, de modo a tomar as suas próprias decisões. Ex: Go, PHP, Python(com Flask).
Para muitos programadores, é difícil organizar um projecto. Torna-se complicado saber como onde encaixar cada parte do código. Logo, o appgen ajuda nesse problema.

## Funcionalidades Principais
- Gerar as pastas do projectos;
- Gerar arquivos estáticos (css, js):
- Gerar arquivos de biblioteca (Bootstrap, JQuery)
- Gerar Models e Controllers;
- Gerar o Script da Base de Dados (Postgres e MySQL);
- Arquivos para o GitHub(README e .gitignore);
- Coleções para teste no Postman (Postman Collections);
- Gerar arquivos de configuração.

## Alguns Comandos do appgen
 - Criação: **appgen** **–name** _aplicação_ **-lang** _linguagem_ **-type** _tipo_ **-db** _sgbd_ 
- Ajuda: **appgen help** 
- Tipos de projecto: **appgen list-langs**

## Vantagens
- Exemplo com cadastro, login, logout, upload de arquivos
- Facilidade no uso(comandos claros);
- Rapidez na geração de código;
- Tamanho (menos de 3MB);
- Comandos de ajuda muito;
- Geração de código simples, arquitectura simples.

## Observação
Inicialmente o **AppGen** apenas suporta a linguagem Python, gerando projectos API e MVC, com o framework Flask. Futuramente, haverá suporte para PHP e Golang.

## Exemplos
Usando a ferramenta **appgen** vamos gerar 2 aplicações:
- Gerar uma API REST com Python e Postgres;
- Gerar uma aplicação MVC com Python e MySQL.

Link para Download
https://github.com/ortizdavid/appgen-files



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


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




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



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



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


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



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


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


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



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fjjhvmzzv2aowlxx6bpz.png)
Resolvendo problemas no HackerRank: Calculando anos.
Tags: javascript, beginners
Published: 2023-02-22 11:20:20

Olá, seja bem vindo a mais uma etapa do Resolvendo problemas no Hacker-Rank,nessa sessão iremos analisar os anos e converter para uma data, caso sejam anos bissextos ou não.


**Day of the Programmer -**

O problema de hoje nos conta uma história de uma viajante no tempo que irá para o dia da programação numa determinada data do passado. O que nos importa é quando nos é pedido certas regras com base na diferença de um calendário Juliano e um Gregoriano, que tem suas características. Nosso objetivo é criar um código que baseado em datas que serão enviadas no problema, sigamos o resultado.


- Fevereiro é o único mês com quantidade variável de dias; tem 29 dias durante um ano bissexto e 28 dias durante todos os outros anos.

- No calendário juliano, os anos bissextos são divisíveis por 4; no calendário gregoriano, os anos bissextos são um dos seguintes: Divisível por 400. Divisível por 4 e não divisível por 100.

- O formato dd.mm.aaaa, onde dd é o dia de dois dígitos, mm é o mês de dois dígitos e aaaa


Nos dão o ano 2017 que retorna um input seguinte:

```
13.09.2017
```

Outro com input 2016 e 1800 que retornam:

```
12.09.2016

12.09.1800
```
Vamos então ao código de execução do desafio:

```
function dayOfProgrammer(year) {
  let day = "";
  if (year === 1918) {
    // Se for o ano de transicao (1918), adiciona 13 dias ao calendario normal
    day = `26.09.${year}`;
  } else if (year > 1918) {
    // Se for apos o ano de transicao, verifica se eh um ano bissexto ou nao
    day =
      year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)
        ? `12.09.${year}`
        : `13.09.${year}`;
  } else {
    // Se for antes do ano de transicao, verifica se eh um ano bissexto ou nao
    day = year % 4 === 0 ? `12.09.${year}` : `13.09.${year}`;
  }
  return day;
}
```

O código está bem explicativo,onde usamos `if` para pôr a condição da primeira data e também mais a frente colocamos as condições para um ano ser divisível por 4 ou 400, ou não ser divisível por 100.

Com isso concluímos mais um episódio, e nos vemos na próxima!!!
How to Run Reactjs Build On Server
Tags: react, serverless, javascript, programming
Published: 2023-02-22 10:59:03

**Step 1)** Add “homepage”:”your url”, to the object in your package.json file.

**Step 2)** In your terminal run npm run build

**Step 3)** Add a .htaccess file to your build folder with the following code:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
```
**Step 4)** Use a file manager to upload all of the files from your build folder including your .htaccess file to the public folder on the server. I used FileZilla, but you can use the built in file manager or SSH keys. If you don’t know how to make an FTP user, go here.

Siteground specific instructions:

**Step 5)** Navigate to the site tools for the desired website. (You can even use a temporary domain for this).

**Step 6)** Install an SSL certificate in Security > SSL Manager. (You can use the free one. Take note of the expiration date.)

**Step 7)** Enforce HTTPS by going to Security > HTTPS Enforce and turn it on.

That should work! Send questions if you have any.
Effects with React useEffect
Tags: react, webdev, javascript
Published: 2023-02-22 10:58:41

Some practical examples of how to use the [React useEffect()](https://beta.reactjs.org/reference/react/useEffect) -

```js
import React from "react";

export default function App() {
  const [name, setName] = React.useState('');
  const [age, setAge] = React.useState(0);

  React.useEffect(() => {
    console.log('component mounted');

    return () => {
      console.log('component unmounted');
    }
  }, []); // empty array means it will only run on mounting

  // Separation of concerns
  // This is a good example of how to separate concerns splitting into two useEffects to handle each value
  React.useEffect(() => {
    console.log('name changed', name);
  }, [name]); // only triggers when name changes

  React.useEffect(() => {
    console.log('age changed', age);
  }, [age]); // only triggers when age changes

  return (
    <div>
      <input type="text" value={name} onChange={e => setName(e.target.value)} />
      <input type="number" value={age} onChange={e => setAge(e.target.value)} />
    </div>
  );
}
```

## On Mounting

Similar to the legacy `componentDidMount` it will trigger on mounting the component:

```js
React.useEffect(() => {
  console.log('component mounted');

  return () => {
    console.log('component unmounted');
  }
}, []); // empty array means it will only run on mounting
```

## On Changing Values

```js
React.useEffect(() => {
  console.log('name changed', name);
}, [name]); // only triggers when name changes
```

## Separation of Concerns

Instead of watching two values at the same useEffect, like the following:

```js
React.useEffect(() => {
  console.log({ name, age });
}, [name, age]);
```

Think in separation of concerns, and split each it will be cleaner and easier for the next person who need to read your code, eg:

```js
// Separation of concerns
// This is a good example of how to separate concerns splitting into two useEffects to handle each value
React.useEffect(() => {
  console.log('name changed', name);
}, [name]); // only triggers when name changes

React.useEffect(() => {
  console.log('age changed', age);
}, [age]); // only triggers when age changes
```
How to start node.js app with pm2
Tags: pm2, serverless, node, package
Published: 2023-02-22 10:57:38

PM2 is a popular process manager that offers all of the features above and then some. It has great documentation and is quick to get started with, which is why I’ve chosen to use it for a number of my applications.

Installing PM2
The PM2 CLI can be installed using npm by running the following in your terminal:

npm install pm2 -g
Running the Application with PM2

To start a file, you can use this command, pm2 start index.js , where index.js is the path to the file that you want to run.
Helpful PM2 Commands

pm2 stop [insert id]— Will stop the process that matches the id (run the list command to get the id)

pm2 start [insert id] — Will start the process that matches the id

pm2 logs [insert id] — Shows logs from the process that matches the id

pm2 delete [insert id] — Will delete the process that matches the id

For more information check Reference Link:

pm2 — npm (npmjs.com)
Manipulating the DOM with React Ref
Tags: react, javascript, webdev
Published: 2023-02-22 10:57:02

When you found something like `document.querySelector('.something')` in your React codebase, it's probably a code smell.

To manipulate the DOM you should consider using "ref" - [React Docs - ref](https://beta.reactjs.org/reference/react/useRef#manipulating-the-dom-with-a-ref)

After rendering the DOM element, it will enable the DOM node and its methods to be called.

To ensure the "inputRef.current" will be available at the moment of the trigger "focus()", you can do an "early return" to bail out the effect early, like the following snippet:

```js
import React from "react";

export default function App() {
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (!inputRef.current) {
      return;
    }

    inputRef.current.focus();
  }, [])

  return <input ref={inputRef} type="text" />;
}
```
Don’t Use Kubernetes Please!
Tags: webdev, kubernetes, startup
Published: 2023-02-22 10:52:28

In my 10 years of working in the software industry in various roles I saw people moving from, the following tools have these benefits and these drawbacks, to it is trendy so lets do it.

Kubernetes is one of those things, hosting your applications on Kubernetes has become the standard in deploying applications regardless of whether it actually has any benefits. I am hoping through this article to put some sanity back into the industry and show the drawbacks of using Kubernetes and how it can damage your software cycle, increase costs and make you not agile in anyway possible.

And here is why: 

1. Kubernetes is by default more expensive
2. Kubernetes deployments are more complicated
3. Kubernetes is not stable !
4. Version Management is hard.
5. DevOps Engineering cost would sky rocket.
6. Bigger attack surface.

In my article [here](https://thetechtrailblazer.blog/2023/02/14/dont-use-kubernetes-please/) I go more in depth in each point and discuss more details about it.
Being a Developer Advocate: Week 22
Tags: devrel, learninpublic
Published: 2023-02-22 10:19:00

I noticed I did not get around to writing my weekly blog post. So let's get it done.

The last two weeks were really stressful as sickness hit my family and a lot of the chores were left to me 😥

Tiago Forte the thinking forward in what is needed to be productive. For him, it is more about energy management as you can do a lot in little time. Without the energy you lack the ability to focus and get less/nothing done.

I can totally relate to his sentiment. At the end of the day, I can not bring myself to sit down and write something when I am mentally drained 😐 

## More Videoediting Insights
Nevertheless I was able to get some deep focus time during the week and managed to do some postproduction on three of my videos where I explain some stuff in under two minutes each.

Putting yourself under constraints for creative work does the opposite of what one intuitively expects.

I came up with ways to make the videos more fast-paced and therefore more interesting. Got a ton of tips on how to make the videos better from tutorials and from colleagues. Cutting out not needed stuff resulted in videos I am confident will help our developers understand a thing or two better 🥳
openGauss operating environment
Published: 2023-02-22 10:03:05

Supported hardware platforms
openGauss supports running on ARM servers and general x86 servers:

Support ARM server and general PC server based on x86_64.
Supports local storage (SATA, SAS, SSD).
Support Gigabit and 10 Gigabit Ethernet networks.
Supported OS
ARM:

openEuler 20.03LTS (this operating system is recommended)
Kirin V10
Asianux 7.5
X86:

openEuler 20.03LTS
CentOS 7.6
Asianux 7.6
openGauss Features
Published: 2023-02-22 10:01:54

openGauss has the characteristics of high performance, high availability, high security and good maintainability.

high performance

Through key technologies such as column storage, vectorized execution engine, and fusion engine, it can achieve second-level response to tens of billions of data queries.

high availability

Cross-AZ (Available Zone) disaster recovery in the same city, no data loss, and recovery within minutes.

high security

It supports security features such as access control, encryption authentication, database audit, and dynamic data desensitization, and provides comprehensive end-to-end data security protection.

high reliability

Flashback and Recycle Bin
Usually, when the table data is wrongly UPDATE, DELETE, TRUNCATE, and DROP, the data is difficult to recover. Even if it is recovered, it can only be recovered to the time before the wrong operation through PITR (Point-in-time recovery, point-in-time recovery). This repair method will make the entire database unavailable, and some table operations that users do not want to "undo" will also be "undo". openGauss supports TIMECAPSULE and RECYCLEBIN, so that users can perform flashback query by specifying a timestamp, or flashback a table by specifying a timestamp, and obtain historical data before an error DELETE or UPDATE. By flashing back TRUNCATE and DROP table objects from RECYCLEBIN, users can restore table data to before the wrong operation, which greatly improves the reliability of user data.

Good maintainability

Support WDR diagnosis, slow SQL diagnosis, Session diagnosis and other maintenance methods to accurately and quickly locate problems. With AI4DB capability, it can realize database self-tuning, self-monitoring, and self-diagnosis through AI algorithms.