teleren/devto huggingface dataset:
Configuring Workbox with Create React App
Tags: react, pwa, workbox, caching
Published: 2020-02-16 09:54:32


There are many ways to integrate Workbox in CRA, you can use a library like **react-app-rewired** or eject react-scripts for taking full control over your configuration for your web app. But we are going to use a small dev dependency called **workbox-build** for this.

## 1 - Add these 2 files to your src folder

###  sw-build.js
```
const workboxBuild = require('workbox-build');
// NOTE: This should be run *AFTER* all your assets are built
const buildSW = () => {
  // This will return a Promise
  workboxBuild
    .injectManifest({
      swSrc: 'src/sw-template.js', // this is your sw template file
      swDest: 'build/service-worker.js', // this will be created in the build step
      globDirectory: 'build',
      globPatterns: ['**/*.{jpg}'], // precaching jpg files
    })
    .then(({ count, size, warnings }) => {
      // Optionally, log any warnings and details.
      warnings.forEach(console.warn);
      console.log(`${count} files will be precached, totaling ${size} bytes.`);
    })
    .catch(console.error);
};
buildSW();
```
This file will run on every build and will inject your custom service worker from sw-template.js in place.

###  sw-template.js
```
if (typeof importScripts === 'function') {
  importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js');
  /* global workbox */
  if (workbox) {
    console.log('Workbox is loaded');
    workbox.core.skipWaiting();

    /* injection point for manifest files.  */
    workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);

    /* custom cache rules */
     workbox.routing.registerRoute(
      new workbox.routing.NavigationRoute(
        new workbox.strategies.NetworkFirst({
          cacheName: 'PRODUCTION',
        })
      )
    );
  } else {
    // console.log('Workbox could not be loaded. No Offline support');
  }
}
```

This file is our custom service worker and uses Network first strategy. Read more about workbox caching strategies [here](https://developers.google.com/web/tools/workbox/modules/workbox-strategies).
 You can try out caching fonts also using CacheFirst strategy.
 
## 2 - Install workbox-build
```
npm install --save-dev workbox-build
```

## 3 - Add the following to your scripts in package.json
```
"build-sw": "node ./src/sw-build.js",
```

## 4 - Add npm run build-sw to your build script in package.json like this
```
"build": "react-scripts build && npm run build-sw",
```
Finally in your index.js replace the serviceWorker.unregister() to serviceWorker.register()

## And there we have it
We have successfully integrated workbox in our React APP. You can find the Github repo [here](https://github.com/divyansh7924/workbox-example-with-cra).
My Visual Studio Code Extensions
Tags: vscode, html, javascript, webdev
Published: 2020-02-16 09:53:39

I use Visual Studio Code as my main code editor. At least for all web development projects. If you haven't seen or tried vscode before [here is a link to their site](https://code.visualstudio.com/), which does a good job of explaining the use cases and features. It is a relative small program that you can add functionality to with extensions. In this post I thought I share which extensions I find useful.

## Install an extension

Just thought I mention how you can install an extension in vscode in case someone was new to it. When you open vscode you can click on the "Extensions" icon in the main toolbar (Ctrl + Shift + X)

![VSCode interface](https://dev-to-uploads.s3.amazonaws.com/i/1nnswpo7a8cc18va1ros.jpg)

Then type in the name of the extension ⇒

![VSCode extension list](https://dev-to-uploads.s3.amazonaws.com/i/3bkkhhfv08cskk2uu1et.jpg)

And hit install when you find the one you are looking for!

## My extensions list

- ESLint - by Dirk Baeumer
    - Integrates ESLint for Javascript into VS Code.
- Auto Rename Tag - by Jun Han
    - Auto rename paired HTML tags
- Auto Close Tag - by Jun Han
    - Automatically add HTML/XML close tags
- Bracket Par Colorizer 2 - by CoenraadS
    - For colorizing matching brackets
- Debugger for Chrome - by Microsoft
    - Debug JavaScript in the Chrome browser
- Debugger for Firefox - by Firefox DevTools
    - Debug JavaScript in Firefox
- Docker - by Microsoft
    - Syntax highlighting, commands, hover tips and linting for Dockerfile
- Document This - by Joel Day
    - Automatically generates detailed JSDocs comments in TypeScript and JavaScript
- ES7 React/Redux/GraphQL/React-Native snippets - dsznajder
    - Simple snippets
- GitLens - Git supercharged - by Eric Amodio
    - Supercharge the Git capabilies built into VS Code
- HTML CSS Support - by ecmal
    - CSS support for HTML documents
- Live Server - by Ritwick Dey
    - Launch a development local Server with live reload feature for static & dynamic pages
- npm Intellisense - Christian Kolher
    - Autocompletes npm modules in import statements
- Prettier - Code formatter - Esben Petersen
    - Code formatter using prettier
- React Native Tools - Microsoft
    - Debugging and integrated commands for React Native
- vscode-icons - VSCode Icons Team
    - Icons for VS Code

I update and change this list when I find some new shiny thing or a new project require more out the editor. Interested in hearing about your collection of extensions, do you see something new here or am I missing something that you would recommend :D

Happy coding!

This post was originally published on my blog [Helmen Design](https://www.helmendesign.no/)
I wrote an ORM for SQLite
Tags: typescript, javascript, sql, showdev
Published: 2020-02-16 09:52:02

It starts with inter-op with [mongoose](https://mongoosejs.com/), and inspired from [Typegoose](https://github.com/typegoose/typegoose).

It is an ORM that

- Can query by Mongo-like query
- Auto-convert back-and-forth for JSON \<=> TEXT, Date \<=> INTEGER and Boolean \<=> INTEGER

For Mongo-like query, it can be tested here -- https://q2search.herokuapp.com/LiteORM (The actual Mongo-like query is in the console)

Still, there are something that would be hard to do / cannot do...

- Case-sensitive LIKE (LIKE in SQLite is case-insensitive)
- Query by RegExp (I use `LIKE '%'||$identifier||'%'` instead. RegExp queries need re-compile.)
- Limited update / delete (like `LIMIT 1` ==> I would have to re-compile SQLite)

{% github patarapolw/liteorm %}
how to pass image file from database to html in django project

Tags: django, python, html, webdev
Published: 2020-02-16 09:19:00

#Django_3.0

I tried many solution to solve it. But I can't fix and resolve. I can't able to pass the image file of my users to my html page. But I can able to access and pass all elements from database of a specific user. When I try to access the Image file of a user, it just returns a file path of the image. Please help me to resolve it.


https://stackoverflow.com/q/60246881/11665780

This is the link where I Posted my issue. Please anyone help me to fix it
Docker Part 1 : A brief theoretical overview
Tags: docker
Published: 2020-02-16 09:16:55


Although I am using Docker for a while now, the theory always seemed a bit complex to me, so I decided to do the in depth search to understand the theory and put it for me and others in simpler words. Although it wouldn't be as simple as this one line from the Stack Overflow user 'L0j1k' that kinda sums it all up :
> Docker is just a fancy way to run a process.
 
# But first Virtualisation 
Virtualisation in a broad sense means creating a simulated, virtual computing environment. 
There are four virtualisation categories: 
+ *Desktop virtualisation*: where a centralised machine manage individualized desktops,
+ *Network virtualisation*: where a network bandwidth is split into independent channels to be assigned to different device, 
+ *Storage virtualisation*: where a hardware storage information is abstracted to create a logical view of storage to be consumed by devices,
+ *Software virtualisation*: where in a hosting physical environment, we get to create several isolated virtual environments.

# What about Docker ?

Docker is not under any of the above categories. It's a container-based virtualisation (OS-level one ). 
All the containers on the host machine share the same kernel and run on the same OS as the host. Each container is identified by a namespace so the kernel can insure the execution isolation.

# So containers ?

A container ideally runs a single process, it's stateless also so it can be created and destroyed without affecting the application behavior.
Since an application usually use multiple containers, Docker offers a YAML  configuration file, that allow us to build the different containers and put them on the same virtual network. 

# What's an Image then ?

Easily put, a Docker Image is a *read-only* template of instructions to create a docker container. 
It's the equivalent of an *Immutable* VM snapshot.
It's the snapshot of the docker container at a specific point of time that contains all the elements needed to run an application (code, configuration files, librairies,etc.)

See you soon in the practical part about Docker (a link would be added later when the other part is up).
I am a professional JavaScript developer, and I recently performed a refactor of a frontend project. Here's what I got.
Tags: javascript, webdev, tutorial
Published: 2020-02-16 08:03:26

I've been a professional web developer for just over 10 years now. I'm currently the lead web development instructor at [Better Coding Academy](https://codebetter.com.au), and as part of what I do, I post videos on our YouTube channel at [https://www.youtube.com/c/BetterCodingAcademy](https://www.youtube.com/c/BetterCodingAcademy).

_(Subscribe for awesome web development content!)_

In this video, I review a JavaScript accordion, identifying and fixing bugs and code smells alike, and explaining my thought processes along the way. I hope you enjoy!

{% youtube WepkZNzOT_Q %}

Happy coding!
CSS Animations Round Two
Tags: css, animation
Published: 2020-02-16 07:22:31

Hi everyone. Last post I did I started to discuss some easy CSS animations. Well guess what! I'm back with a few more fun ones! 

Shall we begin?

Let's start with **Fade In**

Fade in effects are coded in two steps: 1. you set the initial state and then you set the change. 

{% codepen https://codepen.io/jharrel/pen/JjdXEyN %}

The next one we'll look at is **Change Color**

With changing a color with a hover effect, We just need to set the div's class to "color" and specify the color we want. 

{% codepen https://codepen.io/jharrel/pen/poJyRro %}

This will be a fun one. We're going to let it grow! 

To accomplish this, you want to use CSS's transform to enlarge it. You'll want to add 

```
-webkit-transform: scale(number);
-ms-transform: scale(number);
transform: scale(number);
```

{% codepen https://codepen.io/jharrel/pen/oNXxBeG %}

The final one I'm going to cover in this is changing the block to another shape...So square to circle!

Really, this one is simpler than you may think. You mainly just want to change the objects border-radius. So in this example we'd use:

```
.circle:hover
{
   border-radius: 50%; // Or whatever you'd like to change the percentage.
}
```

{% codepen https://codepen.io/jharrel/pen/vYOGgJR %}

That is all for this one. I hope you all enjoyed learning some easy animation effects that you could use on your sites.
Ads or Donations - what you prefer to gain money with your site?
Tags: discuss, money, web
Published: 2020-02-16 06:39:18

After you get, say, your first steady 1000 daily pageviews with your web-site, you become curious - is there a way to make some profit from it?

At least to return money paid for hosting, domain name etc.

If you have some experience in this - please share! If not - welcome to read about mine :)

![Survey about Ads](https://dev-to-uploads.s3.amazonaws.com/i/n8iqoyvs1wkqslsgdguv.png)

_results of survey about ads - people either hate them or block them_

---

## Approach tried - Ads from Google

So I started thinking about [CodeAbbey](https://www.codeabbey.com) - my hobby web-site with coding exercises - after about a year and half after its start.

I read about **Google Adsense** and after some efforts added small ad banner to top-right corner, shown on most of pages. I just didn't want to annoy my users with something larger. However even with this I found that:

- only about half pageviews load ads - obviously many people use ad-blockers!
- my users are of specific category - mostly techies and many of them studying - who don't pay much attention to ads at all
- some ads are quite inappropriate, silly or embarrassing, especially on mobile (so I switched them off on mobile);
- in total, return is small - in best times it generated about 10-15 bucks per month (with hosting currently about 13 per month);
- during last one or two years ads have become even more silly and their revenue dropped to about 7-8 per month.

That's just ain't no good! Of course Google Adsense proposes "to improve your revenue" by putting large (half-screen) ads on pages, but I feel it will look like "damned boolsheet" for our users. And we value our users more than few bucks, right? :)

---

## Considering Donations

So currently I'm thinking about turning off ads at all and switching to donations. I previously had few occasional transfers from some kind people - notably one fellow affectionately sent me $100 after he have impressed his opponent while being interviewed for some developer job - by showing his profile at my site and explaining solution of some advanced tasks.

I've tried survey about people's feeling and it seems to be favorable:

![donations survey](https://dev-to-uploads.s3.amazonaws.com/i/8b439jglys4w5oseoldk.png)

However there seem to be several things to care about yet:

- seemingly I need "business"-type account at paypal - correct me if I'm wrong
- and as I'm going to send some small gifts (mugs, t-shirts) in case of too generous donations - it is important to get notified timely - and arrange some way of asking people for their postal address
- and obviously it is important to come up with some design for any gift postcards, mugs or t-shirts - and find out where to produce them and how to pack them.
- last but not least, I'm sure I'll need to figure out how to properly pay taxes according to our local laws (taxes from normal salary in our country are deducted automatically and we never need to care of this).

**So I'm still working to this switch. If you have any advice - please share!**
CSS Responsive Footer Using Pug
Tags: todayilearned, todayisearched, html, pug
Published: 2020-02-16 05:54:25

Footer important on any website to show important links and a small bio about a website. So here we design a simple footer using css3 with a pug HTML template engine.

In this template, we used  CSS flexbox to make columns in one row and also used focus and hover pseudo-classes.  For making responsive we used media queries and also used flex-wrap CSS properties. Previously we created a pug login form using the pug and we design this simple element in pug. So you can use this element in your project and implement yourself. 

 
Make it yours now by using it, downloading it and please share it. we will design more elements for you.

Download Source code:-

https://w3hubs.com/css-responsive-footer-using-pug
Rails Password Validation
Tags: ruby, rails, activerecord, validation
Published: 2020-02-16 05:52:31

---
title: Rails Password Validation
published: true
description: Validate Special Characters, Numbers, Symbols , upper and lower case, and length
tags: Ruby, Rails, ActiveRecord, validation
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/edn4wop8qkal63b69plq.jpeg
---

[Photo Cred: @breadboyshaun](https://unsplash.com/@mikofilm)

FEBRUARY 15, 2020

# Validate Users Model Password

Alright lets re invent the wheel for funsies. Why? because its saturday night and i want something fun to do- before all these people come trash my house.

# Assumptions

- you know how to Ruby on Rails
- you have a user model set up with a password field

# Why?

I wrote this because i wanted to throw individual errors for each requirement they were missing. Thank you stack overflow ! I didn't cite my sources , but check the stack youll find them.

# What we are building:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3trkc711u4i0iomwhmar.png)

# Code

```ruby
class User < ApplicationRecord
  validate :password_lower_case
  validate :password_uppercase
  validate :password_special_char
  validate :password_contains_number

  def password_uppercase
    return if !!password.match(/\p{Upper}/)
    errors.add :password, ' must contain at least 1 uppercase '
  end

  def password_lower_case
    return if !!password.match(/\p{Lower}/)
    errors.add :password, ' must contain at least 1 lowercase '
  end

  def password_special_char
    special = "?<>',?[]}{=-)(*&^%$#`~{}!"
    regex = /[#{special.gsub(/./){|char| "\\#{char}"}}]/
    return if password =~ regex
    errors.add :password, ' must contain special character'
  end

  def password_contains_number
    return if password.count("0-9") > 0
    errors.add :password, ' must contain at least one number'
  end
end

```

We use `errors.add` to add message to the error messages on attribute. More than one error can be added to the same attribute. If no message is supplied, :invalid is assumed. [ruby docs](https://apidock.com/rails/v3.2.8/ActiveModel/Errors/add)

Notice we have some sick regular expressions i got off stack overflow

in each of these validations, we return if the field matches the requirements, if it doesn't we use `errors.add` to bubble up some sick errors.

This shit is so open source, please use as you will my friends!

happy coding!
javascript get month 2 digit
Tags: javascript, jquery
Published: 2020-02-16 04:46:39

if you are searching like javascript get month 2 digit from given date or current date. So this tutorial will help you find the month two digit from the given date or current date.


How do I get Month and Date of JavaScript in 2 digit format

<!-- wp:paragraph -->
<p>Now we take an example for getting month in 2 digits javascript is:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">&lt;!DOCTYPE html>
&lt;html lang="en">
&lt;head>
&lt;meta charset="utf-8">
&lt;title>javascript get month 2 digits&lt;/title>
&lt;/head>
&lt;body>
  &lt;script type = "text/javascript">
    function month2digits(month)
    { 
        return (month &lt; 10 ? '0' : '') + month;
    }

    var date = new Date(); // date object
    var month2digits = month2digits(date.getMonth()+1); // get month in two digits
    document.write( "javascript get month in 2 digits :- " + month2digits ); 

  &lt;/script>  
&lt;/body>
&lt;/html>
</pre>
<!-- /wp:syntaxhighlighter/code -->

You can found more like javascript get month 2 digit, javascript get year 2, 4 digit ==> https://www.tutsmake.com/javascript-get-month-2-digits-example/
TIL: Some New Console Logging Tricks for Debugging
Tags: todayilearned, webdev, javascript
Published: 2020-02-16 04:20:19

On Friday 2/15/2020 I had an awesome time hosting a Live Stream talking about *Debugging Strategies in JavaScript and Ruby On Rails*. You can catch the first part [Here On Twitch](https://www.twitch.tv/videos/552028180) and on the Zeal YouTube channel.

{% youtube EGjErCdpZEU %}

I wanted to share a couple of new neat things I learned from my co-workers Nate & Matti when doing good old `console.log` style debugging. 

## TIL #1 Using object literals when console logging variables

Normally when debugging and looking to print out values for a request to console I would do something like this
```javascript
let response = await fetch(`https://foaas.com/bag/${thing}`);
console.log(thing, response)
```
The output might end up looking something like this:
```javascript
// Log Outout
cookies 
Response { type: "cors", url: "https://foaas.com/bag/cookies", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }
```
This is fine and all but its not very structured and if you're like me you can forget the order of the values you are logging so you might do something like this:
```javascript
console.log('thing', thing)
console.log('response', response)
```
But not anymore! I have learned you can just as easily do this:
```javascript
console.log({thing, response})
```
Then you can get much more structured logging kinda like this:
```javascript
Object { thing: "cookies", response: Response }
```
So simple so clean.

## TIL #2 Using console.table to print out arrays of data

Now plenty of times I come across a scenario where I want to log arrays of data.
```javascript
console.log(thingsThatAreAwesome)
```
Then when I inspect what was logged it's going to look something like this:
![Image of using console log to print out an array of data](https://dev-to-uploads.s3.amazonaws.com/i/ak50mrh4er52ryopstie.png)

But no longer do I have to look at arrays of data in such a barbaric way! Using `console.table` will give me the structure I need:
```javascript
console.table(thingsThatAreAwesome)
```
Prints out a beautiful table of information:
![Image of a table of data after using the console table to display an array of data](https://dev-to-uploads.s3.amazonaws.com/i/rltu9xlams1jvc6xz14r.png)

I hope these two TIL will help you in your next debugging adventure!
Ask app founders from the Blockstack community anything!
Tags: ama, dapp, blockchain, cantbeevil
Published: 2020-02-16 04:17:11

---
title: Ask app founders from the Blockstack community anything!
published: true
description: Blockstack X Dapp.com monthly AMA 
tags: ama, dapp, blockchain, cantbeevil
---
Hello buidlers, we will be hosting our monthly AMA with app founders from the Blockstack community next Tuesday!
 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zpwgmq6hzzg918mk75xh.jpg)

This time, we are very excited to have <b>Jessica of Dcasso</b> and <b>Colin and Álvaro from Reclaim</b> join Dapp.com Dev Community AMA to answer all the questions from the community in the zoom call! 
 
Ever wondered how the teams decided to start building dapps on top of Blockstack? What it feels like to be a Can't Be Evil advocate? How do they deal with data privacy and the real business world? What are their upcoming projects? Mark your calendar because this is your time to get all those questions answered.

More details > https://www.dapp.com/article/dapp-com-dev-community-ama-guests-dcasso-reclaim

Join us!
Goodbye tmp 👋
Tags: javascript
Published: 2020-02-16 03:18:56

We used **tmp** a lot in JavaScript.
For example, like this ...

```js
let a = [0, 1];
const tmp = a[1];
a[0] = a[1];
a[1] = tmp;
console.log(a); // 1, 0
```

If you don't like this style, what about the following?

```js
let a = [0, 1];
[a[1], a[0]] = [a[0], a[1]];
console.log(a); // 1, 0
```

😉
Want help getting hired?
Tags: discuss, watercooler
Published: 2020-02-16 02:17:38

---
title: Want help getting hired?
published: true
tags: [discuss, watercooler]
---

Hey Dev!

I've been around this industry for a while now and helped a lot of devs figure out what their next steps are for their careers and job searches. I'd like to be available to you all as well.

I was thinking something like I could go on twitch one night and do an AMA for anything related to your career and especially about getting that next job.

Let me know what you think!
Mengapa manusia kerja?
Tags: work, life
Published: 2020-02-16 01:47:04

---
title: Mengapa manusia kerja?
published: true
description: Inilah mengapa kita harus kerja
tags: work, life
series: Life
---

Kita bekerja tentu saja untuk memberi kebaikan di dunia ini. Kok bisa? Coba tonton dulu video di bawah ini:

{% youtube 0JKIIeuzivQ %}

Dari video itu dijelaskan bahwa manusia pada umumnya nggak mau kerja. Capek. Tapi, kalau kita nggak kerja, kita akan susah mencari layanan untuk memenuhi kehidupan sehari-hari.