teleren/devto huggingface dataset:
Retry failed HTTP requests in Angular
Tags: rxjs, httprequest, javascript, angular
Published: 2019-07-03 16:03:59

---
title: Retry failed HTTP requests in Angular
published: true
tags: rxjs,http-request,javascript,angular
canonical_url: https://blog.angularindepth.com/retry-failed-http-requests-in-angular-f5959d486294
---

#### Immediate retry, delayed retry and retry with backoff

![](https://cdn-images-1.medium.com/max/2600/1*dMn_iEu-GH54L18HjQW8qA.png)

Accessing data from a backend is the backbone of almost every single page application. All dynamic content is loaded from a server.

In most cases, those HTTP requests work well and return the desired result. However, there are scenarios where a request might go wrong.

Imagine somebody is using your website over a hotspot on a train that rushes with 200 km/h across the country. 🚅 Well, the network might be slow, and the HTTP request still returns the desired result.

But what if the train enters a tunnel? The chances are high that the user has lost connection and your web app is unable to reach the server. In this case, the user is forced to refresh your application once he exits the tunnel and is back online.

Refreshing the application can have an impact on the current state of the application. The user could, for example, lose data he entered in a form.

Instead of letting a request instantly fail, it would be better to retry it a couple of times and display a corresponding message to the user. With such an approach, a refresh can be prevented.

[Find out more...](https://blog.angularindepth.com/retry-failed-http-requests-in-angular-f5959d486294)
Piping Your Honeybadger Events to Basecamp with Zapier
Tags: honeybadger, rails, zapier, notifications
Published: 2020-01-24 19:21:31

---
title: Piping Your Honeybadger Events to Basecamp with Zapier
published: true
date: 2019-07-03 13:30:00 UTC
tags: Honeybadger,rails,zapier,notifications
canonical_url: https://kylekeesling.dev/posts/2019/07/honeybadger-to-basecamp
---

My team has been working on consolidating and improving our communication tools and practices, and as part of that we’ve decided to ween ourselves off of [Slack](http://slack.com) and totally leverage [Basecamp](http://basecamp.com) for all internal and customer communications.

One of the major things that the team appriciated in Slack was the #dev channel I had created that piped all of our deploys, pull requests, and errors into one central location, allowing everyone to know what’s going on without having to tap someone on the shoulder.

Basecamp provides an easy way, using a [chatbot](https://github.com/basecamp/bc3-api/blob/master/sections/chatbots.md), to feed Github events into a Campfire chat, but getting our application errors in wasn’t quite as straightforward.

We use [Honeybadger](https://www.honeybadger.io/) to track our errors, and while they [offer many integrations](https://docs.honeybadger.io/guides/integrations.html), Basecamp isn’t one of them — enter [Zapier](https://zapier.com).

## How’d I do it?

Zapier made it a very simple process:

1. create a [catch webhook](https://zapier.com/apps/webhook/integrations) to catch [incoming webhooks from Honeybadger](https://docs.honeybadger.io/guides/services.html#1-select-the-webhook-integration)
2. create a POST webhook action that massages the JSON payload from Honeybadger, into [the format Basecamp expects for a chatbot](https://github.com/basecamp/bc3-api/blob/master/sections/chatbots.md#create-a-line)

### The Result in Basecamp

![Honeybadger Chatbot Example](https://kylekeesling.dev/images/2019/07/honeybadger-chatbot1.png)

Using the `details` and `summary` elements gives you the ability in Basecamp to create a collapsable post. In the sample above notice the little black right arrow, if you click it you can even get a little sample of the stacktrace. Here’s the value of the `contents` key I used for the chatbot payload:

```
<details>
      <summary>
        <strong>💥({xxx __fault__ id}){xxx__message}</strong><br>
        <a href="{xxx __fault__ url}">View in Honeybadger</a>
      </summary>
      <br><hr><br>
      <pre>{xxx __notice__ application_trace}</pre>
    </details>
```

And here’s a preview of what the expanded preview looks like:

![Honeybadger Chatbot Example w/ Stacktrace](https://kylekeesling.dev/images/2019/07/honeybadger-chatbot2.png)

## Summary

We are still in the process of fulling moving over to Basecamp, but so far I’ve not missed Slack nearly as much as I thought I would.

In all honestly the things we’ve missed the most from Slack are the GIPHY integration, and the quick access to screen collaboration tools, so if you have any suggestions on how your team addresses those areas, [I’d love to hear about it](https://twitter.com/kylekeesling).
On Glitch This Week
Tags: glitch, glitchthisweek, showdev
Published: 2019-07-03 13:29:24

---
title: On Glitch This Week
published: true
canonical_url: https://glitch.com/@glitch/glitch-this-week-july-3-2019
series: Glitch This Week
cover_image: https://cdn.glitch.com/02863ac1-a499-4a41-ac9c-41792950000f%2FpowDevToBanner.png?v=1562159525791
description: Just a few projects that caught our eye this week on Glitch (July 3, 2019).
tags: glitch,glitchthisweek,showdev
---

Glitch This Week is a regular series in which we round-up just some of the amazing projects that fantastic creators have made on [Glitch](https://glitch.com/). Here are a few projects that caught our eye this week.

## [Play Scattergories with Friends ✍🏽](https://glitch.com/~scatterg)

For the lucky among us enjoying a long weekend this week and hanging out with friends and family, [Steph Monette](https://glitch.com/@smonette)'s "[scatterg](https://glitch.com/~scatterg)" game might come in handy. It's a simple way to play Scattergories. Grab one or more friends, a pen, and a piece of paper. Then use her app to randomly generate a letter, hit play on the timer, and write down words in each of the listed categories.

Remix it to put your own spin on it - change out the categories, or tinker with the rules to make things more interesting.

{% glitch scatterg app %}


## [Map with Me 🌍](https://glitch.com/~mapwithme)

"[mapwithme](https://glitch.com/~mapwithme)" by [Javier Arce](https://glitch.com/@javier) is a collaborative mapping tool that lets anyone with a Twitter account add interesting places to your map. Crowd-source great places to visit, or poll colleagues for restaurants to try - whatever you want to create a create custom map together for.

{% twitter 1143949898439712769 %}


## [Make Card Art 🃏](https://glitch.com/~canvas-cards)

[Luke Patton](https://glitch.com/@lkpttn)'s "[canvas-cards](https://glitch.com/~canvas-cards)" is a gallery of card designs created with JavaScript canvas. Updated weekly, it's an ever-growing collection of generative art inspired by math, architecture, nature, and other things.

What's more - each card includes an editable code block that you can tweak to make your own designs, or learn more about how each one works.

{% user lkpttn %}
{% glitch canvas-cards app %}

Other apps in [this week's round-up](https://glitch.com/@glitch/glitch-this-week-july-3-2019) include an app that turns you into a Roman, a themeable illustration using Material Components, and a Coding Train project to learn about data and APIs in JavaScript. [Check them out](https://glitch.com/@glitch/glitch-this-week-july-3-2019)!
Go Serve static files
Tags: go
Published: 2019-07-03 13:03:27

---
title: Go Serve static files
published: true
description: go, golang
tags: go, golang
---
<img src="https://media.giphy.com/media/1fhKRqbMFgXTYKHaZ6/giphy.gif">

You may know the Go programming language, sometimes called Golang. 

Golang is often used for network related programs. You can easily serve static files with Golang.

First import 3 modules:

    import (
        "fmt"
        "log"
        "net/http"
    )
    
The "net/http" module will give us webserver functionality. Need the "log" module for logging errors. Ok

Then create a handle function to map url requests to files served

        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            http.ServeFile(w, r, r.URL.Path[1:])
        })

Total program:

    package main
    
    import (
        "fmt"
        "log"
        "net/http"
    )
    
    func main() {

        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            http.ServeFile(w, r, r.URL.Path[1:])
        })
    
        log.Fatal(http.ListenAndServe(":8082", nil))
    }

More on Golang:

* https://golangr.com
* https://golang.org
Weekly Picks #82 — Development Posts
Tags: webdev, javascript, go, react
Published: 2019-07-04 16:01:08

---
title: Weekly Picks #82 — Development Posts
published: true
tags: webdev,javascript,go,react
canonical_url: https://medium.com/daily-now/weekly-picks-82-development-posts-e31edf708283
cover_image: https://cdn-images-1.medium.com/max/1024/1*dWCndzCMIKanACG-FNsynQ.jpeg
---
Due to your many requests to remove paywall content from the weekly picks, starting this week we will not share any paywall content on the list. We are also looking for a way to detect automatically paywall content and to remove it from Daily for good.

- [Let’s write frontend in Go](https://app.dailynow.co/r/01f789d538bf25483bb9a6a473f86c48)
- [HTML can do that?](https://app.dailynow.co/r/7ed16765eabc4a841ad9f398e6cb17bc)
- [How to Write a Good Piece of Code](https://app.dailynow.co/r/f961b147c8b48ea98a399c1ab0716dee)
- [Top 5 (Free) Online Courses to Learn HTML, CSS & Web Development in 2020](https://app.dailynow.co/r/ff3ef8bd9cfdeb22ec5c0f08ef75056b)
- [Sizzy — The browser for designers and developers](https://app.dailynow.co/r/8ffeeede71b19b8c63648ae481a3e3f0)
- [Top 20 CSS Navigation Menus ?](https://app.dailynow.co/r/b63f7e35b59d0d985bfd820afc6ba646)
- [React UI animation made simple](https://app.dailynow.co/r/7f2fbaf029726304c00cb19894754f55)
- [10 Things NOT To Do When Building React Applications](https://app.dailynow.co/r/23c0785e188c51b044fa38fbf747097c)
- [What We Learned Rebuilding Our Site From Scratch](https://app.dailynow.co/r/1febfe94a4a4c03c56289fe2459e86f2)
- [How to speed up the initial rendering of a web page](https://app.dailynow.co/r/39ed8ae43cd94f096f49e5b1f2a0c1c5) by [Anton Babakhin](https://medium.com/u/5aa448787b44)

[_Thanks to Daily_](https://www.dailynow.co/) _developers can focus on code instead of searching for news. Get immediate access to all these posts and much more just by opening a new tab._

***

[![](https://cdn-images-1.medium.com/max/1024/1*7bwIhcH467BKX5Ni8XWpQg.jpeg)](https://www.dailynow.co/)
How to add a line break to  PostgreSQL?
Tags: devops
Published: 2019-07-03 12:40:40

You have to insert some data into your PostgreSQL table that has line break. As a result, the cell will look like this:
```text
First line
Second line
```
To use "escape sequences" in a string literal you need to use an ["extended" constant](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-ESCAPE). You can specify the escape character by prefixing the letter E:
```sql
UPDATE posts SET body = E'First Line\nSecond line.' WHERE id = 2701;
```
Reset values in React Final Form w/ keepDirtyOnReinitialize
Tags: react
Published: 2019-07-03 12:39:56

**How to reset values with keepDirtyOnReinitialize in React Final Form after submitting.**
  
**The Issue**
  
If keepDirtyOnReinitialize is applied to your form, then form.reset() no longer able to remove field's value.
    
**The Solution**
    
The Solution is simple— if the form submitted successfully: first change keepDirtyOnReinitialize to false -> perform form reset form.reset() -> and change keepDirtyOnReinitialize back to true.

```js
<Form
  onSubmit={onSubmit}
  keepDirtyOnReinitialize
  render={({ handleSubmit, form }) => (
    <form
       onSubmit={(event) => {
       const promise = handleSubmit(event);
       promise && promise.then(() => {
         form.setConfig('keepDirtyOnReinitialize', false);
         form.reset();
         form.setConfig('keepDirtyOnReinitialize', true);
       })
      return promise;
      }}
    >
    ...
   </form>
}/>
```
Reset values in React Final Form
Tags: react
Published: 2019-07-03 12:39:52

**How to reset values in React Final Form after submitting**

At first I wrote the following code:

```js
<Form
  onSubmit={onSubmit}
  render={({ handleSubmit, form }) => (
    <form
      onSubmit={event => {
        handleSubmit(event).then(() => {
          form.reset();
        })
      }}
    >
    ...
    </form>
  }/>
```
If we implement a function like this, we will get an error "Uncaught TypeError: Cannot read property 'then' of undefined”, when we try to submit invalid form.
Invalid forms — form with validation errors.

**The solution**

To avoid this error, we need to place `handleSubmit(event)` to a variable, and if the variable is not undefined call `.then()`.

```js
onSubmit={(event) => {
  const promise = handleSubmit(event);
  promise && promise.then(() => {
    form.reset();
  })
  return promise;
}}
```
Command for create zip archive without gem's 📁
Tags: ruby
Published: 2019-07-03 12:39:38

```ruby
class CreateZipCommand
  def call(files)
    # Create temp directory for files 
    tmp_dir = Dir.mktmpdir
    tmp_zip_path = File.join(tmp_dir, "files.zip")
    
    # Move files to the temporary folder you created above
    files.map do |file|
      download_file(file, tmp_dir)
    end
    
    # Go to the folder and archive the entire contents
    `cd #{tmp_dir} && zip #{tmp_zip_path} ./*`
    
    # Return zip path
    tmp_zip_path
  end
end

> CreateZipCommand.new.call(files)
=> "/var/folders/bk/0c864z710654sx555jpdpx9c0000gn/T/d20190126-7447-d27fpl/files.zip")

```

Most gems for working with archives eat a lot of memory when working with large files. This solution does not have these problems.

Make sure that the zip utility is installed on your computer - it don't work without it
Swap keys and values in a Python dictionary
Tags: python
Published: 2019-07-03 12:37:53

---
title: Swap keys and values in a Python dictionary
published: true
description: python
tags: python
---
<img src="https://media.tenor.com/images/e4d895552f3844d1bb4c6a4c5c3105ec/tenor.gif" alt="dictionary">

A dictionary is a one to one mapping. Every key has a value.
In Python that can be

    dict = {'a': 1, 'b': 2, 'c': 3}

You can then get the values like this

    print(dict['b'])

That's great and all. But what if you want to flip the entire dictionary?  Where keys are values and values and keys.

### Swap values

You can easily swap the key,dictionary pairs in Python, with a one liner.

    dict = {value:key for key, value in dict.items()}

So in practice you can have something like this:

    dict = {'a': 1, 'b': 2, 'c': 3}
    print(dict)

    dict = {value:key for key, value in dict.items()}
    print(dict)

This will output

    {'a': 1, 'c': 3, 'b': 2}
    {1: 'a', 2: 'b', 3: 'c'}

So the one liner

    dict = {value:key for key, value in dict.items()}

flipped the whole dictionary. Nice trick :)


Learn Python?

* https://pythonbasics.org/
* https://pythonprogramminglanguage.com/
Daily Challenge #6 - Grandma and her friends
Tags: challenge
Published: 2019-07-03 12:32:52

---
title: Daily Challenge #6 - Grandma and her friends
published: true
description: Another challenge in the series.
series: Daily Challenge
tags: challenge
---

Another day, another challenge. Today, your task  is to help your grandmother visit her friends.

This challenge comes from user [@g964 on CodeWars](https://www.codewars.com/kata/5536a85b6ed4ee5a78000035): 

> Your granny, who lives in town X0, has friends. These friends are given in an array, for example: array of friends is

> [ "A1", "A2", "A3", "A4", "A5" ].

Note: the order of friends is this array and it must not be changed since this order gives the order in which they will be visited.

> These friends inhabit towns and you have an array with friends and towns, for example:

> [ ["A1", "X1"], ["A2", "X2"], ["A3", "X3"], ["A4", "X4"] ]
or
[ ("A1", "X1"), ("A2", "X2"), ("A3", "X3"), ("A4", "X4") ]
or
(C)
{"A1", "X1", "A2", "X2", "A3", "X3", "A4", "X4"}

> which means A1 is in town X1, A2 in town X2... It can happen that we don't know the town of one of the friends.

Your granny wants to visit her friends and to know how many miles she will have to travel. Can you help her figure it out?

_Thank you to [CodeWars](https://codewars.com/), who has licensed redistribution of this challenge under the [2-Clause BSD License](https://opensource.org/licenses/BSD-2-Clause)!_

_Want to propose a challenge for a future post?  Email **yo+challenge@dev.to** with your suggestions!_
Custom onChange in React Final Form
Tags: react
Published: 2019-07-03 12:21:49

Let's take a case when we need to call our own function to change a state of a specific field in a form (our react final form).

Here is a way to do the exact that:
You should pass your function as a parameter and after that just call it inside of the onChange method

Example:

```js
const FormGroupAdapter = ({ input, inputOnChange }) => {
    const inputProps = {
        ...input,
        onChange: e => {
            input.onChange(e);
            inputOnChange && inputOnChange(e);
        }
    };

    return <input {...inputProps} />;
};

const handleChange = event => {
    console.log("!!!", event.target.value);
};

const App = () => (
    <Form
        ...
        render={({ handleSubmit, reset, submitting, pristine, values }) => (
            <form onSubmit={handleSubmit}>
                <div>
                    <label>some label</label>
                    <Field
                        name="someField"
                        component={FormGroupAdapter}
                        inputOnChange={handleChange}
                    />
                </div>
                ...
            </form>
      	)}
    />
);

```

[Live example](https://codesandbox.io/s/nk63v7615j)
How to download files with Axios
Tags: javascript
Published: 2019-07-03 12:21:17

A simple example using the Blob() constructor:

```js
export function someFunction(values) {
  return (dispatch) => {
    ...
    const method = 'GET';
    const url = 'http://go.api/download_file';
    ...
    axios
      .request({
        url,
        method,
        responseType: 'blob', //important
      })
      .then(({ data }) => {
        const downloadUrl = window.URL.createObjectURL(new Blob([data]));
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.setAttribute('download', 'file.zip'); //any other extension
        document.body.appendChild(link);
        link.click();
        link.remove();
      });
  };
}
```
Not Quite a Fail
Tags: codenewbie, beginners, javascript, css
Published: 2019-07-03 12:17:58

So yesterday I set out to complete two modules, but didn't get through the first of the two. It's not that I didn't do any work, but I didn't have the time to actually complete it, especially since FCC had an outage mid-day. During the outage I worked on CSS-Battles. I completed 2 and 3, as well as read through [Olzhas'](https://dev.to/pheeria) - [CSS Battle solutions](https://dev.to/pheeria/css-battle-1-simply-square-c19) to get an idea of what other folks did. I've got new ideas about how to complete some and might work through them later. 
![](https://thepracticaldev.s3.amazonaws.com/i/ehmu1gv46cofu1m7jt9m.jpg)

No Big Deal, the streak is in place. Today's attempt finish Applied Accessibility, complete Responsive Web Design Principles, and get through most of CSS Flexbox. I think I can get to CSS Flexbox, but I think it might be a bit EXTRA compared to the previous sections.

My concern over the next few days is the fact that it's a long weekend. I do most of these tasks in slow times throughout my work day. 

How do you stay focused on your goals during holidays and weekends?
Passing events between browser tabs without WebSockets
Tags: javascript
Published: 2019-07-03 12:08:41

What if need to pass some event from one browser tab to each others? And we don't have WebSockets...

It turns out that localStorage raises events 😍

Namely, events are triggered when an item is added, deleted, or changed in another context. In essence, this means that when you change localStorage in one tab, other tabs can find out about this by listening to the storage event of the global window object. For example:

```js
  window.addEventListener('storage', function (event) {
    console.log(event.key, event.newValue);
  });
```

Of course, there are some restrictions on use (you can read about them here [https://www.w3.org/TR/webstorage/](https://www.w3.org/TR/webstorage/)), but for simple cases it is match perfect.
How is Kubernetes related to Docker?
Published: 2019-07-03 11:36:14

It’s a known fact that Docker provides the lifecycle management of containers and a Docker image builds the runtime containers. But, since these individual containers have to communicate, <a href="https://mindmajix.com/kubernetes-training">Kubernetes</a> is used.  So, Docker builds the containers and these containers communicate with each other via Kubernetes. So, containers running on multiple hosts can be manually linked and orchestrated using Kubernetes.
How to get the WordPress cache plugin that works
Tags: wordpress
Published: 2019-07-03 11:53:15

---
title: How to get the WordPress cache plugin that works
published: true
tags: WordPress,wordpress
canonical_url: https://kevinhq.com/how-to-get-the-wordpress-cache-plugin-that-works/
---

There are many WordPress plugins you can use. Each of their developers claimed their plugin was the fastest. The rest claimed their plugin was the simplest and easiest to use. Not only that, there are even those paid or premium plugins for such purpose.  Then, how to pick one of them that really works for… 

[Read More »How to get the WordPress cache plugin that works](https://kevinhq.com/how-to-get-the-wordpress-cache-plugin-that-works/)
Changing the log to daily in CakePHP 3.x
Tags: php, cakephp, log, tutorial
Published: 2019-07-03 10:58:15

---
title: Changing the log to daily in CakePHP 3.x
published: true
description: default CakePHP logs all the data in one file, here we will how to change it to a separate file daily.
tags: PHP, CakePHP, log, tutorial
canonical_url: https://codebysamgan.com/how-to-make-log-daily-in-cakephp-3-x
cover_image: https://codebysamgan.com/wp-content/uploads/2018/12/logging-daily.jpg
---

As you may know according to the default configuration of CakePHP the debug and error log is generated in the same file. But this can be changed in a few simple steps. All you have to do is following.

1. Got to config/app.php
2. Find the ‘Log’ configuration array
3. In both debug and error replace the ‘file’ with “’debug-‘ . date(‘Y-m-d’),” and “’error-‘ . date(‘Y-m-d’),” respectively
4. Save the file and you are good to go.

Now, the log will be generated on a daily basis.
My VS Code theme.....
Tags: vscode, design
Published: 2019-07-03 09:56:27

I like to customize editors. Vscode is my most favorite editor ever. So I tried my best to customize it. Here is the full screen screenshot of vscode....

![](https://thepracticaldev.s3.amazonaws.com/i/en2zg7mfryltjljpe93z.png)
https://thepracticaldev.s3.amazonaws.com/i/6khuhv34hkmkzp9hdmmw.png

I've removed close button from tabs so that I don't accidentally close tabs when I click on tabs. Colors are my own choice....... I've modified color theme extensions and made it to my own package in my own repository. My VS Code is completely keyboard driven. I never touch my mouse while I use vscode. 

I supported vscode CZ it supports vim. Vscode vim extension can provide almost full vim experience. Though it doesn't support loading local vimrc file but through vscode settings, many vim customizations are possible. It supports key mapping and leader key.

 I mapped all the key bindings so that it becomes blazing fast. Even after using unnecessary 126 extensions my VS Code is super fast. I've removed all boring menus so that it becomes clean-wide.