teleren/devto huggingface dataset:
Unable to set request header in laravel tests
Tags: help
Published: 2020-03-27 16:45:39



I have a test which is trying to login and get details. I need to pass a bearer token in request header for this operation. Please see the below code. I could see that the header seldom has the headers that I set. Can anyone give me a pointer to fix this issue?

I am using Laravel 7.2.2, PHP 7.4, 

And I am running php artisan test

Code:


    public function a_user_can_get_details()
        {
            $this->create_user();
    
            $response = $this->json('POST', 
                        '/api/login', 
                        [
                            "email" => "john.doe@example.com",
                            "password" => "john123"
                        ]);
            $response->assertSuccessful();
    
            $token = Str::replaceLast('"', '', Str::replaceFirst('"', '', $response->getContent()));
            $headers = [
                            'Accept' => 'application/json',
                            'Content-Type' => 'application/json',
                            'Authorization' => 'Bearer ' . $token
                        ];
            
    
            $response = $this->withHeaders($headers)
                            ->get('api/user');
                        
            $response->assertSuccessful();
            $this->assertCount(1, User::all());
            
        }

And here is the error I am getting. Actually, the test must pass. That is the right user name and password:

    Response status code [403] is not a successful status code. Failed asserting that false is true.
    
      at tests/Feature/UserTest.php:141
        137|
        138|         $response = $this->withHeaders($headers)
        139|                         ->get('api/user');
        140|
      > 141|         $response->assertSuccessful();
        142|         $this->assertCount(1, User::all());
        143|
        144|     }
        145|
> Written with [StackEdit](https://stackedit.io/).
What are your best solutions to integrate your SVG icons in your web app ?
Tags: webdev, icon, svg
Published: 2020-03-27 16:35:17

Hello,

I'm developing a web app and there is something I can't manage very well: it's SVG icons management !

Let me explain, I'm working with a Designer who creates SVG icons for the website, and I don't know how to manage them correctly and I would like to know which solution do you use everyday to manage them.

I know there are tools like Icomoon, but I don't want to regenerate a font everytime we add a new SVG to our icon library. I would like to use my svg icons easily and be able to customize them (fill color, size, ...) that's why I can't use a `<img src="my-svg"/>`.

Actually, I'm using Vue.js to build my web app and when I have a new icon, I create a new Vue component which is a copy of the SVG icon and I add some props like: color, width, height ... but I'm pretty sure there's a better way to handle my problem.

Do you have any suggestion of tools I could use to better manage my SVG icons ?
First Steps 👶 with Node.js Part 1
Tags: beginners, node, tutorial
Published: 2020-03-27 16:18:40

---
title: First Steps 👶 with Node.js Part 1
published: true
description: Take your first steps toward backend development using your existing Javascript skills. Watch this video to work along with me through a Node.js workshop!
tags: beginners,node,tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/nc25wj054wdme4gb9o9b.jpg
canonical_url: https://raddevon.com/articles/first-steps-with-node-js-part-1/
---

{% youtube hRXFobkJN1M %}

# Video Notes

Node.js allows you to run Javascript code outside your web browser. That makes it possible for you to take what you already know about Javascript and apply it to backend development as well as frontend.

📝 We'll be working through [the Learn You Node workshop](https://github.com/workshopper/learnyounode) together.

📚 As you work through the exercises, you'll want to reference [the Node.js documentation](https://nodejs.org/dist/latest-v12.x/docs/api/).

👋 Thank you for watching and for working through the exercises with me! Look out for upcoming videos in which we'll work through the remaining exercises together.
Minimal Productivity Apps
Tags: productivity, organization, minimalizem, vue
Published: 2020-03-27 16:17:20

I needed a tool for managing tasks and writing down notes, but most of the tools out there are either complicated or lacking a nice and solid UI. So I decided to make one that suits my needs. It's minimal and includs Tasks Tracker, Timer and Notes manager.

I made this website using Vue.js that is so easy and fun to use - enjoyed building this so much. I'm storing the data in the localStorage.

[website](https://saconway.github.io/minimal-productivity-apps/) | [code](https://github.com/SaConway/minimal-productivity-apps)

![preview](https://saconway.github.io/minimal-productivity-apps/preview.jpg)
Aprendi Lógica de Programação. E agora?
Published: 2020-03-27 15:59:22

Agora que você aprendeu a lógica de programação, é necessário entender alguns conceitos antes de iniciar o próximo curso.

Primeiro, veremos na prática a diferença entre back-end e front-end:

**Front-End**

![https://upload.wikimedia.org/wikipedia/commons/thumb/c/c9/Client-server-model.svg/1200px-Client-server-model.svg.png](https://upload.wikimedia.org/wikipedia/commons/thumb/c/c9/Client-server-model.svg/1200px-Client-server-model.svg.png)

O lado do Cliente (também conhecido como Front-End) é responsável por "dar vida" à interface. Trabalha com a parte da aplicação que interage diretamente com o usuário. Por isso, é importante que esse desenvolvedor também se preocupe com a experiência que o usuário vai ter.

A grosso modo essas são as ferramentas básicas para o desenvolvedor front-end usar:

![https://becode.com.br/wp-content/uploads/2016/05/O-Front-end-Developer-Entenda-a-Diferen%C3%A7a-entre-um-Webdesigner-e-um-Desenvolvedor-Web.jpg](https://becode.com.br/wp-content/uploads/2016/05/O-Front-end-Developer-Entenda-a-Diferen%C3%A7a-entre-um-Webdesigner-e-um-Desenvolvedor-Web.jpg)

**Back-End**

O desenvolvedor back-end trabalha na parte de "trás" da aplicação. Ele é o responsável, de forma geral, pela lógica envolvida no sistema e pela implementação das regras de negócios. Em uma aplicação web, este desenvolvedor, quando focado, não toca na parte visual da aplicação.

Quando falamos de back-end em desenvolvimento web, nos deparamos com várias linguagens, como *Go*, *Clojure*, *C#*, *PHP*, *Java*, *Python*, *Ruby*, entre outras. Cada uma possui vantagens e desvantagens em relação ao uso no desenvolvimento web, bem como no mercado de trabalho.

![https://becode.com.br/wp-content/uploads/2017/02/As-15-principais-linguagens-de-programa%C3%A7%C3%A3o-no-mundo.png](https://becode.com.br/wp-content/uploads/2017/02/As-15-principais-linguagens-de-programa%C3%A7%C3%A3o-no-mundo.png)

E o desenvolvedor FullStack atua nestas duas vertentes.

**Básico de Front-End:**

**HTML:**

**[https://www.devmedia.com.br/html-basico-codigos-html/16596](https://www.devmedia.com.br/html-basico-codigos-html/16596)**

**CSS:**

**[https://www.hostinger.com.br/tutoriais/o-que-e-css-guia-basico-de-css/](https://www.hostinger.com.br/tutoriais/o-que-e-css-guia-basico-de-css/)**

**Back-End - Com foco na linguagem JavaScript:**

[https://rocketseat.com.br/starter/curso-gratuito-javascript](https://rocketseat.com.br/starter/curso-gratuito-javascript)

Dicionário Básico de Programação:

console.log("Hello World"); = Escreva("Hello World");

Concatenação = + (ao invés de usar vírgula para juntas variáveis com caracteres, usa-se o simbolo de +)

Variáveis:

int = Inteiros

String = Caracteres,

Float (ou Double) = Números decimais

Boolean = Verdadeiro ou Falso

True = Verdadeiro

False = Falso

Estruturas Condicionais:

If = Se

Else = Senão

Switch Case = Escolha

Estruturas de Repetição:

For = Para

While = Enquanto

Outras estruturas =

Funções = Function

Classes = Class

Vetor = Array

Fontes:

Google Images,

TreinaWeb: [https://www.treinaweb.com.br](https://www.treinaweb.com.br/),
What's the best way to connect to an machine behind CGNAT.
Tags: discuss, security, devops
Published: 2020-03-27 15:13:41

I have a server at home , but my ISP is CGNAT, and I can't connect to it directly from the internet. I've used tailscale and FRP to connect with it. 

What's the best way to do it? Port forwarding from my router is not an option for me.
Avoiding Awkward Element Breaks in Print HTML
Tags: tutorial, print, html, css
Published: 2020-03-27 15:00:21

As some of you might have seen on my previous post here on DEV.to, I've been working hard on a Resume Builder web app.

You can read more about it here.

{% link https://dev.to/amruthpillai/ever-dreamed-of-a-free-and-open-source-resume-builder-that-doesn-t-store-your-data-meet-reactive-resume-1dpl %}

Anyway, I'm not here to plug the app. I wanted to share something that I learned recently in the process of building the app. When dealing with resumes, you're going to have people print the page a lot, so the app needs to handle all cases of print. And that's a whole side of CSS that I was not aware of before.

### TL;DR

```css
div {
  page-break-inside: avoid;
}
```

Let's get back to the development process... For example, without any styles related to print, this is how it looks when I hit `Cmd + P`:

![Image](https://i.imgur.com/nfcmteV.png)

It shows the sidebars too and the entire app. The margins are all off and it's just a mess. Thankfully, CSS helps us here. This is what I used to make it look a bit neater:

```css
@page {
  size: A4;
  margin: 2.5em;
}

@media print {
  html,
  body,
  body * {
    -webkit-print-color-adjust: exact;
    color-adjust: exact;
    visibility: hidden;
  }

  #page,
  #page * {
    visibility: visible;
  }

  #page {
    background-color: white;
    margin: 0;
    padding: 0;
    box-shadow: none;
    position: absolute;
    left: 0;
    top: 0;
  }
}
```

Now it looked great, but there was still one problem. See if you can guess?

![Image](https://i.imgur.com/4niGYcJ.png)

Yep, ugly page breaks that I do not want on my resume or any website for that matter. You never know when someone is going to print your DEV.to article and pass it around the office!

### So, how do I fix this issue?

Well, for those who read the **TL;DR**, that's how. `page-break-inside: avoid;` can avoid you loads of trouble during print. And this is how I used it within my `#page` body:

```css
#page,
#page * {
  page-break-inside: avoid;
  visibility: visible;
}
```

And now, voila... doesn't this look much better?

![Image](https://i.imgur.com/DoryNsO.png)

Basically, the `page-break-inside` property sets whether a page-break should be avoided inside a specified element. I've applied it to all the elements inside the resume, so nothing gets cut off.

Hope this neat little tip helps you in your development as well :)
How do you maintain your passion?
Tags: beginners, discuss, feels, watercooler
Published: 2020-03-27 15:00:14

---
title: How do you maintain your passion?
published: true
description: I want your advice about passion in tech
tags: beginners, discuss, feels, watercooler 
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/5ho2uaz8m6k3y0vtmvag.jpg
---

_cover image by By [PumpkinSky](https://commons.wikimedia.org/w/index.php?curid=60639478)_

I'm looking for my next side project at the moment and I'd like to know what motivates you to go out and start creating your next big project.
Github collaboration: does it matter where the GitHub repo lives?
Tags: discuss
Published: 2020-03-27 14:44:20

Hey friends! 
I am wondering if it matters on whose account a github repo lives. I oftentimes have some project idea and then usually my collaborator goes ahead and creates a github repo for it. I didn't mind it until I noticed that this is a pattern with so many people  — folks seem to care a great deal to have the repo live on their accounts.

**My questions:**
- When and why does it matter? 
- Does it matter, if the project is non-commercial? 
- And does it matter if the project will be monetized? 

Thank you!
Ponteiros em Golang
Tags: go
Published: 2020-03-27 14:34:05

Ponteiros me lembra o primeiro e segundo semestre da faculdade, ao aprender algoritmos e estruturas de dados em C. Eles eram a principal dor de cabeça em meus estudos. Algumas linguagens como Java, C/C++ e o Go têm conceitos de ponteiros, que permitem manipular variáveis na forma de endereço de memória. O ponteiro talvez não seja o conteúdo mais importante de Golang, mas é usado em quase todo o seu código, se você estiver trabalhando em um projeto Go com alto desempenho e padrão.

## Os ponteiros no mundo real
Podemos relacionar os ponteiros das linguagens de programação com o mundo real, de forma análoga. Atualmente está popular a entregas online, que pela comodidade receber em casa se torna atrativa. Pense é mais fácil passar o endereço da sua casa para o entregador, do que sua casa ir até o entregador. O problema é se você enviar o endereço errado. Você não receberá a sua encomenda.

## Voltando ao mundo da Programação
Digamos que exista uma variável e ela seja usada em várias funções ao mesmo tempo. Você deseja que ele seja atualizado automaticamente sempre que alguma função alterar seu valor para permitir que outras pessoas possam obter o novo valor. Ponteiro é o conceito que pode resolver essa situação.

```golang
package main

import "fmt"

func main() {
  x := 0
  y := 0
  fmt.Printf("Antes:\tx=%d\ty=%d\n", x, y)
  atualizando(x, &y)
  fmt.Printf("Depois:\tx=%d\ty=%d\n", x, y)
}

func atualizando(x int, y *int) {
  x = 10
  *y = 10
  fmt.Printf("inside:\tx=%d\ty=%d\n", x, *y)
}

/*
>>> Saída <<<
Antes:	x=0  y=0
Dentro da função: x=10 y=10
Depois:	x=0  y=10
*/
```
No exemplo assim podemos ver, que os valores após passar pela função *atualizando*, ficaram o seguinte x permaneceu o mesmo e o y atualizou. Isso acontece pelo fato de x ser passado como valor e y como referência. Mas a diferença é antes de passar y para a função de atualizando, ela é convertida em ponteiro e enviada para a função. Portanto, a função obterá o endereço de memória de y e o utilizará para alterar o valor de y diretamente.
Simple DecisionTreeClassifier in Python
Tags: python, machinelearning, showdev, datascience
Published: 2020-03-27 14:33:05


Decision Trees (DTs) are a non-parametric supervised learning method used for classification and regression. The goal is to create a model that predicts the value of a target variable by learning simple decision rules inferred from the data features.

For instance, in the example below, decision trees learn from data to determine the preferred music genre based on the year and gender of the person. The deeper the tree, the more complex the decision rules and the fitter the model.


DecisionTreeClassifier is a class capable of performing multi-class classification on a dataset.


As with other classifiers, DecisionTreeClassifier takes as input two arrays: an array X, sparse or dense, of size [n_samples, n_features] holding the training samples, and an array Y of integer values, size [n_samples], holding the class labels for the training samples:


``` python
from sklearn import tree
import sys

# age
# sex [0: male, 1: female]

features = [
    [18, 0], [19, 0], [22, 0], [25, 0], [28, 0], [31, 0], [34, 0], [40, 0], [45, 0],
    [18, 1], [19, 1], [22, 1], [25, 1], [28, 1], [31, 1], [34, 1], [40, 1], [45, 1]
]

# music genre

labels = [
    'rap', 'rap', 'hip hop', 'hip hop',
    'rock', 'rock', 'rock', 'country', 'country',
    'dance', 'dance', 'hip hop', 'hip hop',
    'rap', 'rap', 'rap', 'classical', 'classical'
]

clf = tree.DecisionTreeClassifier()

clf.fit(features, labels)

# pass age and sex as script params with sys.argv
prediction = clf.predict([[sys.argv[1], sys.argv[2]]])

print(prediction)


```

Try it!

``` bash

python3.7 decision_tree_classifier.py 18 1
['dance']

```

the tree can also be exported in textual format with the function export_text. 

``` python

from sklearn.tree.export import export_text

decision_tree_text = export_text(clf, feature_names=['age', 'sex'])
print(decision_tree_text)

```

```

|--- age <= 37.00
|   |--- age <= 26.50
|   |   |--- age <= 20.50
|   |   |   |--- sex <= 0.50
|   |   |   |   |--- class: rap
|   |   |   |--- sex >  0.50
|   |   |   |   |--- class: dance
|   |   |--- age >  20.50
|   |   |   |--- class: hip hop
|   |--- age >  26.50
|   |   |--- sex <= 0.50
|   |   |   |--- class: rock
|   |   |--- sex >  0.50
|   |   |   |--- class: rap
|--- age >  37.00
|   |--- sex <= 0.50
|   |   |--- class: country
|   |--- sex >  0.50
|   |   |--- class: classical


```
Weeknote 13/2020
Tags: weeknote, livecoding, remotework
Published: 2020-03-27 14:45:22

---
title: Weeknote 13/2020
published: true
date: 2020-03-27 14:31:00 UTC
tags: weeknote,livecoding,remotework
canonical_url: https://www.geewiz.dev/2020/03/27/weeknote.html
---

### Learning JavaScript

While I’ve learned more than a dozen different programming languages in my three decades of using computers, I’ve been focusing on Ruby for the last one. At my company, we automate our hosting infrastructure with Chef, we build our websites with Rails or Jekyll, and even for more complex command line scripts, Ruby has replaced Bash for us. But lately, I’ve actually added another programming language to my roster that I wanted to learn for years: Javascript. With StimulusJS, it was really easy to add a bit of client-side logic to our hosting dashboard. There’s a lot to learn and I’m really looking forward to doing more frontend development!

### Icons for everything

Talking about frontend: Iconography is an important part of every user interface nowadays. Of course, the internet offers endless supply of icons but many of these collections are of low quality, have unclear licensing policies or are of a quality that doesn’t justify their price. Discovering the [Noun Project](https://thenounproject.com/) has solved this problem for me completely. I’ve started using their icons on web sites, in my talk slides and even to give my Stream Deck a more consistent look.

### Live stream for remote workers

With so many more people now working from home (and struggling with the change), I thought I’d share my 10 years of experience with remote work. I’ve started doing a 30-minute live stream over on my [live coding](https://www.twitch.tv/fullstacklive) channel every morning at 9:30am (10:30 on the continent) where I chat with viewers about how to make remote work… work. The stream is titled “[The Daily Bootup](https://www.twitch.tv/fullstacklive)”. How about you join me Monday morning and we start the day together? Simply click “Follow” to get a notification when we start!
Multiple language website
Tags: multiplelanguagewebsite
Published: 2020-03-27 14:20:28

When creating a new website, developers may want to add a translation feature that allows users of different languages other than English to read and use their website.

Well, I am going to share with you one way in which we can add a translation feature to a website.

Firstly add 

<div id="google_translate_element"></div>
 
add script 

   <script type="text/javascript">
      function googleTranslateElementInit() {
      new google.translate.TranslateElement({pageLanguage: 'en'},  
      'google_translate_element'); 
       }
    </script>
@discardableResult
Tags: ios, swift
Published: 2020-03-27 14:18:28

> Ignoring non-void function returns so they do not warn on unused results.

You are writing your code and have a couple of functions that return some values. But when you are invoking some of these functions you are not using the returning values and are getting warnings like this through your compiler.

**`warning:` result of call to 'someFunction()' is unused**

So to avoid these warnings, your code starts looking like this:

```Swift
let _ = someFunction()
```

The warning was now suppressed and your console outputs the expected result. But you are feeling not happy about seeing your code with a lot of `let _`. This can be prone to future errors. 

## 👉🏿 You need `@discardableResult`.

In Swift annotating methods and functions with @discardableResult informs the compiler that a non-void return type should be consumed. So, ignored results do not raise warnings or errors.

**`warning:` result of call to 'someFunction()' is unused**

The @discardableResult attribute enables developers to indicate when their functions and methods produce a non-essential result and should not produce a warning.

```Swift
extension Array { 
    mutating func removeLast() -> Element {
        return remove(at: count - 1)
    }
}
```

The above function removes the last element of an `Array`. When we call `array.removeLast()` from `var array = [2, 4, 7, 0]`, `array.removeLast()` returns 0. 

```Swift
var array = [2, 4, 7, 0]
array.removeLast()
// warning: result of call to 'removeLast()' is unused
// array.removeLast()
//      ^         ~~
// [2, 4, 7]
```

As our intention was just to remove the last element of the array and do nothing with the returned value, it makes sense to us to discard this value. So rather suppress the warning message with `let _ = array.removeLast()`, we should use `@discardableResult`.

In the following snippet, we expect to be able to discard the return value after invoking `array.removeLast()`.

```Swift
extension Array { 
    @discardableResult
    mutating func removeLast() -> Element {
        return remove(at: count - 1)
    }
}
```

When we call `array.removeLast()` again, we will not see the warning anymore.

```Swift
var array = [2, 4, 7, 0]
array.removeLast()
// [2, 4, 7]
```

# 🙌🏿
Major Trends Of SEO Taking Place 
Tags: seo, digitalmarketing
Published: 2020-03-27 14:15:12

Dramatic trends in SEO services are rising. Today, if a business wants to survive in this highly competitive environment, it is important to craft its own effective online marketing strategies and implement them in a successful manner. Before you go on to  <a href="http://www.webmynesystems.com/search-engine-optimization/">explore SEO specialist India </a>made available at the most affordable cost, here are some of the SEO trends that you must know about. 

1. There is a dramatic rise in voice searches. Smartphone virtual assistants and smart speakers are becoming highly popular. SEO strategies therefore must incorporate optimization for the voice search to be in line. 

2. There is a market of paid results, map packs, snippets that are featured online, and even knowledge graphs. Google or search engines undoubtedly value these aspects because they certainly improve users’ experience by providing crucial information that users are looking for. 

3. Building unique content that engages the audience is going to be one of the most important trends; in fact, it is the necessity of today. A concise and accurate content strategy can work wonders for your business. 
 
4. Notably, Google is improving its own understanding of user search intent. Efforts are being made so that Google can better understand what a specific keyword means in context. This facilitates more conversational queries. As a result, content creators must focus on creating experiences for all users. SEO professionals need to craft effective and creative online strategies and use tricks to improve rankings in the search engine.   

<b>It's Necessary To Check Good SEO Agency</b>

These are some of the major changes taking place in the world of the internet. Today, a large number of consumers use the internet to explore specific services or products. As a result, it becomes imperative for organizations to look for the best digital marketing agency service online. 

<b>Best Company Does Great Work</b>

Creating a strong online presence to sustain existing customers and attracting new ones or simply spreading brand awareness is not going to be an easy task. You need support from an affordable SEO company that has the necessary technological tools and experienced professionals.

Need info about more services? Visit <a href="http://www.webmynesystems.com/">WebmyneSystems</a>.