teleren/devto huggingface dataset:
How to call a function from within a Go html template
Tags: go
Published: 2023-03-29 15:40:31

Using Go for web development is not that common, but I find it rather simple to create static web sites and the site often will be faster than other tools like Drupal, Wordpress and PHP. 

Web development using Go means that you use at least 3 other “languages”. HTML, CSS and Javascript. The challenge is to get these languages to “talk” to each other. It is rather trivial to put data in a Go html template, but sometimes you want the HTML template to call a function in Go.

This is of course possible, but all sources I have found do not explain this in a simple way. The Go documentation is not that friendly to a newbie. And almost all examples on the net are either at “hello world” level OR too complicated.

Finally I found a solution by using 3 simple steps. Hope this will help somebody that also has been struggling with this.

1. Write the HTML and call the function with parameters.
2. Tell the templates to use this function.
3. Finally create the desired **func** in Go.

Using Funcs in HTML you can do a lot of things in a HTML template.

Here is the code and live preview https://funcs.go4webdev.org
JS Classes: Extend and Super Keyword
Published: 2023-03-29 15:27:16


## Extend and Super Keywords are used to implement [Inheritance](https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)) in JS. 

The `extends` keyword, as the name suggests, extends a class - meaning, one class inherits the properties from another class.

The `super` keyword refers to superclass or parent objects. It is used to call and to access superclass methods and constructor.

### How to use the Extend and Super Keywords?
```
class Vehicle{
 constructor(vehicleType,numofSeats){
   this.vehicleType = vehicleType;
   this.numofSeats = numofSeats;
   this.forSale = false;
 }
 describe(){
  return `This ${vehicleType} has ${numofSeats}`;
 }
}
```
Here we will use the **extend** keyword to inherit the properties of the Vehicle class.
```
class Car extends Vehicle{
  constructor(vehicleType,numofSeats,color){
    super(vehicleType,numofSeats);
     this.color = color;
     this.forSale = true;
  }
  describe(){
    super();
  }
}

```

`super` calls the constructor function of the Vehicle class since we are extending from Vehicle. 

Doing so reduces your hassle of writing
```
this.vehicleType = vehicleType;
this.numofSeats = numofSeats;
```
all over again for the `Car` class.

`color` is a property that was not in the `Vehicle` class, therefore - we add it in the `Car` constructor and assign `this.color` to `color`.
Since we are selling the Car, `this.forSale` should be set to `true`.

In case of functions, you can also inherit and call it from the parent class. Such as the code snippet 
```
describe(){
  super();
}
```
as shown in the code above invokes the super function inside the `describe()` function. What this does is the `Car` class invokes the `describe` function from the `Vehicle` class. Meaning that the `Car` subclass is calling the `describe()`function from the `Vehicle` class while using the parameters of the `Car` subclass.

### To learn about `static` methods, check out [JS Classes: Static Methods](#)
Flatiron - Phase 3
Tags: python, input
Published: 2023-03-29 15:25:40

In this rendition of blogs I will be going over something in python that was not utilized in our curriculum. Python has many capabilities and functionalities but one thing that i came across in my studies is that we have had the capability to integrate user inputs for specific functionalities in the code we write. 
`input()`
is a function that will prompt the user to enter a desired value into the command line when running our code. 
How it works: 
When calling this function we must assign it to a variable
`Name = input('What is your name? ')`
I have seen the most examples that show the naming convention is to capitalizes the variable. When we run our code the it will be read top down, hit the input function, then stop and ask for the user to enter the asked prompt in our code. It is also a good idea to leave a single space before our question mark. Once the user enters their answer the code will finish reading and that variable is now useable in our code. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yf5n0h4vvgis9goedrf0.png)
The function will take the typed in value and set it in a string, from there evaluate and use it however we see fit 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hgek38mpt8gjxkaou5sw.png)
17 berufliches Vorwärtskommen: Weshalb du dienen solltest.
Tags: deutsch, career, austausch, 1min
Published: 2023-03-29 15:20:00

Moin Moin,

[dienen↗](https://www.dwds.de/wb/dienen#d-1-4), also etwas für jemanden zu etwas brauchbar machen, in der Art einer Dienstleistung, kann auch als bezahltes Problemelösen bezeichnet werden.
Lösungen für Probleme zu entwickeln ist der Kern unserer Tätigkeit als Software-Entwickler. 
Wenn wir uns dabei darauf konzentrieren, dass unsere Lösungen unserer Zielgruppe dienen, brauchen wir uns um Profit keine weiteren Gedanken machen. Ähnlich verhält es sich mit Nachhaltigkeit. Beides, Profit und Nachhaltigkeit sollten Begleiterscheinungen des _Zielgruppendienstes_ sein.

- Was denkst du dazu?
- Arbeitet dein Unternehmen zielgruppenorientiert? Oder profitorientiert? Oder anders?
- Wie steht es dabei um dich?

Beste Grüße,
Mustafa
[Desafio] - 10 Desafios Simples de System Design: Resolução 3/9 (Transformar um Processamento Síncrono de uma API em Assíncrono)
Published: 2023-03-29 15:19:24

> Conteúdo original em https://twitter.com/zanfranceschi/status/1641096795853066240

---

Ei dev,

Discussão sobre a resolução do Desafio 3/9 dos 10 Desafios Simples de System Design que postei recentemente.

"Transformar um Processamento Síncrono de uma API em Assíncrono"

↓

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

https://twitter.com/zanfranceschi/status/1638232590812585985

---

Esse desafio é interessante e relativamente comum. É uma abordagem que pode ter algumas coisa como finalidade:

- Melhorar performance e escalabilidade;
- Um caminho para transformar monolitos em microsserviços;
- Separação de responsabilidades; e etc.

---

Esse é um assunto/desafio que já escrevi algumas vezes sobre. Então, em vez de me repetir aqui, vou apontar alguns conteúdos relacionados.

---

Essa thread aqui basicamente discute uma abordagem pra resolver esse desafio pelo viés da escalabilidade falando sobre prós e contras.

https://twitter.com/zanfranceschi/status/1587431299458813952

---

Um conceito super importante para entender nesse desafio/área é sobre (des)acoplamento e indireção.

https://twitter.com/zanfranceschi/status/1504516518264164360

---

Esse desafio aqui poderia ser resolvido com a introdução de processamento assíncrono.

https://twitter.com/zanfranceschi/status/1579279644720738304

---

Outro desafio em que o processamento assíncrono poderia ser um candidato para resolução.

https://twitter.com/zanfranceschi/status/1572256034340868097

---

Uma forma bem usual para criar soluções de processamentos assíncronos é através de tópicos e filas. E com isso, os conceitos de dead-letter e retry são essenciais.

https://twitter.com/zanfranceschi/status/1522554964534435840

---

Por fim, essa thread – que basicamente foi minha estréia de criação de conteúdo no Twitter – é um desafio para que você implemente uma solução (já dada) de processamento assíncrono. Vale para quem for iniciante no assunto.

https://twitter.com/zanfranceschi/status/1501583683685425159

---

É isso! Espero que tenha curtido e muito obrigado por ter lido até aqui.
Alpine Linux in WSL
Tags: alpine, linux, wsl, windows
Published: 2023-03-29 15:15:24

After trying [Debian in WSL](https://dev.to/dendihandian/debian-in-wsl-55o7), now I'm trying for something lighter, the Alpine distro.

## Requirements

- Having WSL (WSL2) activated

## Installing Alpine WSL

Open Microsoft Store and search for `Alpine WSL`. Install and Open after it installed.

![alpine wsl microsoft store](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bgbx4rjbtpbgd8gn32wu.png)

When you launch it at first, it will perform the installation setup and wait for it.


![alpine wsl installing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qkgd2szmcqk0d0fo97ke.png)

> If your installation froze up to the last line like in the image above for like more than few minutes, try to close it and reopen alpine linux. Somehow the installation was actually completed.

## Checking the installed Alpine version

Use the `cat /etc/os-release` command to see the release information.

![alpine version using cli](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0wdq441z1vi6a5u45c1j.png)

## Common APK commands for Alpine

Alpine is powered with command tools named `apk`, stands for Alpine Package Keeper. You can confirm it's installed by typing `apk` and you will see the apk version and usage information.


![apk help info](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ao4jrf3ouu4h2liq8b4.png)

### Updating the repository indexes

To download and update the packages information to the latest, use this command:

```
apk update
```

![apk update result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3emmuhe3loimqhhj5xo.png)

### Installing packages with `apk`

You can browse for the available packages at [pkgs.alpinelinux.org/packages](https://pkgs.alpinelinux.org/packages) or you can search it using CLI. Since Alpine Linux doesn't come with built-in editor like `nano` in ubuntu, we have to install it as the demo.

```
apk search nano
```

Above commands will list available packages that has `nano` on it's name.

![apk search nano](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tgqivmwlz76l8jk0kzw9.png)

But the straightforward to install it, just type this:

```
apk add nano
```

Check if the nano version actually matches the version in the latest available packages.

```
nano --version
```

![nano version cli](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dk3bdjofq1qbshpn3mm1.png)

Now you can try to edit a file using nano. But maybe you have to create it first using `touch sample.txt` and then you can `nano sample.txt` afterward.

## Testing Python server in Alpine WSL

You can install python3 using apk command:

```
apk add python3
```

Confirm the python installation using `python3 --version`. Just like what we've tried in Debian WSL, you can start a simpl python server using 

```
python3 -m http.server 8000
```

And open `http://localhost:8000` in your browser to confirm it.
TIL 03/29/23
Published: 2023-03-29 15:12:36

Today I learned something vital....

ALWAYS PUSH TO GITHUB...

After multiple commits to my linktree project, I lost all my work because I did not push to github and I did not pin my workspace.
Even though it was frustrating to have to redo the entire project, it was a great lesson.
I bet I wont forget to do it again!!
historia salonów piękności
Tags: history, beginners
Published: 2023-03-29 15:09:55

Jedna z pierwszych wzmianek o salonie piękności, jako miejscu, do którego przychodzili poprawiać swój wygląd, pochodzi z połowy IX wieku. To właśnie wtedy władca muzułmańskiej Hiszpanii zaprosił słynnego piosenkarza do swojego domu w Kordobie, z którego jak się okazało, udało mu się nie tylko pogłaskać i pobawić, ale także wyjechać pod płaszczykiem wysokich, modnych trendów. W szale wziął pastę do zębów. Niestety jej receptura się nie zachowała, cóż, w dokumentach historycznych odnotowano, że jest ona właściwością krwi.Istnieje wersja, że ​​kilka razy otwierał salony piękności dla arystokratek z Kordoby. Tam nauczył się ubierać stosownie do pory roku, myć włosy aromatycznymi olejkami, pokazał nowe zanieczyszczenia w strzyżeniu i makijażu, ładną fryzurę z grzywką do brwi.

Salony piękności po prostu nie mogły istnieć w średniowieczu. Surowe surowe zasady religijne ograniczają granice grzeszności całego testu, więc standardy są standardami piękna byroinno ale sam ten kosmetyk wprowadził się w eliminację zmysłowych ekstraktów i małych dziecięcych zachcianek.

Pierwsze salony kosmetyczne w Ameryce Północnej pojawiły się pod koniec XIX wieku. Większość z nich prowadziła jinshin. Żywym tego powodem jest historia Marty Matyldy Harper. Martha, urodzona w Kanadzie, jest gospodynią domową, która przez 25 lat pracowała jako pokojówka. W tym czasie wiele się nauczyła o ziołolecznictwie w pielęgnacji twarzy i skóry. Spełniła swoje życzenie, otwierając pierwszy wolnostojący salon kosmetyczny w Rochester w stanie Nowy Jork w 1888 roku. Tak, nie miał równych sukcesów - w końcu w 1928 roku do Harpera przylegało około 500 salonów.

Sama Marta była krytykowana przez zastępcę Martyto za ograniczanie produktów i pracowników, effektya, że ​​niedokładnie lepiej.Dlatego w laboratoriach salonów kosmetycznych produkowane są leki, które stymulują naturalny wzrost i rozjaśniają skórę. To podejście zostało nazwane

W XX wieku salony piękności otwierały się w innych miejscach. W 1905 roku Hatsuko Endo odkrył swoją pracę w Ginza, głównej dzielnicy handlowej Tokio w Japonii. Warto zauważyć, że ten biznes rozpoczął się w kadencji salonu rzemieślniczego. Wraz z planowaniem samodzielnej turystyki, organizacją uroczystości i bankietów, Endo oferuje również usługi okupowania prosomoi, nierozłącznie dziś, ponad 100 lat później, znakiem firmowym Hatsuko Endo protatet.
Resolvendo problemas no HackerRank: Cortando palitos
Tags: javascript, beginners, programming
Published: 2023-03-29 15:01:37

Olá, seja bem vindo a mais um Resolvendo problemas no HackerRank: No caso de hoje, iremos cortar palitos para que eles estejam do mesmo tamanho e depois descartá-los. Vejamos mais informações com a explicação detalhada e sua resolução.

**Cut the sticks -**

Você recebe vários bastões de comprimentos variados. Você cortará iterativamente os palitos em palitos menores, descartando os pedaços mais curtos até não sobrar nenhum. Em cada iteração, você determinará o comprimento do bastão mais curto restante, cortará esse comprimento de cada um dos bastões mais longos e descartará todos os pedaços desse menor comprimento. Quando todos os bastões restantes tiverem o mesmo comprimento, eles não podem ser encurtados, então descarte-os.

Dados os comprimentos de N bastões, imprima o número de bastões restantes antes de cada iteração até que não reste nenhum.

Vejamos um exemplo:

- arr = [1,2,3]

O palito de menor comprimento é 1, logo cortamos esse comprimento dos dois mais longos e descarte os pedaços de comprimento de 1. Temos agora arr = [1,2]. Novamente, o palito mais curto tem comprimento 1, então cortamos essa quantidade do palito mais longo e descarte esses pedaços. Resta apenas, arr = [1], então o descartamos. O número de bastões em cada iteração será: [3,2,1].

- return: _int[]: o número de sticks após cada iteração_.

Vejamos o código em ação:


```
function cutTheSticks(arr) {
    // Write your code here
  let min = 0;
  let count = 0;
  let result = []

  for(let wow = 0; wow < arr.length; wow += 1) {
    let filtered = arr.filter((value) => value > 0);
    count = 0;

  min = filtered.sort((a, b) => a - b)[0];
  
  for(let index = 0; index < arr.length; index += 1) {
    if(arr[index] > 0) {
    arr[index] = arr[index] - min;
    count ++;
    }
  }

  count > 0 && result.push(count);
  }

  return result;

}
```

O código utiliza dois loops for para iterar sobre o array "arr". Dentro do primeiro loop, é feita a filtragem dos valores maiores que zero do array "arr" e é armazenado em "filtered". Depois é definido o valor mínimo de "filtered" em "min". Em seguida, dentro do segundo loop, é verificado se o valor atual do array é maior que zero. Se sim, o valor é subtraído do valor mínimo encontrado em "filtered" e a variável "count" é incrementada. Esse segundo loop realiza a operação de corte dos bastões.

Fora dos loops, é verificado se "count" é maior que zero e se for, adiciona ao array "result". Ao final dos loops, "result" é retornado. O código utiliza o método "filter()" para filtrar os valores maiores que zero e o método "sort()" para ordenar o array em ordem crescente. A função também utiliza variáveis como "min", "count" e "result" para armazenar valores e realizar contagens.


Assim, concluímos mais um _Resolvendo problemas no HackerRank:_ até a próxima.
Backup and Restore Your WordPress Database
Tags: database, wordpress, programming, webdev
Published: 2023-03-29 14:51:39

Your WordPress database is a crucial part of your website, containing all your posts, pages, comments, user data, and more. It’s important to regularly backup your database to protect against data loss and to have a restore point in case something goes wrong. In this blog post, we’ll walk you through how to backup and restore your WordPress database.

**Backup your WordPress Database**
Before making any changes to your website, it’s essential to make a backup of your database. Here are some ways you can backup your WordPress database:

**1. USING A PLUGIN**
There are many plugins available that allow you to backup your WordPress database. Some popular options include UpdraftPlus, BackupBuddy, and WP-DB-Backup. Once you install and activate the plugin, you can set up automatic backups and store them in a secure location, such as cloud storage or an external hard drive.

**2. USING PHPMYADMIN**
You can also manually backup your WordPress database using phpMyAdmin. To do this, follow these steps:

- Log in to your cPanel or Plesk control panel and access phpMyAdmin.
- Select your WordPress database from the left-hand sidebar.
- Click on the “Export” tab at the top.
- Choose the format you want to export your database in (e.g., SQL).
- Click “Go” to download the backup file to your computer.

**3. RESTORE YOUR WORDPRESS DATABASE**
If something goes wrong with your website, such as a hack or a plugin causing issues, you may need to restore your database to a previous version. Here’s how to restore your WordPress database:

**Using a plugin**

If you’re using a backup plugin like UpdraftPlus or BackupBuddy, you can easily restore your database by accessing the plugin settings and selecting the backup file you want to restore from.

**Manually restoring your database**
To manually restore your database, follow these steps:
- Log in to your cPanel or Plesk control panel and access phpMyAdmin.
- Select your WordPress database from the left-hand sidebar.
- Click on the “Import” tab at the top.
- Choose the backup file you want to restore.
- Click “Go” to import the database into your WordPress installation.

In conclusion, backing up and restoring your WordPress database is an essential part of website maintenance. By regularly backing up your database, you can protect against data loss and have a restore point in case something goes wrong. Whether you use a plugin or do it manually, make sure to do it regularly and store it in a secure location.

https://user-meta.com/blog/backup-restore-wordpress-database/
Should AI development beyond GPT-4 be paused?
Tags: discuss, ai, healthydebate, openai
Published: 2023-03-29 14:35:39

Leading AI academics and industry experts - including Steve Wozniak and Elon Musk, published an [open letter](https://futureoflife.org/open-letter/pause-giant-ai-experiments/) today calling for a pause on developing more sophisticated AI beyond OpenAI's GPT-4.  The letter cites _risks to society and humanity_ as a major concern and asks for the pause to enable the industry to develop shared safety protocols. 

Do you agree with the consensus of the experts?  Is a pause even a realistic option when you factor in global politics and capitalism?  Share your thoughts below!
simple start with ACF - plugin (wordpress) to get started with a widget
Tags: wordpress, php, webdev
Published: 2023-03-29 14:29:49

simple start with ACF - plugin (wordpress) to get a widget that contains where a user of the website can send a image and a link in - that has to be approved by the webadmin 

!
here a simple starting point for creating a widget in WordPress using the Advanced Custom Fields (ACF) plugin that allows users to submit an image and a link that needs to be approved by the web admin.

Here are the steps you can follow:

Install and activate the ACF plugin in your WordPress website.

Create a new custom post type for the user submissions by adding the following code to your functions.php file:

`function create_submission_post_type() {
    register_post_type( 'user-submissions',
        array(
            'labels' => array(
                'name' => __( 'User Submissions' ),
                'singular_name' => __( 'User Submission' )
            ),
            'public' => true,
            'has_archive' => true,
            'supports' => array( 'title', 'thumbnail' )
        )
    );
}
add_action( 'init', 'create_submission_post_type' );
This will create a new custom post type called "User Submissions" with support for title and thumbnail.`

**Create a new ACF field group** for the user submissions by going to Custom Fields > Add New in the WordPress admin dashboard.

Add two fields to the ACF field group:

A file upload field for the image
A text field for the link
In the ACF field group settings, set the location rule to "Post Type is equal to User Submissions" so that the fields only appear on the user submission post type.

**Create a new widget **by adding the following code to your functions.php file:


`class User_Submission_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'user_submission_widget',
            __('User Submission Widget', 'text_domain'),
            array( 'description' => __( 'Allows users to submit an image and`
Next.js 13.2.4
Tags: nextjs, javascript, webdev, programming
Published: 2023-03-29 14:19:14

To initialize your project, you should use 

```
npx create-next-app . --experimental-app
```


>Next.js uses server-side rendering by default, be mindful of any code that may rely on browser-specific objects such as **window**

**API**
The API folder allows us to query data from a database.

**Metadata**
We can inject meta data for the web site very easily. 

Adding metadata in the `app/layout` will be applied to the whole website or, You can add this statically to any page that you want create that with.

```javascript
// app/layout.tsx

import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Home',
  description: 'Welcome to Next.js',
};
```

**Tips & Tricks**

<u>Shipping to Production</u>
This will give a production server 

```javascript
npx next build && npx next start
```

<u>To convert to static HTML</u>

```javascript
npx next build && npx next export
```

**Adding env variables**

create a file `.env.local` in the root dir of your project.

The environment variable is only made available server side. To make it available on client side, we use 

```
NEXT_PUBLIC_API_URL=dev
```

**Naming structure**

`page.tsx`

In every route or folder, this serves as the "index" page, this is the component that will be served to you when you go to `/about` on the browser.

```javascript

import type { Metadata } from 'next'

export const metadata:Metadata = {
    title: "Users"
}


const usersPage = () => {
  return (
    <div>page</div>
  )
}

export default usersPage

```

The file is called **page.tsx** but the functional component is called `usersPage`


##Thank you, please follow me


<a href="https://www.buymeacoffee.com/ifeanyichima" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>


<span> 
[![HTML](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://linkedin.com/ifeanyi-thankgod-chima)&nbsp;[![GitHub](https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white)](https://github.com/masterifeanyi)
</span>