teleren/devto huggingface dataset:
create-react-app using Bash
Tags: react, codenewbie, bash, tailwindcss
Published: 2022-07-10 18:54:43

Hi, this is my first post!

This post I am going to share how to setup a React project using Bash

## Why did I did what I did??
I started using Ubuntu as my primary Operating System and eventually as any developer out there I came across the point when I had to start learning Bash. Scripting in Bash always felt fascinating but while I was on my learning ropes I wanted to create an actual script that could help me with my daily tasks.
So one of the most mundane things beginners do while starting a React project is open up the terminal, navigate to location, enter `npx create-react-app xyz-project`, wait for it to finish, enter the src and public and remove everything and then finally start. Since I was also on the initial stages of React, I didn't have much knowledge about all the other things that we could do but anyway.
What my script does is, all we need to do is execute and enter the name of the project and whether we wanna install tailwind or not (I love Tailwind CSS and its my goto framework) and voila we're ready to start development.

```
#!/bin/bash
read -p "Enter the name of the project: " projectName
echo "#######################################"
echo "########### Starting Script ###########"
echo "#######################################"

#Change the directory according to wherever you store your development file
startupFolder='/home/brownie/Desktop/Development/react-startup-files'

npx create-react-app $projectName

cd $projectName

echo "This is the $projectName directory"

ls -la

echo "Removing src folder"

rm -r src/

mkdir src

cd src

touch index.js App.js index.css

mkdir components

echo "The new src/ directory"

for i in $(ls)
do
    echo $i
done

echo "Writing in the index.js"
cp $startupFolder/index.js index.js
cat index.js

echo "Writing in the App.js file" 
cp $startupFolder/App.js App.js
cat App.js

cd ..

echo "Removing public folder"

rm -r public/

mkdir public

cd public/

touch index.html

echo "The new public/ directory"

for i in $(ls)
do
    echo $i
done

echo "Writing index.html"
cp $startupFolder/index.html index.html
cp $startupFolder/favicon.ico ./
cat index.html

cd ..

read -p "Do you want to install Tailwind?(y/n) " tailwindChoice

if [[ "$tailwindChoice" == "y" ]]
then
    npm install -D tailwindcss postcss autoprefixer
    npx tailwindcss init -p

    echo "Writing the index.css file"
    cd src/
    cp $startupFolder/index.css index.css
    cat index.css

    echo "Writing the tailwind.config.js file"
    cd ..
    cp $startupFolder/tailwind.config.js tailwind.config.js
    cat tailwind.config.js
fi

echo "Removing Git Files"
sudo rm -r .git
rm .gitignore

read -p "Do you want to open in code?(y/n) " codeChoice

if [[ "$codeChoice" == "y" ]]
then
    code .
fi

echo "Closing Terminal"

exit
```

Ofcourse there can be a lot of modifications that can be made that being said its just a basic bash script to improve basic producivity workflow. 
Feel free to share your thoughts on how you would upgrade this script to better suit your needs
Install Bun on WSL
Tags: javascript, bunjs, tutorial, wsl
Published: 2022-07-10 18:54:18

Bun(https://bun.sh) is a new JavaScript runtime with a native bundler, transpiler, task runner and NPM client built-in. Bun is superfast compared to NodeJS. 

## Enable WSL from Windows Features

> To turn on the Windows Subsystem for Linux feature, click the checkbox like this:

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

## Install Linux Distro

- To work with WSL, you should have installed at least one distro on your computer.

> To install Ubuntu, Run this:

```
winget install -e --id Canonical.Ubuntu
```

If you want to install any other distro, you can get it here by searching; https://winget.run/

After installed, To check all the available distros, run this:

```
wsl --list
```

- If you get any error, just update the wsl by running `wsl --update`. And install the distro again.

## Install Bun

After setting up the Unix admin for the respective distro, run this(in your WSL terminal, not in CMD):

```
curl https://bun.sh/install | bash
```
If there's any error occurs while unzipping, install the unzip package like this:

```
sudo apt install unzip
```
Now you can unzip it, and the installation will be done in seconds.

> To check the installed Bun version, run this:

```
bun -version
```

## Try React on Bun

To scrutinize the specialty of Bun, we'll try installing React via Bun.

The following command will create a React project inside the myapp folder.

```
bun create react ./myapp
```
_Installed path will be like this: wsl.localhost\Ubuntu\home\USER\myapp_

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

To start the React app, run these commands:

```
cd myapp
bun dev
```

Now you can see your React app by navigating to http://localhost:3000.

All this can take significantly less time than NodeJS. That's the magic what Bun can do.
Shared ViewModel: A modern way to share data between android fragments and activities
Tags: android, sharedviewmodel
Published: 2022-07-10 18:42:38

In android development, developer multiple time come across a situation where needs to share the data between fragments and activities. So there are multiple ways to share the data between fragments and activities such as

1. Bundle while replacing the fragment/activity
2. By using interface
3. Shared viewModel

Let's start with shared viewModel which is the simplest way of sharing the data between fragments/activities.

**What is viewModel and responsibility of viewModel**
The ViewModel class is designed to store and manage UI-related data in a lifecycle-conscious way. ViewModel class acts as an interface between Fragments to sharing data.
ViewModel Life cycle helps us to hold the data and keep that live even if fragment is replaced.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a2o8ndifx8a3idqg2u67.png)



**Shared viewModel**
The shared view model is the normal view model only but the data holding behaviour and life cycle of view model help us to make it shared view model.
As per life cycle data is available even if caller fragment get destroy and we can get that data for other fragments.

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

**Example**

Sender Fragment

```
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
        button.setOnClickListener { model.sendMessage("Techno Learning") }
    }
```
Receiver Fragment

```
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
        model.message.observe(viewLifecycleOwner, Observer {
            textViewReceiver.text = it
        })
    }
```

Precaution: Create SharedViewModel using the same owner.

Git Repository Link 
[](https://github.com/SandeepSatpute9271/SharedViewModel/tree/master/SharedViewModel/app/src/main/java/com/demo/shared_view_model)

  
**Conclusion**
We learned about Shared ViewModel in Android to communicate with other fragments. Hope you enjoyed this blog.

Happy Learning
Visual Studio Code For Absolute Beginner
Tags: vscode, git, javascript, beginners
Published: 2022-07-10 18:34:22

In this course, I’ll walk you step-by-step about Visual Studio Code and some of its extensions.

The complete playlist of Visual Studio Code For Absolute Beginner gives you basic setup knowledge to advance usage of the tool.

{% embed https://www.youtube.com/playlist?list=PL3IwAics3J0dwxdpjH88df2tVV39RaMdT %}

**We will be covering the following topics:**

1. Introduction to Visual Studio Code and Installation - https://youtu.be/h6NGKBX7rFM
2. Format On Save in Visual Studio Code - https://youtu.be/R7Uw8BHL2RQ
3. Git Integration in Visual Studio Code - https://youtu.be/fP2fFG2Ck2o
4. GitLens Extension for Visual Studio Code - https://youtu.be/uQB7eGncFEA
5. Code Icons Extension for Visual Studio Code - https://youtu.be/23cU2wq87vw

👍 You can follow my content here as well -

[Website](https://www.codewithmmak.com/)
[GitHub](https://github.com/codewithmmak)
[LinkedIn](https://www.linkedin.com/company/codewithmmak)
[Twitter](https://twitter.com/codewithmmak/)
[Facebook](https://www.facebook.com/codewithmmak)
[Instagram](https://www.instagram.com/codewithmmak/)

...

I love coffees! And, if this post helped you out and you would like to support my work, you can do that by clicking on the button below and buying me a cup of coffee -

[Buy me a coffee](https://www.buymeacoffee.com/codewithmmak)

You can also support me by liking and sharing this content.

Thanks for reading!
Basic Bash Scripting
Tags: bash, beginners, scripting
Published: 2022-07-10 18:25:37

> Bash is a command language interpreter. It is widely available on various operating systems and is a default command interpreter on most GNU/Linux systems. The name is an acronym for the ‘Bourne-Again SHell’.


## Table of Contents
 * [Comments](#comments)
 * [Variables](#variables)
 * [Functions](#functions)
 * [Conditionals](#conditionals)
 * [Loops](#loops)
 * [Execution](#execution)

### Comments <a name="comments"></a>
```bash
# Single line comment
: '
This is a
multi line
comment
'
```

### Variables <a name="variables"></a>
```bash
#!/usr/bin/env bash

NAME="John"
echo "Hello $NAME!"
```

### Functions <a name="functions"></a>
```bash
get_name() {
  echo "John"
}

echo "You are $(get_name)"
```

### Conditionals <a name="conditionals"></a>
```bash
if [[ -z "$string" ]]; then
  echo "String is empty"
elif [[ -n "$string" ]]; then
  echo "String is not empty"
fi
```

### Loops <a name="loops"></a>
```bash
for i in /etc/rc.*; do
  echo $i
done

for ((i = 0 ; i < 100 ; i++)); do
  echo $i
done

for i in {1..5}; do
    echo "Welcome $i"
done
```

### Execution <a name="execution"></a>
Make your bash script executable by running this command.
```bash
sudo chmod +x script.sh

./script.sh
```
I was featured on the Scrimba podcast 🎉🎉🎉
Tags: webdev, podcast, career
Published: 2022-07-10 18:19:07

Check out the episode:
[Nadia Zhuk: Anybody Can Code, and Your Background Doesn't Define You](https://scrimba.com/podcast/nadia-zhuk-anybody-can-code-and-your-background-doesnt-define-you/)
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ltb2e2ipbjcxqbc4mist.png)
AWS custom metrics with python boto3
Tags: aws, awscommunity
Published: 2022-07-10 17:57:11

For server performance monitoring we use AWS metrics and alarms for CPU & memory utilization but for webservers sometimes apache process itself and for dB server mysql/SqlServer itself consumes almost full memory and cpu also sometime.

We will use python psutil library with boto3 to send custom metrics for memory used by apache and mysql .

With psutil (python system and process utilities) library we can use for retrieving information on running processes and system utilization (CPU, memory, disks, network) in Python.

![psutil example1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mptxpnqylsoakinlm180.png)

Below example use Top 3 processes which consumed the most CPU time:

![psutil example2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dtc0s7hfk8kn4b4tm2na.png)
 
 
We use two function for which retrieve memory info for apache and mysql process & send to cloudwatch metrics,full source code [link](https://github.com/devopssourav/aws-cwmetrics-psutil).

def memUsedByApache():
    return round(sum([p.info['memory_info'].rss for p in psutil.process_iter(attrs=['name','memory_info']) if 'httpd' in p.info['name']]) / (1024*1024), 1)

def memUsedByMysql():
    return round(sum([p.info['memory_info'].rss for p in psutil.process_iter(attrs=['name','memory_info']) if 'mysqld' in p.info['name']]) / (1024*1024), 1)
 

And finally we will send this memory information to main function 
![psutil-cw](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xqywxltiv634pipaov4o.png)
 
In cloudwatch , you can search for custom metrics 

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

and you will get metrics like below
![cw2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/di6aytsz4ailwmb73bfr.png)
 
You can create alarms based on performance and recommendation.
What advice would you have given yourself before a job interview?
Tags: webdev, javascript, beginners, discuss
Published: 2022-07-10 17:37:29

## A Front-end developer interview:

So , I am applying for jobs, and i don't know absolutely nothing about how the interview process will go, basically when i up to something would like to know about it more. 
Can you please help me to know more about how front-end job interview goes 🙏
[Solved] 'ImportError: cannot import name 'ParamSpec' from 'typing_extensions' (.../lib/site-packages/typing_extensions.py)'
Published: 2022-07-10 16:36:00


**Problem:** Running into the following error when trying to start up a FastAPI app via `uvicorn main:app --reload`:

```
ImportError: cannot import name 'ParamSpec' from 'typing_extensions' (.../lib/site-packages/typing_extensions.py)
```

**Solution:** Change the installed version of the `typing-extensions` package to a more recent version such as `4.3.0`.

```
pip install typing-extensions==4.3.0
```

Note: You can check your current version of this package via the command `pip show typing-extensions`.

FYI, this solution was done on a Windows machine

## Conclusion

Thanks for reading this blog post!

If you have any questions or concerns please feel free to post a comment in this post and I will get back to you when I find the time.

If you found this article helpful please share it and make sure to follow me on [Twitter ](https://twitter.com/SeanAtukorala)and [GitHub](https://github.com/ShehanAT), connect with me on [LinkedIn](https://www.linkedin.com/in/shehan-atukorala-8631491a5/) and subscribe to my [YouTube channel](https://www.youtube.com/channel/UCtxed_NljgtAXrQMMdLvhrQ).
Peculiaridades do JS. Que não são erros! Nem esquisitice! - Null
Tags: javascript, braziliandevs
Published: 2022-07-10 16:30:00

JavaScript é uma linguagem interessante. 
Null pode ser um grande problema em JS.

Null não é um primitivo. Mas por qual motivo? 

Java. Sim é culpa do Java. 

Saiba que null foi introduzido no início para representar "ausência de um objeto" em uma ponte **Java-para-JavaScript** planejada . Por isso typeof null é object.
Com a palavra o criador da linguagem. 

{% embed https://twitter.com/BrendanEich/status/652442934151938048?s=20&t=QY0iGy7wHXFJvTEHLUyl_A %}

{% embed https://twitter.com/BrendanEich/status/1271954691421691905 %}


lembre-se Null é um objeto. 
```javascript 
typeof null === 'object'
```
Então temos Null em JS por causa do JAVA. 

Algo importante evite Null o máximo possivel. 

A maioria dos desenvolvedores usa **null** e **undefined** de forma inconsistente e intercambiável, e poucos sabem quando usar qual.
Suportando ambos null e undefined complica a validação de entrada.
Os recursos JS mais recentes, como parâmetros padrão, funcionam apenas com undefined.

Prefira SEMPRE que puder **undefined** 

Douglas Crockford acha que null é uma má ideia:

{% embed https://www.youtube.com/watch?v=PSGEjv3Tqo0&feature=youtu.be&t=9m21s&ab_channel=Nordic.js %}

O proprio criador do Null se arrepende muito disso. 

{% embed https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/ %}

Claro que isso de não usar Null não é uma lei. 
Você pode sim usar, mas a ideia é deixar de usar. 
Seus casos especificos podem continuar usando sem problemas. 



Algo pertinente. 

**Não aborde o JavaScript e Java como um ponto de familiaridade**

Nem outra linguagem orientada a objetos que você conheça!

Esse é um caminho de dor e expectativas não atendidas.
Frustrações e xingamentos para todo lado...

JavaScript é algo próprio - comece do zero. Brendan Eich foi contratado com a intenção de fazer "Scheme no navegador" - por de marketing impuseram o nome JavaScript (primeiro nome foi Mocha e depois LiveScript) colocam uma sintaxe semelhante a JAVA numa esperança de aumentar a adoção. 

{% embed https://www.youtube.com/watch?v=aX3ZABCdC38&ab_channel=dotconferences %}
Создаем на Flow | Изучаем FCL — 11. Как установить и создать новую учетную запись Testnet с помощью Lillico
Published: 2022-07-10 16:20:26

## Краткий обзор
Подобно кошельку Blocto, о котором мы рассказывали в [прошлый раз](https://dev.to/egormajj/sozdaiem-na-flow-izuchaiem-fcl-10-kak-sozdat-novyi-akkaunt-testnet-s-pomoshchiu-blocto-wallet-3hk5), [Lilico](https://lilico.app/) - это еще один кошелек, который позволяет создавать счета в Mainnet и Testnet. В этом посте мы расскажем вам, как:

- установить расширение Lilico Chrome
- настроить свой кошелек
- переключить в "Режим разработчика"

Давайте начнем! 💪

## Шаг 1 - Установка
Перейдите в Chrome Web Store и установите Lilico - https://chrome.google.com/webstore/detail/lilico/hpclkefagolihohboafpheddmmgdffjm

## Шаг 2 - Настройка
Нажмите на значок расширения в правом верхнем углу панели браузера и пройдите пошаговый процесс.

- Выберите свое имя пользователя


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

- Скопируйте и сохраните `recovery phrase`. Это очень важно, если вы собираетесь использовать этот кошелек не только для разработки, но и в качестве основного способа подписания транзакций.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/009bnum3ji0dyuh8av6n.jpeg)

- Создайте пароль - он будет использоваться для разблокировки кошелька перед его использованием.


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

- **(Необязательно)** Создайте резервную копию Google Drive, чтобы вы могли восстановить кошелек в будущем, если забудете пароль


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

- 🎉 Поздравляем! Теперь у вас есть кошелек Lilico в вашем браузере и вы готовы подписать несколько транзакций 😁


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

Вы можете увидеть свой адрес в верхней части окна.

Прежде чем мы продолжим, давайте нажмем на значок `gear` (шестеренки) (нижняя панель, та, что справа) и выберем `Developer Mode`.


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

Это позволит вам включить `Developer Mode` и переключить режим на `Testnet` (который мы будем использовать для уменьшения ущерба, который мы можем нанести😅)


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

Обратите внимание, что ваш адрес в Testnet также изменился.

Вот и все! Теперь ваш кошелек Lilico правильно настроен и готов к работе 🙂 .

До следующего раза! 👋

## Информационные ресурсы

- Установите Lilico - https://lilico.app/
- Аккаунт Lilico в Twitter - https://twitter.com/lilico_app
AWS Community Builders
Tags: aws, awscommuitybuilders, cloudcomputing, blogging
Published: 2022-07-10 16:08:30

**What the AWS Community Builders Program and how to get in.
**
The AWS Community Builders Program is an initiative undertaken by Amazon to offer not only technical resources but mentorship and networking opportunities to technical enthusiast interested in getting into cloud computing or looking connect with peers in the cloud computing realm.

## Below are few reasons what you should apply

Curated technical resources
You will be eligible for AWS promotional credits
Get to join a private slack channel, hang around and learn from the bests in the field of cloud computing.
Get access to mentorship and networking opportunities
A surprise box containing swags.

**Before applying**
During the application process, applicants will be given the chance to select their area of expiries. You will find bellow the existing category from which each applicant will be free to choose from.

Containers
Storage
Developers tools
Serverless
Game Tech
Networking and CDN
Data
Machine Learning
Mobile and Web Apps
Security, Identify and Compliance
Management, Governance and Migration
IoT
Before applying to the program, it is important that you have an expertise in one of the categories above mentioned and also show a willingness to learn and contribute to the and share your knowledge and experience with the amazing builder's community
Before applying The AWS Community Builders Program, here are few that can increase your odds of being selected

**Blogging.**
Make sure that you have a blog and actively blogging about your area of expertise. If you don't have the means to get a personal website, you can use free services like medium.com or Dev.to or hasnode.com or GitHub page to name these few resources.

**Social Media Trail**

When it comes to social media, I will highly recommend having a twitter account and leverage the hashtags that are related to the topics of your posts. I do. Feel free to follow me at @asksouley LinkedIn and Reddit and GitHub are also good place to spread the word about your skillsets

**YouTube**
For those who would like to go the extra miles and are good at making video tutorials, making YouTube Videos are also a good way to increase your chance of getting selected

To learn more about the program, feel free to check the link below, it will lead you to the official amazon community builders program page.
https://aws.amazon.com/developer/community/community-builders/



![awscommunity-Builder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kya40lcfjbdq4ryn71zi.JPG)

**follow me **
 Twitter: @asksouley 
 Instagram: https://www.instagram.com/asksouley/?hl=en
 website: www.asksouley.com


Good luck
Circular sorting algorithm
Tags: sorting, java, algorithms
Published: 2022-07-10 16:08:18

**Circular sorting**
Pre-requisite : elements of the array should be between 1 to length of the array
In `Circular Sorting` elements are placed at their natural indexs 
Example:` if the array is [5,4,2,1,3] => [1,2,3,4,5]`
```java
class Solution {
    public List<Integer> findDuplicates(int[] nums){
        int i =0,n  = nums.length;
        while(i<n){
            int j = nums[i]-1;
            if(nums[i]!=nums[j]){
                swap(nums,i,j);
            }
            else i++;
        }
       
    }
    public void swap(int[] nums,int i ,int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
```

**Usage**:

- Its useful in identifying duplicates in the array

- It can also be used to find missing elements in the array

Example : Finding missing element in the array of length `n` where the elements of the array are in the range `0<=element<=n`
```java
class Solution {
    public int missingNumber(int[] nums) {
        int i =0,n = nums.length;
        // circular sorting
        while(i<n){
            int  j = nums[i]-1;
            if(j<0) {i++ ; continue;}
            else if(nums[i]!=nums[j]) swap(nums,i,j);
            else i++;
        }
        int missing = 0;
        for(int k = 0;k<nums.length;k++){
            if(k!=nums[k]-1){ missing = k+1; break;}
        }
        return missing;
        
    }
    public void swap(int[] nums,int i,int j){
        int temp  = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
```