teleren/devto huggingface dataset:
Wiremock as a Web Server for Testing
Tags: testing, mocking
Published: 2019-12-01 00:50:47

This requires a little bit of background. Our product is sold highly customized so we utilize a forking model for development. The UI has a clear interface to the backend (no backend rendering), there are only a few files (not a sprawling website of content).

---

Wiremock provides a http(s) server which will respond to a request based on matching criteria (this can be the url, header, or body content). 

Wiremock exposes a rest api allowing for the mocking to be defined with the tests and posted to the server before test execution (or as part of). This keeps the test self contained, preventing the need to maintain a "test" environment. 

Multithreaded testing can be challenging in this situation because the mappings can conflict with each other if the match criteria is not sufficiently unique to the test session. 

---

Wiremock is our chosen mocking solution. We have hosted our product in a docker container with Wiremock serving the UI and the UI configured to communicate back to wiremock for all requests. This provides a self contained UI build where our selenium tests can handle and mock all UI interactions.

To add this testing into a pipeline, we needed to stand up the container and have a predictable url. This meant we have Nginx provide redirection based on project and branch. It also provide an environmental config our test solution utilizes. This is needed because we host for many projects and branches, so the container selects a random port. 

---

To provide pre-defined mappings. Start from the docker image. You then need to copy over the [mappings](http://wiremock.org/docs/stubbing/), and duplicate the [entry point and cmd](https://github.com/rodolpheche/wiremock-docker/blob/master/Dockerfile#L37) 

{% github https://github.com/rodolpheche/wiremock-docker %}
Using Laravel Valet On Linux/Ubuntu! 🐘 🔑
Tags: laravel, php, linux, tutorial
Published: 2019-11-21 19:58:42

Valet is an elegant way to create a local webserver for testing your Laravel applications on Mac.

Fortunately there is a fork allowing us to use Valet on a Linux based OS as well thanks to [@cpriego](https://github.com/cpriego).

Let's get started.

## Helpful Links

- [Docs](https://cpriego.github.io/valet-linux/)

- [Repo](https://github.com/cpriego/valet-linux )

## Prerequisites

- Laravel installation must be complete (see [Setting Up A Laravel Local Dev Environment On Ubuntu](https://dev.to/andrewbrooks/setting-up-laravel-local-dev-environment-on-ubuntu-51kp)

- Ubuntu 18.04/19.04

### Installing Dependencies

```
sudo apt-get install php7.3-curl
sudo apt-get install jq
sudo apt-get install xsel
sudo apt-get install libnss3-tools
```

### Installing Valet

```
composer global require cpriego/valet-linux
```

```
test -d ~/.composer && bash ~/.composer/vendor/bin/valet install || bash ~/.config/composer/vendor/bin/valet install
```

Restart your terminal


### Serving your project


`cd` into project root and run the following command


```
valet park
```

The web URL generated will be `{project_folder_name}.test`.

For example:

```
laravel new blog

cd blog

valet park
```

will provide a working URL of `blog.test`

### Things to remember

If you have a local Apache serve running you need to disable it or your Valet URLs will lead to the Apache welcome page.
```
sudo systemctl stop apache2
sudo systemctl disable apache2
```


To un-park a project `cd` into the root and run

```
valet forget
```

----

I'm Andrew, a full stack software developer from the deep south who makes internet things.

Hit me up on twitter [@andrew_brooksie](http://www.twitter.com/andrew_brooksie)

Reach out if you have any questions or requests for future write-ups!
WTF is Amazon S3?
Tags: aws, webdev
Published: 2019-11-21 18:20:50

---
title: WTF is Amazon S3?
published: true
description: Learn WTF is Amazon S3 in 2 minutes
tags: aws, webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/sph8x1z6yinrx1l0pq54.jpg
canonical_url: https://tlakomy.com/wtf-is-s3/
---

Before we start - I'm working on [https://cloudash.dev](https://cloudash.dev), a brand new way of monitoring serverless apps 🚀. Check it our if you're tired of switching between 50 CloudWatch tabs when debugging a production incident.

<hr/>

Amazon S3 is one of those things you may have heard about in the context of:

>So, we keep our static files on Amazon S3

or 

>Every image uploaded to dev.to is stored on an S3 bucket (_which is true, btw_)

and if you're not sure what _exactly_ S3 is, this post is for you.

# WTF is Amazon S3?

Amazon S3 stands for _Amazon Simple Storage Service_ and it's one of the most popular services provided by AWS (_Amazon Web Services_).

It's an object storage service which takes care of scalability, data availability, security, and performance. By "_object storage service_" I mean - "_this is a place for you to store your files_".

Files in S3 are stored in things called **buckets**, which sounds weird at the beginning but you quickly get used to it. What's important to remember is that S3 bucket names need to be **globally unique**.

If I've created a bucket called `tlakomyBucket`, you are **not** able to create a bucket with exactly the same name, no matter how hard you try. 

Speaking of names, you're not able to change the bucket name after you create it - choose wisely!

S3 offers virtually unlimited storage capacity, if you managed to collect every cat picture on the Internet, you'd be able to put it on S3.

There are two kind of buckets: private or public ones. If, for instance, you allow users to upload their CVs to a website, you'd probably want to use a private bucket. S3 can be used for hosting static websites and in order to do that - you need to convert it to a public one. By default all newly created buckets and their contents are **private**.

The image with 3 buckets on top of this post is, in fact, hosted on S3, here's the url:

`https://thepracticaldev.s3.amazonaws.com/i/sph8x1z6yinrx1l0pq54.jpg`

as you can see, name of the bucket is `thepracticaldev`. AWS does **a lot** of things to ensure that this file is accessible 99.99999999% of the time (literally).
Making a dynamic Stored Procedure with SQL and C#
Published: 2019-11-21 18:08:06

```
﻿using Backend.Infrastructura.ProcedimientosAlmacenados.Command;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace Backend.Infrastructura
{
    public class SqlStoredProcedureServiceManager
    {
        public async Task<List<T>> Get<T>(string uri)
        {
            HttpClient client = new HttpClient();

            HttpResponseMessage response = await client.GetAsync(uri);
            bool responseWasWrong = !response.IsSuccessStatusCode;
            if (responseWasWrong)
            {
                return null;
            }

            string jsonString = await response.Content.ReadAsStringAsync(); 
            JavaScriptSerializer JSserializer = new JavaScriptSerializer();
                         
            return JSserializer.Deserialize<List<T>>(jsonString);
        }

        private DataTable GetDataTable(string query)
        {
          
                SqlDataAdapter adapter = new SqlDataAdapter(query,SQLConfiguration.GetDbString());
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);

                SQLConfiguration.Close();
                return dataTable;
            
        }

        public DataTable GetDataByStoredProcedure(CommandSender cmdSnd)
        {

            using (SqlDataAdapter sda = new SqlDataAdapter(cmdSnd.GetCommand()))
            {

                DataTable dt = new DataTable();
                sda.Fill(dt);
                SQLConfiguration.Close();
                return dt;
            }

        }

        public List<T> GetAnyDataByCommand<T>(CommandSender cmdSender)
        {
            DataTable table = GetDataByStoredProcedure(cmdSender);
            return ConvertToList<T>(table);
        }


        public List<T> ConvertToList<T>(DataTable dataTable)
        {
            var columnNames = dataTable.Columns.Cast<DataColumn>()
                    .Select(c => c.ColumnName)
                    .ToList();
            var properties = typeof(T).GetProperties();

            return dataTable.AsEnumerable().Select(row =>
            {
                var objectType = Activator.CreateInstance<T>();
                foreach (var prop in properties)
                {
                    if (columnNames.Contains(prop.Name))
                    {
                        PropertyInfo propInfo = objectType.GetType().GetProperty(prop.Name);


                        prop.SetValue(objectType, row[prop.Name] == DBNull.Value ? null : Convert.ChangeType(row[prop.Name], propInfo.PropertyType));
                    }
                }
                return objectType;
            }).ToList();
        }
    }
}
```
Arguments and Parameters - do you know the difference?
Tags: javascript, webdev, beginners
Published: 2019-11-21 22:26:13

When talking about code, arguments and parameters are oftentimes mixed up. So let's clarify that once and for all!

Let's have a look at a simple JavaScript function:

```js
function log(a, b) {
  // do something
}

const myString = "codesnacks"

log(10, myString)
```

So we have a `log` function, that takes two **parameters**, `a` and `b`. And we're calling it with the two **arguments** `10` and `myString`. 

The **parameters** `a` and `b` are **potential values**, `10` and `myString`, the **arguments**, are **actual values**.

It's relatively easy to remember if you keep the following in mind:

**P**arameters are **P**laceholders.
**A**rguments are **A**ctual values.
The history prop in Route
Tags: react, javascript, frontend, webdev
Published: 2019-11-22 14:18:12

---
title: The history prop in Route
published: true
description: How to programmatically navigate a React app
tags: reactjs, javascript, frontend, webdev
cover_image: https://ferrariwebdevelopment.s3.us-east-2.amazonaws.com/assets/20191008-history-prop.jpeg
---

## How to programmatically navigate a React app

We have previously seen how `Route` defines some props that can be passed down to components.

Here's an example.
`Route` passes its `props` down to the `Books` component by using the spread operator:

```js
<Route
  path="/books"
  render={(props) => <Books {...props} />}
/>
```

The props defined by `Route` are `history`, `match` and `location`. They are used in different situations. Let's look briefly at the `history` prop.

### The `history` prop

Route defines a `history` prop that helps us navigate programmatically between pages.
The `history` prop has a similar function as the `history` object in the browser. It facilitates navigation between pages and remembers the URLs we have visited earlier.

`history` is similar to an array that we can modify by adding or removing items from it.

### Let’s look at an example

An example of how we use the `history` prop in `Route` is when we have a button and we want to move to another URL by pressing it. In this case we want to move to the *store* page.

```js
<button>Go to the store</button>
```

Right now the button is not doing anything. To make the button work we need to add an `onClick` event to it. The `onClick` event will listen for a click on the button and perform some action as a result of it.

```js
<button onClick={goToStore}>Shop now</button>
```

Now we have added an `onClick` event to the button and assigned a function to this event. The function name is `gotoStore`.
Let's actually write the function:

```js
const goToStore = event => {
  event.preventDefault();
  props.history.push('/store')
}
```

`goToStore` receives the click event as an argument, and the first thing we do in our function should be to prevent the default browser action of reloading a page when a button is clicked. We do this with `event.preventDefault()`

With that out of the way we then do something with the `history` property that lives on the `props` object.
Remember when we said that the `history` property is similar to an array where you can add or remove items? Here we use the `.push()` method of the `history` property to add a URL to the history.

We add the `/store` URL to the end of the `history`. This will activate the route that handles this URL and will effectively take us to the *store* page.

In summary

- Route defines some props that can be passed down to components
- The history prop of Route is used to programmatically facilitate navigation
- `history` is similar to an array that keeps a list of visited locations
- We can add a new location to the `history` prop by using the `push()` method
How do you share your projects on your portfolio website? 
Tags: webdev, beginners, career, freelance
Published: 2019-11-22 20:13:04

---
title: How do you share your projects on your portfolio website? 
published: true
cover_image: https://imgbbb.com/images/2019/11/22/carlos-muza-hpjSkU2UYSU-unsplash.jpg
description: developer portfolio
tags: webdev,beginners,career,freelance
---

##I am planning to make a simple portfolio website of mine.##

##Why?##
I want to share that with my potential clients. And, I always wanted to know how other freelance/ professional developers share their portfolio/ projects with clients?

##Make it. What's the problem?##
The problem is - most of my projects done for clients are their own web applications. Some of these applications are not live and some of the clients didn't give me the live link. 

**So, how do I share my past projects which are done for a client? Screenshots? Videos or deploy codes on netlify and link them?**

##What do you do? And, can you share your one (that'll help us for some inspiration)?##

Cover Photo by Carlos Muza on Unsplash
Ambiente Web PHP Docker, utilizando container Ubuntu
Tags: docker, devops, php, webdev
Published: 2019-11-23 20:47:54

Atualmente, existem diversas tutoriais de como utilizar o Docker como ambiente de desenvolvimento, porém vou demonstrar aqui, uma maneira de como criar um ambiente Web Apache e PHP, executando no Docker, com container Ubuntu. Este método é interessante, pois possibilita recriar a máquina linux do servidor em produção, em sua máquina pessoal, evitando surpresas de compilação de códigos.

####Primeiro passo, instalar o Docker.####
Não irei especificar a instalação do Docker, porém a documentação do mesmo é completa e fácil de entender, [acesse aqui:](https://docs.docker.com/).  

####Configuração do Projeto####
Vamos criar uma pasta Docker no diretório Documentos, recomendo utilizar a estrutura de pastas a seguir, pois centralizará seus documentos de desenvolvimento. 
Defina a estrutura a seguir:

-Documentos
  -Workplace
    -Docker
      -Tutorial

Dentro da pasta Tutorial, crie os arquivos a seguir.

[docker.dockerfile](https://github.com/britoerick/tutorialDocker/blob/master/docker.dockerfile)
[apache-config.conf](https://github.com/britoerick/tutorialDocker/blob/master/apache-config.conf)

Pasta www e dentro da pasta arquivo [index.php](https://github.com/britoerick/tutorialDocker/blob/master/www/index.php)

####Construindo o Container####
Agora abra o terminal e execute o comando a seguir:

docker build -t mysite


####Executando####
Executa o comando para rodar o apache em segundo plano.

docker run -p 8080: myd site -d

####Mudanças####
Se for necessário realizar alguma mudança, poderá alterar seu arquivo original, sem precisa reconstruir.

docker run -p 8080: 80 -d / Usuários / dan / site: / var / www / site mysite
Styling React
Tags: css, react, javascript, cssinjs
Published: 2019-11-23 10:27:35

---
title: Styling React
published: true
description: Handling styles/css in a react application
tags: css, react, js, cssinjs
---

When it comes to styling our React application, there’s a list of options available for us to choose from. I’ve recently worked upon starting a fresh React project and since there are so many of these options, I wanted to take my time and explore them.

So, we could divide them into three major categories/ways of styling:

1. CSS
2. CSS-in-JS
3. Component libraries

Each of these comes with their own perks and some pitfalls, you can decide which way to choose or you can use them in combination.


1. CSS

Writing CSS in .css files is perhaps the simplest option to go for, where there’s not need to learn a single new thing. All we need is to setup the css-loader for Webpack (that too, is already set-up in create-react-app).
With this way, we’re not adding another layer in our application. Adding another layer such as a framework or library requires us to invest into that which is not a desired thing in longterm. It mean we’ll have to learn to write/use CSS in a different way and adds limitations as well.
The CSS written in .css files is independent of React or the application structure for the most part, thus it is easily reusable. By default, there’s not code-splitting here but there’s ways to work around that in case you have massive application.
Here’s a simple example:

{% codesandbox sgmxl %}

2. CSS-in-JS

This is a fairly new concept which came along and has been gaining popularity lately. The idea is to keep the styles attached to the components, mainly to achieve component-scoped styling and code-splitting. It might be a little tricky to get used to but libraries such as styled-components has now made it very easy to work with.
You could simply start from scratch or, there are component libraries built upon css-in-js as well.
Updating CSS dynamically without a refresh is pretty straight forward here, specifically for the purpose of theming.
Here’s an example with styled-components:

{% codesandbox 2gcbq %}

3. Component Libraries

Just like how there have always been CSS frameworks, there are component libraries very similar to that. Component libraries such as Google Material or Ant-d comes with pre-built components to use. This sounds like it will be very quick for development, however, it takes a bit of learning and getting used to, to be working with any of these libraries. Here, the limitations might appear in our way of controlling customisability, component behaviour, updated features etc.
Components such as buttons are easier to use compared to using the more complicated, layout components. It not very convenient to work with and challenging to understand what's the behaviour on the rendered side of it.

{% codesandbox r56dw %}

I'd use CSS for a normal case and could go to css-in-js for more advanced requirements.

Let me know the ways that you prefer to use for your react applications!
How to programmatically extract data from a webpage (e.g your dev.to reading list)
Tags: javascript, beginners, dom
Published: 2019-11-23 13:35:44

Sometimes you need to get the information presented on a webpage in a structured form out of that page. Let's have a look at your dev.to reading list for example. Let's imagine, that we want to extract a list of the articles listed there. So let's scroll through our reading list, open the console and let's get going!

Let's inspect the elements, that contain the links to the articles. 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/0475bbnre3jtj1lvsq4d.png)

We can see, that the anchor, which contains the link has a class `item`. So let's try to grab all elements of that page with `class="item`. 

```js
document.querySelectorAll('.item')
```

This will return a `NodeList` with the selected elements.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/o5r0igd2i8h3s3gzu917.png)

Next, we want to convert this NodeList to an array, because it's easier to iterate on that. We use an `Array.from` for that:

```js
Array.from(document.querySelectorAll('.item'))
```

We now have an array with the selected DOM elements, that contain all the necessary information. To get an array of just the links, we can simply access the `href` property of our DOM elements.

```js
Array.from(document.querySelectorAll('.item'))
  .map(a => a.href)
```

But it would be nicer, to also have the title. So let's have a look at the DOM structure again:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/aioa638ixzfbx8dcmhl8.png)

We can see, that the title is contained in a div with the class `item-title` inside of the already selected anchor. So we can use another `querySelector` on that anchor to get the title:

```js
Array.from(document.querySelectorAll('.item')).map(a => ({
  href: a.href,
  title: a.querySelector('.item-title').innerText,
}))
```

To access the text content of a DOM node we can use the `innerText` prop.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/2lwrbuctc0shk70wlayd.png)

Well done! We now have all the information of our reading list as structured content.

If you want to get your links as a pastable markdown snippet, you wouldn't return an array in the map function, but a string in the structure `[title](href)`. Afterwards you can use `reduce` to boil the array down to just one string, that contains the links as a list.

```js
Array.from(document.querySelectorAll('.item'))
  .map(a => `[${a.querySelector('.item-title').innerText}](${a.href})`)
  .reduce((acc, e) => `${acc}\n* ${e}`, '')
```
Tips for container, DNS & database security
Tags: todayilearned, security, database
Published: 2019-12-06 02:44:41

*TL;DR style notes from articles I read today.*

### [3 steps toward improving container security](https://red.ht/37oAcp8)

- Vet the use of code from online sources. Use discovery tools to manage and scale up containers securely with runtime protection. 
- Focus on how you build access rules and permissions. Understand the level of granularity needed right from day one to build this. 
- Harden the container host with policies to prevent resource abuse. Use access control groups, and run containers with read-only images.
- Secure content inside containers by limiting Linux OS features running within it.
- Enforce image source integrity protection to track content changes and determine who made them.

*[Full post here](https://red.ht/37oAcp8), 5 mins read*

---

### [Five strategies to remove single points of DNS failure](http://bit.ly/2Oz1BMy)

- Stay aware of trends that can compromise the 13 root name servers. 
- Choose a top-level domain more likely to stay up under large-scale attacks or software faults, unlikely to change hands and with significant investment in infrastructure.
- Choose a DNS provider that uses Anycast and is large and scalable; use a different company to service your endpoints.
- Keep track of expiration dates of domains and SSL certificates.
- Don’t couple your endpoints and DNS zone control in one provider. 

*[Full post here](http://bit.ly/2Oz1BMy), 11 mins read*

---

### [Secure databases in complex backend systems with these 5 best practices](http://bit.ly/2OdNeOF)

- Keep application and database servers on different physical machines, with a high-performance host for the apps & high-level security for databases.
- Set up web application firewalls, and anti-malware & anti-ransomware solutions for the database server and review them regularly. Turn off any services not frequently used.
- Encrypt data residing on servers with a private key and also encrypt before transit.
- Limit the number of users accessing the database. Allow access only when required. Maintain and monitor activity logs. Keep database credentials hashed and salted.
- Patch the OS and third-party software, APIs and plug-ins using the latest versions. Remove or deactivate unused apps.
- Schedule regular backups and use a database proxy to accept requests only from trusted sources. 

*[Full post here](http://bit.ly/2OdNeOF), 6 mins read*

---

*[Get these TL;DR style notes directly to your inbox every weekday by signing up for my newsletter, in.snippets(), here.](https://mailchi.mp/appsmith/insnippets?utm_source=devto&utm_medium=post08&utm_campaign=is)*