teleren/devto huggingface dataset:
How to debug errors in Lambda functions
Tags: node, serverless, aws
Published: 2020-09-23 23:21:32


Troubleshooting production issues in Lambda environments is often challenging. CloudWatch is not easy to use to quickly identify and resolve issues. CloudWatch requires me to go into logs, search for relevant terms that I may not always know and has hard to consume stack traces.

I am using [Sentry](http://sentry.io/) to instrument my Lambda Functions code in order to report error stack traces and associated debugging context. 

Here's how I instrumented my Node function. If you are using Python environment, there are parallel [docs](https://docs.sentry.io/platforms/python/guides/aws-lambda/).

Step 1: Create a dummy function to test the error reporting - I created a simple function that calls an unknown function.

```jsx
const mySyncHandler = (event, context, callback) => {

  notDefinedFunc();
};
```

Step 2: Add Sentry to the Node folder - I used npm for this but you can use yarn as well

```bash
npm install --save @sentry/serverless
```

Step 3: Initialize Sentry in my Lambda function - This required me to import Sentry's serverless package and wrap. my handler. 

```jsx
const Sentry = require("@sentry/serverless");

Sentry.init({
  dsn:
    "Get your dsn by creating a free account with Sentry",
});

const mySyncHandler = (event, context, callback) => {

  notDefinedFunc();
};

exports.handler = Sentry.AWSLambda.wrapHandler(mySyncHandler);
```


That's it. I now have visibility into errors from my lambda functions. 

The stack traces are detailed and point me to the line of code that's causing the exception.

![Screen_Shot_2020-09-23_at_11.13.05_AM](https://dev-to-uploads.s3.amazonaws.com/i/vamvtl5ddyvw2dclik0e.png)
 

Function context like `aws_request_id` and `remaining_time_in_milis` are super helpful. In addition, I have deep links to CloudWatch logs.

![Screen_Shot_2020-09-23_at_11.13.28_AM](https://dev-to-uploads.s3.amazonaws.com/i/i6zvdgl8z0gt845b1b8n.png)

In addition, I made couple customizations to my error reporting:

1. I really care about timeout issues. They end up bleeding into unknown issues that are difficult to debug. So, I enabled timeout warnings.

    ```jsx
    exports.handler =     Sentry.AWSLambda.wrapHandler(yourHandler, {
      captureTimeoutWarning: false,
    });
    ```

2.  Also, while Sentry automatically captured breadcrumbs from console logs, I added some of my own

```jsx
Sentry.addBreadcrumb({
  category: "auth",
  message: "Authenticated user " + user.email,
  level: Sentry.Severity.Info,
});
```

With this instrumentation, I have visibility that's unparalleled to any other solution out there. I can quickly identify issues, reproduce issues in my local environment and get to root cause of the problem.

Please share if you have used a better way to monitor errors for your Lambda functions.
90% of Linux Commands
Tags: linux, beginners, learning
Published: 2020-09-23 23:13:25

---
title: 90% of Linux Commands
published: true
description: Here is a list of the most used Linux Commands
tags: Linux, Beginners, Learning
//cover_image: https://direct_url_to_image.jpg
---

man 
sudo
cd
pwd
ls
clear
bash
ssh
history
grep
whereis
chmod
chown
find
apt
echo
cat
systemctl
df
htop
rm
mv
mkdir
cp
nano
ip
netstat

If you want to learn how to use the command just type in the terminal (man follwed by the command name)
Example:
Ubuntu@ubuntu$ man cd

Your Welcome to add more commands in the comments, if i forgot to include them.
Be Careful when Using Python Datetime Module
Tags: python, datetime, string, isoformat
Published: 2020-09-23 22:59:58

---
title: Be Careful when Using Python Datetime Module
published: true
description: Be Careful when Using Python Datetime Module 
tags: python, datetime, string, isoformat
//cover_image: https://direct_url_to_image.jpg
---

I was struggling with a bug for a while with Python datetime until I found the cause of the bug was using naive datetime object. I will not write what was the bug since it will make the post longer. 

Datetime allow for naive datetime objects which means datetime object without a time zone. For example:
```python
import datetime as dt

t = dt.datetime.now() # this is naive datetime object
print(t) # => 2020-09-23 22:28:36.836077 
```
the problem comes when you start to convert a datetime to string or to json using different community packages. The packages will make assumption that naive datetime object is based on UTC time or Local time. The time after converting will become different without knowing what the issue and without warning you are using naive datetime object. To avoid these kind of problems always use datetime module with time zone info, like this:
```python
import datetime as dt
import pytz

t = dt.datetime.now(tz=pytz.utc) # this is aware datetime object
print(t) # => 2020-09-23 22:28:36.836077+00:00
``` 

You can specify any time zone you want like this
```python

t = dt.datetime.now(tz=pytz.timezone('UTC'))
t1 = dt.datetime.now(tz=pytz.timezone('Asia/Riyadh'))

print(t) # => 2020-09-23 22:55:07.635498+00:00
print(t1) # => 2020-09-24 01:55:07.670677+03:00
```
To know the available list of time zones check [this link on Wikipedia](https://www.wikiwand.com/en/List_of_tz_database_time_zones)
Writing a queue in JS (using a Linked List)
Tags: javascript, beginners, computerscience
Published: 2020-09-23 22:26:46

I recently [wrote a post on how to build a Queue using an Array](https://dev.to/petrussola/writting-a-queue-in-js-1g7h). I love when people comment to my posts, because I always learn things. [Someone](https://dev.to/scarvps/comment/151k5) said that in order to make dequeuing O(1), I could use a Linked List. Thanks for your input, I thought it would be fun to do so and write here about it. As usual, if something is wrong or I say nonsese, let me know!

First we implement the Linked List:

```
class Node {
	constructor(data) {
		this.data = data;
		this.next = null;
	}
}

class LinkedList {
	constructor() {
		this.head = null;
		this.size = 0;
	}

	// add node to the linked list
	add(element) {
		// creates node
		const newNode = new Node(element);
		// if list is empty, set node to be the head
		if (this.size === 0) {
			this.head = newNode;
		} else {
			// otherwise, loop until we find last node, and we set next to be the new node
			let current = this.head;
			while (current.next) {
				current = current.next;
			}
			current.next = newNode;
		}
		// increase size
		this.size++;
	}
	// remove node that contains a certain elements
	removeElement(element) {
		// set current to head
		let current = this.head;
		// if current.data === element, set next as head and return
		if (current.data === element) {
			this.head = current.next;
			console.log(`${element} removed`);
			this.size--;
			return;
		// otherwise
		} else {
			// loop the linked list until the end (while current.next is not null)
			while (current.next) {
				// if we find a node with the data we are looking for
				if (current.next.data === element) {
					// if it is, set the next node of current as the next of the one we want to remove (current.next.next)
					current.next = current.next.next;
					console.log(`${element} removed`);
                                        // decrease size of the linked list
					this.size--;
					return;
				} else {
					// otherwise, set current to be current.next so we can continue the loop
					current = current.next;
				}
			}
			// print "not found" and return
			console.log(`${element} not found`);
			return;
		}
	}

	removeHead() {
                // store head's next in a temp variable
		const temp = this.head.next;
                // we set the tem as head, so the old head is gone
		this.head = temp;
                // reduce size as the LL is one element less
		this.size--;
	}

	// Helper Methods
	// isEmpty
	isEmpty() {
		return this.size === 0;
	}
	// size_Of_List
	getSize() {
		return this.size;
	}
	// PrintList
	print() {
		// set current node
		let current = this.head;
		// iterate over ll
		while (current) {
			// console.log every node's data
			console.log(current.data);
			// set next node to be the current
			current = current.next;
		}
		console.log('-------------');
	}
}

module.exports = { Node, LinkedList };
``` 

We export it so we can build the Queu in anothed file
How to add captions to YouTube videos that you don't own with Captionfy.io
Tags: youtube, captions, subtitles, video
Published: 2020-09-23 22:15:00

Youtube is removing its community captions functionality in the end of September 2020, and this has created some discussion regarding accessibility. Mainly due to the hard of hearing community, which benefits from that feature.

However, there are other ways to contribute or create your own captions for any Youtube video out there, and help this community watch any video they want. Plus, these tools help with any language barrier. Let me list some options you will have for this:

**Option 1**: Use third party websites that provide community captions. There you can watch Youtube videos with captions from their own platforms that may not be available on Youtube directly. Examples are [Captionfy](https://www.captionfy.com) (my baby) and Amara.org (my inspiration). With these platforms, people can create their own captions and anyone who needs them can watch the video now using their custom subtitles.

**Option 2**: Use a Chrome Extension. Yash Agarwal’s Subtitles For YouTube is an extension that allows you to use their library of captions in Youtube videos. It also allows you to upload your own captions.

In the end, any public Youtube video should be accessible by any person, no matter if there is a language barrier or a hearing problem. I hope these platforms can help everyone to access a broader variety of Youtube videos.

Captionfy is helping me achieve my goal to help with accessibility, and I hope many others can benefit from it :)

_Here is a preview of how a subtitle editor may look like_
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/emp395pdwvfvh82f2dbc.png)
Custom Dissertation Writing Services
Published: 2020-09-23 22:10:27

We know then significant contribution that a dissertation has on graduating and getting a high grade. We take the paper instructions and other requirements into consideration when choosing the right writer for the job. Our writers are well-qualified experts who only write after passing tough screening tests and processes to evaluate their skills. We only hire those who have the skill and passion for writing academic work for this highest level of education. Our writers are well-educated with each possessing a doctoral degree. Since we cover a wide range of subject, we work with writers with a background in various areas of academia.
https://www.dissertationcenter.com/custom-dissertation/
Writing your first API Test using JavaScript
Tags: javascript, testing, beginners, webdev
Published: 2020-09-23 22:07:03

In this post, we'll take a look at what tools/technologies do we need for writing API tests using JavaScript and then we'll also write our first API test. So let's get started...

### ⚙️ **Dependencies:** 
First off, we'll need to get the following dependencies installed to set up our base framework - 
- [Node JS and NPM](https://nodejs.org/en/) (to install the packages below)
- [Mocha JS](https://mochajs.org/) (for test framework)
- [Chai JS](https://www.chaijs.com/) (for assertions)
- [SuperTest](https://www.npmjs.com/package/supertest) (for making API calls)
- [Babel](https://babeljs.io/) (to use ES6+ in our tests)

Note: the above libraries/frameworks are optional to use, you can replace any one or all of them to meet your desired goals.

#### 📁 **Setup your project:**
You can watch the installation video below to see how to install all these packages and get your project setup.
{% youtube 7cDRqi2G6Nw %}

---

### ✍️ **Write API Test:** 

Once you have your project setup, we will begin to write our API test in the `users.js` file (created as part of the installation video above).

```javascript
import supertest from 'supertest';
const request = supertest('https://gorest.co.in/public-api/');

import { expect } from 'chai';

// watch the installation video to create your token
const TOKEN = {your_token_here}

describe('Users', () => {
  it('GET /users', (done) => {
    // make a GET call to the users api
    request.get(`users?access-token=${TOKEN}`).end((err, res) => {
      // assertion to ensure data is not empty
      expect(res.body.data).to.not.be.empty;
      // done callback to handle async calls
      done();
    });
  });
});

```
#### 🏃‍♂️ **Run your test:**

Now, its time to run your test, you can do that by running the `mocha` command or doing `npm test` which will also run the same `mocha` command if you followed the installation video. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/73oek7v9ej5i19i2wv5s.png)

There you go, we just created our first API test and it ran successfully 🙌. 

Time to celebrate - 
![Celebration Gif](https://media.giphy.com/media/kyLYXonQYYfwYDIeZl/source.gif)

---

#### Check out this video to see a detailed explanation on how to write your first API test:

{% youtube TTyl1psI4DE%}

You can also clone the [GitHub repo](https://github.com/automationbro/JavaScript-API-Automation-Tests) to access this code

***

#### To learn more about API testing, check out my free tutorial series here - 
https://www.youtube.com/watch?v=ZSVw3TyZur4&list=PL6AdzyjjD5HDR2kNRU2dA1C8ydXRAaaBV&ab_channel=AutomationBro
***

I hope this post helped you out, let me know in the comments below! 

Happy testing! 😄 

...

Subscribe to my [YouTube](https://www.youtube.com/channel/UCjugV5pnY6WjvTGYm7U1ucg?sub_confirmation=1) channel
Support my work - https://www.buymeacoffee.com/dilpreetjohal
Follow [sdetunicorns](https://twitter.com/sdetunicorns) on Twitter

---

#### Enjoyed this read? Discover more insightful articles on software testing and development on my [blog](https://sdetunicorns.com/blog). 🌐
C Functions Calling Other Functions With Side Effects
Tags: c
Published: 2020-09-23 21:44:59

Recently, I've been working on a project and seeing a lot of this pattern:

```
void func(void) {
  retVal = thing1WithSideEffects();
  if (0 == retVal) thing2WithSideEffects();
  if (0 == retVal) thing3WithSideEffects()
  if (0 == retVal) thing4WithSideEffects();

  if (0 != retVal) return retVal;

  // do other func()y stuff
}
```

By side effect, I mean a change in the state of the system. The side effect might be a new open file, a memory allocation, the establishment of a TCP connection, whatever.

First, the style. The tests of retVal are actually checking things from the line above so reading this code is weird.
While I'm nitpicking, I hate "Yoda Conditions".

Way more importantly, however, is that if any one of the calls fails, the system is left in an indeterminate state. If retVal has a value by line 7, we have no idea what the failure was and we cannot call any cleanup functions to undo any of the side effects.

The calling program/function, detecting an error with `func()` cannot call `func()` again unless _it_ knows how to clean things up.

Yes, getting this right is hard since you end up with something like this:

```
void func(void)
{
  if (retVal = thing1WithSideEffects()) return retVal;
  if (retVal = thing2WithSideEffects()) {
    undoThing1();
    return retVal;
  }
  if (retVal = thing3WithSideEffects()) {
    undoThing2();
    undoThing1();
    return retVal;
  }
  // ad nauseum -- you get the idea
}
```

A little bit gross (clean-up is beyond the scope of what I'm trying to get across) and hard to get-right/test.

I totally understand not wanting to do all this when you’re just under deadline, trying to get stuff working and out the door but the code we write tends to outlive us.

But we can and should do better.
Welcome Thread - v92
Tags: welcome
Published: 2020-09-23 21:37:58

---
title: Welcome Thread - v92
published: true
description: Welcome to DEV! A thread of hellos and intros.
tags: welcome
canonical_url: 
---

![waving bear](https://media.giphy.com/media/3o7TKMt1VVNkHV2PaE/giphy.gif)

### Welcome to DEV!

1. Leave a comment below to introduce yourself! You can talk about what brought you here, what you're learning, or just a fun fact about yourself.

2. Reply to someone's comment, either with a question or just a hello. 👋 

**Great to have you in the community!**
Javascript method to return flags of cards.
Tags: javascript
Published: 2020-09-23 21:25:10

I'm not really sure which cards we have to deal with in nowadays, but i got this problem to evaluate correctly the cards before sending the number to the **gateway** that not have something like this (or another solution more professional) to get flag card based on the number, so i've searched, compiled in my snippets and now wrinting here to ... just write, so i hope this could help someone out there 😁

> by default, the flag returned is 'visa' if nothings match.

PS: The truth is that i have no idea how this regular expression works.

```
   returnflag('2014 7722409 8894');

   function returnflag(cardNumber) {
        cardNumber = cardNumber.toString().replace(/[^0-9]+/g, '');
        const cards = {
            visa: /^4[0-9]{12}(?:[0-9]{3})?/,
            mastercard: /^(((51)|(52)|(53)|(54)|(55))\d{0,14})/,
            diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}/,
            amex: /^3[47][0-9]{13}/,
            discover: /^6(?:011|5[0-9]{2})[0-9]{12}/,
            hipercard: /^(606282\d{10}(\d{3})?)|(3841\d{15})/,
            elo: /^((((636368)|(438935)|(504175)|(451416)|(636297))\d{0,10})|((5090)|(5067)|(4576)|(4011))\d{0,12})/,
            jcb: /^(?:2131|1800|35\d{3})\d{11}/,
            aura: /^(5078\d{2})(\d{2})(\d{11})$/
        };

        for (let flag in cards) {
            if (cards[flag].test(cardNumber)) {
                return flag;
            }
        }
        return 'visa';
    }
```
Just some bash notes for self
Published: 2020-09-23 21:07:00

if [ -d $1 ]; then
            echo "That file is there and is a directory"
## Here $1 is a variable input from the user in the terminal.
## E.g. bash test.sh "Your path" where your path will become $1

else
        echo "Not there or not a directory"
fi

## if statements always close with fi

## - commands e.g -d, -e. -f etc.
Link to sheet: [Link](https://tldp.org/LDP/abs/html/fto.html)
Realtime Chat App - Golang
Tags: go, webdev, programming
Published: 2020-09-23 21:06:50

So in this chapter, we will to learn how to create chat app with Gorilla web socket, u should to download library with **go get -u github.com/gorilla/websocket**. So let`s do it.

# BACKEND
Create file main.go, we will to create Socket Server first.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mjf7urybfik4dxnx5cru.JPG)

Next create 3 struct like this.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lry588luasek8wcei9vw.JPG)

Next, create function main() its contents display template view **index.html**.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3bv2hrk7wx2ho8b1g12k.JPG)

Next, create function handleIO()

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bfc1xfixmmnonwlkm4xk.JPG)

Last, create function ejectConnection() & broadcastMessage().

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8jg4uvhr5kobizokr7sx.JPG)

# FRONTEND
Create file index.html and follow this code

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lg9xtu6yjohvyuzwxqi8.JPG)

Next, we also to add style css.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/amkjggn2tdo7wn3fyov6.JPG)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/amkjggn2tdo7wn3fyov6.JPG)

And then last add also javascript.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nr70mw78ksc1l9qbjfzd.JPG)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wagfw33bkkwcl6mzy3xj.JPG)

# TESTING

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/sr3dyxgeayt2ll3pqrcw.JPG)


**[Full Source Code in here](https://github.com/lheartz/ChatAppGolang)**
📜 Roadmap for HTML developer
Tags: html, career, webdev, beginners
Published: 2020-09-23 20:52:11

Useful for beginners in HTML: [Roadmap for html developer](https://infinite.education/expertise/html_1)

Roadmap shows your points of grows. VIsualize your career

Project page: https://www.facebook.com/InfEducation

![HTML developer roadmap](https://dev-to-uploads.s3.amazonaws.com/i/ik25qpd728lkb3u6e5bv.png)
The cost of editing (or not)
Tags: writing
Published: 2020-09-23 20:21:59

Whether you are writing a blog post or a full-length book, it helps to have another set of eyes. In a tech book, a typo can mean the example you wrote doesn't run or the instruction stumps a newbie. A real-world example: "so the dtype of out is not float64" where "not" should have been "now," -- a tiny typo of one letter that completely changed the meaning. So what does it cost to have your writing edited? The Editorial Freelancers Association just updated their Rates page based on a 2020 survey of all their members, which you can see here: https://www.the-efa.org/rates. In today's world, where so many authors are choosing to self-publish, you may want to use this resource (once you decide editing is important) to figure out what you should be paying for editing.