teleren/devto huggingface dataset:
An Introduction to Computer Networking for Web Developers
Tags: beginners, webdev
Published: 2020-08-18 15:34:51

Have you ever stopped to think about how information is transmitted from computer to computer? 

![Rabbit Hole](https://media1.tenor.com/images/ae0a1d53525901b101b0af2e88a0abc4/tenor.gif?itemid=7713390)

It's mind-blowing and we do it all the time – from making `fetch` calls in our applications to the daily usage of our computers. 

Let's contextualize this exploration through the lens of RESTful protocols. Our data, like an email that we'd like to send to a friend, is broken up into "packets" that are transmitted from one computer and rebuilt on the receiving computer. Let's follow an email from your computer with an IP address of 1.2.3.4 as it traverses the internet to your friend's computer at IP address of 5.6.7.8.

![IPCisco Image of TCP-IP Model](https://ipcisco.com/wp-content/uploads/email-transfer-over-tcpip-model-1.jpg)


We start from the top left corner of the diagram and work our way to the upper right hand corner:

- The **application layer** is where we navigate to [https://gmail.com](https://gmail.com) to compose and send an email. If your message is too long, it will be broken up into packets as we enter the TCP layer of the networking protocol stack.
- At the **TCP layer**, packets are assigned to port numbers based on the data type. The IANA governs and documents these conventions. For purposes of this introductory post, our takeaway should be that our packets are assigned to the appropriate port number for the receiving computer.
- At the **IP layer**, our packets receive the destination address (e.g*., IP address of 5.6.7.8*).
- Finally, we arrive at the **hardware layer** (*e.g., ethernet cables*) where our encapsulated alphanumeric data (*i.e., strings*) is transformed into electronic signals and gets sent across phone/cable lines – or light, if you have fiber.

Similarly to how UPS or USPS would route your online order from a warehouse overseas to your doorstep, your email packet traverses the internet in milliseconds to your figurative doorstep. Once arrived at 5.6.7.8, we reverse the steps outlined above. And with the help of checksums (a computation to confirm that no packets are missing or tampered with), the packets we sent are collected and reassembled on our friend's computer.

From a technical perspective, the data contained within (*i.e., the email or picture*) is very much the same. For those that are philosophically inclined, is the reassembled email *really* the same as what you sent?

---
*In a future post, I would like to explore the OSI/TCP-IP model in more detail to explore topics such as security and performance to help us become better coders.*
Ferramentas de otimização de imagem via linha de comando
Tags: shell, jpegoptim, optipng, gifsicle
Published: 2020-08-18 15:32:51

Na última semana durante um trabalho de otimização de performance para um site, chegou a hora das imagens. Muitas imagens antigas de produtos e também peças de layout que tinham bom espaço para ganho. Diminuir o tamanho dos arquivos sem perder tanto as cores e a qualidade gráfica das imagens.

Eu estava procurando por ferramentas para otimizar as imagens de uma maneira que eu pudesse fazer diretamente no servidor, via terminal. Dessa forma eu não precisaria fazer o download de tudo para minha máquina, depois subir novamente e nem nada similar. Apenas um Backup no próprio servidor e rodar os comandos.

Haviam imagens das famílias PNG, GIF e JPG e acabei chegando nas seguintes ferramentas:

* jpegoptim
* optiPNG
* gifsicle

Todas as três instaladas via apt-get e similares, super leves, fácéis de instalar e também de usar, como mostro a seguir:

### jpegoptim

Uso simples:

``jpegoptim filename.jpg``

Seu arquivo pode ser jpg, jpeg, JPG, JPEG, ...

O comando acima, faz a otimização mantendo a qualidade da imagem, o que queremos. Mas você pode também passar um parâmetro para controlar isso.

Tive excelentes resultados sem muita perda de qualidade e com excelentes ganhos de compressão com o seguinte comando:

``jpegoptim --max=80 filename.jpg``

### optiPNG

Uso simples:

``optipng filename.png``

Seu arquivo pode ser png, PNG, etc.

Diferente da ferramenta anterior para jpg, essa não permite parâmetros considerando perda de qualidade por conta do formato PNG e como ele foi concebido.

### gifsicle

Uso simples:

``gifsicle --batch --optimize=3 filename.gif``

**--batch** é o parâmetro para dizer que você quer manter o arquivo no mesmo lugar e com o mesmo nome.

**--optimize** é um parâmtro que determina o nível de otimização. 3 é uma opção que tenta vários métodos em cima da imagem. Consulte o manual parr
a as outras opções.

Seu arquivo pode ser gif, GIF, ..

Em caso de gifs animados, dê uma lida no manual. Existem alguns parâmetros adicionais para otimização de animações.

### Várias imagens de uma vez só

Para rodar os comandos acima em várias imagens, dentro de vários diretórios, use a opção **-exec** do comando **find**

``find -name '*.png' -exec optipng {} \;``

**-name** para buscar por nome dos arquivos

**.png** irá buscar por arquivos com a extensão .png. Não esqueça das aspas.

Após o **-exec** adicione o comando que você quer executar para todas as ocorrências que serão encontradas.

**{}** As chaves representam as ocorrências encontradas.

Feche com **\;**

Antes de sair executando essa combinação, teste com um *ls -l* no lugar do comando. Assim você verá o que o **find** vai retornar. E claro, faço um backup das imagens em outra pasta para evitar maiores problemas.

### man

Todas as ferramentas acima possuem um manual bem completo e fácil de compreender. Basta digitar **man** e o nome da ferramenta para acessar.

Grande Abraço!
Use laravel .env variable in Vue
Tags: laravel, vue, javascript, tutorial
Published: 2020-08-18 15:24:45

This used to drive me nuts, many times I wanted a .env in Vue that was easy to use and maintain. So when I had a Laravel back end I found the best way was to use the .env that comes with Laravel and pull variables from there. 

So how do we do it? 

Let's say we have an API key and of course we do not want people to be able to see it on the Javascript end. We start by defining the variable in the .env. We define mixable variables using 'MIX'. 

```
MIX_API_KEY=this_will_be_our_key
```

So as long as we run ```php artisan config:clear``` we can now use the variable in our component.

To use it we simply call 

```
process.env.MIX_API_KEY
```

In the real world, it will look like so

```
data() {
   return() { 
     api_key: process.env.MIX_API_KEY
  }
}
```

and perfection! We can now use the laravel .env file to host and use any variables we don't want to store in javascript.
Rust Announces Plans to Form a Foundation
Tags: news, rust, mozilla
Published: 2020-08-18 15:24:32

---
title: Rust Announces Plans to Form a Foundation
published: true
description: Rust announces their plans to create a Rust Foundation.
tags: news, rust, mozilla
//cover_image: https://direct_url_to_image.jpg
---

From the [Rust Blog](https://blog.rust-lang.org/):

>> The Rust project was originally conceived in 2010 (depending on how you count, you might even say 2006!) as a Mozilla Research project, but the long term goal has always been to establish Rust as a self-sustaining project. In 2015, with the launch of Rust 1.0, Rust established its project direction and governance independent of the Mozilla organization. Since then, Rust has been operating as an autonomous organization, with Mozilla being a prominent and consistent financial and legal sponsor.

>> Mozilla was, and continues to be, excited by the opportunity for the Rust language to be widely used, and supported, by many companies throughout the industry. Today, many companies, both large and small, are using Rust in more diverse and more significant ways, from Amazon’s Firecracker, to Fastly’s Lucet, to critical services that power Discord, Cloudflare, Figma, 1Password, and many, many more...

## Read the [full announcement](https://blog.rust-lang.org/2020/08/18/laying-the-foundation-for-rusts-future.html).
I've changed default branch from Master to Main
Tags: git, github
Published: 2020-08-18 15:22:19

---
title: I've changed default branch from Master to Main
published: true
description: 
tags: git, github
//cover_image: https://direct_url_to_image.jpg
---

I've made a small change to my git configuration, which anyone should be able to do today. I've updated my git to the latest 2.28. I think is a good step for my workflow, as seeing and repeating master on conference calls was a bit aggravating for me.

### On Windows:

```
git update-git-for-windows
```
Run through the prompts.

### On Ubuntu:

Canonical repos might not be up to date, so you will need a ppa repo fortunately there is one for git:

```
sudo add-apt-repository ppa:git-core/ppa
sudo apt update
sudo apt install git -y
```

### On Mac:

```
brew ugprade git
```

> I no longer have a mac, so can't confirm this is the latest.

Check version, and update your default branch name. Mine is main, but yours can be something else like latest, production, etc.
```
git --version
git config --global init.defaultBranch main
```
Building The Open Data Ecosystem For Music And More At Metabrainz
Published: 2020-08-18 15:14:09

<p>The Musicbrainz project was an early entry in the movement to build an open data ecosystem. In recent years, the Metabrainz Foundation has fostered a growing ecosystem of projects to support the contribution of, and access to, metadata, listening habits, and review of music. The majority of those projects are written in Python, and in this episode Param Singh explains how they are built, how they fit together, and how they support the goals of the Metabrains Foundation. This was an interesting exporation of the work involved in building an ecosystem of open data, the challenges of making it sustainable, and the benefits of building for the long term rather than trying to achieve a quick win.</p><p><a href='https://www.pythonpodcast.com/metabrainz-open-data-episode-276/'>Listen Now!</a></p>
I've Been Teaching Myself How to Code Full-Time for 2 Months... Now What?
Tags: career, codenewbie, devpride, csharp
Published: 2020-08-18 15:09:19

13 days ago I started the #100daysofCode challege, I went into it working through the Team Treehouse JavaScript Track. I was really struggling with JavaScript for quite some time but I was getting through it bit by bit. 

When I first started this journey, quitting my job and saying "OK I'm going to learn to code full time", I did not know just HOW many jobs there are! I assumed that I would just be a web developer and make websites. I learned how to make some pretty cool sites and I was enjoying it for the most part. I really was just enjoying learning something new and in the last month networking with some incredible people I met at a coding festival. 

11 days ago, I stumbled upon the C# track on Treehouse. I had heard of Unity Game Engine but I did not realize that you use C# to code games on there. I found an incredible Udemy course on using C# with Unity and built my first game in 9 days. I refused to use their basic ships, enemies, and powerups and designed my own in Photoshop. (That skill came in handy!) I am a huge Trekkie... So of course, when the teacher said that we are making a space shooter my mind instantly when to Star Trek. 

You can play the full game here! [Link](https://n0nb1narydev.github.io/voyage-game.html)

In the past 9 days, I felt more alive when it comes to being passionate about work than I have ever felt. I've decided that I want to continue learning C# and see where Game Development takes me. 

I have always LOVED playing games, but being able to see how it works from the inside, fixing the errors, succeeding and having a finished game that people enjoy, dude... THAT is where my heart is.
Hello Next.js!
Tags: nextjs
Published: 2020-08-18 14:58:41

# Create Next.js Project
Just type 
```sh
npx create-next-app project-name
```

Directory
```sh
project-name
  ┣ node_modules/
  ┣ public/
  ┃ ┣ favicon.ico
  ┃ ┗ versal.svg
  ┣ pages/
  ┃ ┣ api/
  ┃ ┃ ┗ helle.js
  ┃ ┣ _app.js
  ┃ ┗ index.js
  ┣ styles/
  ┃ ┣ global.css
  ┃ ┗ Home.module.css
  ┣ package.json
  ┣ package-lock.json
  ┗ README.md
```

# Hello Next.js

```sh
npm run dev
```

Access localhost:3000, then you can see a welcome page

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nsg1ay3btok82m2qeo78.png)
Liman MYS'de Samba DNS Yönetimi
Tags: limanmys, sambadns, samba, dns
Published: 2020-08-18 14:56:26

Liman MYS'de bulunan DNS eklentisi bind9, samba dns ve windows DNS'i yönetmeyi sağlayan bir eklentidir. DNS, makine adlarını ip adreslerine çevirerek makineler arasında iletişim kurulmasını sağlamaktadır. Kullanım amacı ise ip adresi gibi karmaşık yapı ile kolay anlaşılabilir ve kullanabilir makine isimleri arasında çift taraflı dönüşüm sağlamaktır.

### 1. Kurulu sistemler üzerinde DNS eklentisi yükleme

Liman MYS'de **Sistem Ayarları > Eklentiler > Yükle** yolunu izleyerek eklenti yükleyebiliriz. Ardından **Sunucular** kısmından DNS yönetimini yapacağımız sunucuyu buluruz. Sunucuda **Eklentiler** sekmesinden eklentimizi sunucuya ekleriz.


### 2. Zone Listeleme

DNS eklentisinde Samba DNS, bind9 servisi ve Windows DNS olmak üzere 3 temel DNS yönetimi bulunmaktadır. Eklenti otomatik olarak sunucuda kullanılan DNS yönetimini algılayarak gerekli arayüzü açmaktadır. Şu anki örneklerde Samba DNS kullanılmıştır.

Aşağıda karşımıza ilk gelecek ekran gözükmektedir. Tablo yapısında primary zone listesi bulunmaktadır.

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



### 3. Zone Ekleme, Düzenleme ve Silme

Yeni bir zone eklemek için **Primary Zone > Zone Ekle** butonu ile zone ekleme modalına ulaşırız. Oluşturulmak istenen zone ismi girilerek oluşturma işlemi gerçekleştirilir.

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

Eklediğimiz zone ismine tıkladığımızda zone hakkında detaylar karşımıza gelmektedir. Bu ekranda zone tipi, Zone DN, Fqdn, Allow Update ve kayıtların türleri hakkında bilgiler bulunmaktadır.

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

### 4. Kayıt Listeleme

**Kayıtlar** sekmesi ise kayıt ekleme, silme ve güncelleme işlemleri yapabildiğimiz kısımdır. Aşağıdaki ekran kayıtlar sekmesine aittir.

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

### 5. Kayıt Ekleme, Düzenleme ve Silme

Yeni kayıt eklemek için **Kayıtlar > Kayıt Ekle** modalından kayıt tipi, hostlabel ve recor datasını girerek kayıt oluşturulur. Kayıt tipinde A, AAAA, NS, MX, CNAME ve TXT seçilebilir.


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

İstenen kayıta sağ tıklayarak silebilir veya güncelleyebiliriz.  

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

Bir A kayıtı ekledikten sonra zone detaylar sekmesindeki chart da değişmektedir.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wr8as5amr0c3273quk60.JPG)
Understanding Svelte's $: (dollar label) syntax
Tags: svelte, javascript
Published: 2020-08-18 14:53:00

In the long list of cool features of svelte, The one which I use more often is this dollar label thing. Initially, it looked strange to me but later I realized it is a valid javascript syntax. You can use it for doing side effects like `useEffect` of React, there is also a syntactic sugar way of declaring computed properties.

1. Doing side effects on state change

Let's say we have a messaging app.  You need to change the title when a new unread message comes and you need to update title when the message is read. Traditionally, we will make a function which will update the title and use that function in both places (1. where we are getting new messages from server 2. event listener on user clicking mark as read) but with the svelte's approach we can do this

```javascript
$: {
    let unreadMessages = messages.filter(m => m.read === false);
    document.title = `${unreadMessages.length} unread messages`;
}
```

with this approach, we can just change the value of messages in both the places (1. where we are getting new messages from server 2. event listener on user reading the message) and it will be changed in the title. One thing to notice is unlike `useEffect` of React you don't have to explicitly write the dependencies of this block.  The component would be something like this

{% codesandbox zghkj module=App.svelte view=split %}

2. Computed properties

A computed property is one that will be recalculated if the property it dependents on changes.

Let's say we get another requirement, we also need to show the numbers of unread messages to users above the message list. Since we already have the list of unread messages, we can copy the same logic in the template to show the unread messages or we can do this.

```javascript
$: unreadMessages = messages.filter(m => m.read === false);
$: {
    document.title = `${unreadMessages.length} unread messages`;
}
``` 
here we declared a computed property (unreadMessages). Essentially unreadMessage is a variable that will be recalculated if messages property change. Now we can use this unreadMessages array in the template to show numbers of unread messages.

{% codesandbox i11oj module=App.svelte view=split %}
Package Validator for V
Tags: actionshackathon, github, opensource, productivity
Published: 2020-08-18 14:52:56

This workflow is a package validator for [V](vlang.io) Language. It uses V Actions for building and using V for Windows 10, Ubuntu 18.04 LTS and MacOS. This is a pretty simple workflow as V is really a new language and most things are handled by V itself!

It took a lot of time to create as I was backed by the limitations of V so I had to tell the creator about these issues which he fixed it in his free time but of course he couldn't solve all.

More things will be added soon. Any suggestions are welcome!

### My Workflow

I am using this as my Actions for V as its made by the community.

{%github https://github.com/nocturlab/setup-vlang-action %}

### Submission Category: 

Maintainer Must-Haves

### Yaml File or Link to Code

```yaml
name: CI
on:
  push:
    branches: [master]
  pull_request:
    types: [opened, synchronize]
jobs:  
 test:
  name: Run tests on ${{ matrix.os }} ${{ matrix.v-version }}
  strategy:
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
        v-version: [master, latest]
  runs-on: ${{ matrix.os }}
  steps:
      - uses: actions/checkout@v1
      - uses: nocturlab/setup-vlang-action@master
        with:
          v-version: master
      - name: Run vet
        run: v vet .
      - name: Run tests
        run: v test .
      - name: vfmt verify
        run: v fmt -verify -diff *.v
```

### How it works

This workflow uses the master branch of [V](https://github.com/vlang/v) repo. It goes through all the `.v` files in the current directory which includes `vet` i.e. find unnecessary code which can be optimized, `test` which tests all files with `__test` as suffix and `fmt` which formats the code but here we are using using `-verify` flag to see it's the files are formatted or not.

Currently `v fmt -verify -diff` shows the diff of the original and formatted files as `-verify` doesn't assert true even though they are formatted, its due to line endings. (LF v/s CRLF) 


### Additional Resources / Info

Example of Repo using it:

{%github https://github.com/v-community/repo_template %}
A quick way to prune local branches
Tags: git, bash, gists
Published: 2020-08-18 14:44:05

When I worked with a lot of features at the same time, it was really common to create a bunch of branches locally.

I felt really annoyed when I run `git branch` locally... It gives me a ton of legacy branches... This is super annoying especially when I use the tab-complete function.

When I searched for the way to clean up my local environment, it is common that the community will suggest `git fetch origin -p`. But, in fact, this is just a way to clean up the remote branches cached locally, i.e. the branches you see when you run `git branch -r`.

It seems that the current git does not implement such handy feature. I have quickly created this snippet in GitHub.
```bash
#!/bin/bash -e

git fetch origin -p
REMOTE=$(git branch -r | sed "s/origin\///g")
BRANCHES=$(git branch | awk -F ' +' '! /\(no branch\)/ {print $2}')
for branch in $BRANCHES; do
  if [[ -z $(echo $REMOTE | grep -w $branch) ]]; then
    git branch -D $branch
  fi
done
```
Ref: https://gist.github.com/RyanSiu1995/da44646f747623d9f51ec52724f16066

Once you create a file with this code, run the following command to put it to your `PATH`.
```bash
chmod 777 git-prune-branches
mv git-prune-branches /usr/local/bin
```

Enjoy!
Как протестировать конфиг whenever
Tags: ruby, rspec, testing
Published: 2021-01-19 10:59:52

---
title: Как протестировать конфиг whenever
published: true
date: 2020-08-18 00:00:00 UTC
tags: ruby, rspec, testing
canonical_url: https://vasily.polovnyov.ru/posts/testing-whenever.html
---

Недавно я опечатался в конфиге whenever:

```ruby
every 1.day, at: "03:30 am", roles: %i(backupable) do
  rake %(
    backup:db
    backup:assets
  ).join(" ")
end
```

При деплое whenever взорвался:

```
NoMethodError: undefined method `join' for "backup:db backup:assets":String
```

Чтобы в будущем такого не было, нужна хотя бы минимальная валидация конфига whenever. Решение оказалось простым: достаточно запустить на CI:

```ruby
bundle exec whenever
```

Если в конфиге есть проблемы, он взорвется ошибкой. Если проблем нет, выведет на экран получающийся кронтаб.
How to check Laravel view syntax
Tags: laravel, blade, lint, syntax
Published: 2020-08-18 14:22:44

---
title: How to check Laravel view syntax
published: true
description: With a simle command you can validate your Blade files
tags: ['laravel','blade','lint','syntax'] 
//cover_image: https://direct_url_to_image.jpg
---

[See it on GitHub](https://github.com/bdelespierre/laravel-blade-linter)

## TL;DR

From inside your Laravel project, do:

```BASH
composer require bdelespierre/laravel-blade-linter
php artisan blade:lint
```

Example output:
```
PHP Parse error:  syntax error, unexpected ')' in resources/views/_form_errors.blade.php on line 19
```

## Add it to your pre-commit hook so you never commit an invalid file

1. Open `.git/hooks/pre-commit`

2. Add the following:

```BASH
#!/bin/bash
output=$(git diff --name-only --diff-filter=d --cached | grep ".blade.php$" | xargs -r php artisan blade:lint)
exitcode=$?

C_RESET='\e[0m'
C_RED='\e[31m'
C_GREEN='\e[32m'

if [[ 0 == $exitcode || 130 == $exitcode ]]; then
    echo -e "${C_GREEN}BLADE OK!${C_RESET}"
else
    echo -e "${C_RED}BLADE NOK!${C_RESET}\n\n$output"
    exit 1
fi
```

3. ???
4. PROFIT!!!

---

As usual, leave a like and a comment. Don't hesitate to reach out if you have issues with this script.
who uses StoryBook JS? Is it a “playground”?
Tags: javascript, storybook, react, vue
Published: 2020-08-18 14:17:55

Does storybook let you perfect a component before using it?
I get tired of my browser refreshing or not loading right.
Does storybook let you test things out? 
There’s a VSC plug in for React that’s like that, but, which is better?