teleren/devto huggingface dataset:
Did you know Ruby has resolv-replace?
Tags: ruby
Published: 2020-12-13 22:22:21

In Ruby, there's a library called [`resolv-replace`](https://ruby-doc.org/stdlib-2.7.0/libdoc/resolv-replace/rdoc/index.html).

This is a drop-in replacement (moneky patch) of libc DNS resolver Ruby's using under the hood. It'll use a pure Ruby implementation called [`Resolv`](https://docs.ruby-lang.org/en/2.7.0/Resolv.html).

The doc states the merit of `Resolv` as _"Resolv can handle multiple DNS requests concurrently without blocking the entire Ruby interpreter"_. So ppl probably reach out to this when they want to improve the performance.

You can read how `resolv-replace` is patching a set of Ruby's stdlibc network calls at https://ruby-doc.org/stdlib-2.7.0/libdoc/resolv-replace/rdoc/index.html.

If you'd like more control on the DNS layer due to how your app's constructed, I'd recommend checking out this library.

---

<span>Cover Photo by <a href="https://unsplash.com/@jjying?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">JJ Ying</a> on <a href="https://unsplash.com/s/photos/network?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>
Padrões de Projeto
Published: 2020-12-13 21:56:39

No desenvolvimento de software sempre nos deparamos com problemas recorrentes, os Padrões de Projeto são soluções práticas para estes problemas.

Os Padrões são conceitos gerais, como receitas com etapas claras que devem ser seguidas para solucionar um problema e assim melhorar a qualidade do software em geral, facilitando o desenvolvimento, refatoração, manutenção do código e ainda facilita a comunicação entre colegas desenvolvedores de um mesmo projeto.

Um padrão deve conter um propósito, uma motivação, as estruturas das classes de todas as partes do padrão e exemplos de código. Algumas classificações para padrões são: **criacionais**, **estruturais** e **comportamentais**. 

Padrões **criacionais** oferecem maneiras de criação de objetos buscando mais flexibilidade e reutilização de código.
Padrões **estruturais** mostram como produzir grandes objetos e classes mantendo a flexibilidade e eficiência do código.
Padrões **comportamentais** especificam as características que os objetos precisam para possuírem uma comunicação eficiente e responsabilidades bem especificadas.

Neste blog serão trabalhados alguns exemplos de cada uma destas classificações.


***
**Referências**
[Padrões de Projeto](https://diogomoreira.gitbook.io/padroes-de-projeto/) (Diogo Moreira, 2020)
[Mergulho nos Padrões de Projeto - v2020-1.14](https://refactoring.guru/pt-br/design-patterns/book) (Alexander Shvets, 2020)
Using pg_dump and pg_restore to backup and restore PostgreSQL database
Tags: postgres, psql, database
Published: 2021-05-27 10:35:27

---
title: Using pg_dump and pg_restore to backup and restore PostgreSQL database
published: true
date: 2020-12-13 21:47:26 UTC
tags: postgres,psql,database
canonical_url: 
---

So, I was trying to reproduce some issues and bugs that only happened in production. I needed an exact copy of the production database and run it locally.

Here’s how I did it using `pg_dump` and `pg_restore`.

```
$ pg_dump -U postgres -Fc -Z 9 -j 8 production.dump -d postgres
```

Here’s the breakdown for the arguments:

- `U` means username. It’s used to connect to your postgres database. In this case, my username is `postgres`.
- `F` means format. It’s usually combined with `c` that means **c** ustom
- `Z` means compress. It can have values from 0 to 9. 0 being no compression and 9 being the maximum compression. It’s supposed to make the dump file smaller. I used 9 here because I know that my database doesn’t contain much data and I want its size to be small as possible. You might be asking why not use 9 all the time? The answer to that is it takes a while to restore compressed dumps. So if you want to restore it faster, use a lower value.
- `j` means jobs. It’s the number of jobs that we want to run. You can think of it as how many persons are going to dump your databse. More jobs means faster dump.
- `d` means database. It’s the name of the database you want to dump. The name of the database I also want to dump is `postgres`.

After that, I copied it from my remote ssh machine to my local machine

```
$ scp yujinyuz@myremotesite:/usr/share/nginx/repo/production.dump ~/Downloads/
```

And then restored it locally:

```
$ pg_restore -U postgres -Fc -j 8 production.dump -d postgres -c
```

Notice that most of the arguments are almost the same except for the new `-c`.

- `c` means clean. It will drop database objects before creating them. So, if I have existing tables in my local, it would just drop them and recreate it so I would have the exact copy of my production database.

That’s it! Hope that also helps you, too!
On testing private methods
Tags: testing, ios, codequality
Published: 2020-12-13 21:38:22

# Do you have to test private methods?

There is a lot said about this. Just check this [thread](https://stackoverflow.com/questions/105007/should-i-test-private-methods-or-only-public-ones).

The short answer is **no**.

The slightly longer answer is as follows.

# The goal of Unit testing

When you write unit tests, you are testing the logic behind some module in your project. There are many ways of writing unit tests, with and without mocking or stubbing, or maybe testing pure functions. 

In any case, when you write a unit test, you first create and configure the object you are testing (the SUT, system under test). This step is called **arrange**. After that, you **act** on your SUT. And finally **assert** that some state in your SUT or result returned from it is as expected. However, the act part can be as complex behind the scenes as you can imagine.

# What is a private method?

Private methods are hidden complexity. That is great. I mean, you hide the complexity behind your implementation so the user of your module doesn't need to bother on how did you write the logic in it. The user just call on the public interface of your module, and the magic happens.

![private-0001](https://dev-to-uploads.s3.amazonaws.com/i/ijykqwesw78za4af9pja.png) 

This diagram shows how simple can it be for the client perspective to call a method in the module.

However, hidden complexity is free when using the module, but has its cost when testing it.

![private-0002](https://dev-to-uploads.s3.amazonaws.com/i/7baftausk12jlbn220zh.png)
 
Imagine the method you are testing from the SUT has 10 lines of code. If it calls three 15 LoC methods, you are testing 55 LoC. And you can imagine how complex the test can become... 

# A better approach

Single responsibility principle encourages us to create simple, small, concise functions and modules that do one and only one thing. If your module has many private functions, the SRP is not correctly implemented.

The better approach is to split the private SUT in a set of objects that can be injected in your SUT as needed, and also be mocked.

![private-003](https://dev-to-uploads.s3.amazonaws.com/i/gw1atlwu53loguxt21tt.png) 

This is the first step in making a class more testable. The next step I always recommend taking is to hide every dependency under an interface, so you can mock each dependency in a simple way.

![private-0004](https://dev-to-uploads.s3.amazonaws.com/i/cq991rdf0lzmv7xskc9w.png) 

Once you have this, your module becomes much more testable. 

If you now need to test that method with complex private dependencies, you can just inject mocked objects that implement the right interfaces so you can test just the piece of logic you are interested in.

Of course, the new objects you have created are now testable as well, because each of them is a simple, concise unit of logic.

# To sum up

When you write a module, keep testability in mind, keep them small, and take care of their private interfaces using this simple technique.
DAY 13 - Advent of Code 2020 w/ GoLang
Tags: go, adventofcode
Published: 2020-12-13 21:37:02

---
title: DAY 13 - Advent of Code 2020 w/ GoLang
published: true
description: AoC 2020 Day13 solutions in GoLang
tags: golang, AdventOfCode
series: Advent of Code 2020
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/gb6jnhz1didpnth3pbsw.jpeg
---

**DAY13:**

**TLDR:** Use *modulo* and look at [least common multiple](https://www.mathsisfun.com/least-common-multiple.html)

Again, part one went pretty well. Part two read like it would be a similar difficulty. It *was* about a similar difficulty level but if not optimized could potentially take **hours** to run. When I got the solution the first time, it was after passing all test cases and allowing my code to run for about 4 hours. While that was happening, I did some research (Google) and got reminded of [least common multiple](https://www.mathsisfun.com/least-common-multiple.html) which after implemented, allowed my program to finish MUCH faster. Essentially it allows you to short circuit and skips forward to the next best potential timestamp without evaluating every single one in between.

```golang
package days

import (
	"fmt"
	"strconv"

	inputs "../inputs"
)

// https://adventofcode.com/2020/day/13
// Thirteen : advent of code, day thirteen part1 and 2
func Thirteen() {
	inputSlice := inputs.Day13
	earliestTimeStamp := inputs.Day13EarliestTimestamp
	buses := []int{}

	for bus := range inputSlice {
		if inputSlice[bus] == "x" {
			buses = append(buses, 1)
		} else {
			asInt, _ := strconv.Atoi(inputSlice[bus])
			buses = append(buses, asInt)
		}
	}

	fmt.Print("(Part 1) - Minutes to catch multiplied by the bus ID: ")
	fmt.Println(catchNextPossibleBus(buses, earliestTimeStamp))

	fmt.Print("(Part 2) - Earliest timestamp of subsequent series: ")
	fmt.Println(startStampOfSubsequentSeries(buses, 0))

}

func catchNextPossibleBus(buses []int, earliestTimeStamp int) int {
	busMap := make(map[int]int)

	for bus := range buses {
		if buses[bus] > 1 {
			busMap[buses[bus]] = buses[bus] - (earliestTimeStamp % buses[bus]) + earliestTimeStamp
		}
	}

	nextBusTimeStamp := 0
	nextBus := 0

	for k, v := range busMap {
		if v < nextBusTimeStamp || nextBusTimeStamp == 0 {
			nextBusTimeStamp = v
			nextBus = k
		}
	}

	return nextBus * (nextBusTimeStamp - earliestTimeStamp)
}

func startStampOfSubsequentSeries(buses []int, multiplier int) int {
	start := 0
	properBusSeries := false

	for !properBusSeries {
		skipFactor := 1
		properBusSeries, skipFactor = checkThisSeries(buses, start, skipFactor)
		if !properBusSeries {
			start = start + skipFactor
		}
	}

	return start
}

func checkThisSeries(buses []int, start int, skipFactor int) (bool, int) {
	for bus := 0; bus < len(buses); bus++ {

		if (start+bus)%buses[bus] != 0 {
			return false, skipFactor
		}

		skipFactor = skipFactor * buses[bus]
	}

	return true, skipFactor
}

```

[Link to Github source file](https://github.com/dizveloper/AdventOfCode/blob/main/2020/days/day13.go)
JavaScript Blog
Published: 2020-12-13 21:19:17

JavaScript uses several different data types: 

* Numbers (only doubles are used, no ints)
* Strings
* Booleans 
* Undefined
* Symbol
* Object

These data types are declared as follows:

`var variable_name = [data e.g "hi", 5.2 false]`

These data types can also be stored into `arrays` which are a list of variables of the same data type. Arrays are used as folows:

`var array_name = [ 1,2,3,4] `

The members of the array are then accessed as follows:

`array_name[index]`

The array has several methods aswell:

* .length - Get length of array
* .sort - Sort array
* .push - add element at end of array
* .pop - remove element at end of array


With these data types several different operators can be used in order to manipulate them:

* `=` Will assign a value to the variable in use.
* `+` Will either add variables together or append them 
* `-` Subtracts numbers 
* `*` Multiples numbers 
* `/` Divides numbers
* `%` Gets the remainder of the division operation 

Comparison operators can also be used to return a Boolean value:

* `==` Checks if equal to
* `!=` Checks if not equal to
* `===` Check if equal to AND the same data type
* `!==` Checks if not equal value or type
* `>` Greater than
* `<` Less than
* `=>` Greater than or equal to
* `<=` Less than or equal to

In order to control the execution of our code JavaScript has several 'control flow' methods. 

*while(x) - Does whatever is in the brackets until x is 0 or false.
*for(int i = 0; i < n; i++) - Does whatever is in the brackets until the termination condition (i < n) is met
*if(x) - Does whatever in the brackets if x evaluates to true.

JavaScript also has functions which allows segments of code to be executed repeatedly without rewriting it. It is written as follows:

`function functionName(p1, p2)
{
//code
return x;
}` 

Where p1 & p2 are the inputs and x is the output.
Smart textwidth on Vim when writing comments
Tags: vim
Published: 2020-12-13 21:30:13

I was checking my `init.vim` today trying to find how to improve it a bit.

I found this case that could be interesting to share... so there it goes.

I write a lot of documentation. One thing I always try to do is to keep the comments I write well aligned and easy to read. That's why I keep them at a length of 80 characters, I find that to be easier to read than long lines.

You can use the `textwidth` configuration in vim to do that.

```viml
set textwidth=80
```

Once the text you write gets to a width of 80 characters vim will split it to the next line.

![vim auto splitting text](https://dev-to-uploads.s3.amazonaws.com/i/wam03sbvk61ub7i260ga.gif)

This is a very well known fact about vim, but you can read more about it if you're interested with `:help textwidth`

```vimhelp
						*'textwidth'* *'tw'*
'textwidth' 'tw'	number	(default 0)
			local to buffer
	Maximum width of text that is being inserted.  A longer line will be
	broken after white space to get this width.  A zero value disables
	this.
	'textwidth' is set to 0 when the 'paste' option is set and restored
	when 'paste' is reset.
	When 'textwidth' is zero, 'wrapmargin' may be used.  See also
	'formatoptions' and |ins-textwidth|.
	When 'formatexpr' is set it will be used to break the line.

```

The thing is that I don't want vim to do the same on the code I write. Mainly because it will end up splitting the code on a different place than the one I would want it to.

I needed a way to `set textwidth=80` when editing comments and then `set textwidth=0` when not editing comments anymore.

Enter [OnSyntaxChange](https://github.com/inkarkat/vim-OnSyntaxChange). This plugin allows you to define vim autocommands that execute when the syntax of the current file changes, in our case, when we're editing comments.

I use [vim-plug](https://github.com/junegunn/vim-plug) so I install it like this:

```viml
Plug 'inkarkat/vim-OnSyntaxChange'
" This is a dependency library from the same author that includes
" some autoload functions that he uses on the plugins he writes.
Plug 'inkarkat/vim-ingo-library'
```

```viml
" Add a new autocommand that will activate when the cursor is on a Comment and
" it either enters or leaves insert mode.
" 1. The name: `Comment` means the autocmd will be called
" `SyntaxCommentEnter{MODE}`
" 2. A regex to max the syntax, on our case any syntax similar to `Comment`
" will match to us.
" 3. Whether we want to generate it to all buffers or only a particular one,
" we're ok with only the current buffer.
" 4. To which mode we want to link the autocommand. We're only interested in
" the insert mode
call OnSyntaxChange#Install('Comment', '^Comment$', 1, 'i')

augroup auto_wrap_comments
  " Set textwidth to 80 when editing
  autocmd User SyntaxCommentEnterI setlocal textwidth=80
  " Remove it again when leaving insert mode
  autocmd User SyntaxCommentLeaveI setlocal tw=0
augroup END
```

And with that code on our `init.vim` we now have that the split behaves like this :)

![Smart text width](https://dev-to-uploads.s3.amazonaws.com/i/ir7ufq4g0xz9h22aq237.gif)
Elementary OS
Published: 2020-12-13 21:25:54

Há três anos decidi adotar o Linux para ser o único sistema operacional em minha máquina e não me arrependi, nesse período já experimentei algumas distros, tais como: Linux Minti, Ubuntu, Xubuntu, Kubuntu, Lubuntu e nos últimos dias migrei para o Elementary OS (Sim, é isso mesmo, eu amo mudanças). Esse último possui um fã clube grande de pessoas insatisfeitas, no entanto, até o dia de hoje a única reclamação que possuo é sobre uma certa carência de material de apoio em português para os usuários. 

O Elementary OS possui algumas particularidades e nos próximos dias iremos abordá-las aos poucos a fim de ajudar os usuários que o adotarem, para que o ambiente seja configurado com maior facilidade.

Bom, esse é meu primeiro contato com a distro mencionada, então algumas informações serão compartilhadas aqui a medida que eu for descobrindo também.

Até logo, pessoal :)
VARIOUS STUDY PLANS DEPENDING ON YOUR BACKGROUND
Tags: cybersecurity, beginners
Published: 2020-12-13 21:00:41

GROUP ONE: COMPLETELY NEW TO TECH
Learn the basics of programming
Read some basic security content such as web hacking 101
Hack your projects 
Begin practicing on ctfs as you learn more about bug hunting
Keep reading and learning immerse yourself into security
Start hacking on a real target

GROUP TWO: A STUDENT IN CS/ SOFTWARE ENGINEERING
Take advantage of any formal security courses your school, university or college offers
Get involved with the local community eg Hacking club in school
Learn more about OWASP top 10
Begin practicing on ctfs as you learn more about bug hunting
Keep reading and learning immerse yourself into security
Start hacking on a real target

GROUP THREE: A DEVELOPER / PROGRAMMING EXPERIENCE
Learn more about OWASP top ten 
Read some security write ups which targeted a language you are familiar with
Begin practicing on your CTF’s as you learn more about the common bugs
KEEP READING AND LEARNING IMMERSE YOURSELF INTO SECURITY
START HACKING ON A REAL TARGET

GROUP FOUR: HAVE SOME EXPERIENCE WITH SECURITY
Begin practicing on CTFs
Watch or read content on specific bugs from an attackers side
Keep reading and learning, immerse yourself into security
Start hacking on a real target

GROUP FIVE: A SECURITY SPECIALIST
Watch or read content on specific bugs from an attackers side
Start hacking on a real target 

GROUP SIX: ANOTHER SPECIALIST EG DATA SCIENTIST/ENGINEER
Take a look at some beginners content but skip what you are already familiar with
Begin practicing on your CTF’s as you learn more about common bugs
Watch or listen to beginner friendly content to introduce the more technical side of hacking
Keep reading and learning, immerse yourself into security
Start hacking on a real target

NEVER STOP LEARNING.
Grocery checklist app using localStorage
Tags: beginners, firstyearincode
Published: 2020-12-13 20:38:14

When I make my list of grocery items I need to buy, I typically use the *Notes* app on my iPhone. I already use it to keep track of a bunch of other items and notes, so it's somewhat convenient, but it is somewhat annoying when I'm standing in the grocery store and deleting items one by one as I place them into my shopping cart.

Recently in my review of bootcamp materials, I've been covering localStorage, and I thought, *why don't I create a grocery checklist for my local device? I could totally use it when I'm grocery shopping!* I know there are other grocery shopping apps out there already, but hey, it never hurt to recreate something for good practice.

I wanted to start out with something simple — an app where users can enter and save items, and then delete them with a single tap. 

## **About the App**
The app is built using HTML, CSS and JavaScript. It saves items that a user enters to localStorage, so as long as the app is accessed from the same device the items were saved from (and the cache is not cleared), it'll retrieve them to display for the user to see. 


| **DO YOU HAVE ANY TIPS?** |
| ------------------------- |
| I have found that this app works just fine with saving and retrieving data when I use it from my laptop. However, when I create a list from my iPhone, the data disappears when I close my browser. I'm not sure why this happens — does closing out a browser on my phone automatically clear the cache? Perhaps it's a setting on my phone? I would love to hear any tips if anyone thinks they know why. |

## **Future Developments**

Right now, this app is very simple, but I'd like to work on it further down the line to allow for grouping of items by category, and also add a 'recently removed items' section where I have the ability to quickly add back items at the simple click of a button. 

Check out the current app here!
https://jungjungie.github.io/grocery-checklist/

![GIF demo](https://github.com/jungjungie/grocery-checklist/raw/main/images/demo.gif)
Book recommendations about the social aspects of dev teams
Tags: discuss, books, management
Published: 2020-12-13 20:26:51

I'm currently reading [Peopleware](https://www.goodreads.com/book/show/67825.Peopleware), but I would love to more books that look at the social dynamics of professional software development: managing a team, how teams work or what the social dynamics usually are in development teams?

(This is really wide topic, and I'm generally interested in anything under this wide umbrella, so comment a suggestion even if the book you're thinking covers only some area of this.)

Got any recommendations that you have read yourself, or that are still on your to-read list?

<span>Photo by <a href="https://unsplash.com/@itfeelslikefilm?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">🇸🇮 Janko Ferlič</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>
Daddy's Coffee
Tags: android, java, uiweekly, ux
Published: 2020-12-13 19:59:46

This app based on Coffee shop APK and also there is an API called coffee API this will be helpful for testing purpose and links for github repos available

Daddy's coffee APP (Android): https://github.com/hexhad/DaddysCoffee.git

Coffee API (Spring Boot): https://github.com/hexhad/CoffeeAPI.git
Series Open CSS Loaders ["1. Setting up backend"]
Tags: javascript
Published: 2020-12-13 19:49:35

This is **PART-1** of the series for my entry in the hackathon.

##The Idea
For the hackathon, I decided to complete my Open CSS Loaders and host it on the Digital Ocean platform.
So I began the work. The cover image you see is the design I had in mind. The top Being the Header "Open CSS Loaders", then a hr, the links to my social media accounts, followed by a quote, and the two buttons, one for adding a code and the other to set editor theme.

## The work 
But this was the front end. First I started with the backend on Node.js and Express.
Install the basic packages.
```CLI
npm i express request mongoose dotenv body-parser --save
```
Now, it was just defining the routes and testing them which was pretty straightforward. So as of now I have the following routes:-
1. `/` => the home page
1. `/getquote` => to get a quote
1. `/api/serveranypopup` => to check if there is any popup message to show on the page 
1. `/api/setpopup` => to set a popup message
1. `/api/getloader` => to get all the loaders
1. `/api/addthiscode` => to add a code
1. `/api/like/:loaderid` => to like a loader

There are other routes for managing the page
1. `/iamadmin` => to go to the admin page
2. `/api/updatecode` => it requires a password to update any code
3. `/api/iamgoingtodeletethispost` => it deletes any of the loader but requires password