teleren/devto huggingface dataset:
Top 7 Featured DEV Posts from the Past Week
Tags: top7
Published: 2022-02-23 01:30:07

---
title: Top 7 Featured DEV Posts from the Past Week
published: true
description: A round up of the most-read and most-loved contributions from the community this past week
tags: icymi 
cover_image: https://thepracticaldev.s3.amazonaws.com/i/sfwcvweirpf2qka2lg2b.png
---

_Every Tuesday we round up the previous week's top posts based on traffic, engagement, and a hint of editorial curation. The typical week starts on Monday and ends on Sunday, but don't worry, we take into account posts that are published later in the week._ 

## Biases... we all have them.

... and developers are no exception. This quick tour of software developer-specific biases by @rajasegar is a great way to check in on your own assumptions and unproductive thought patterns as a dev.

{% embed https://dev.to/rajasegar/web-developers-and-cognitive-biases-245b %}


## Move on up

SQL databases are a staple in commercial programming. To that effect, @mauriciolinhares teaches us how to optimize our queries correctly.

{% embed https://dev.to/mauriciolinhares/optimizing-your-mysql-queries-437i %}


## Autoplaying around 

Autoplay can be pesky. @thormeier will show you how to create a web component that allows your users to decide whether they want to play a gif or not. 

{% embed https://dev.to/thormeier/autoplay-begone-how-to-create-a-non-autoplay-gif-web-component-hbf %}

## When the leap pays off

@amanda_peters12322 went from Registered Nurse to Software Developer in 2021 for a variety of reasons — one of which being career fatigue _(and literal fatigue, I'm sure. Shoutout to all the hardworking nurses out there like Amanda_). In this post, you'll learn a bit about their switch to software development. Motivating to say the least!

{% embed https://dev.to/amanda_peters12322/i-put-away-my-stethoscope-and-grabbed-my-laptop-4g2j %}


## Gotta catch 'em all — and then some

There are only 893 unique pokemon, but @mage_ai taught their AI to fix that problem. Check out their other creations like Firenite, Hydraleaf, and Albapod!

{% embed https://dev.to/mage_ai/teaching-ai-to-generate-new-pokemon-3kk1 %}


## GitHub window-dressing

If you haven’t updated your GitHub profile in a while, @saritchaethudis runs through all of the fundamentals to make sure your GitHub profile shines.

{% embed https://dev.to/saritchaethudis/make-your-github-profile-stand-out-19b2 %}


## Meet Convoy

Convoy is an open-source "Swiss army knife" for publishing web-hook events. @subomioluwalana created it after looking for a tool to push web-hook events while building a Fintech API and not finding anything they liked. SUper interesting looking service. Congrats, Subomi! 

{% embed https://dev.to/subomioluwalana/introducing-convoy-18f4 %}


_That's it for our weekly Top 7 for this Tuesday! Keep an eye on dev.to this week for daily content and discussions...and be sure to keep an eye on this series in the future. You might just be in it!_
005/100 Days of Code: The habits
Tags: 100daysofcode, javascript, beginners
Published: 2022-02-23 00:50:02

Toda mudança de hábito requer **esforço** e **constância**, e isso não é problema nenhum quando estamos empolgados com uma nova ideia e com a expectativa do quanto ela pode ajudar outras pessoas!

O problema é que durante esse processo de construção somos pegos de surpresa por dias em que a nossa produtividade, criatividade e disposição não parecem colaborar com nenhuma atividade, são nesses momentos que nossa mente começa a criar justificativas, muitas vezes bem lógicas, para postergarmos ou deixarmos de lado qualquer atividade, principalmente as que ainda estamos nos acostumando a fazer.

## Ontem foi um desses dias pra mim!
E por mais que tenha produzido algumas horas de código, o sentimento de falta de progresso liderou em grande parte do meu dia, antes de dormir a minha lista de atividades e meu painel de controle de novos hábitos estavam pintados em escarlate e a frustração foi ainda maior.

Mas não ache que isso tudo é apenas um desabafo de alguém descontente, muito pelo contrário, é na verdade pra te falar:
> "Hoje o dia pode ter sido ruim, talvez seu sentimento seja de total improdutividade nesse momento e ESTÁ TUDO BEM!"

Lembre-se sempre:
- Amanhã é uma nova oportunidade para avançar, não abra mão da sua evolução por um dia que, aparentemente, não deu muito certo
- Pare, respire e repense no planejamento, aproveite a recuperação de um dia improdutivo para reconhecer as suas atuais limitações e, caso entenda que alguma atitude específica e dependente totalmente de você, possa ter contribuido para a indisposição, crie formas de combatê-las
- Prefira redistribuir as atividades do dia anterior ao invés de tentar executá-las de uma só vez junto com as atividades de hoje na intenção de "correr atrás do tempo perdido", isso pode criar uma grande bola de neve de atividades não realizadas

## Disclaimer
Se você identificar que esses episódios são recorrentes e/ou duradouros busque ajuda profissional, nunca descarte a alternativa de uma boa terapia, uma consulta a uma nutricionista ou um checkup rotineiro, leve sua disposição a sério!

## Outros Canais
Fique à vontade para entrar em contato comigo por essas outras mídias sociais também:
- [LinkedIn](https://www.linkedin.com/in/joaovitoralexandre/)
- [Instagram](https://www.instagram.com/alexandrebekor/)
- [Twitter](https://twitter.com/alexandrebekor)
splStorage.js (Stupid Library) !!!
Tags: javascript, tooling, showdev, webdev
Published: 2022-02-23 00:42:17

{% github https://github.com/darkterminal/splStorage.js %}
Simple LocalStorage Wrapper for CRUD

---

## Available Mehod
- `splStorageJs.isDefined(collection)` This code is checking to see if the collection is defined in local storage.
- `splStorageJs.collections(name)` This is a function that will return the collection of data that is stored in local storage.
- `splStorageJs.whereNotEqual(collection, key, value)` This code is filtering out the items in the collection that do not have the key equal to the value.
- `splStorageJs.whereEqual(collection, key, value)` This code is filtering the collection of objects by the key and value.
- `splStorageJs.insert(collection, data)` This is a function that inserts data into a collection.
- `splStorageJs.insert(collection, where[key, value], data[key, value])` This is a function that update data in a collection
- `splStorageJs.delete(collection, key, value)` This a function that delete data in a collection
- `splStorageJs.has(collection, key, value)` This a function that check data is exists or not in a collection

### Install
- unminified `https://cdn.jsdelivr.net/gh/darkterminal/splStorage.js@master/splStorage.js`
- minified `https://cdn.jsdelivr.net/gh/darkterminal/splStorage.js@master/splStorage.min.js`
Não use mais switch no PHP 8
Tags: php, webdev, laravel, tutorial
Published: 2022-02-23 00:26:04

`Match expression` faz parte dos novos recursos do `php8`, com sintaxe sucinta, substitui o uso de `switch` no seu código.

---

**Com switch:**

```
$numero = 1;
$resposta = '';
switch ($numero) {
    case 0:
        $resposta = "$numero é igual a 0";
        break;
    case 1:
        $resposta = "$numero é igual a 1";
        break;
    case 2:
        $resposta = "$numero é igual a 2";
        break;
    default:
        $resposta = "$numero não é igual a 0, 1 ou 2";
}

echo $resposta;
```

**Com match expression:**

```
$numero = 1;
$resposta = '';

$resposta = match($numero) {
    0 => "$numero é igual a 0",
    1 => "$numero é igual a 1",
    2 => "$numero é igual a 2",
    default => throw new \Exception("$numero não é igual a 0, 1 ou 2")
};

echo $resposta
```

_Match expression utiliza `===` na comparação._
A arte de fazer
Tags: braziliandevs, brasil
Published: 2022-02-23 00:05:12

Bom este é um daqueles posts que te motivam a fazer o seu portfólio, sei que já tem muito post parecido (e com listas do que fazer)... Quero registrar aqui minha opinião.

E a minha opinião é faça seu portfólio, mesmo que ninguém veja, mesmo que ninguém elogie seu trabalho, mesmo que não seja útil. Faça nem que seja pela sua diversão, que seja algo que você goste.

Muitos podem dizer ah mas eu não tenho o equipamento XYZ (pra não dizer marcas iiii), e com ele eu faria muito melhor. Que nada, a 10 anos não tínhamos esses equipamentos tecnológicos que temos hoje e desde a época de Davinci já tinhamos coisas maravilhosas (como seus desenhos).

Se você quer desenvolver você não precisa de um computador da Nasa. Se meu computador (Deus me livre iiii) quebrasse hoje eu não pararia de desenvolver, porque tenho um Raspberry Pi. Sei que é muito limitado, mas é algo supriria minha necessidade neste momento e ainda faria algo com eletronica iiii.

E só concluindo que mesmo que ninguém veja, mesmo que ninguém fale nada. E faça algo que você gosta, algo que você use, algo que você veja depois e pense "Foi legal fazer isso!". Mesmo que seja copiando tutoriais na internet (mas por favor, dê o seu toque de personalidade)...

E é isso agradeço a todos que lerem, e como disse acima mesmo que ninguém leia, comente, etc iiii estou fazendo isto para treinar também a minha escrita iii

PS.: Isto também é pra mim, pra me lembrar de nunca deixar de fazer algo iii
Using sql.js-httpvfs with browser <script type=module>
Tags: sqlite, webassembly, javascript, webpack
Published: 2022-02-22 23:32:49

---
title: Using sql.js-httpvfs with browser <script type=module>
published: true
description: 
tags: sqlite,wasm,javascript,webpack
//cover_image: https://direct_url_to_image.jpg
---

https://www.npmjs.com/package/sql.js-httpvfs is an amazing package that lets us perform SQL queries against a remote database hosted anywhere [range requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests) are supported. A special .wasm SQLite runs in the browser; a typical query might only need to fetch half a dozen 4kb pages from a 1GB database file.

It is normally used with webpack. What if we want to distribute it as a [JavaScript module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) so we can just import it from our browser-native `<script type=module>` and develop a simple project in pure JavaScript?

I edited the example's `webpack.config.js` (https://github.com/phiresky/sql.js-httpvfs/tree/master/example) to output a module:
```javascript
module.exports = {
  entry: "./src/index.ts",
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
  },
  output: {
    filename: "sql-httpvfs.js",
    library: {
      type: "module" // output a JavaScript module
    },
    module: true, // truly
  },
  experiments: {
    outputModule: true  // yes, we really want one
  },
  optimization: {
    minimize: true
  },
};
```

`index.ts` is changed to export a useful function:
```javascript
import { createDbWorker } from "sql.js-httpvfs";

const workerUrl = new URL(
  "sql.js-httpvfs/dist/sqlite.worker.js",
  import.meta.url
);
const wasmUrl = new URL("sql.js-httpvfs/dist/sql-wasm.wasm", import.meta.url);

async function load(url: string) {
  const worker = await createDbWorker(
    [
      {
        from: "inline",
        config: {
          serverMode: "full",
          url: url,
          requestChunkSize: 4096,
        },
      },
    ],
    workerUrl.toString(),
    wasmUrl.toString()
  );
  return worker;
}

export { load }; // only `load` is visible to the importer
```
Run webpack. In this example it will write 3 files to `./dist/`. We can copy those files to wherever we want to use our new module.

Now we can import that module directly in `index.html`, and play around with loading database URLs in the browser console:
```html
<script type="module">
    import { load } from "./dist/sql-httpvfs.js";
    window.loadDB = load;
</script>
```

Modules are automatically [deferred](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer), and won't run until the document has been parsed. Our module code can start manipulating the page right away without having to e.g. register a `load` or `$(document).ready` handler.
First Day at Flatiron 
Tags: beginners, programming
Published: 2022-02-22 22:44:14

Reporting in during my first day of the software engineering program at Flatiron School.

I'd be lying if I said that my nerves aren't running a little high. I feel as though all of the pre-work I completed has given me a solid starting off point to tackle this course but I know there are still tons of challenges ahead.

I'm updating this blog as I go through my first day, and there are currently a few of us getting to know each other in one of the Breakout rooms that our instructor Sam set up. Everyone seems super supportive so far and that already makes me feel much easier about getting through this program. The collaborative aspect of this field is one of the major aspects that drew me towards this space and I look forward to working closely with the members of my cohort.

1:00 pm has come and so it's time for lunch break. Taking 30 minutes to get outside, walk the dog, and take in some fresh air. After a brisk break to keep the mind clear, I'll be back to get some studying in before our lecture on Variables and Data Types begins. 

2:00pm is now here and its time to hop into lecture. Today's topic was Variables and Data Types. Nothing all new information wise compared to what we touched on this topic during the pre-work. The instructor did provide some clarity on if, else, if conditions for me, this was definitely an area where I struggled a bit during pre-work.

We had a brief sync with Sam, our cohort leader, after the lecture and then broke for the day to tackle some assignments given to us. I think I'm going to end this first post here and I'll check back in tomorrow morning.
Converting a site to Nextjs
Tags: nextjs, javascript, webdev
Published: 2022-02-22 23:26:43

Hello there, I'm new to Next and I am trying to get this [template ](https://www.free-css.com/free-css-templates/page273/savory) to Nextjs. But I've been stuck trying to get the:

```
<script>
  document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
  });
</script>
```

At this point I don't know what to do anymore.
This is what I have:
```
<Script
        id="load-content"
        dangerouslySetInnerHTML={{
          __html: `document.addEventListener("DOMContentLoaded", function (event) {
            masonryBuild();
          });`,
        }}
      />
      <Script
        id="load-content2"
        dangerouslySetInnerHTML={{
          __html: `document.addEventListener("DOMContentLoaded", function (event) {
            navbarToggleSidebar();
            navActivePage();
          });`,
        }}
      />
      <Script src="/main.js" />
      <Script src="/mine.js" />
```

It's supposed to work, but it's not!
Freshly Learned Kotlin Techniques
Tags: kotlin, programming, beginners, tutorial
Published: 2022-02-22 23:25:14

Recently, the get/set methods have been making more sense.

In Android Studio, in the XML pages (activity) you can create an object. Once you give it a name, you can start some code in the .kt side

Like all variables before you change them, objects too have to be defined.

[val or var] [name of string you want to create] : [type of object] = findViewById (R.id.[the id name you created in the XML page])

Once you call it, you can set it.

[string name you created].[type of input you are going to change] = [value]

Example below for the most used type, TextView

```
val strengthText: TextView = findViewById(R.id.strengthText)
strengthText.text = "Strength"
```
There are other types and methods, but they all follow the same pattern. I’ll leave an example of how to change a picture.

```
val carPicture = findViewById<ImageView>(R.id.carPicture)
carPicture.setImageResource(R.drawable.car_one_detail)
```
Using attr_accessor to clean up your calls between models

Tags: rails, ruby, webdev, beginners
Published: 2022-02-22 22:53:14


In my [glorious real estate management app](https://github.com/marelons1337/kapturek) I thought that it'd be cool to know how much rent a tenant has to pay without typing `tenant.flat.rent` every single time (tenant `belongs_to :flat`)
So instead, we can just use `attr_accessor :rent` as below. 
{% embed https://gist.github.com/marelons1337/1ece689d5cda0f8e4937f4fca2b5f4bc.js %}
Now I can always access tenant's rent by simply going for `tenant.rent`
Rollback Functions in Golang
Tags: go, backend, rollbackfunctions, errorshandling
Published: 2022-02-22 21:42:06

**Errors in Go**

Go methods can return multiple values. One of these values can be an error. The zero value of an error is nil. After the call of each method, you check the error value with nil. If it is not equal to nil, then an error has occurred.

**How to Implement a Rollback Function?**

A function can call multiple methods in it. When an error occurs in one of the methods, you will need to reverse the methods called before the error. Reverting the output of the methods is done by implementing a rollback function and calling it every time an error occurs.

The concept of the rollback function is reverse-engineering. First, extract information from the called methods. This information is the success status of each method. The state may be a boolean variable with a value equal to true when the method succeeds and false when it fails; it also may be a string with the result of the method.

Then, collect the information and abstract it into a model. Finally, pass this model to the rollback function and review each status; if it is a success status, reverse the method and if it is a failure status, ignore it.

In this way, there are no side effects to the function when an error occurs. Moreover, the program will be maintainable.

**Example**

```
//Modeling
type CreateHotelStatusModel struct {
	HotelId             string `json:"hotelId"`
	FloorId             string `json:"floorId"`
	RoomId              string `json:"roomId"`
	IsFirstFloorCreated bool   `json:"isFirstFloorCreated"`
	IsFirstRoomCreated  bool   `json:"isFirstRoomCreated"`
}

func CreateHotel(hotelName string) error {
	var hotelStatusModel CreateHotelStatusModel
	//create hotel DB record
	hotelId, createHotelDBErr := CreateHotelDBRecord(hotelName)
	//Information extraction
	hotelStatusModel.HotelId = hotelId
	if createHotelDBErr != nil {
		createHotelRollback(&hotelStatusModel)
		return createHotelDBErr
	}

	//create first floor
	floorId, isFloorCreated, createFloorErr := CreateFirstFloor(hotelId)
	hotelStatusModel.FloorId = floorId
	hotelStatusModel.IsFirstFloorCreated = isFloorCreated
	if createFloorErr != nil {
		createHotelRollback(&hotelStatusModel)
		return createFloorErr
	}

	//create first room
	roomId, isRoomCreated, createRoomErr := CreateFirstRoom(floorId)
	hotelStatusModel.RoomId = roomId
	hotelStatusModel.IsFirstRoomCreated = isRoomCreated
	if createRoomErr != nil {
		createHotelRollback(&hotelStatusModel)
		return createRoomErr
	}
	DispatchEvent("success","topic")
	return nil
}

//Review
func createHotelRollback(statusModel *CreateHotelStatusModel) {
	if statusModel.HotelId != "" {
		DeleteHotelDBRecord(statusModel.HotelId)
	}
	if statusModel.IsFirstFloorCreated {
		DeleteFloor(statusModel.FloorId)
	}
	if statusModel.IsFirstRoomCreated {
		DeleteRoom(statusModel.RoomId)
	}
	DispatchEvent("failure","topic")
}
```
Some good link
Published: 2022-02-22 21:35:15

https://dev.to/byteslash/metamask-authentication-in-nextjs-with-third-web-55ff

https://dev.to/ishanme/building-a-web3-dapp-authentication-with-react-web3js-and-metamask-12a7

https://dev.to/anishde12020/twnft-mint-your-tweets-as-nfts-easily-and-for-free-2c45


https://dev.to/byteslash/metamask-authentication-in-nextjs-with-clerk-34fe
Let Your Enthusiasm Shine
Tags: jobseeker, career, gettinghired, beginners
Published: 2022-02-22 21:12:57

_Written by Brian Skory, Tech Talent Manager of [Stout Systems](https://www.stoutsystems.com/meet-stout-systems/)_

When someone checks in with me after having completed their interview, my guess is as good as anyone’s whether they will be the candidate of choice or not…except when I hear them say one thing: “I am really excited about this opportunity.” More times than not, when I hear them say those words, they actually do end up being the candidate of choice. When the interviewee reports back that “this would be my dream job,” or “they seem like exactly the kind of people I want to work with” or “this is the perfect work culture for me,” I’m confident that the hiring manager will pick up on that. 

And think about it... if you narrowed down your interview pool to three good candidates, all of them with similar skills, education, and experience, wouldn’t you be attracted to the candidate most attracted to you, your role, and your company? As the saying goes, we tend to like people who like us. Additionally, hiring managers don’t just want good technical fits, they want people who are going to stick around for a while. People who are genuinely excited about their jobs are generally the ones who end up staying. 

Now, I’m not saying to fake, or even exaggerate, your enthusiasm in an interview. What I am suggesting is that if you genuinely are excited about the opportunity, now is not the time to put on your poker face. If you are feeling excited about a role, a company, or a development team, make sure that your interviewers know it. It just might make the difference between your getting the role over somebody else.

If you're looking for work, please [submit your resume](mailto:recruit@stoutsystems.com) or [browse our job board](https://www.stoutsystems.com/jobs) to determine if you are a match for a job that we have available. We host free career webinars every week - [visit our event calendar](https://www.stoutsystems.com/events) to RSVP!
Laravel 8 Ecommerce Development
Tags: laravel, php, javascript
Published: 2022-02-22 21:00:20

Welcome to my laravel 8 ecommerce development with paystack payment integration.

{% embed https://www.youtube.com/watch?v=0k9pmBYgWkU&list=PLN-ksS_i1Xpwu9xDRcGhaWxFQUQfi469y %}

Features:
- Add to cart
- Checkout
- Payment Verification
- Admin Dashboard
- Customer Dashboard
and more
Junior ASP.NET developer confusion 
Published: 2022-02-22 20:40:02

Hi .. what do you think is most important for me to learn as a junior ASP.NET Core developer                                    I've just made a career shift from electrical engineering and I'm little confused abuout topics to study beside my web work                        Is more important to focus on dotnet core or the science part like algo & ds or to keep focus on C# advanced topics to master it
First Post!
Tags: beginners
Published: 2022-02-22 20:21:19

Today I am posting about my time with Flatiron School so far. 

I really enjoy the way the online curriculum is laid out. In addition to making content easy to understand, they have technical coaches standing by to help when necessary. The group of students I am with seems very kind and I'm hoping we can help each other through this first phase of our schooling.