teleren/devto huggingface dataset:
The OR operator (||) vs Nullish Coalescing (??)
Tags: javascript, codequality, webdev
Published: 2023-04-25 13:57:44

You may have seen OR operator `||` used commonly to handle default values. But, there is also the less known nullish coalescing operator `??` that can also help with handling default values. Though similar, there are some key deferences between the two.

The OR operator `||` returns the first [truthy ](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value in a series of expressions. If all expressions evaluate to [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) values, the final expression is returned. This means that the OR operator will return the second expression if the first expression is falsy, even if the second expression is also falsy.

For example, consider the following code:
```
const x = 0 || false;
console.log(x); // false
```
In this case, the OR operator returns the second expression `false` because the first expression `0` is falsy.

The nullish coalescing operator (??) returns the first defined value in a series of expressions. If the first expression is null or undefined, the second expression is returned. This means that the nullish coalescing operator will only return the second expression if the first expression is null or undefined.

For example, consider the following code:

```
const y = null ?? 'default';
console.log(y); // 'default'
```
In this case, the nullish coalescing operator returns the second expression `default` because the first expression `null` is nullish.

One of the key differences between these two operators is how they handle falsy values. The OR operator considers any falsy value (e.g. 0, '', false) to be equivalent to false, while the nullish coalescing operator only considers `null` and `undefined` to be nullish.

For example, consider the following code:

```
const z = '' || 'default';
console.log(z); // 'default'

const w = '' ?? 'default';
console.log(w); // ''

```

In this case, the OR operator returns the second expression `'default'` because the first expression `''` is falsy, while the nullish coalescing operator returns the first expression `''` because it is not nullish.

In general, developers should use the nullish coalescing operator when they want to specifically check for null or undefined values, and the OR operator when they want to handle any falsy value. However, it's important to consider the context in which these operators are being used and choose the one for your specific use case.
Protect Production Database from Wrong Migrations
Tags: dotnet, database
Published: 2023-04-25 15:03:58

As a .NET developer, I had a close call when I applied a migration to my production database without changing the database connection string. I was mortified when I realized my mistake, but I quickly got to work finding a solution to prevent it from happening again.

That's when I came up with the idea to add a console message that displays the migration details before applying it. This simple addition gives me the chance to review the migration details and ensure that I am working with the correct database before making any changes.

With this new safeguard in place, I can breathe easy knowing that my production database is safe from accidental alterations. It just goes to show that sometimes the simplest solutions can be the most effective.

```csharp
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        // ... Some code to generate dbContextBuilder
        var context = new ApplicationDbContext(dbContextBuilder.Options);

        // This is where magic happends
        var pendingMigrations = context.Database.GetPendingMigrations();
        Console.WriteLine("*********************************************\n");

        Console.WriteLine("This command is going to apply migrations with following details");

        Console.Write("ConnectionString: ");
        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine(connectionString);
        Console.ResetColor();

        Console.Write("Migrations:\n\t");
        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine(string.Join("\n\t", value: pendingMigrations.ToArray()));
        Console.ResetColor();
        Console.WriteLine();
        Console.WriteLine("*********************************************");

        Console.WriteLine("Do You confirm? (Y/N)");
        var userInput = (Console.ReadLine());

        if (userInput is "Y" or "y")
            return context;

        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Aborted!");
        Environment.Exit(1);
        return null;
    }
}

```

- More info about the [`ApplicationDbContextFactory`](https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli)
The Future of Work: How Automation is Changing the Job Landscape
Tags: automation, information, api, javascript
Published: 2023-04-25 14:51:57


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p6bwzm4qn1o7nojuzl3b.jpg)
Automation is already transforming the job landscape, and its impact is likely to become even more significant in the years to come. In many industries, machines and software are replacing human workers in routine, repetitive, and low-skill tasks. At the same time, new jobs are being created that require new skills and competencies, such as data analysis, programming, and digital marketing.

The future of work is likely to be characterized by greater automation, as machines become increasingly capable of performing complex tasks. This will have both positive and negative impacts on the job market. On the one hand, automation will lead to increased productivity and efficiency, which could boost economic growth and create new job opportunities. On the other hand, it could also lead to job losses and income inequality, as workers with low skills are displaced by machines.

One potential outcome of increased automation is the creation of a "gig economy," where workers are hired on a project-by-project basis rather than being employed full-time. This could offer greater flexibility for workers but also create greater uncertainty and insecurity. It could also lead to a situation where a small number of highly skilled workers control the majority of the work, while others struggle to find employment.

To address these challenges, policymakers and businesses will need to focus on developing new training programs and education initiatives to equip workers with the skills they need to thrive in an automated world. They will also need to consider measures to address income inequality and provide a safety net for workers who are displaced by automation.

Overall, the future of work is likely to be shaped by automation, but its impact will depend on how we choose to respond to the opportunities and challenges it presents.
I draw your weird game ideas, Episode 0.
Published: 2023-04-25 14:49:28

Hello Everyone! Starting today, I will draw your weird game ideas. Yes, I will draw them. It will no doubt be horribly stupid-looking, but I will. Each episode, 3 ideas will be randomly selected via the comments in the ENTER HERE post. That post will look like EPISODE 1: ENTER HERE and the results will look like (title) EPISODE 1. Also, Episode One enter here is live!!!
[Lançamento] Motoca App
Tags: flutter, firebase, astro, tailwindcss
Published: 2023-04-25 14:48:00

---
title: [Lançamento] Motoca App
published: true
description: 
tags: #flutter #firebase #astro #tailwindcss
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8009b4r61fd10pshvarx.png
published_at: 2023-04-25 14:48 +0000
---

Gostaria de compartilhar o lançamento do meu novo aplicativo: Motoca

https://motoca.app/

É um aplicativo para motociclistas. Com ele é possível:

- Criar e compartilhar eventos de motos.
- Controlar o consumo da moto, armazenando os abastecimentos.
- Gerenciar o gasto com manutençoes e salvar a nota fiscal.
- Criar um perfil e armazenar os dados do motociclista e da motoca.
Tecnologias:

Landing page: Astro + TailwindCSS
Aplicativo: Flutter + Firebase

Deixe um comentário se tiver interesse que eu faça um post mais detalhado sobre o processo.
Python Project - Map of Subway of São Paulo
Tags: python, datascience, braziliandevs
Published: 2023-04-25 14:38:29

## Hi everyone! 🤍
Recently I wrote an article where I teach how to make this project using Python, where you build a map with all kind of information of the Subway of São Paulo, Brazil. 

I wrote it with great care and dedication, but it seems like no one is reading this on Medium. I would be happy if you read it and give me feedback on this project. Maybe even interact by liking or commenting on Medium.

I chose to write this tutorial in Portuguese because I don't find much content of this type in my language. But the code is easy to understand, no matter what language you speak. Maybe later on I can bring content in English as well.

[Link to Medium Page](https://medium.com/@liviaalvzs/plotando-um-mapa-interativo-com-informa%C3%A7%C3%B5es-do-metr%C3%B4-de-s%C3%A3o-paulo-usando-python-b0470d8d0b10)
Building the development environment on Amazon Linux 2023 with user_data.txt
Tags: aws, ec2, ansible
Published: 2023-04-25 14:30:14

---
title: Building the development environment on Amazon Linux 2023 with user_data.txt
published: true
description: This article introduces how to build a hook script(user_data.txt) when running EC2 instance on AWS. 
tags: #aws #ec2 #ansible
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-04-25 14:12 +0000
---

In my case, requirements for an expected development environment on EC2 are as follows.

### Requirements
#### Mandatory:
- The following programming language can be available with a specific(latest) version:
  - Ruby
  - Python
  - Node.js
  - Rust
- Well equipped with build essential and useful tools
  - jq
  - ripgrep(rg)
  - fd(fd-find)
  - fzf

#### Optional:
- Could be accessed through EC2 instance connect, the browser-based terminal on AWS Management Console


### user_data.txt

https://gist.github.com/kyagi/c28935eeb83b3b03a296a7ed2a179abc#file-user_data-txt

### how to run

I use ansible and its collection `amazon.aws.ec2_instance collection` with my configuration json file with variables to pass over ansible at runtime. 

```
➜ pyenv exec ansible-playbook -i hosts site.yml --extra-vars "@workstation.json"
```

```
➜ cat roles/spawn/tasks/main.yml
---
- name: Spawn an ec2 instance
  amazon.aws.ec2_instance:
    name: "{{ instance_name }}"
    key_name: "{{ key_name }}"
    vpc_subnet_id: "{{ vpc_subnet_id }}"
    instance_type: "{{ instance_type }}"
    security_groups: "{{ security_groups }}"
    network:
      assign_public_ip: true
      private_ip_address: "{{ private_ip_address }}"
    image_id: "{{ image_id }}"
    user_data: "{{ lookup('file', 'user_data.txt') }}"
    volumes:
      - device_name: /dev/xvda
        ebs:
          volume_size: 30
          volume_type: gp2
          delete_on_termination: true
    tags:
      Owner: "{{ owner }}"
      Stack: "{{ stack }}"
      Project: "{{ project }}"
      Application: "{{ application }}"
      Ec2InstanceConnectAccess: "{{ ec2_instance_connect_access }}"
```

```
➜ cat workstation/workstation.json
{
  "instance_name": "workstation",
  "key_name": "__key-name__",
  "vpc_subnet_id": "__subnet-id__",
  "instance_type": "t4g.small",
  "security_groups": ["__sg-id1__", "__sg-id2__"],
  "private_ip_address": "10.0.0.10",
  "image_id": "resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64",
  "owner": "kyagi",
  "stack": "deveplopment",
  "project": "workstation",
  "application": "hodgepodge of development tools",
  "ec2_instance_connect_access": "true"
}
```
Automate Weekly Newsletter
Tags: powerfuldevs, learning, security, automation
Published: 2023-04-25 14:05:10

Last week the [**blog**](https://dev.to/balagmadhu/stay-ahead-in-power-platform-the-role-of-continuous-learning-3o5l) was to automate the Microsoft RSS feed. This week the concept is same but the power automate flow is simplified and the RSS feed that is automated is with security podcast [**_SmashingSecurity_**](https://www.smashingsecurity.com/)

## Implementation:

- **Collection of data**:
The RSS connector would enable you to get a JSON data which we would manipulate in the following steps


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


- **Condition**:
Instead of leveraging filter array, condition is leveraged to pull the needed content. We will Parse the Publish Date field from the RSS feed leveraging function as below. Grabbing the last published feed would be using the **[0]** index and the object is  
**['publishDate']**

```
body('List_all_RSS_feed_items')[0]?['publishDate']
```

Compare the latest publishDate and validated if its published in the last 7 days. 

`addDays(utcNow(),-7)`


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



1. Yes - If the condition above is satisfied , post the message in a Microsoft TEAMS channel

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

2. If the condition is not met then no action 

- **Email Composition**
Mapping the Subject of email as the RSS feed title 

```
body('List_all_RSS_feed_items')[0]?['title']
```

- **Extracting Test for body of email**
The split() function returns an array of substrings. We have used 2 delimiters with the split function ('Sponsored by:' or 'Episode links:'). [0]: This specifies that we want to access the first item in the resulting array, which is the substring before "Sponsored by:".[1]: This specifies that we want to access the second item in the resulting array, which is the substring after "Episode links:".

```
split(split(body('List_all_RSS_feed_items')[0]?['summary'],'Sponsored by:')[0],'Episode links:')[1]
```

The simplified PowerAutomate flow would be 

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



The **result** !! automated the PodCast summary as a weekly newsletter to the team to learn and enrich the knowledge ....


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3p9y1995nfst4key894.png)
Mix
Tags: elixir, beginners, backend
Published: 2023-04-25 14:01:04

This is going to be the last (I hope) post that is not focused on programming. But, for me, it's important to know all the aspects I've written before dive into the language, because all of them are important tools in a day to day writing code in Elixir.

Mix is a build tool and package manager for Elixir. It is used to create, compile, and manage Elixir projects.

Mix is designed to simplify the build process of Elixir applications by automating tasks such as compiling modules, managing dependencies, and generating documentation. It also provides a testing framework to help developers ensure the quality of their code. In addition, Mix comes with a powerful set of tasks and plugins that make it easy to manage project tasks like running migrations or deploying code to production.

For example you can create Elixir projects with this:

```
> mix new my_elixir_project
```

If you need to add dependencies to your projects you have to add them to your `mix.ex` file and then in the terminal download those dependencies:

```
> mix deps.get
```

You can also run your tests to check that everything is working as expected:

```
> mix test
```

If you want to see all the options you have you could use the help

```
>  mix help
mix                   # Runs the default task (current: "mix run")
mix app.config        # Configures all registered apps
mix app.start         # Starts all registered apps
mix app.tree          # Prints the application tree
mix archive           # Lists installed archives
mix archive.build     # Archives this project into a .ez file
mix archive.install   # Installs an archive locally
mix archive.uninstall # Uninstalls archives
mix clean             # Deletes generated application files
...
...
...

```

Overall, Mix is an essential tool for any Elixir developer and helps to streamline the development process.

---
Thanks for reading! My goal is to make Elixir accessible and easy to understand for everyone. If you have any questions or feedback, please don't hesitate to reach out. And be sure to check back regularly for more articles on https://dev.to/calbertora, as I strive to make each post as clear and readable as possible.
Moonly weekly progress update #46 - New design for a login page
Tags: javascript, blockchain, saas, nft
Published: 2023-04-25 13:57:32


## Moonly weekly progress update #46 — New design for a login page

![](https://cdn-images-1.medium.com/max/3200/1*r1Y2Xo2OVDBmkPmFK1V-fQ.png)

Hello Guys! How are you all? Some devs were on a small vacation (deserved vacation) this week, but we manage to finish some important stuff.

Finished a new design for a login page. Users can log in via Wallet or via Discord but now we will also integrate logging via Twitter(coming soon).

Once you are logged in you can link your Wallet and your Discord and that way you can upgrade your profile to the next level and you will be able to use some of the new tools and new features that will be locked for the visitors!

**Weekly developer progress:**

* Checked and fixed the dropdown not showing in some page source

* Finished login page

* Migrated new changes on the sniper bot to the Moonly codebase

* Finalise changes to Big DB structure

* Run reprocessing of transactions

* Start transaction ID scan over

* Modernise scrapers-mints package to discover mints from the blockchain

* Started working on the multi-collection functionality

* Implemented a workable multi-collection feature except for the submission

* Rewrote the submission form algorithm

* Deployed the multi-collection HVB at the bot test server

* The research was done on Solana runtime limitations

* Fixed RPC server out of disk space

**Staking (Locking):**

* Update tokens and seed attributes for selected collections

* Populate collections on production

* Fixed issue with new wallet staking

* Brainstorming about raffle reward

* Setup Staking environment on Windows to investigate phantom mobile-related issues

* Fixed multi-select button responsive issue on the small screen

Check out our latest blog posts:

[https://moon.ly/blog/moonlys-staking-service-is-live/](https://moon.ly/blog/moonlys-staking-service-is-live/)

[https://moon.ly/blog/trump-launches-second-nft-wave-seems-to-ditch-the-first-trump-card/](https://moon.ly/blog/trump-launches-second-nft-wave-seems-to-ditch-the-first-trump-card/)

[https://moon.ly/blog/nft-use-cases-beyond-digital-artworks/](https://moon.ly/blog/nft-use-cases-beyond-digital-artworks/)

Upcoming NFT collections:

[https://moon.ly/nft/tri3ute](https://moon.ly/nft/tri3ute)

[https://moon.ly/nft/cyber-syndicate-nft](https://moon.ly/nft/cyber-syndicate-nft)

[https://moon.ly/nft/webcityclub](https://moon.ly/nft/webcityclub)

[https://moon.ly/nft/the-humania--season-2](https://moon.ly/nft/the-humania--season-2)

Minted projects worth mentioning:

[https://moon.ly/nft/the-heist](https://moon.ly/nft/the-heist)

[https://moon.ly/nft/mad-lads](https://moon.ly/nft/mad-lads)

[https://moon.ly/nft/sharx](https://moon.ly/nft/sharx)

[https://moon.ly/nft/okay-bears](https://moon.ly/nft/okay-bears)
Handle protected page routes in NextJS using NextAuth
Tags: nextjs, nextauth, route
Published: 2023-04-25 13:44:39

For this article, we will use the middleware technique.

To use this functionality, you must have at least `NextAuth.js 4.2.0` and `Next.js 12` installed.


## Configuration
Let's configure the server by adding a new environment variable to the `.env.local` file.
```
NEXTAUTH_SECRET=addAnythingYouLike
```

## Create a Middleware
Create a file named `middleware.js` or `.tsx` in the `src` folder.

> Note: if you don't have `src` folder create the `middleware.js` on the root folder

Lets add code for middleware

**Protect all routes**
Use the piece of code below to make all pages protected.

```javascript
export { default } from "next-auth/middleware";
```

**Protect selective routes**
Lets protect profile and posts route with the help of `matcher`. You can put the route based on your requirements 
```javascript
export { default } from "next-auth/middleware";

export const config = { matcher: ["/profile", "/posts"] };

```

**Protect routes inside directory**
Lets protect all routes inside dashboard folder.

```javascript
export { default } from "next-auth/middleware";

export const config = { matcher: ["/dashboard/", "/dashboard/:path*"] };

```
Read more about [matcher](https://nextjs.org/docs/advanced-features/middleware#matcher) and [NextAuth Middleware](https://next-auth.js.org/configuration/nextjs#middleware)

Thats It! 



Happy Coding!
2 ways to check file size in Linux
Tags: linux
Published: 2023-04-25 13:28:48

If you are a Linux user, you might have wondered how to get the file size of a file or a directory on your system. There are several ways to do this, and in this blog post, I will show you some of the most common and useful commands to find out the file size in Linux.

One of the simplest and most widely used commands to get the file size is the `du` command. The `du` command stands for disk usage, and it displays the disk space occupied by files and directories. You can use the `du` command with various options to customize the output. For example, if you want to see the file size in human-readable format (such as kilobytes, megabytes, gigabytes, etc.), you can use the `-h` option. If you want to see the total file size of a directory and its subdirectories, you can use the `-s` option. If you want to see the file size of each file and directory in a directory, you can use the `-a` option. Here are some examples of using the `du` command:

- To see the file size of a single file, such as `file.txt`, you can use: `du -h file.txt`
- To see the total file size of a directory, such as `dir`, you can use: `du -sh dir`
- To see the file size of each file and directory in a directory, such as `dir`, you can use: `du -ah dir`


{% embed https://www.howtouselinux.com/post/check-file-size-in-linux %}


Another command that you can use to get the file size is the `ls` command. The `ls` command stands for list, and it displays information about files and directories. You can use the `ls` command with various options to customize the output. For example, if you want to see the file size in human-readable format, you can use the `-h` option. If you want to see the file size in bytes, you can use the `-s` option. If you want to see more details about files and directories, such as permissions, ownership, modification date, etc., you can use the `-l` option. Here are some examples of using the `ls` command:

- To see the file size of a single file, such as `file.txt`, you can use: `ls -sh file.txt`
- To see more details and file size of a single file, such as `file.txt`, you can use: `ls -lsh file.txt`
- To see more details and file size of each file and directory in a directory, such as `dir`, you can use: `ls -lsh dir`

There are other commands that you can use to get the file size in Linux, such as `stat`, `find`, or `wc`. However, I find that the `du` and `ls` commands are enough for most cases. I hope this blog post has helped you learn how to get the file size in Linux. If you have any questions or feedback, please leave a comment below.