teleren/devto huggingface dataset:
Day 2 Struggles & Victory!
Published: 2020-10-02 23:38:38

It's almost 11:30 pm as I type this. Today I actually planned to rest and use my Friday night for leisure activities. I had a coaching session and told my coachee that's what I would do. Fortunately or unfortunately, I didn't. 

So I did today's Hackerrank challenge. It took longer than I expected and when I finally got it right I felt...kinda dumb but only for the first few minutes. It was on Data Types and basically I had to get user input of different types (int, float & string), sum them to their already declared variable matches and display them on new lines.

It was easy, true. But, your girl didn't read the question well enough so omitted the input part from her solution and kept going at it for almost thirty minutes. I mean it worked for the sample test case but not the hidden one so I was confused. When I figured it out too, I was making very silly mistakes. I was getting a headache... and it's only day two _AND_ I already know the basics of Python. *Sigh*.

Anyway, I've learnt to always read and understand questions clearly before I tackle a problem. I'll be more conscious of it now because I don't want to go through that again. 

There's something good that came out of that though. My mind was more alert and ready to do some work. Fortunately, I could finally install and get a particular version of Angular to work for a project I was doing as part of the Google Africa Developers' Scholarship Program. Mind you this wasn't working for the past three days. Now although previously I had reached module 3, I had to start all over again and frankly, I needed that refresher. I wanted to stop at 4 and sleep but I wasn't ready to take any risks in case the installation wanted to switch up on me again. So I completed it and I'm very very relieved. I guess the leisure day would have to be moved to tomorrow morning :)

So Lily, next time:

1. Don't procrastinate. 
2. Ask for help (looking through responses from other people's issues don't count please).
3. Take your time.
4. Read and understand. If you get it wrong, take a deep breath and go at it again.
5. Also, try working in WSL more to save yourself stress.
6. You'll be fine, you won't get overwhelmed. You can do this.
7. Hold on to your faith, it won't let you down even when you want to give up on yourself especially.
Learning from working on other's project
Published: 2020-10-02 23:32:05

It is a unique learning experience for me to build a new feature on anther person's project repository.

1.  Development environment:
	Even though I expected that Java’s development environment could be complicated, I spent much more time on setting up Eclipse than I expected. The project I choose to work on uses Maven to handle dependencies for Apache Common CLI and IO while I use them via importing corresponding JAR files of those libraries by setting the Classpath under Eclipse’s Java Build Path.

	Another known issue is the version conflict of jdk. The latest free jdk download through Oracle’s official website is the 15th version. However, as of September 2020, the latest version of jdk Eclipse uses is the 14th. I have to adjust the environment variable for the System path on my Windows 10 machine even after I downloaded and installed the corresponding old version. The situation gets worse when Oracle requires a user to register in order to download any of the older versions.

2. Learning something new:
	It is quite pleasantly surprised to find an existing library Apache Common CLI my colleague uses to parse and process the user input via the command line, especially after I programmed everything from the ground up all by myself in Java. His usage of Apache Common CLI makes his project better organized than mine. I should do more research next time when I work on any new project. I am not intended to become lazy. Just that I don’t have to re-invent the wheel when there exists a library created by some collective professional efforts. 

3. Eclipse is not well integrated with Git as VS Code:
	To be honest, I spent almost 15 percent of my time on setting up my colleague’s project locally via Eclipse. According to my professor’s video instruction on how to use Git, any file or directory created via Git is displayed immediately by VS Code, which reflects what has happened on the system the computer is operating on. When in Eclipse I can pick which branch I am going to work on, I cannot see new files and directory on Windows system. This fact complicates my work processes.

4. The importance of modular programming:
	While working on my colleague’s project, I can get a sense that a good programming project should be modularized by creating standardized interface via an object’s public methods. In other words, via encapsulation, one can provide coherent public interface without exposing the inner complexity of implementation and private states. When I added a recursively searching all sub-directory feature, my colleague’s existing method makes it simple and clean for me to implement mine.
Django ORM Optimization Tips #4 recursive query
Tags: python, django, database, sql
Published: 2020-10-02 23:13:55


Recursive quires is frequently needed when you have a self referencing table

Our example today will be items and categories user wants to get item details with item category path to root category.  
> *Root-Category* **>** *Category* **>** *Sub-Category* **>** *leaf-Category*

```python
#models.py
class Category(models.Model):
    name = models.CharField(max_length=127)
    parent = models.ForeignKey('self', null=True)

```
![data example](https://dev-to-uploads.s3.amazonaws.com/i/xgw2vzkvc64p10ra1co4.PNG)

### We need to implement query that get the category path to root:

#### The naive solution:
```python
def path_to_root_category(category_id):
    if category_id is None:
        return []
    category = Category.objects.get(pk=category_id)
    result = path_to_root_category(category.parent_id)
    result.append(category)
    return result
```

`path_to_root_category(4)`
`[<Category: root>, <Category: category>, <Category: sub-category>, <Category: leaf-category>]`

The cost of this function is 4 queries (number of nodes in the path)
If we have a path of large number of nodes this will be so bad.

#### The optimized solution:

```python
def path_to_root_category(category_id):
    query = '''
    WITH RECURSIVE parents AS (
        SELECT category.*, 0 AS relative_depth
        FROM category
        WHERE id = %s
        
        UNION ALL
        
        SELECT category.*, parents.relative_depth - 1
        FROM category,parents
        WHERE category.id = parents.parent_id
    )
    SELECT id, name, parent_id, relative_depth
    FROM parents
    ORDER BY relative_depth;
    '''
    return Category.objects.raw(query, [category_id])
```
Result:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9s9qde88v88t3day663d.PNG)

**Query explanation**
![SQL query](https://dev-to-uploads.s3.amazonaws.com/i/212te6vgosalpvhokpkb.PNG)


1. First find the target category element and make it the first element of the `parents` set

2. Follow parent of all categories in `parents` set and add them to the same set

3. Finally select all categories in the `parents` set ordered by their depth
Composite Pattern
Tags: structural, pattern, designpattern, java
Published: 2020-10-02 23:06:24

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

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

#Participants#

* Component: declares the interface for objects in the composition. Implements default behavior for the interface common to all classes, as appropriate. Declares an interface for accessing and managing its child components.
(optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate.
* Leaf: represents leaf objects in the composition. A leaf has no children. Defines behavior for primitive objects in the composition.
* Composite: defines behavior for components having children.
Stores child components.
Implements child-related operations in the Component interface.
* Client: manipulates objects in the composition through the Component interface.

#Code#

```java
public class Main {

	public static void main(String[] args) {
		// Create a tree structure
		Composite root = new Composite("root");
		root.add(new Leaf("Leaf A"));
		root.add(new Leaf("Leaf B"));

		Composite comp = new Composite("Composite X");
		comp.add(new Leaf("Leaf XA"));
		comp.add(new Leaf("Leaf XB"));

		root.add(comp);
		root.add(new Leaf("Leaf C"));

		// Add and remove a leaf
		Leaf leaf = new Leaf("Leaf D");
		root.add(leaf);
		root.remove(leaf);

		// Recursively display tree
		root.display(1);
	}
}

public abstract class Component {
	protected String name;

	public Component(String name) {
		this.name = name;
	}

	public abstract void add(Component c);

	public abstract void remove(Component c);

	public abstract void display(int depth);
}

public class Composite extends Component {
	private List<Component> children = new ArrayList<>();

	public Composite(String name) {
		super(name);
	}

	@Override
	public void add(Component component) {
		children.add(component);
	}

	@Override
	public void remove(Component component) {
		children.remove(component);
	}

	@Override
	public void display(int depth) {
		System.out.println("-".repeat(depth) + name);

		for (Component component : children) {
			component.display(depth + 2);
		}
	}
}

public class Leaf extends Component {

	public Leaf(String name) {
		super(name);
	}

	@Override
	public void add(Component c) {
		System.out.println("Cannot add to a leaf");
	}

	@Override
	public void remove(Component c) {
		System.out.println("Cannot remove from a leaf");
	}

	@Override
	public void display(int depth) {
		System.out.println("-".repeat(depth) + name);
	}
}
```

#Output#
```
-root
---Leaf A
---Leaf B
---Composite X
-----Leaf XA
-----Leaf XB
---Leaf C
```
{% github https://github.com/eidherjulian61/design-patterns no-readme %}
{% link https://dev.to/eidher/principales-patrones-de-diseno-13ao
 %}
What's your use of Raspberry Pi?
Tags: technology, hardware, raspberrypi, discuss
Published: 2020-10-02 22:49:39

---
title: What's your use of Raspberry Pi?
published: true
description: 
tags: technology, hardware, raspberrypi, discuss
cover_image: https://blog.ibertronica.es/wp-content/uploads/2014/05/raspberry.jpg
---
[The Raspberry Pi](https://www.raspberrypi.org/) is a series of very affordable credit card-sized single-board computers developed in the United Kingdom.

As it is described in this awesome [GitHub repo](https://github.com/thibmaek/awesome-raspberry-pi), the sky is the limit when it comes to the projects and the use cases of it, it all basically boils down to your creativity and needs.

As of June 2020, the most advanced version is [Raspberry Pi 4 Model B](https://www.raspberrypi.org/products/raspberry-pi-4-model-b/), offering up to 8GB of RAM, USB-3 ports, Dual Micro HDMI ports (supporting 2k and 4k displays) and other superior features.

Do you already own some? What is/would be your use of Raspberry Pi?
Python List Comprehension
Tags: python
Published: 2020-09-28 14:52:49

##List Creation
The below code is the normal way of creating a list in python and using the append function to append an element at the end of the list.

Python List
```
num_list = []
num_list2 = ['Hello', 'world']
num_list.append(1)
num_list.append(2)
num_list.append(3)
num_list.append(4)
num_list.append(5)

print(num_list)
print(num_list2)
Output:
[1, 2, 3, 4, 5]
['Hello', 'world']
```

List Creation Using The List() Function
The list() function doesn’t take any argument and constructor creates an empty list and returns it. The list is then appended using the append function.

##Python List using list() function
```
num_list = list()
num_list.append(1)
num_list.append(2)
num_list.append(3)
num_list.append(4)
num_list.append(5)

print(num_list)
Output:
[1, 2, 3, 4, 5]
```

##Python List Comprehension
In the above section, we took a brief look at the python list, now we will understand what is list comprehension in python.

In the above examples, we either first created an empty list or manually added the items. List Comprehension makes it easy for us.

Example:
```
[expression for an item in iterable]
```

```
num_list = [number for number in range(1, 10)]

print(num_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
```

This would have taken 8-9 lines to add elements to a list or we would have used a loop that would have taken about 2 lines of code too. But Comprehension List can do that in only a single line.

Python List using loop
```
list_num = []
for num in range(0,10):
    list_num.append(num)

print(list_num)
```
Comparing this example with the list comprehension, there the loop is directly placed in the square brackets and an expression sits before the loop that is basically what is stored in the list.

Example:
```
Change in Expression
num_list = [number**2 for number in range(1, 10)]

print(num_list)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81]
```

number**2 – This expression makes a list of squares of numbers between 1 to 10 (excluding 10).

Read the whole post [Python List Comprehension](https://hackthedeveloper.com/python-list-comprehension/) from the original Post.
OSD-Lab2
Published: 2020-10-02 22:25:22

This week for my open source development class I was assigned to help a classmate add a optional feature to their dead link checker. The purpose of this was to practice the proper workflow of open source development. Fork -> Clone -> Branch -> Add Feature -> Push -> Pull Request.

Simple enough when you write it out like that but It can actually get complicated when you actually try and FIND something that can be added to someones code!

Skimming through the list of repositories for Release 1.0 I wanted to find a Python project that I could do something in since I have decided for this course I will try and learn at least two languages, one of which will by Python.

![I found one](https://github.com/sonechca/Dead_Link_Checker)
Finally after looking through the list I found a project that I was determined to add a feature. What I immediately found was that my classmate was using Requests, which is the same library that I used to make my http requests in my project. I knew what to look for instantly, was my classmate using requests.get or requests.head. One line of code can actually make a huge difference in runtime since .get requests the entire page and .head only requests the headers. Unfortunately for them was using requests.get. But fortunately for me that means I get to fix it for them. 

[The pull request](https://github.com/sonechca/Dead_Link_Checker/pull/5)

The fix was incredibly small, literally just change requests.get -> request.head. But the process was what I was after, which was not hard either. One thing that I found interesting though it calling the branch that you create the issue number, pretty intuitive and I never though about doing that. Previously I would have to think about what my branch name will be but this is simple and gets the job done. Luckily I had no issues with my pull request and it was merged the next day.

Overall the process was easy and fun, so fun in fact that I decided to create 3 more pull requests for other classmates:
(https://github.com/rjayroso/haystack-link-checker/issues/6)
(https://github.com/HenryZerocool/henz-cli/issues/3)
(https://github.com/rjayroso/haystack-link-checker/pull/9)
Using Sentry for Lambda Functions
Published: 2020-10-02 22:23:52

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

Step 1: Create a dummy function - I created a simple function that tries Division By Zero. (Skip this if you already have your function)

```python
import json

def lambda_handler(event, context):
    
    message = 'Hello {} {}!'.format(event['first_name'], 
                                    event['last_name'])  
    
    x=3/0
    
    return { 
        'message' : message
    }
```

Step 2: Add Sentry to the Python function folder using `pip`

```bash
pip install --upgrade sentry-sdk
```

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

```python
import json
import sentry_sdk
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration

sentry_sdk.init(
    dsn="Your dsn from sentry.io",
    integrations=[AwsLambdaIntegration()],
    traces_sample_rate=1.0,
)

def lambda_handler(event, context):
    
    message = 'Hello {} {}!'.format(event['first_name'], 
                                    event['last_name'])  
    
    x=3/0
    
    return { 
        'message' : message
    }
```

That's it. I now have complete visibility into my Lambda functions.

The stack traces are detailed and point me to the line of code that's causing the exception.
![Screen Shot 2020-10-02 at 3.21.54 PM](https://dev-to-uploads.s3.amazonaws.com/i/csipczhm6y9klupr6jod.png)

  


Sentry captured my function transactions automatically (although, the transaction is pretty empty because my function doesn't do much)
![Screen Shot 2020-10-02 at 3.00.36 PM](https://dev-to-uploads.s3.amazonaws.com/i/8ckq5mabas9wjrw9tjk7.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-10-02 at 3.23.03 PM](https://dev-to-uploads.s3.amazonaws.com/i/34doeg1icpuoq8zxu3va.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_warning`.

    ```python
    sentry_sdk.init(
        dsn="Your dsn from sentry.io",
        integrations=[AwsLambdaIntegration(timeout_warning=True)],
        traces_sample_rate=1.0,
    )
    ```

2.  Also, while Sentry automatically captured tons of context, I did want to look at my payload to the function. So, I enabled `send_default_pii`

```python
python
sentry_sdk.init(
    dsn="Your dsn from sentry.io",
    integrations=[AwsLambdaIntegration(timeout_warning=True)],
    traces_sample_rate=1.0,
		send_default_pii=True,
)
```

With this instrumentation, I have visibility that's unparalleled to any other out there. I can quickly debug issues and identify root causes for slow executing functions. Thus, saving tons of time and unnecessary lambda cost.
Getting started with Nodejs using Grandjs
Tags: node, javascript, grandjs
Published: 2020-10-02 22:23:13

In this tutorial you will get started with nodejs using grandjs for building scalable, solid server side applications in nodejs, typescript

## What do you need before?

you just need basic knowledge in javascript, node js and express js

## Tutorial

https://www.youtube.com/watch?v=FeGMDB4I5tI&list=PL6nDsSa1XozaV_8zsr9EYukTvSbGlfed1
Using JWT Token/Cookie based session authentication — Potential Identity Theft & Data Exploitation
Tags: security, node, privacy, identitytheft
Published: 2020-10-02 22:18:50

The majority of organisation are using token base or cookie based session authentication, whether through OpenID or other authentication libraries.
A token can be stolen and reused till it expires! Mobile application tokens usually has an unlimited expiration time.

A token cannot be changed due to the fact that it’s encoded and password protected, which is an advantage!

However what happens if an attacker gets a hold of your token? It can expose your organisation and users information and operation!

Same with a session based authentication, the client posts the login credential to the server, server verifies the credential and creates session id which is stored in server and returned to client via set-cookie. On subsequent request the session id from the cookie is sent back to the server for authentication.

A session id taken from the cookie can also be stolen and reused till it expires!

There are solution that you can invalidate a token or session but you don’t know when your token is misuse…

###There are number of ways an attacker can steal your organisation token/session id:
- Websites store their token on the local storage which can be accessed e.g adding a zero iframe with your org domains to another web page.
- Monitor local network traffic to intercept the token or session id.
- Malicious Browser add-ons.
- Access your mobile phone storage.
- Physically copy it.

To secure the above vulnerability I developed a middleware that monitors token usage and report back misusage.
Just declare a set of predefined roles and the middleware will monitor it for you and report back it’s findings, then you can decide whether you ask your user to re-authenticate.

Checkout this node package:

https://www.npmjs.com/package/@mbsoft/veritoken

The README has a simple example how to use it.

https://www.youtube.com/embed/OaKEu9Ju3UA
Hacktoberfest has Begun.
Published: 2020-10-02 22:07:40

![Captain Marvel with her fists together saying "Let's do this!"](https://yodaarchives.files.wordpress.com/2018/05/captain_marvel_motivates.jpg)

Hacktoberfest has begun. I joined a group that had a community project. I made a contribution and have my first commit of the season. 
I had an interview this morning followed by PyGotham online so I haven't had time to work on it today. I'm browsing for some issues now.