teleren/devto huggingface dataset:
Laravel Moonlight
Tags: laravel, tailwindcss, inertiajs, vue
Published: 2020-04-13 11:48:07

---
title: Laravel Moonlight
published: true
description: Your next API-less SPA application.
tags: laravel, tailwindcss, inertiajs, vuejs
---

![Laravel Moonlight](https://dev-to-uploads.s3.amazonaws.com/i/cbrw6o58f3yul88ixj47.jpg)

[Laravel Moonlight](https://github.com/TitasGailius/laravel-moonlight) is a carefully crafted Laravel preset.

The goal of this preset is to provide an elegant scaffolding for your next single-page application.

---
# Stack

- VueJS
- InertiaJS
- TailwindCSS
- Ziggy (Use named routes from your JS)

---
# Usage

You may generate a basic scaffolding running this artisan command:

```bash
php artisan ui moonlight
```

Laravel Moonlight comes with a full-featured authentication scaffolding. You may include the authentication scaffolding by adding the `--auth` option:

```bash
php artisan ui moonlight --auth
```

Authentication scaffolding comes with these views:
- Login
- Register
- Resend verification email
- Reset password
- Confirm new password (after password reset)
- Confirm password (just like when GitHub asks to confirm your password for certain actions)

---
# Routes

You may use Laravel named routes straight from your Vue components:

```
<a :href="$route('login')">Login</a>
```

The `$route` helper is powered by [Ziggy](https://github.com/tightenco/ziggy).

---
# Authenticated User

Every page has access to the authenticated user through a prop:

```js
export default {
    props: {
        user: Object,
    }
}
```

Alternatively, you may access the authenticated user through a global variable: `$page.user`.

```html
<h1>Hello, {{ $page.user.name }}</h1>
```

---
# Validation Errors

Just like the authenticated user, you may access the validation errors through a prop:

```js
export default {
    props: {
        errors: Object,
    }
}
```

Alternatively, you may access the validation errors through a global variable: `$page.errors`.

```html
<span class="form-error">{{ $page.errors.email[0] }}</span>
```
---

---
# Screenshots

Lastly, here are a few screenshots with the views that are included with this preset. You may find more on the GitHub repo.


![GitHub Logo](https://raw.githubusercontent.com/TitasGailius/laravel-moonlight/master/screenshots/signup.png)

---

![GitHub Logo](https://raw.githubusercontent.com/TitasGailius/laravel-moonlight/master/screenshots/email.png)

---

![GitHub Logo](https://raw.githubusercontent.com/TitasGailius/laravel-moonlight/master/screenshots/confirm.png)

---

Feel free to check out full documentation at https://github.com/TitasGailius/laravel-moonlight

Feedback is more than welcome!
Flowify - an app to optimize flow state
Tags: productivity
Published: 2020-04-13 11:45:41

My first Android app is now live in the play store :tada: :tada: :tada: : https://play.google.com/store/apps/details?id=me.flowify.flowify

Flowify is a productivity app that leverages the timeboxing technique to maximize focus and flow state while working. The app features a work session planner to create work and break time blocks. There is a built-in automatic task generator that uses a customizable pattern to generate work and break time blocks; this feature can be used to generate pomodoros for example.

The app features a count-down timer to track the time spent and remaining on each task (or break); it is possible to add more time to the current task while working. The app triggers a notification (sound and/or vibration) when the allocated time has elapsed.

Flowify also features a subtle background beep that sounds every two minutes (this interval can be customized). The beep breaks an otherwise unnoticed mental distraction and triggers to refocus on the work. The beeps can as well be used to gamify work by mentally setting nano-objectives to reach before the next beep; thus transforming the work session into a beat-the-clock game that maximizes engagement and focus.

Other features offered:
- Time tracking: the app tracks and stores the time spent on each task
- Voice alerts: the app announces the work to do and the allocated time when a task starts; it also notifies when one minute is left and when the time is over;
- Displays a widget in the notifications and lock-screen with controls to pause and start the timer, add more time to the current task and move between tasks;
- Displays in real-time statistics about the current work session

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

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

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

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

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

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

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

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

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/79s7y4bl50umkip37y5f.png)
No Optional Chaining? No Problem. Write Your Own deepGet Function!
Tags: javascript, webdev, tutorial, programming
Published: 2020-04-13 11:37:51

---
title: No Optional Chaining? No Problem. Write Your Own deepGet Function!
published: true
description: Optional chaining is great, but a lot of us don't have support for it yet. Today we'll quickly write our own deepGet function.
tags: javascript, webdev, tutorial, programming
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/50e41couy38c2mz19qhs.png
---

Optional chaining is great: it allows us to safely access object properties without worrying if they exist:

```javascript
const user: {
  name: "Bob"
}
const val = user?.pet?.name;
```

Rather than crashing if `pet` doesn't exist on `user`, it'll simply return `undefined`.

While this is promising, optional chaining is in [stage 4](https://tc39.es/proposal-optional-chaining/#sec-scope) of proposal for the ECMAScript standard, and is therefore not guaranteed to be available unless specifically accommodated in a transpiler you're using. 

# Rolling Your Own

The good news is we can fairly easily roll our own optional chaining-like function! Let's call it `deepGet`:

```javascript
function deepGet(obj, ...props) {
  try {
    return props.reduce((acc, el) => acc[el], obj);
  } catch (e) {
    return undefined;
  }
}
```

We can see that we try to iterate over all `props` in our `reduce` function. If an error is ever thrown, we just return `undefined`! Let's see it in action:

```javascript
const obj = {
  user: {
    name: "Joe",
    age: 20,
    pets: [
      {
        name: "Daffodil",
        type: "dog",
        toys: [
          {
            name: "Toughy",
            price: 1999
          }
        ]
      }
    ]
  }
};

function deepGet(obj, ...props) {
  try {
    return props.reduce((acc, el) => acc[el], obj);
  } catch (e) {
    return undefined;
  }
}

console.log(deepGet(obj, "user", "pets", 0, "toys", 0, "price"));
// 1999
console.log(deepGet(obj, "user", "dogs", 0, "toys", 0, "price"));
// undefined
```

And there you have it, your own safe `deepGet` function!
I built an Overly Complex Random Number Generator with Docker Compose!
Tags: devops, showdev, beginners, tutorial
Published: 2020-04-13 11:16:02

This is an Overly Complex Random Number Generator, created to demystify how containers work. 

## Demo

1. User sets a Random Seed
2. Clicks Generate a Random Number
3. Random Number is generated

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/04han5p98tsc2oji8irv.gif)

{% github CT83/The-Overly-Complicated-Random-Number-Generator %}


### Prerequisites

* You have an understanding of Docker and Docker Compose
* You have heard about Python, React and Redis

### Aim 

* To illustrate how containerization actually looks in the wild
* We will be skipping how the actual Python, JavaScript Apps work, as we want to focus on containerization here, you can find all of the code on [Github - CT83/The-Complicated-Simple-Container-App](https://github.com/CT83/The-Overly-Complicated-Random-Number-Generator)



## Architecture

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

1. Nginx Proxy - Exposed on port 80, Manages networking
2. React Dev Server - Accepts Input, Supports Live Reloading, Replaced with Nginx in Production
3. Flask Server - Serves the API
4. Redis Cache - To maintain the Task Queue
5. Python Worker - Uses specified Seed to Generate Random Number, stores it in DB
6. Database - PostGreSQL DB to store generated random numbers

## Working

1. React App is served, user inputs the random seed.
2. Seed is sent to the Flask API through a POST
3. Task is added to Queue
4. Worker picks up the task, generates a random number and store result in the database
5. Result is returned to the user.

## Configuration

Here, is the minified [docker-compose-prod.yml](https://github.com/CT83/The-Complicated-Simple-Container-App/blob/master/docker-compose-prod.yml)

```yaml
version: "3.3"

services:
  proxy:
    container_name: proxy
    build: 
      ...
    ports:
      - 80:80

  database:
    container_name: database
    build: database/.
    volumes:
      - ./database/db_data:/var/lib/postgresql
    ...

  client:
    container_name: client
    build: 
      ...
    environment:
      ...

  api:
    container_name: api
    build: 
    ...
    volumes:
      - ./api:/app

  worker:
    container_name: worker
    build:
    ...

  redis:
    container_name: redis
    build: 
    ...
```

You can find the development [docker-compose.yml here](https://github.com/CT83/The-Complicated-Simple-Container-App/blob/master/docker-compose.yml). It even supports Live Reloading for both, the Flask and React Container!

## Next Steps

You could now move on to trying to push the built images to DockerHub, or add TravisCI integration!

## Inspirations

[Stephen Grider](https://twitter.com/ste_grider) in his Udemy Course [Docker and Kubernetes: The Complete Guide](https://www.udemy.com/course/docker-and-kubernetes-the-complete-guide/) built an overly complex simple app, that greatly inspired me.
Patrones de diseño en #javascript - ¿Qué son?
Tags: javascript, webdev, designpatterns, patronesdediseño
Published: 2020-04-13 11:10:47

Los patrones de diseño o design patterns son soluciones de estructura creados para facilitar la escritura de código.
Digamos con palabras claras, son utilizados para que el código mantenga una misma estructura y sea más legible.

### Categorías

|De|Descripción|
|----|:----------|
|Creación de Objetos| Se usa para definir la manera de crear objetos|
|Estructura| Definen cómo se componen y relacionan los objetos entre sí|
|Comportamiento| Definen la comunicación entre objetos|
|Arquitectura| Definen la funcionalidad sobre la arquitectura de la creación de carpetas, nombres y qué funcionalidad tiene cada archivo|

En cada categoría existen varios tipos pero voy a explicar los más importantes en diferentes posts.

#### Creación de objetos

1. [Module](https://dev.to/3rchuss/patrones-de-diseno-en-javascript-module-12ji)
2. [Factory](https://dev.to/3rchuss/patrones-de-diseno-javascript-factory-2k0l)
3. [Singleton](https://dev.to/3rchuss/patrones-de-diseno-en-javascript-singleton-81g)

#### Comportamiento

1. [Observer](https://dev.to) ***en construcción***
2. [Mediator](https://dev.to) ***en construcción***


Los patrones de diseño son muy importantes y son preguntas clave en entrevistas personales.
Google Authentication
Tags: rails, javascript, softwaredevelopment
Published: 2020-05-03 18:01:43

---
title: Google Authentication
published: true
date: 2020-04-13 00:00:00 UTC
tags: ruby-on-rails,javascript,software-development,rails
canonical_url: 
---

[OmniAuth](https://github.com/omniauth/omniauth) is a gem for Rails that lets you use multiple authentication providers alongside the more traditional username/password setup. It supports many authentication providers: Facebook, LinkedIn, GitHub full list can be found [here](https://github.com/omniauth/omniauth/wiki/List-of-Strategies).

![](https://cdn-images-1.medium.com/max/522/0*lPXw7ElhqD2B99sI.png)

### Here’s how OmniAuth works from the user’s standpoint:

1. User tries to access a page on **yoursite** that requires them to be logged in. They are redirected to the login screen.
2. The login screen offers the options of creating an account or logging in with Google.
3. The user clicks Log in with Google. This momentarily sends the user to **yoursite.com/auth/google** , which quickly redirects to the Google sign-in page.
4. If the user is not already signed in to Google, they sign in normally. More likely, they are already signed in, so Google simply asks if it’s okay to let yoursite.com access the user’s information. The user agrees.
5. They are (hopefully quickly) redirected to **yoursite.com/auth/google/callback** and, from there, to the page they initially tried to access.

### Installation

Add to your Gemfile:

Then bundle instal

Go to [https://console.developers.google.com](https://console.developers.google.com) and login with your google account. Click on select a project

Click on Credentials and click on the “OAuth consent screen” tab to set up You require the client ID and client secret for your rails app

### Middleware

Add the middleware to the project in config/initializers/omniauth.rb.

You can now visit the url:/auth/google\_oauth2 to assess the google authentication.

### Routes

Routes for Google authentication, expect callback from server

get '/auth/:provider/callback' => 'sessions#omniauth'

### Controller

Uid ensures its unique instance that we haven’t had before.

### Migration

In the migration add:

![](https://cdn-images-1.medium.com/max/640/0*66ArzU9m-a7gDmf3.jpg)

Connect with Me on [Twitter](https://twitter.com/LloydPile) or [LinkedIn](https://www.linkedin.com/in/ivana-dokic-b96460120/)

_Originally published at_ [_https://ivanadokic.github.io_](https://ivanadokic.github.io/google_authentication) _on April 13, 2020._
How to Leverage the Quarantine time as a Software Tester?
Tags: testing, beginners, productivity, tutorial
Published: 2020-04-13 11:10:05


[![How to Leverage the Quarantine time as a Software Tester](https://i.imgur.com/FE4gwrw.png)](http://www.youtube.com/watch?v=FAfR2xYD6EA "How to Leverage the Quarantine time as a Software Tester")


Download Mindmap : https://bit.ly/3edzej4

--
Be sure to subscribe for more videos like this!

[![ TheTestingAcademy](https://dev-to-uploads.s3.amazonaws.com/i/r7vcy6wbvyjbk1y1uu0o.png
)](https://www.youtube.com/TheTestingAcademy?sub_confirmation=1 "TheTestingAcademy")
Patrones de diseño en #javascript - Module
Tags: javascript, design, designpatterns
Published: 2020-04-13 11:10:02

Es una forma de crear variables públicas y privadas en tus objetos. Es la encapsulación de código.

Veamos un ejemplo.

```javascript
const comprarTicket = ( () => {
     // privado
     let evento = 'Conferencia Js 2020';
     const getTicket = () => {
          const elemento = document.createElement('p');
          console.log(`Ticket comprado para ${evento}`);
     }
     // público
     return {
          mostrarTicket: () => {
               getTicket();
          }
     }
})();

comprarTicket.mostrarTicket();

// Ticket comprado para Conferencia Js 2020
```
Que normalmente está asociado con **[IIFE - Expresión de función ejecutada inmediatamente](https://developer.mozilla.org/es/docs/Glossary/IIFE)**

Es muy común su uso y seguramente que ya lo estás utilizando desde hace tiempo.

Este patrón hace que evitemos problemas como la re-declaración de variables con el mismo nombre o bien evita que re-escribas el contenido de tu variable.

El patrón de diseño module no tiene nada que ver con javascript modules, recordemos que los patrones de diseño son la manera más idónea para estructurar tu código.
Learn ML from blogs
Tags: machinelearning, python, blog, code
Published: 2020-04-13 11:09:08

As a person, I prefer blogs over videos every time and I feel there might be many people like me. I am currently learning Machine Learning from various online sources and paid courses, I feel like sharing everything I learn through blogs.

I am starting a Machine Learning course through blogs. It's free of cost. Now comes what I had done in ML, I myself am learning ML right now(you cant completely learn anything in technology or a language), I was among top ten finalists in techgig's ML hackathon(was unable to participate in finals due main semester exams). Now, why should you choose my blogs over any other learning website?
1. It's free of cost.
2. I am trying to cover a vast syllabus. (a little bit of data analytics too)
3. You will get everything in one place i.e maths part of ML, Python prerequisites for ML, and of course ML.
4. I will be writing blogs for making projects too step by step.

The overview of the curriculum for maths and python (Would update with detailed one soon)

1. Python - keywords, variables, data types, operators, loops, data structures(list, tuple, set, dictionary, strings), functions, modules, packages, file handling, exception handling, Numpy, matplotlib

2. Maths - 3d plot, binary search, histogram, distribution, mean, median, vectors, dot product, projection, basic figures, probability, statistics, binomial distribution, variance, creation, K-S test, MNIST data set, PCA. 

I will be posting blogs on dev and my site both. (will put the topic number in every blog to arrange the content). 

My website
http://www.harshitaramchandani.tech/

To get subscribed to notifications of posts send "I want to subscribe" in contact box of the website or comment your email id below.
Container to container communication with bridge network
Tags: bridge, containers, networking, docker
Published: 2020-04-14 02:38:35

---
title: Container to container communication with bridge network
published: true
date: 2020-04-13 11:01:00 UTC
tags: bridge,containers,networking,docker
canonical_url: 
---

In this post, you will learn how to establish container to container communication by creating a Docker bridge network.

![](https://cdn-images-1.medium.com/max/1024/0*2YSlMPy99gm1auAe)<figcaption>source:<a href="https://unsplash.com/photos/SxQn-Or41ok">https://unsplash.com/photos/SxQn-Or41ok</a></figcaption>

### The back story

Currently, I am working on a sample code that includes a frontend (web) and a backend (API). The frontend provides UI to upload an image and passes the image to the backend for external storage. So, I decided to go with to container images as per user requirement.

Built the individual container images

```
docker build . -t <DockerID>/frontend
docker build . -t <DockerID>/backend
```

Time to create containers from the respective images. But, before doing that we need to establish communication between these two containers.

> _The frontend talks to the backend through the backend URL set as an environment variable in the frontend. So, we need to create the backend first and set the frontend env variable with the backend URL._

### The climax

To do that, the option I am aware was using _–link_ flag. But, as I hit the [_documentation_](https://docs.docker.com/network/links/), I could see that the option is now deprecated and tagged as legacy.

Digging through Docker’s documentation, I landed on the [_ne_t_working_](https://docs.docker.com/network/) page. Where on of the options is _bridge network_

> _bridge: The default network driver. If you don’t specify a driver, this is the type of network you are creating._ **_Bridge networks are usually used when your applications run in standalone containers that need to communicate._** _See_ [_bridge networks_](https://docs.docker.com/network/bridge/)_._

> [_https://docs.docker.com/network/_](https://docs.docker.com/network/)

So, here’s how I established the communication between the frontend and backend containers

Create a bridge called _mybridge_:

```
docker network create -d bridge mybridge
```

Run the backend container by adding it to the bridge. Don’t forget to give a _–name_:

```
docker run -p 3001:3001 --name=backend --network=mybridge -d <DockerID>/backend
```

Run the frontend container also by adding it to the bridge:

```
docker run -p 3000:3000 --name=frontend --network=mybridge -d <DockerID>/frontend
```

The env variable on the frontend will be set to [_http://backend:3001/_](http://backend:3001/) and Hola! everything works.

* * *
How to write a Backoff function in Typescript
Tags: typescript, javascript, backoff, network
Published: 2020-04-13 10:53:23

---
title: How to write a Backoff function in Typescript
published: true
description: Implementation of function backoff which will retry to run a function with exponentially increased delay. Useful for network operations.

tags: typescript, javascript, backoff, network
---

Imagine you want to call your backend API (or other network operation) but it fails.

You would like to call it 2 or 3 times more with some delay. Much like how Gmail works when it tries to connect back after losing a connection.

The code below implements an async function that works just like that. 

{% gist https://gist.github.com/svitekpavel/1e198bc9ba977eb56755f405410a848e file=backoff.ts %}

The code should be self-explainable, but feel free to ask in comments if anything is not clear.

The KUDOS for implementation of the original function `backoffOrig()` goes to Saša Savić 
https://www.linkedin.com/feed/update/urn:li:activity:6655380458282594304
Vue 3 Composition API + D3.js
Tags: vue3, compositionapi, d3
Published: 2020-04-13 10:46:21

Recently I created a visualization tool that gives an insight into a particular flow. For this, I used the Composition API in combination with D3.js.

There are three functionalities I took into consideration;
1. Initial drawing
2. Interactivity on the diagram elements
3. Updating the information based on the interactions

## Initial drawing
Within the new composition API, the initialization of the diagram has to be in the setup() method. This is called after the "beforeCreated" hook and before the created hook.

In the setup hook, we use a method called useDiagram. This is where we organize all the feature code. Thanks to the composition API in Vue 3 we now can reuse most of the controllers we write, like the "useDiagram" and end up with a much cleaner code.

// index.vue
```vue
<template>
  <svg ref="diagramEl" />
  <button @click="redrawDiagram">Update Diagram</button>
</template>

<style lang="scss">
  // diagram styles
</style>

<script>
import useDiagram from './useDiagram.js';

export default {
  setup() {
    const { 
      drawDiagram,
      redrawDiagram,
      resizeDiagram
    } = useDiagram({ diagramEl });

    onMounted(()=>{
      window.addEventListener('resize', resizeDiagram);
      drawDiagram();
    });

    onUnmounted(()=>{
      window.removeEventListener('resize', resizeDiagram);
    });

    return {
      drawDiagram,
      redrawDiagram,
      resizeDiagram
    }
  }
}
</script>
```

// useDiagram.js

```js
import { select } from 'd3';
import d3Sankey from './d3-sankey-extention';
import { callbackX } from 'extra-utils';

export default function({ diagramEl }) {
  const element = diagramEl.value;
  const drawDiagram = () => {
    const svg = select(element);
    // ... usual append, attr, and transform methods
    const sankey = d3Sankey();
    // ... usual append sankey links, nodes methods
    // on the links or nodes you can attach event listeners
    // .on('click / mouseenter / ...', d => callbackX)
  };

  const redrawDiagram = () => {
    // update props or the whole diagram based on use-case
  };

  const resizeDiagram = () => {
    // resize the diagram to match viewport props
  };

  return {
    drawDiagram,
    redrawDiagram,
    resizeDiagram
  }
}

```

That's all. Feel free to comment your thoughts or experiences.