teleren/devto huggingface dataset:
Translations on-the-fly using Go
Tags: webdev, go
Published: 2023-04-30 06:14:44

There are several methods to make a Go web app "multilingual". I chose to store the translations in .po files. One language per file.

The Go html template looks like this: 

`<p>{{trans "Company"}}</p>`

This means that the html template calls a `func trans()` and translates "Company" into the set language.

The html template is translated by Go web server before the page is rendered without noticeable delay.

[Here is both an example and the code behind.](https://lang.go4webdev.org)
Setting up Sonartype nexus on your local docker
Tags: devops, cicd, artifacts, docker
Published: 2023-04-30 05:33:55

If you installed Sonatype Nexus Repository Manager with Docker and the generated password for the admin user is stored in a file named admin.password inside a volume, you can retrieve the password by accessing the file.

Here are the steps to retrieve the admin password:

 Identify the volume that contains the admin.password file. You can do this by running the docker inspect command on your Nexus container:


docker inspect <nexus_container_name> | grep Source

Replace <nexus_container_name> with the name of your Nexus container.

Once you have identified the volume, you can use the docker run command to start a temporary container with access to that volume:

bash

   docker run --rm -v <volume_name>:/data alpine cat /data/admin.password

Replace <volume_name> with the name of the volume that contains the admin.password file.

The output of the command will be the generated password for the admin user. You can use this password to log in to the Nexus web interface and change the admin password to something more secure.

Note that the docker run command used in step 2 starts a temporary container and mounts the specified volume to the /data directory in the container. The cat command is used to read the contents of the admin.password file and output it to the terminal. Once the command has completed, the temporary container is automatically removed with the --rm option.
Job Searching!
Tags: job
Published: 2023-04-30 06:05:24

Good morning,


my name is Carlos Campo, 27 and fluent in Spanish and English, and know a little bit of German. I would like to get a job part-time as a developer, and I was wondering if you guys could answer some of my questions please!

. I'm looking for quick certifications that I can earn online, paid if necessary, altough my budget is not so high, in order to learn how to code, both front and back end, or anything that is well know nowadays and that will give me the chance to find a job fast. Do you have any good recommendations?

. Where are the best ways to find  job in this field? I'm looking for a part-time job mainly. Do you have any recommendations on sites that would help me to do so?

. Which technologies do you think I should go for, that are more demanded?


Thanks in dvance for your time, and wishing you a great day ahead!


Carlos.
More "FUN-ctions"
Tags: javascript, frontend, learning, coding
Published: 2023-04-30 05:16:54

As promised, we are back with some more fun..
![whoops](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y1w9224eiry1bjt7886o.gif)
**Um, I mean functions**😅
As, like myself, if you are on the uphill journey that is learning JavaScript - you are aware that trying to master functions is far from fun.

In my last blog post I started discussing the general JavaScript function basics, such as (_inputs, actions,_ and _outputs_).
For this second iteration, I wanted to touch on other function variations.

First, lets touch on the <u>Anonymous Function</u>, this is relative to the basic function, just in a different format. This type of function is not required to use the declaration of 'function' keyword for creation. But instead can be declared with a variable and assigned a value of a function.
![anonymous function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/66fbqfh43ec3ppi2idy5.png)
This just makes writing a function a little easier, maybe even cleaner. An added bonus is how the anonymous function factors into writing/utilizing _callback functions_, as well as _arrow functions_.

We will cover those variations and in more depth in the next few blog posts, continuing the function saga!

Until then, continuing coding comrades👋
Configurando um Cluster Elasticsearch em Contêineres Docker
Tags: elasticsearch, docker, devops, braziliandevs
Published: 2023-04-30 03:03:08

O Elasticsearch é uma poderosa ferramenta de análise e busca de dados distribuída que permite que os usuários armazenem, pesquisem e analisem grandes volumes de dados em tempo real. É construído em cima do Apache Lucene, uma biblioteca de busca de texto de código aberto e amplamente utilizada.

No entanto, configurar um cluster Elasticsearch pode ser uma tarefa complexa e desafiadora, envolvendo vários processos, como a instalação do software, a configuração de rede e o gerenciamento de nós. Além disso, é importante garantir que o cluster esteja disponível, escalável e seguro.

É aí que entra o Docker, uma plataforma de virtualização de software que permite que os usuários empacotem e executem aplicativos em contêineres leves e portáteis. Com o Docker, os usuários podem criar contêineres que possuem todas as dependências necessárias para executar seus aplicativos, incluindo o Elasticsearch.

O elastic-docker, um projeto de código aberto desenvolvido por Guilherme Silveira, é uma excelente opção para quem deseja configurar um cluster Elasticsearch facilmente. O projeto fornece um conjunto de scripts e configurações para executar um cluster Elasticsearch em contêineres Docker. Além disso, o elastic-docker é compatível com as versões mais recentes do Elasticsearch e do Docker.

Com o elastic-docker, é possível configurar um cluster Elasticsearch com várias instâncias em contêineres Docker separados de forma fácil e rápida. O projeto oferece scripts para configurar o número de nós, o tamanho do cluster e outras opções avançadas. Além disso, o elastic-docker pode ser personalizado de acordo com as necessidades específicas do usuário. É possível modificar as configurações padrão do Elasticsearch e utilizar plugins personalizados para adicionar recursos adicionais ao seu cluster.

Uma das principais vantagens do elastic-docker é que ele simplifica o processo de configuração de um cluster Elasticsearch, eliminando a necessidade de configurar a rede e gerenciar os nós manualmente. Com o elastic-docker, os usuários podem criar um cluster Elasticsearch escalável e disponível em questão de minutos.

Para começar com o elastic-docker, é necessário instalar o Docker em seu computador e, em seguida, baixar os scripts e configurações do projeto no GitHub e seguir as instruções de configuração fornecidas. Com sua personalização e facilidade de uso, o elastic-docker se torna a solução perfeita para aqueles que desejam configurar seu cluster Elasticsearch sem enfrentar os desafios comuns dessa tarefa.

[Projeto elastic-docker no GitHub](https://github.com/Guilherme-Silveira/elastic-docker#elastic-stack-on-docker)
Survey of Expert
Tags: software, softwaredesign
Published: 2023-04-30 04:42:07

I am doing MS from Peshawar University and conducting research on " Software Ecosystem Architecture . This questionnaire has been designed to elicit your response. it will not take more than 5 minutes of yours.
https://docs.google.com/forms/d/e/1FAIpQLSdBWA6wOASrOtdtlY194Hby5Iv969_qX7uznDvbtsDFPP40Pg/viewform?usp=sf_link
How To Make A Snake Game In JavaScript : A Beginners Guide
Published: 2023-04-30 04:33:55

<div class="separator"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja9NUG-_bi2OouSmO91MMrkLVMq3TtBdaNek3aMG9QZIdI-wuF1E6o8b7wK7HPUEkKI95SdxqoRnhveYTUk_F7cI30PgahOj_yqtQNFQnoQAUy-pyxzBOUyIAbv2kFrg6kCT9SNs3fqqiMFRR2A_MHg0GBYI7mLCjH6nPsF7KwYc9OCnTYRl5vwyxh8A/s300/94984424-044e0a80-0509-11eb-903a-c114d5b6f061.png" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Noto Sans;"></span></a></div><span style="font-family: Noto Sans;"><br /></span><p style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Noto Sans;"><br /></span></p></div>
<h1 id="basic-snake-html-and-javascript-game"><span style="font-family: Noto Sans;">Basic Snake HTML and JavaScript Game<span><!--more--></span></span></h1>
<p><span style="font-family: Noto Sans;">Snake is a fun game to make as it doesn't require a lot of code (less than 100 lines with all comments removed). This is a basic implementation of the snake game, but it's missing a few things intentionally and they're left as further exploration for the reader.</span></p><p><span style="font-family: Noto Sans;">Create a fun Snake game with &lt;100 lines of code using HTML and JavaScript. Basic version with room for exploration.</span></p>

<span style="font-family: Noto Sans;"><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="600" src="https://wiz-aiimages.github.io/snack-game-simple-in-javascript/" width="600"></iframe></div></span><gwofw><span style="font-family: Noto Sans;">
<br />
<br />
</span><h2 id="further-exploration"><span style="font-family: Noto Sans;">Further Exploration<span><!--more--></span></span></h2>
<ul>
<li><span style="font-family: Noto Sans;">Score</span><ul>
<li><span style="font-family: Noto Sans;">When the snake eats an apple, the score should increase by one. Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillText">context.fillText()</a> to display the score on the screen</span></li>
</ul>
</li>
<li><span style="font-family: Noto Sans;">Mobile and touchscreen support</span><ul>
<li><span style="font-family: Noto Sans;">Allow the game to be scaled down to a phone size. See <a href="https://codepen.io/straker/pen/VazMaL">https://codepen.io/straker/pen/VazMaL</a></span></li>
<li><span style="font-family: Noto Sans;">Support <a href="https://developer.mozilla.org/en-US/docs/Web/API/Touch_events">touch controls</a></span></li>
</ul>
</li>
<li><span style="font-family: Noto Sans;">Better apple spawning</span><ul>
<li><span style="font-family: Noto Sans;">Currently, the apple spawns in any random grid in the game, even if the snake is already on that spot. Improve it so it only spawns in empty grid locations</span></li>




[READ MORE](https://wiz-official.blogspot.com/2023/04/how-to-make-snake-game-in-javascript.html)
Understanding the Logical Structure of PostgreSQL
Tags: postgres, database, beginners
Published: 2023-04-30 04:33:41

## What is a Database Cluster?

A **database cluster** is a **collection** of databases looked after by **one** **PostgreSQL server**. Don't get confused - **_a database cluster isn't a group of database servers_**. Just one server runs on one computer and deals with one database cluster.


![Visualisation of Databases and Database Clusters](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mzddqaklv4mrmvrv9t0i.png)

## Stepping into the Database Cluster

Each database within a cluster in PostgreSQL is _**logically separated**_ from the others. This implies that **_each database has a unique set of database objects_** that only belong to that database. A specific database's _tables_, _indexes_, and _other objects_, for instance, are only accessible within that database.

## Object Identifiers (OIDs)

Each database object in PostgreSQL is managed by an object identifier (**OID**), a _**4-byte unsigned integer**_. Depending on the type of object, the relationships between database objects and the corresponding OIDs are stored in the appropriate system catalogues. For instance, _**heap tables'** _and **_databases' OIDs**_ are stored in the respective **_pg_database_** and **_pg_class_**.
Installing and using Glint in Ember.js
Tags: ember, typescript, javascript
Published: 2023-04-30 02:24:52

Glint is a set of tools that aids in the typechecking of projects that use Glimmer, such as Ember.js and GlimmerX. This guide will show you how to install and use Glint in an Ember.js project.

# Step 1: Install

Create a new Ember app:

```
ember new my-app --typescript
cd my-app
```

Install Glint dependencies:

```
npm install -D @glint/core @glint/template @glint/environment-ember-loose
```

Update `tsconfig.json`:

```diff
// tsconfig.json

{
  "compilerOptions": {
    ...
  },
+ "glint": {
+   "environment": "ember-loose"
+ }
}
```

Create a new file called `types/glint.d.ts`:

```js
// types/glint.d.ts

import '@glint/environment-ember-loose';
```

# Step 2: Add signatures to template registry

Add the following declaration to your components to index their signatures in the template registry. For example:

```diff
// app/components/avatar.ts

import Component from '@glimmer/component';

export default class Avatar extends Component {}
+
+ declare module '@glint/environment-ember-loose/registry' {
+   export default interface Registry {
+     Avatar: typeof Avatar;
+   }
+ }
```

Do the same with your helpers and modifiers. For example:

```diff
// app/helpers/sum.ts

import { helper } from '@ember/component/helper';

const sum = helper((values: Array<number>) => {
  return values.reduce((sum, next) => sum + next, 0);
});

export default sum;
+
+ declare module '@glint/environment-ember-loose/registry' {
+   export default interface Registry {
+     sum: typeof sum;
+   }
+ }
```

You can also use `{{! @glint-ignore }}`, `{{! @glint-nocheck }}`, and `{{! @glint-expect-error }}` to ignore code in your templates.

# Step 3: Add dependency signatures

For addons that do not supply Glint types, manually add their component/helper/modifier signatures to the registry:

```diff
// types/glint.d.ts

import '@glint/environment-ember-loose';
+ import { ComponentLike, HelperLike } from '@glint/template';
+
+ declare module '@glint/environment-ember-loose/registry' {
+   export default interface Registry {
+     WelcomePage: ComponentLike;
+     'page-title': HelperLike<{
+       Args: { Positional: [title: string] };
+       Return: void;
+     }>;
+   }
+ }

```

# Step 4: Run executable

Run the `glint` command to typecheck your project. This command could be worked into your linting scripts, for example:

```diff
//  package.json

{
  ...
  "scripts": {
    "build": "ember build --environment=production",
    "lint": "concurrently \"npm:lint:*(!fix)\" --names \"lint:\"",
    "lint:fix": "concurrently \"npm:lint:*:fix\" --names \"fix:\"",
+   "lint:glint": "glint",
    "lint:hbs": "ember-template-lint .",
    "lint:hbs:fix": "ember-template-lint . --fix",
    "lint:js": "eslint . --cache",
    "lint:js:fix": "eslint . --fix",
    "start": "ember serve",
    "test": "concurrently \"npm:lint\" \"npm:test:*\" --names \"lint,test:\"",
    "test:ember": "ember test"
  },
  ...
}
```

# Conclusion

Using Glint and TypeScript, you should now have end-to-end typechecking in your Ember.js project templates.
How to install npm AKA Node.js package manager the right way on openSUSE Linux
Tags: npm, linux, beginners, tutorial
Published: 2023-04-30 00:43:38

If you're a Node.js developer, you might be familiar with the `npm install -g packagename` command. However, if you run the command without `sudo`, you will likely face with the permission issue. This is due to your `npm` installation method.

In fact, you shouldn't use `sudo` with `npm` at all. See more about this **[here](https://medium.com/@ExplosionPills/dont-use-sudo-with-npm-5711d2726aa3)**.

---

## Installing `npm` the right way

First, if you installed `npm` via your repo's package manager, please uninstall it first!, either by using _YaST Software Management_ and search for `npm`, or using this command:

```
sudo zypper remove npm
```

Then, follow these steps:

1. Install `nvm` with **[this install instruction](https://github.com/nvm-sh/nvm#installing-and-updating)**. It's not only a node version manager, but also lets you use `npm` command without `sudo`.

     > After running the `curl` or `wget` installation script, you will need to close the terminal window as the current terminal window doesn't know the `nvm` command yet.

2. Run `nvm install node` to install the latest `node`(Node.js) along with the latest `npm`. It should return something like this:

     ```
Downloading and installing node v20.0.0...
Downloading https://nodejs.org/dist/v20.0.0/node-v20.0.0-linux-x64.tar.xz...
##################################################################################################### 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v20.0.0 (npm v9.6.4)
Creating default alias: default -> node (-> v20.0.0)
     ```

     > Note, the `node` installing via `nvm` will use its version by default, not the version on your system.

3. If you want to update `nvm`, simply running the latest installation script on **[this page](https://github.com/nvm-sh/nvm#installing-and-updating)**. You can monitor a new release of `nvm` version by watching their git as shown in the screenshot below:

     ![monitor a new version #1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mitjzytcteln3nnv5vb7.png) 

     ![monitor a new version #2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v6tkkzbpqy9psxc572ut.png)

---

I hope this helps, bye 💨

---

**Cover** Photo by **[GuerrillaBuzz](https://unsplash.com/@guerrillabuzz?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)** on **[Unsplash](https://unsplash.com/photos/1_5FWSsyDmc?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)**
How to Serialize Errors in Javascript
Tags: javascript, errors
Published: 2023-07-25 16:26:39

---
title: How to Serialize Errors in Javascript
published: true
date: 2023-04-30 00:00:00 UTC
tags: javascript,errors
canonical_url: https://goulet.dev/posts/error-serialization-in-js/
---

## Don't use a simple `JSON.stringify`

If you want to serialize an Error in Javascript you might be tempted to simply use `JSON.stringify`, but that won't be very helpful.

```js
const error = new Error("Something went wrong");
const serialized = JSON.stringify(error);
// serialized -> '{}'
```

## Normalize the error

Instead what I like to do is "normalize" the error (in case it's not actually an [`Error` object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)) and then use the error message:

```js
/**
 * @param {unknown} error
 * @returns {Error}
 */
export function normalizeError(error) {
  if (typeof error === "object" && error instanceof Error) {
    return error;
  } else if (typeof error === "string") {
    return new Error(error);
  }

  // else turn this unknown thing into a string
  return new Error(JSON.stringify(error));
}

// NOW I CAN CATCH ERRORS...
try {
  throw new Error("Something went wrong");
} catch (error) {
  const normalized = normalizeError(error);
  const serialized = normalized.message;
  // serialized -> "Something went wrong"
}

// AND ANYTHING ELSE
try {
  throw "Who throws a string? ME!";
} catch (error) {
  const normalized = normalizeError(error);
  const serialized = normalized.message;
  // serialized -> "Who throws a string? ME!"
}
```

## Alternative: Use overloaded `JSON.stringify`

If you _know_ you are dealing with an `Error` object (so you don't need to normalize it) then you can use `JSON.stringify` with a second argument to tell JSON stringify which properties to enumerate:

```js
const error = new Error("Something went wrong");
const serialized = JSON.stringify(error, Object.getOwnPropertyNames(error));
// serialized -> '{"stack":"Error: Something went wrong\\n at REPL9:1:13\\n at Script.runInThisContext (node:vm:131:12)\\n at REPLServer.defaultEval (node:repl:522:29)\\n at bound (node:domain:416:15)\\n at REPLServer.runBound [as eval] (node:domain:427:12)\\n at REPLServer.onLine (node:repl:844:10)\\n at REPLServer.emit (node:events:390:22)\\n at REPLServer.EventEmitter.emit (node:domain:470:12)\\n at REPLServer.Interface._onLine (node:readline:418:10)\\n at REPLServer.Interface._line (node:readline:763:8)","message":"Something went wrong"}'
```

If you don't want the stack in there you can just list an array of the properties you want:

```js
const error = new Error("Something went wrong");
const serialized = JSON.stringify(error, ["message", "name"]);
// serialized -> '{"message":"Something went wrong", "name": "Error"}'
```
A Simple Introduction
Published: 2023-04-29 23:43:41

Hey everyone! 👋 As a civil engineer with a passion for machine learning and programming, I bring a unique perspective to software development. I'm excited to share that I'm actively contributing to open-source projects and creating software that is accessible to everyone, everywhere.

Python is my go-to programming language, and I've been working on a diverse range of projects, which you can check out on my  [GitHub profile](https://github.com/patrickboateng).

I'm particularly interested in applying my technical expertise to tackle complex civil engineering challenges, especially in the geotechnical and structural engineering spaces.

If you're passionate about open source or have a civil engineering challenge that needs solving, feel free to reach out to me. I'd love to connect with like-minded individuals and see how we can collaborate to make a difference. Let's make an impact together! 💪
Exploring DeFi and Building DBANK: My Experience with Angela Yu's Course - Day 89 of #100DaysOfCode
Tags: blockchain, web3, dapp, programming
Published: 2023-04-29 22:48:42

Day 89 of #100DaysOfCode. Today, I decided to switch things up and focus on the last module in Angela Yu's course before getting back to my project tomorrow. The module covers the theory behind blockchain, DApps, and how to develop them, as well as ICP.

To kick things off, I started building a DeFi (Decentralized Finance) DApp called DBANK, inspired by Compound. Today's lesson focused on the basics, such as making functions in canisters public so that they are accessible from any canister. This is especially helpful when your app becomes more complex with many different parts.

I began by interacting with the functions via the CLI, then moved on to Candid UI. It's fascinating to learn about how decentralized finance works and how it's changing the world of finance. I'm excited to continue building and exploring this space!