teleren/devto huggingface dataset:
Rest parameters of JavaScript
Tags: javascript
Published: 2022-04-10 05:23:23

---
title: Rest parameters of JavaScript
published: true
description: "A tutorial on rest parameter of JavaScript." 
tags: ["javascript"]
canonical_url: https://ashutoshbw.github.io/blog/rest-parameter/
---

Have you ever dreamed of creating your own JavaScript function that can accept **any** number arguments? Today we will learn how to do that with modern JavaScript syntax. And as you might already have guessed: the name of that syntax is **rest parameter**.

## Rest parameter

If we put 3 dots(`...`) before the *last parameter* of a function, that last parameter is called **rest parameter**.

If we do so, we can access any number of arguments given to that function from the position of the *rest paramter* to the right, wrapped in an *array*. For example:

```js
function foo(a, b, ...c) {
  console.log('a:', a);
  console.log('b:', b);
  console.log('c:', c);
}

foo(1, 2, 3, 4, 5, 6);
```
It will print the following:
```
a: 1
b: 2
c: [3, 4, 5, 6]
```


**Note**: The array that rest parameter gives us is a standard JavaScript array, which means we can use any available array method on it.


That's all there is to know about rest parameter.


**Info**: The `...` in JavaScript can have different meanings based on where it is used. Other JavaScript syntaxes that uses `...` are [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).


## When there was no rest parameter&hellip;
From ancient times JavaScript gives all regular functions(non-arrow functions) an local variable named [`arguments`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments) pointing to an array-like object that holds all the arguments we give to it. Developers faces few problems in that approach however. For example:
  * Since it's not an array, array methods don't work on it.
  * We need extra boilerplate code to convert `arguments` object to an actual array.

In ES6, **rest parameter** is introduced to overcome these limitations.

## Exercises
Do the exercises below to sharpen your understanding:

Feel free to add your answers in the comment section. You can check my answers [here](https://www.ashutoshbiswas.dev/blog/rest-parameter/#exercises).

### When no arguments given
What will be the output of the following code:

```js
function foo(...args) {
  console.log(args);
};

foo();
```

### Adder
Write a function named `adder` that takes a number as the first argument. After the first argument it takes any number of number arguments. What `adder` does is:
* It adds the number of 1st argument to all the other numbers it gets and returns all of those resulted numbers wrapped in an array.

---

If this article helped you, please buy me a coffee:
<a href="https://www.buymeacoffee.com/ashutoshbiswas" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>
Web3 be the msg.sender of a functioncall to a Smart Contract - Returned error: unknown account
Tags: smartcontract, blockchain, web3
Published: 2022-04-10 03:40:57

Hello, i trying to call the function getRewards() from this contract:
https://polygonscan.com/address/0x4AB071C42C28c4858C4BAc171F06b13586b20F30#code

This function use msg.sender to give me the rewards to my accounts.
What i need to do that iam the message sender.

This is my code at the moment:

    Web3 = require('web3')
    const fs = require('fs');
    
    const web3 = new Web3("https://polygon-rpc.com")
    const contractAddress = "0x4AB071C42C28c4858C4BAc171F06b13586b20F30"
    const contractJson = fs.readFileSync('./abi.json')
    const abi = JSON.parse(contractJson)
    const mSandMaticContract = new web3.eth.Contract(abi, contractAddress)
    
    asyncCall()
    async function asyncCall() {
        await mSandMaticContract.methods.getReward().send({ from: '0x560CC2be59c5deF53431783C3583B8f9F63b7793' })
    }

Maybe this is allready correct but i get the error:

Error: Returned error: unknown account

Any idea how to solve it?

I think i need to add to from a account instead of my public key so i tried:

    web3.eth.accounts.privateKeyToAccount('PRIVATE_KEY');

but if i try to access the account with 

    var accounts = await web3.eth.getAccounts()
    console.log(accounts[0])

or

    console.log(await web3.eth.accounts[0])

i just get beck "undefined".
What is drwx when using ls -la
Published: 2022-04-10 03:25:23

Display the content of a folder including hidden files and additional information using this command:
```ls -la ~/.ssh```

* Note: l stands for long, it will display additional information about the files and directories
* Note: a stands for all, it will display hidden files as well

~/.ssh: find .ssh folder in root directory

The terminal shows:
`drwx--xr-x 1 user staff 3389 10 Apr 11:11 id_rsa`

It is about file permissions on unix/linux/whatever on the net. 
The first character tells you if it is a directory (marked as ‚d‘), then you continue in groups of three for read (‚r‘), write (‚w’) and execute (‚x’) permissions for the owning user, group and everyone else.
VS Code Shortcuts for Web Developers
Tags: vscode, webdev, shortcuts, beginners
Published: 2022-04-10 03:18:53

**1. ID & class attributes**

- div#header

```
<div id="header"></div>
```


- div.header

```
<div class="header"></div>
```

- div#id1.class1

```
<div id=id1" class="class1"></div>
```

- p.class1.class2.class3

```
<p class="class1 class2 class3"></p>
```


**2. Multiplication**

- ul>li*2

```
<ul>
  <li></li>
  <li></li>
</ul>
```


**3. Child**

- nav>ul>li

```
<nav> 
  <ul><li></li></ul>
</nav>
```

**4. Sibling**

- div+p+a

```
<div></div>
<p></p>
<a></a>
```

**5. Text**

- a{Click Me}

```
<a href="">Click Me</a>
```


**6. Grouping**

- div>(header>ul>li*2>a)+footer>p

```
<div>
  <header>
   <ul>
     <li><a href=""></a></li>
     <li><a href=""></a></li>
   </ul>
  </header>
<footer>
  <p></p>
</footer>
</div>
```


**7. Implicit Tag Names**

- ul>.class

```
<ul>
  <li class="class"></li>
</ul>
```


- table>.row>.col

```
<table>
  <tr class="row">
    <td class="col"></td>
  </tr>
</table>
```

**8. Item Numbering**

- ul>li.item$*3

```
<ul>
  <li classs="item1"></li>
  <li classs="item1"></li>
  <li classs="item1"></li>
</ul>
```
Create Opensea like NFT marketplace using Moralis.
Tags: blockchain, node, ethereum, javascript
Published: 2022-04-10 02:39:53

Hello, if you would like to create NFT marketplace within 10 mins without going from scratch just do follow my below blog its open source.

https://pankajsinghrathore9599.medium.com/cloned-opensea-nft-marketplace-in-10-mins-fed4b1af2884
How to become a Machine Learning Engineer?
Tags: programming, python, career, machinelearning
Published: 2022-04-10 01:26:37

## 1. Learn a Programming Language :

Popular Programming Languages for Machine Learning

- R
- Matlab
- SAS
- Python
- WEKA
- Excel

If you go with **Python**, you must learn **sklearn** for Machine Learning. **Sklearn** is a modern machine learning library written in Python.

## 2. Learn Mathematics for Machine Learning :

Importance of Mathematics topics needed for Machine Learning

- Linear Algebra - 35%
- Probability and Statistics - 25%
- Algorithm and Complexity - 15%
- Calculus - 15%
- Others - 10%

Having a basic understanding of **probability and statistics** is important when it comes to mastering Machine Learning.

## 3. Learn Core Machine Learning Algorithms :

**Supervised Machine Learning** :

- **Regression** :
- Linear Regression
- Polynomial Regression

- **Decision Tree**

- **Random Forest Model**

- **Classification** :
- KNN
- Trees
- Logistic Regression
- Naive-Bayes
- SVM


**Unsupervised Machine Learning** :

- **Clustering** :
- SVD
- PCA
- K-Means

- **Association Analysis** :
- Apriori
- FP-Growth

- **Hidden Markev Model**

**Reinforcement Machine Learning**

## 4. Learn the basics Libraries for Mathematical and Data Handling :

- Spark
- Pytorch
- Scikit-learn
- Keras
- Pandas
- mxnet
- Numpy
- NLTK
- TensorFlow

## 5. Learn Deep Learning
Tips and How to name your API endpoint?
Tags: tips, webdev, api, tutorial
Published: 2022-04-10 01:21:02

Sometimes, it can be very confusing on how to name your api endpoint.

This is the tips and guideline for you on how to name your API endpoint

## 1. Use only nouns, rather than adding verbs
Example:
> 👍🏻 /users
> 👎🏻 /get-users

It will be funny if you put action in the endpoint. We will directly straight know, it use a GET request.
Use singular or plural nouns? It depends. 
If get more user, preferably use `/users`. If one user, then `/user` is the answer

## 2. Short, Clear and Intuitive
Example:
> 👍🏻 /id 
> 👎🏻 /identification-number
> 👎🏻 /id/1234/fn

For example 3, this would be misleading. It's not clear. What is fn? As for me, I would think it a function

## 3. Build hierarchy and grouping into logical groups
Example:
> 👍🏻 /departments/managers
> 👍🏻 /product/variation

## 4. Use only lowercase
Example:
> 👍🏻 /kyc-form-application 
> 👎🏻 /KYCFormApplication

URIs are case sensitive, try to avoid upper case unless it is necessary. And also, avoid unnecessary confusion and inconsistency in naming your endpoint.

## 5. Avoid special characters in the endpoint
Example:
> 👍🏻 /store
> 👎🏻 /%store

You can refer [here](https://www.computerhope.com/jargon/s/specchar.htm) for list of special character

## 6. Use hyphen (-) to separate words rather than underscore (_) or camelCase
Example:
> 👍🏻 /generate-s3-presigned-url
> 👎🏻 /generateS3PresignedUrl

Your endpoint will looks more cleaner, clearer and user friendly. Google recommend us to use hyphens as it is good for Google search, it make its web crawling job easier, thus creating more consistent results.

## 7. Use camelCase for parameters
Example:
> 👍🏻 /user/{userId}
> 👎🏻 /user/{user_id}

## 8. Do versioning for your user to use the endpoint
Example:
![Ways to do versioning in your API endpoint](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4h956w9f9dtvry9lfy1n.png)

Our API will keep changing over the time, the implementation, the request body, the response etc, hence versioning is important to avoid the endpoint from breaking when the user use it. For me, the easiest way to do versioning is the 1st way.

Avoid doing silly mistake like me when I create my endpoint before this. But hey, we learn from our mistakes right? 
![Silly mistake by me](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wvncc0ublouyyvsrmlir.png)
 
 
That's all for the tips and how to naming your endpoint! 

---------------------------------------------------------
Thank you for reading :D

Psstt pstt :p
Do consider to love this article ❤️ and follow me! Why not right? It's FREE~ 
I would really appreciate it 👨🏻‍💻 
Will be posting more on things related to AWS, Javascript, Python, Serverless and more!
How to import csv data in mongoDB
Tags: mongodb
Published: 2022-04-10 01:10:01

Question: How to add CSV data in mongoDB Atlas or local mongoDB?
Answer: 
1) MongoDB command line utility mongoimport is used to import csv/json data in mongoDB. It is bundled in MongoDB Database Tools package which can be downloaded by vising Tools section on mongoDB official website. Here is the link to download this https://www.mongodb.com/try/download/database-tools

2) After installing to your machine to the install folder and run the following command 
mongoimport --uri "mongodb+srv://username:password@cluster0.xxxxx.mongodb.net/database_name?retryWrites=true&w=majority" --collection=collection_name --mode=insert --type=csv --headerline --file=d:\data\userlist.csv

Replace username, password, database_name, collection_name and --file with your own values. Also replace cluster0.xxxxx.mongodb.net with your own cluster address. Full database connect string including cluster address can be found on Database page by pressing Connect button. --mode=insert will append data into your collection. --headerline will tell mongo that first line contains field names. For full mongoimport options please visit official documentation at https://www.mongodb.com/docs/database-tools/mongoimport/#csv-import

For local mongoDB instance instead of --uri, --hostname can be used. Syntax will be like --host=<hostname><:port>
How to track user activities on your website
Tags: webdev, javascript, tutorial
Published: 2022-04-10 01:00:07

Hello World! :wave:

So are you curious on how much visitors you have on your website? Or what users do on your website? As usual, I am here to help, and a few days ago, I figured out how to do that very thing.

The good news, It's completely free, so without further ado, let's get started! Basically, this is what we are going to do.

1. Sign up at [hotjar](https://www.hotjar.com/r/r7164cf) .
2. Get a code.
3. Put the code to your websites HTML file.
4. Learn how to track your visitors.

## Step 1, Signing up

So let's sign up, to get started, visit[ hotjar's official website.](https://www.hotjar.com/r/r7164cf) After you clicked [the link](https://www.hotjar.com/r/r7164cf), you press the try it free button.

You know the usual's, you enter your email, then the password, those stuff. You can also sign up with google, it doesn't really matter, just sign up.

After you signed up, you answer a quick form, then after that, you get to enter your website's address. You can click the do it later button if you don't have a website address yet. 

If you chose not to install now, you'll go to hotjar's home screen, to continue, press install hotjar. If you already installed hotjar, skip to the next part.

Now press add code manually, copy the script code, and add it to the head tag of every page you want to have the code.

## Using Hotjar

I am sure everyone reading this is smart enough to install the code, if my method is outdated, I am sure you'll be able to figure it out. Anyway, now, you can create heatmaps and record your visitors.

You can now get a deeper insight at what your audience is doing! You can press recordings to watch user recording, and heatmap to see which part of your website needs improvement.

I am sure you will get something out of Hotjar, thank you all for your time!

## Conclusion

Farewell, I really hope to see you again and have a good day! Enjoy coding, and enjoy your life! :)
Remote Access Private EC2 Instances via System Manager
Published: 2022-04-10 00:19:27

## Summary
System manager enable remote access to EC2 instances (both private and public subnet) without using SSH and opening port 22. In addition, from the private EC2, it is possible to access other services such as S3 via VPC service endpoints. In this post, I would like share how to deploy these by using CDK. 

- Remote access a prviate EC2 by system mananger
- The private EC2 can access S3 via VPC endpoint
- Deply by a CDK stack
- [GitHub](https://github.com/entest-hai/aws-devops/tree/system-manager-vpc-endpoint)


## Architecture

![aws_devops-Expriment drawio](https://user-images.githubusercontent.com/20411077/162595535-59610cf8-233c-423f-9a13-bb3f1cffacc3.png)

## CDK Stack

Create a VPC with a S3 VPC endpoint

```
    const vpc = new aws_ec2.Vpc(
      this,
      'VpcWithS3Endpoint',
      {
        gatewayEndpoints: {
          S3: {
            service: aws_ec2.GatewayVpcEndpointAwsService.S3
          }
        }
      }
    )
```

Add system manager VPC interface endpoint

```
    vpc.addInterfaceEndpoint(
      'VpcIterfaceEndpointSSM',
      {
        service: aws_ec2.InterfaceVpcEndpointAwsService.SSM
      }
    )
```

Create an IAM role for the EC2

```
    const role = new aws_iam.Role(
      this,
      'RoleForEc2ToAccessS3',
      {
        roleName: 'RoleForEc2ToAccessS3',
        assumedBy: new aws_iam.ServicePrincipal('ec2.amazonaws.com'),
      }
    )
```

Role for EC2 to communicate with SSM

```
    role.addManagedPolicy(
      aws_iam.ManagedPolicy.fromManagedPolicyArn(
        this,
        'PolicySSMMangerAccessS3',
        'arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore'
      )
    )
```

Policy for EC2 to access S3

```
    role.attachInlinePolicy(
      new aws_iam.Policy(
        this,
        'PolicyForEc2AccessS3',
        {
          policyName: 'PolicyForEc2AccessS3',
          statements: [
            new aws_iam.PolicyStatement(
              {
                actions: ['s3:*'],
                resources: ['*']
              }
            ),
          ]
        }
      )
    )

```

Launch an EC2 in a private subnet

```
    const ec2 = new aws_ec2.Instance(
      this,
      'Ec2ConnectVpcEndpointS3',
      {
        role: role,
        keyName: 'hai_ec2_t4g_large',
        vpc: vpc,
        instanceName: 'Ec2ConnectVpcEndpointS3',
        instanceType: aws_ec2.InstanceType.of(aws_ec2.InstanceClass.T2, aws_ec2.InstanceSize.SMALL),
        machineImage: aws_ec2.MachineImage.latestAmazonLinux(),
        securityGroup: sg,
        vpcSubnets: {
          subnetType: aws_ec2.SubnetType.PRIVATE
        }
      }
    )
```
How do you know a good Agile Coach?
Tags: agilecoaching, hiring
Published: 2022-10-19 16:59:42

---
title: How do you know a good Agile Coach?
published: true
date: 2022-04-10 00:00:00 UTC
tags: agilecoaching,hiring
canonical_url: https://jhall.io/archive/2022/04/10/how-do-you-know-a-good-agile-coach/
---

“How do you know a good Agile Coach?”

I’ve been asked this question a few times. I don’t have a complete answer, but I do have some thoughts on the topic. If I were interviewing someone to come work with me, and help coach my teams with agility, these are the two most important things I think I would ask about:

- How many years of software development experience do you have?

- What is your track record for continuously delivering customer value?

What’s on your short list? Do you disagree with mine?

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
Interact with existing Smart Contract
Published: 2022-04-09 23:04:48

Hey i want to automate my staking on The Sandbox. For that i need in the first step to interact with the mSand-Matic Pool Contract. It is this one: https://polygonscan.com/address/0x4ab071c42c28c4858c4bac171f06b13586b20f30#code

I have written a little programm in a github repo to show what i have done see here: https://github.com/ChristianErdtmann/mSandMaticStakingAutomation

Or here the code example from the contract-interact.js

    Web3 = require('web3')
    const fs = require('fs');
    
    const web3 = new Web3("https://polygon-rpc.com")
    const contractAddress = "0x4AB071C42C28c4858C4BAc171F06b13586b20F30"
    const contractJson = fs.readFileSync('./abi.json')
    const abi = JSON.parse(contractJson)
    const mSandMaticContract = new web3.eth.Contract(abi, contractAddress)
    mSandMaticContract.balanceOf('0x7e5475290Df8E66234A541483453B5503551C780')

The abi i have taken from the contract link on the top. But it seems there is a problem.

I tried for testing to read someting from the contract. For that i used the function balanceOf(address), how you can see in the code.

But i get alltimes the error: TypeError: mSandMaticContract.balanceOf is not a function
Discord.py | 02 Not that usual log bot the first part!
Tags: discord, python, tutorial, codenewbie
Published: 2022-04-09 22:51:34

Hello, Today we're going to create a discord bot that logs the messages in any server in a text file.
Before going any further please read the first part. {% embed https://dev.to/oxy_oxide/discordpy-01-31jh %}
## The code
The code is very simple as usual.
As usual let's start by importing discord.py module and defining the client(bot).
```python
#No need to explain this piece of code just read the first part.
import discord
from discord.ext import commands


client = commands.Bot(command_prefix="!")

@client.event
async def on_ready():
    print("started")

```
Then, We are going to use the on_message event.
This event listens to the messages sent in all the servers that the bot is in then executes some code.

```python

@client.event
async def on_message(message):
    if message == "":
        return
    else:
        id = str(message.author)
        #Sorts the message time of creation
        # %d : day of the month (01 to 31)
        # %m : month
        # %Y : year including the century
        # %H : Hour (00 to 23)
        # %M : minute
        # %S : second 

        time = str(message.created_at.strftime("%d-%m-%Y %H:%M:%S"))
        mss = str(message.content)
        #Opening the file in appending mode.
        data = open("data.txt","a")
        #writing the message into the file 
        data.write(f"({time}) {id} : {mss}\n")
#Don't forget to run the bot
client.run("Your Token")
```
You can find the full code in [here](https://github.com/0x1Ox1d3/DEV_bot/blob/main/part%7C02%20logger%20bot.py)
## Testing the code

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3wblil1tb998mx02ygzm.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/08kagq1c3suf15whoibx.jpg)
Thanks for reading, See you in the next part.
NPM Needs: pretty-bytes
Tags: javascript, webdev
Published: 2022-04-09 22:31:15

> Note: this was originally [posted on my personal site](https://andrewusher.dev/blog/npm-needs-pretty-bytes)

## What Is It?

`pretty-bytes` is a utility used to convert an integer form of bytes to a more human readable form (bytes to kilobytes, for example). `pretty-bytes-cli` is a command line wrapper for the same package.

## Usage Examples

```js
import prettyBytes from 'pretty-bytes'

prettyBytes(100)
// '100 B'
prettyBytes(1650)
// '1.65 kB'
```

## More Info

- Github Repo: [sindresorhus/pretty-bytes](https://github.com/sindresorhus/pretty-bytes)
- Author: [Sindre Sorhus](https://sindresorhus.com/)