teleren/devto huggingface dataset:
What's Your Favourite Group Side-Project So far?
Tags: showdev, python, discuss, javascript
Published: 2020-05-28 15:07:58

# #Satisfying 😌
![Quality Work](https://media.tenor.com/images/8818a6b1669d4af3b2f20fb2c55a87c5/tenor.gif)
First off, I'm ***NOT*** a group person. Teamwork has never been my thing. Maybe it's because I don't like sharing credit, but I have to admit working as a team is crucial to advancement in any form. Also, when everyone has their own different sphere of expertise stuff gets done.
###So what's this post about?
This is me pretty much showing two of my best group projects in python and in JavaScript.

###Run them if you want
##Python #1
{% replit @OreOlad2/Crypto-time %}
##Python #2
{% replit @OreOlad2/web-miner %}
##JavaScript #1
{% replit @OreOlad2/Simple-Live-Chat %}
######I take almost no credit for the live chat. There were a lot of people who worked on it. Like, almost more than **50** people worked on it. Compared to some of the guys who worked on it, my contribution was super small., but I still have a copy of it. 
##JavaScript #2
{% replit @OreOlad2/Santafy %}
######This project was done with a friend of mine. He didn't contribute much, since he was practically a noob, but it was a good way to show him another practical use of JS, CSS, and HTML web development other than website

#What are yours?
Put a link to one of your group projects in the comments. It can be in any language.
CKA exam prep tips
Tags: kubernetes, cka, certification
Published: 2020-05-28 11:15:47

I thought I share a couple things about how I'm preparing for my CKA exam, so here it is...

* read Managing Kubernetes (available by O'Reilly), make notes, better, make **ANKI notes** (you'll use those later), go back and read the parts that are a little unclear again
* do at least one **online CKA prep course**, it'll make sure you know all the basics, if you already do and this was boring, great! I'm sure there will be the odd thing you didn't quite know yet though
  * there are some good and cheap ones out there, I realise that not everyone is able to do this though :(
* use **ANKI** to add new notes to remember, **rinse & repeat rigorously every day**, good examples to add are 
  * **kubectl commands** that help you get set up
  * best **keywords to look for** on k8s docs to find details how to do something (e.g. affinity)
  * .. you get the gist ..
* use **KinD** to do **a task a day**
* do a **mock exam** (20-30 tasks) at least once a week*
  * set up a new cluster, add and remove nodes as part of your mock exam, every time
  * make sure you cover all things etcd, especially backup & restore
  * have tasks that exercise _every_ possible resource in a cluster, e.g. Pod, Deployment, DaemonSet, StatefulSet, RBAC, Volumes, Secrets, ConfigMap, Quotas, CSR, etc. etc.
  * many resources also have _"commands"_ that you may need to know how to use, e.g. how do you scale a deployment up/down, how do you get a Pod's log output, etc. most of these are part of the _"daily administration"_ of a cluster so they need exercising as part of your prep
* **use a timer** when doing mock exams or the daily task/s, remember time isn't your friend, current time limit is 3 hours and trust me, that's over sooner than you'd think!
* ever wondered _"what happens when I ..."_ or _"I wonder how to do X"_ ? do it, see what happens, really undestand what's happening, try to fix it afterwards too - e.g. try enabling firewalld is a good one ;)
* make sure your **mock environment is the same as the actual** test environment, that means, for example, the same OS (**Ubuntu16** at the time of writing)
  * I use one of the public cloud providers to set up my test environment, but feel free to use whatever fits your budget; Digital Ocean, GCP, AWS, Linode should all have Ubuntu16 cloud images available
* make sure you're using the **correct version of k8s**, when I started preparing, the test asked for 1.17, by now it's already 1.18 and it'll be a moving target, so I'd suggest to always use the **latest major release**
* know a thing or two about **iptables, docker, systemd** - nothing too fancy, but you should know how to use it


_* I'll share my mock exam in another post_


That's all folks, now go forth and be awesome!
Day 23 of #100DaysOfCode: Create endpoints with query string on Django REST Framework
Tags: 100daysofcode, django, python, webdev
Published: 2020-05-28 14:44:00

## Introduction
On the last post, we have learned how to create endpoints on DRF. What if we want to create endpoints with query string? We can use the filter to filter the result. 

## Overview
* The roles between endpoints and the database includes models, serializers, views, and urls
* You can also refer to https://medium.com/a-layman/build-single-page-application-with-react-and-django-part-4-create-endpoints-to-manipulate-13aefa60625b
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/srzx8k8qvtnt4rdv3w4q.png)

## Implementation
* This is an example for passing a category parameter to get articles

#### Model
```python
class Article(models.Model):
    title = models.CharField(max_length = 200)
    subtitle = models.CharField(max_length = 200)
    image = models.TextField()
    url =models.TextField()
    name = models.CharField(max_length = 64)
    time = models.DateField()
    readtime = models.CharField(max_length = 64)
    CATEGORY = Choices((0, 'devto', _('devto')), (1, 'medium', _('medium')))
    category = models.IntegerField(choices=CATEGORY, default=CATEGORY.devto)
    description = models.CharField(max_length = 64, default='')

    def __str__(self):
        return f"{self.id} - {self.title}, {self.subtitle}, {self.image}, {self.name}, {self.url}, {self.time}, {self.readtime}, {self.category}"

```

#### Serializers
```python
from rest_framework import serializers
from .models import Article

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = '__all__'
```

#### Views

```python
class ArticleByCategoryViewSet(generics.ListAPIView):
    permission_classes = (permissions.AllowAny,)
    serializer_class = ArticleSerializer
    http_method_names = ['get']

    def get_queryset(self):
        queryset = Article.objects.all()
        category = self.request.query_params.get('category', None)
        if category is not None:
            queryset = queryset.filter(category=category)
        return queryset
```

#### URLs
```
urlpatterns = [
    ...
    path("api/articles", ArticleByCategoryViewSet.as_view(), name='articles'),
    ...
]
```

## Testing
Test the endpoint by Postman
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3zv3nbe27nd6k7diryg2.png)

That's it

## Articles
There are some of my articles. Feel free to check if you like! 
* My blog-posts for software developing: https://medium.com/a-layman
* My web resume: https://jenhsuan.github.io/ALayman/cover.html
* Facebook page: https://www.facebook.com/imalayman
Six minutes to learn Azure Static Web Apps
Tags: javascript, webdev, beginners, programming
Published: 2020-05-28 14:30:09

Another day, another new thing to learn. That's the great thing about programming - if you don't like things, just wait 24 hours and it will all change.

One of those new things is Azure Static Web Apps; a new service for deploying and hosting Static Web Apps with Serverless APIs. But how does it work? What is a "static web app"? Why am I turning into my father when I SWORE that would never happen?

To help you get up to speed, I've made a six minute(ish) video to help you get up and running with Azure Static Web Apps with the quickness.

{% youtube gWEYfyLu1ew %}

For more answers to all your burning Static Web Apps questions, check out the [Azure Static Web Apps Docs](aka.ms/swadocs).

If you want to get started now, head over to the [interactive tutorial for JavaScript Frameworks](aka.ms/swaframeworks), or the [interactive tutorial for static site generators](aka.ms/staticsitegen). Unfortunately, there is no interactive tutorial for "mid-life crisis".
Any tree with at least two vertices must have at least two vertices of degree one.
Tags: math, graphtheory, trees
Published: 2020-05-28 14:04:20

---
title: Any tree with at least two vertices must have at least two vertices of degree one.
published: true
description: Let's prove this proposition about trees by contradiction.
tags: math, graphtheory, trees
---

> Proposition: Any nontrivial tree must have at least two vertices of degree one (sometimes called leaves)

Here's a proof by contradiction:

Let $T$ be a nontrivial tree, that is, one with at least two vertices. In fact, let's draw one, just for fun:

```
        o (v1)
      /   \
(v0) o     o (v2)
         / 
        o (v3)
```
I might be easier to look at the tree like this:
```
        o (v0 = u)
        |
        o (v1)
        |
        o (v2)
        | 
        o (v3 = v)
```
Of note: I labeled v<sub><sub>0</sub> as <sub>u</sub> and <sub>v_3</sub> as <sub>v</sub>. More on that later.

Let _P_ be a path in _T_ of the longest possible length. It's alright if your tree has more than one path of equal length, so long as we choose one with the longest possible length. As mentioned above, u and v represent the start and finish vertices of _P_. So our _P_ is u, v<sub>1</sub>, v<sub>2<sub>, v.

Next, suppose, contrary to the proposition, that there are NOT two vertices of degree one. This brings us to why we care about _P_. The longest path, in any tree, contains a start and end vertex of degree one. 

Both ends of _P_ must be vertices with degree one, satisfying the "at least two vertices of degree one" part of the original proposition. But we're supposing that there are NOT two vertices of degree one.

That means either <sub>u</sub> or <sub>v</sub> need to be adjacent to one more vertex in _T_. Let's pick $u$, the start vertex and we will call the adjacent vertex u'.  

Which vertex is u'? u is already adjacent to a vertex on the path _P_ (v<sub>1</sub>). If u' was another vertex on the path _P_, then we'd get a cycle. I've illustrated this below:

```
        o (v0 = u)
      / |
     |  o (v1)
     |  |
      \ |
        o (v2 = u')
        | 
        o (v3 = v)
```
We cannot have cycles in a tree, since a tree is an undirected acyclic graph. So this can't be. 

However, if we think u' is a vertex adjacent to u, but not on the path _P_, then we will contradict our previous choice of _P_ as longest path since there would be a vertex preceding u.
Discussion: How to find top n users with five recent posts
Tags: sql, database, help, discuss
Published: 2020-05-28 14:14:33

Hello all,

I hope all are fine in this lockdown and learning new things in this period. I want to discuss something with you guys. 

THE OPTIMAL WAY OF FINDING RECORDS FROM THE DATABASE.

Let us say, the users who have multiple comments on different posts and they are stored in users, comments and posts tables respectively. On a dashboard page we want to list top n users with the most five recent comments on different posts. HOW would you achieve this through the query?  If possible, write your query also and the reason that your query is the most optimal one.
Speedup Docker Build
Tags: docker, ci
Published: 2020-05-28 13:57:56

So I just learned about the `.dockerignore` file after realising how uploading my `context` to the docker deamon got 1.5 GB big and took forever.

Look at the ref docs here: https://docs.docker.com/engine/reference/builder/#dockerignore-file

But the kicker was to find out how to use it as a whitelist and ignore **everything** but the stuff u need docker to put in your container:
```
# Ignore everything
*

# only add prebuild binary
!bin/linux/*
```

This turns out to be a lifesaver bin node/rust projects where the working directory contains a giant pile of generated/compiled junk!
Fixing coc-tsserver errors due to Deno
Tags: vim, productivity, typescript
Published: 2020-05-28 13:56:18

This is a quick post detailing how to fix issues with [`coc-tsserver`](https://github.com/neoclide/coc-tsserver).

I am a long term Neovim user and feel that the only Intellisense engine to use is [CocVim](https://github.com/neoclide/coc.nvim). It is simply amazing. It breathes so much power into you Vim setup.

I write Typescript daily and so use the [`coc-tsserver`](https://github.com/neoclide/coc-tsserver) plugin. It gives all the power of VSCodes typescript engine in NeoVim. But recently it broke. It was reporting errors when there was nothing wrong. I made sure all my dependencies we up to date and still nothing. All I was seeing was this:

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

The error message is: `The error message is: [tsserver 2307] [E] Cannot find module <import-path>`

Something was wrong.

Thankfully someone was having the same issue and had created an issue in the CocVim git repo. It turns out that there is a bug in the `coc-deno` plugin that has some problems with non-deno projects.

Thankfully the fix is simple. Disable the deno plugin for non deno projects.

With in Vim: `:CocList extensions` and find the Deno plugin. Press tab and select `d` to disable it. Restart Vim and all your issues should have disappeared.

# Thanks for reading 🙏

If there is anything I have missed, or if there is a better way to do something then please let me kno
Como configurar caminhos absolutos em sua aplicação.
Tags: react, javascript, todayilearned
Published: 2020-05-28 13:50:54

---
title: Como configurar caminhos absolutos em sua aplicação.
published: true
description: É tão fácil quanto parece.
tags: React, JS, TIL
---

Em nossa vivência de projeto, algumas arquiteturas de pastas favorecem nosso entendimento de cada módulo do projeto.

No entanto, algumas situações podem nos levar a caminhos extensos, de difícil entendimento e que necessitam obrigatoriamente de se guiar pelo intellisense do vs-code (ou algo similar).

```javascript
import { Module } from '../../../Folder'
```

Situações como esta podem se tornar comuns e cansativas ao importar um módulo/componente. E é aí que entra a magia dos caminhos absolutos para importação.

Em nosso arquivo `jsconfig.json` (ou `tsconfig.json` pra quem usa TypeScript) - vale ressaltar, se você não tem este arquivo, basta cria-lo na raiz do seu projeto e voilá! - precisamos inserir uma simples regra:

```json
{
  "compilerOptions": {
    "baseUrl": "src" // <- Este é o nosso cara.
  },
  "include": ["src"]
}
```

Modificando nossa `baseUrl`, podemos definir qual será o caminho para importação, mudando totalmente a forma como importamos componentes dentro da nossa aplicação.

A mesma situação apresentada anteriormente pode se tornar:

```javascript
import { Module } from 'components/Folder'
```

Onde `components` é uma pasta diretamente ramificada de `src`.

Espero que este breve artigo sirva de algum auxílio!
VimTrick: Reselect last visual selection
Tags: vim
Published: 2020-05-28 13:46:15

Often times I’m working with a visual selection of text and need to operate on that selection again. Most often this is because I’m working on a substitution pattern and don’t quite have it right. I’m swapping out some text and the regex is a bit off and I need to try again. Other times I might want to perform a substitution and then perhaps format the section with `=`.

Fortunately, Vim provides `gv` to reselect the last visual selection.

Consider the following file. It is not valid JSON. We’d like to format it as valid JSON, and improve the readability by indenting better.

![](https://cdn.substack.com/image/fetch/c_limit,f_auto,q_auto:good/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2Fabe08a76-77ac-48a0-bc13-682b73e7d86d_848x510.gif)

The animation shows the following steps:

* Visual selection: `shift-v %`
* Substitution: `s/\(.*\):/"\1":/g`
* Reselect last visual selection: `gv`
* Format selection: `=`

Does anyone have a good mnemonic for `gv`? Something to help me internalize this? Maybe “aGain Visual” but that’s a bit of a stretch. Let me know in the comments.

And if you like this trick, I'm publishing a twice-weekly newsletter called [VimTricks](https://vimtricks.substack.com).
Daily Challenge #250 - Last Digit of a Large Number
Tags: challenge
Published: 2020-05-28 13:15:35

---
title: Daily Challenge #250 - Last Digit of a Large Number
published: true
series: Daily Challenge
description: Square two nums and return the last digit. 
tags: challenge
---
Define a function that takes in two non-negative integers `a` and `b` and returns the last decimal digit of `a^b`. Note that a and b may be very large!

For example, the last decimal digit of 9^7 is 9, since 9^7 = 4782969. The last decimal digit of (2^200)^(2^300), which has over 10^92 decimal digits, is 6. Also, please take 0^0 to be 1.

You may assume that the input will always be valid.

####Examples
lastDigit 4 1             `shouldBe` 4
lastDigit 4 2             `shouldBe` 6
lastDigit 9 7             `shouldBe` 9

####Tests
lastDigit 10 (10^10)     
lastDigit (2^200) (2^300) 

***
_This [challenge](https://www.codewars.com/kata/5511b2f550906349a70004e1/) comes from dburgoyne on CodeWars. Thank you to [CodeWars](<https://codewars.com/>), who has licensed redistribution of this challenge under the [2-Clause BSD License](<https://opensource.org/licenses/BSD-2-Clause>)!_

_Want to propose a challenge idea for a future post?  Email **yo+challenge@dev.to** with your suggestions!_
Mid Meet Py - Ep.9 - Interview with Ian Ozsvald
Tags: python, datascience, interview, chat
Published: 2020-05-28 13:22:54

---
title: Mid Meet Py - Ep.9 - Interview with Ian Ozsvald
published: true
description: We meet in the middle of the day in the middle of the week to chat about Python. This week we have an interview with Ian Ozsvald - co-founder of PyData London.
tags: python, data science, interview, chat
---
PyChat:
  [Free Python DS book (online)](https://jakevdp.github.io/PythonDataScienceHandbook/) Intro to NumPy, Matplotlib & sci-kit learn
  [CfP for FlaskCon is open!](https://flaskcon.com/)
  [Way to have more diverse board members is to have diverse voters](https://twitter.com/NaomiCeder/status/1264025804125716482) - become a voting member of the PSF
  [Test pip’s alpha resolver](http://www.ei8fdb.org/thoughts/2020/05/test-pips-alpha-resolver-and-help-us-document-dependency-conflicts/)
  [New pymsbuild for windows people](https://pypi.org/project/pymsbuild/)
  [Workshop online PythonIreland](https://www.meetup.com/pythonireland/events/270568029/)

Mid Meet - Hall of Fame:
  Ian Ozsvald - co-founder of PyData London
  Follow Ian on Twitter [@ianozsvald](https://twitter.com/ianozsvald)

PyPI highlights:
  [Tesseract OCR text localization & detection](https://pypi.org/project/pytesseract/)
  [Shed](https://github.com/Zac-HD/shed) - black plus autoflake plus isort plus pyupgrade plus some custom fixers

[Listen to MidMeetPy podcast](https://anchor.fm/midmeetpy)
Forking - A guide for contributing to opensource
Tags: github, git, webdev
Published: 2020-05-28 13:18:00

##What is a fork?
A fork is a copy of a repository. Forking a repository allows you to freely experiment with changes without affecting the original project.

##How to fork?
It's so simple that it happens on a click of a button. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vsmur4civstkmllxk1ki.png)
The fork button will be available on the top right corner of any Github repository.

Now you can clone the forked project to your machine locally. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/d9zm7n8om6vqa2exj3ih.png)

You can clone using SSH or HTTPS.

```bash 
git clone git@github.com:sudharsangs/styled-components.git
```

Now that you have cloned the repository. You have to make sure you are syncing with the original one. Syncing means if the maintainer of the repository updates the code you should be able to get that in your forked repository.

```bash 
cd styled-components
git remote add upstream https://github.com/styled-components/styled-components.git
```

Now you have set the upstream of your cloned repository to the original one. 

To get the updated code you should execute the following commands.

```bash 
git fetch upstream
git merge master upstream/master
```

This is how you fork and contribute to any repositories on Github.

Happy Forking 

![gif](https://media.giphy.com/media/13z1xhUK1ogrde/source.gif)
Using filter() in Javascript
Tags: javascript, node, webdev, tutorial
Published: 2020-05-28 13:14:41

Hey guys, what’s up?!

Today I want to teach you guys how to easily filter **Arrays** using the [Array.prototype.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method.

The **filter()** method it’s very simple to implement but it’s also very powerful and helpful way to filter your data.

In this article, I’ll use the same example data object that I used on my previous article, about the map() method:
{% post https://dev.to/guilhermetoti/using-map-in-javascript-3ff3 %}

So, the example data object is:

```javascript
const data = [
  {
    id: 1,
    name: 'John Doe',
    location: {
      city: 'São Paulo',
      state: 'SP',
      country: 'Brazil',
      zipcode: '00000-000'
    }
  },
  {
    id: 2,
    name: 'Don Juan',
    location: {
      city: 'Rio de Janeiro',
      state: 'RJ',
      country: 'Brazil',
      zipcode: '11111-111'
    }
  },
  {
    id: 3,
    name: 'The Rock',
    location: {
      city: 'Curitiba',
      state: 'SP',
      country: 'Brazil',
      zipcode: '22222-222'
    }
  }
]
```

Let’s imagine that you want to get from this array, only the objects where the `location.state` are equal to **SP**.

```javascript
let newData = [];
for (let index in data) {
  const currentElement = data[index];
  if (currentElement.location.state === 'SP') {
    newData.push(currentElement);
  }
}
```

It would work, right? Right! But, we are creating another variable to handle the new data and looping through the **data** object, searching for a state equal to **SP** and then, pushing this object to the new variable.

I think we can do better than this, can't we?
![Yes, we can!](https://www.xpertnifty.in/wp-content/uploads/2018/11/YesWeCan-01.jpg)
# **Yes! We can do it better!** Using the `filter()` method!

Let’s see how it would be written using the filter() method:

```javascript
const newData = data.filter(function(currentElement) {
  return currentElement.location.state === 'SP';
});
```

The basic idea of the `filter()` method is:

```
- Pass to the filter() method a function who:
  - Receives the current element of the data array you're filtering;
  - Do your logic;
  - Returns a boolean;
- The filter() method will loop through the data array executing your function and passing each element of the array as a param;
- If your function has returned true, then the current element will be added to the new array;
- Otherwise it will be just ignored;
- Returns the new array with the filtered data;
```

And if you are learning about ES6, the same code could be written as:

```javascript
const newData = data.filter((currentElement) => currentElement.location.state === 'SP');
```

Cool, huh? :D

Probably at this moment you must be thinking about your old codes and how to refactor them to use the `filter()` method, right?

Well, I hope so!

That's all folks!
I hope you guys enjoy it, and keep learning!