teleren/devto huggingface dataset:
Define your own facade in laravel
Tags: php, laravel, facade
Published: 2020-06-17 13:41:14

In this article we want to know how can we define our own facade
and use it in our application 

### In this article I want to make SmartLogger class and try to use it with Facades so lets start

## Create a directory in app and which has SmartLogger name and fill it like below
```
.
├── SmartLoggerFacade.php
└── SmartLogger.php

0 directories, 2 files
```

### SmartLogger.php
```php
<?php

namespace App\SmartLogger;

class SmartLogger {
    public function log($text) {
        $path = storage_path('logs');
        $myfile = fopen("{$path}/SmartLog.txt", "a");
        fwrite($myfile, $text);
        fwrite($myfile, PHP_EOL);
        fclose($myfile);
    }
}
```

### SmartLoggerFacade.php
```php
<?php

namespace App\SmartLogger;
use Illuminate\Support\Facades\Facade;

class SmartLoggerFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'smartlogger';
    }
}
```
  
### lets make service provider
```
php artisan make:provider SmartLoggerServiceProvider
```

### SmartLoggerServiceProvider.php
```php
<?php

namespace App\Providers;

use App\SmartLogger\SmartLogger;
use Illuminate\Support\ServiceProvider;

class SmartLoggerServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('smartlogger',function(){
            return new SmartLogger();
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}
```

### Now open config\app.php and add this lines in it
Add it in "providers" array
```php
...
        App\Providers\SmartLoggerServiceProvider::class
```
Add it in "aliases" array
```php
...
        'Smartlogger'   =>  App\SmartLogger\SmartLoggerFacade::class
```

### Now lets test it :)
Add this code in your controller 
```php
SmartLogger::log("Hi");
```

And add this in top of your controller
```php
use App\SmartLogger\SmartLoggerFacade as SmartLogger; 
```

### Feel free to ask any questions :)
Revealing Module Design Pattern
Tags: javascript, webdev, codenewbie, codequality
Published: 2020-06-17 13:38:09

*Defining all functions and variables in private scope and return an anonymous object with pointers to the private functionality we wished to reveal as public.*

```javascript
var myRevealingModule = (function() {
  var privateVar = "Awais Mughal";
  function privateFunction() {
    console.log('name: ', privateVar);
  }

  function publicGetName() {
    privateFunction();
  }

  return {
    getName: publicGetName
  }
})()

myRevealingModule.getName(); // * name: Awais Mughal

```

### How you can improve the readability in case of multiple functions?

* __*Move the return object to the top, so when you look at the code days after writing, it'll be easy to know the public methods.*__

* __*Focus on Naming conventions*__


### Advantages:

* Syntax of our Script will be more consistent.
* readability
* Accessibility Concerns are handled 

### Disadvantages:

* If a private function refers to the public function, that public function can't be overridden wile using it on other places(calling the public function from another file) if a patch is necessary. __WHY?__ Because you can't manipulate the implementation of private function from outside.

* Public Object members which refer to __private variables__ are also subject to the no-patch rule note above.
Javascript Array methods used in my work
Tags: javascript, tricks
Published: 2020-06-17 13:35:56

---
title: Javascript Array methods used in my work
published: true
description: useful array methods in javascript
tags: Javascript,Tricks
---
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/t15b93lvyanr2d7v1qws.jpg)

Here list some `Javascript` Array methods witch helpful and useful to my work

### some & every

```javascript
let users = [{name: 'foo',age: 18},{name: 'bar',age: 21}]
users.some((user)=>user.age < 20) // true
users.every((user)=>user.age < 20) // false
```

* `some` just return `true` if `users` has one user age < 20
* `every` just return true if all `users` age < 20 



### splice

```javascript
// splice(index[, deleteCount, elem1, ..., elemN])
const fruits = ['apple','pera','grape']
fruits.splice(1,1,'pineapple','watermelon') // ['pera']
// fruits: ['apple','pineapple','watermelon','grape']
```

`splice` method will return modified array elements but will mutation origin array. `fruits` will be `['apple','pineapple','watermelon','grape']`

Args

* `index` which started index you will mutation
* `deleteCount` will declare how many element you will replaced
* `elem1,...eleN` will after `index` poistion



### unshift & push

```javascript
const fruits = ['apple','pera','grape']

fruits.unshift(...['pineapple']) // will return fruits length 4
console.log(fruits) // (4) ["pineapple", "apple", "pera", "grape"]

fruits.push('watermelon')  // will return fruits length 5
console.log(fruits) //(5) ["pineapple", "apple", "pera", "grape", "watermelon"]
```



* `unshfit(...item)` will push item to beginning of array
* `push(item)` will push item to end of array



### forEach

```javascript
["foo", "bar", "zzzzz"].forEach((item, index, array) => {
  console.log(`${item} is at index ${index} in ${array}`);
});
```

Usual we just pass first two args `item`, `index` but `array` used when you need referer  the iterate object here is `["foo", "bar", "zzzzz"]` 



### find & findIndex

```javascript
const fruits = ['apple','pera','grape']

fruits.find((fruit)=> fruit==='apple') // apple
fruits.findIndex((fruit)=> fruit==='grape') // 2

// if not found will return -1
fruits.findIndex((fruit)=> fruit==='notfound') // -1
```

* `find` will return the first matched element in `fruits`
* `findIndex` will return the first matched element index at `fruits` array



### filter

```javascript
const fruits = ['apple','pera','grape']
let results = fruits.filter((fruit) => fruit.length > 4) // (2) ["apple", "grape"]
```

`fileter` will return new array witch iterate callback return `true`



### map

```javascript
let items = ["foo", "bar", "zzz"].map(item => `lol:${item}`);
console.log(items); // (3) ["lol:foo", "lol:bar", "lol:zzz"]
```

We can use `map` transform array element and return new array



Not limited to the above method aslo includes: `reverse`, `reduce`, `concat` ,`slice` ,  `join`



Hope it can help you :)
Daily Challenge #260 - Subtract the Sum
Tags: challenge
Published: 2020-06-17 13:27:42

---
title: Daily Challenge #260 - Subtract the Sum
published: true
series: Daily Challenge
description: Add all digits in N together, then subtract the sum of those digits from the original number. Keep going till it lands on the list!
tags: challenge
//cover_image: https://direct_url_to_image.jpg
---

Complete the function which get an input number n such that n >= 10 and n < 10000, then:

Sum all the digits of n.
Subtract the sum from n, and it is your new n.
If the new n is in the list below return the associated fruit, otherwise return back to task 1.

**Example**
`n = 325`
`sum = 3+2+5 = 10`
`n = 325-10 = 315 (not in the list)`
`sum = 3+1+5 = 9`
`n = 315-9 = 306 (not in the list)`
`sum = 3+0+6 = 9`
`n =306-9 = 297 (not in the list)`
...
. ...until you find the first n in the list below.

Here are all possible values of n:

```
1-kiwi
2-pear
3-kiwi
4-banana
5-melon
6-banana
7-melon
8-pineapple
9-apple
10-pineapple
11-cucumber
12-pineapple
13-cucumber
14-orange
15-grape
16-orange
17-grape
18-apple
19-grape
20-cherry
21-pear
22-cherry
23-pear
24-kiwi
25-banana
26-kiwi
27-apple
28-melon
29-banana
30-melon
31-pineapple
32-melon
33-pineapple
34-cucumber
35-orange
36-apple
37-orange
38-grape
39-orange
40-grape
41-cherry
42-pear
43-cherry
44-pear
45-apple
46-pear
47-kiwi
48-banana
49-kiwi
50-banana
51-melon
52-pineapple
53-melon
54-apple
55-cucumber
56-pineapple
57-cucumber
58-orange
59-cucumber
60-orange
61-grape
62-cherry
63-apple
64-cherry
65-pear
66-cherry
67-pear
68-kiwi
69-pear
70-kiwi
71-banana
72-apple
73-banana
74-melon
75-pineapple
76-melon
77-pineapple
78-cucumber
79-pineapple
80-cucumber
81-apple
82-grape
83-orange
84-grape
85-cherry
86-grape
87-cherry
88-pear
89-cherry
90-apple
91-kiwi
92-banana
93-kiwi
94-banana
95-melon
96-banana
97-melon
98-pineapple
99-apple
100-pineapple
```

**Tests:**
SubtractSum(10)
SubtractSum(1204)

Good luck!

***
_This [challenge](https://www.codewars.com/kata/56c5847f27be2c3db20009c3) comes from aryan-firouzian on CodeWars. 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 idea for a future post?  Email **yo+challenge@dev.to** with your suggestions!_
3 minimal features for my dev.to api wrapper
Tags: projectbenatar, showdev, rstats, functional
Published: 2020-06-17 13:02:10

I’ve made 3 very small features for my [open source R package wrapping
the dev.to API](https://github.com/DaveParr/dev.to.ol).

## `create_new_article`

Now that the main requirements for the file to post are stabilising,
I’ve written a quick and dirty function to make a boilerplate article:

``` r
create_new_article <-
  function(title,
           series = 'series',
           tags = '["tag1", "tag2"]',
           file = "") {
    boilerplate_frontmatter <-
      glue::glue(
        '---\ntitle: "{title}"\noutput: github_document\nseries: "{series}"\ntags: {tags}\n---'
      )

    cat(boilerplate_frontmatter, file = file)
  }
```

This will use the [`glue`](https://glue.tidyverse.org/) package to put
the strings in the function argument into the right place in the
boilerplate YAML front matter. If then uses `cat` to either print that
to screen, or to create a new file with it, if a file path is supplied.

## `main_image`

If there is a `main_image` parameter in the `YAML` front matter that is
a url of an image, that image will be set as the cover image of the
post. I got this one from a photo by [Julian
Dufort](https://unsplash.com/@juliandufort?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
on
[Unsplash](https://unsplash.com/s/photos/3?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText).
I *believe* that if you put an unsplash URL into this field that goes
**directly to the image** it is within their
[license](https://unsplash.com/license), though if anyone knows
something to the contrary please let me know. It’s the first time I have
used this service, despite hearing about it for years.

## Collapse spaces tags

I recently fooled myself for a good ten minutes into thinking that there
was a problem with my API code yesterday when I kept getting a 422
response to putting a new article up, when in fact it was that I had a
space character in one of my tags. Now the `post_new_article` function
collapses any spaces it encounters in tags. Achieving this was a breeze
with [`purrr`](https://purrr.tidyverse.org/) and
[`stringr`](https://stringr.tidyverse.org//):

``` r
purrr::map(file_frontmatter$tags, stringr::str_remove_all, " ")
```

This little nugget takes the list of tags, and then maps the function
`str_remove_all` across all the spaces. This isn’t at all exposed to the
user, as it’s non-negotiable from the API side anyway :)
Using recursion to build a slideshow with React
Tags: react, javascript, functional, frontenddev
Published: 2020-06-17 12:57:49

Ever since dabbling with Elixir, I've taken to working pure functional principles into a lot of my everyday coding. In particular, I really enjoy using recursion - I find it especially useful as a way of managing state, especially in combination with React hooks.

One simple way to illustrate how powerful this can be is this [Slideshow example](https://jsfiddle.net/vbktf9wm/) - a simple component which cycles through a series of slides, infinitely. 

So let's break down some of what's happening in this example, starting with the state management:

```javascript
const initialIndices = slides.map((_, index) => index);
const stepThroughSlides = async ({ remainingIndices }) => {
  setActiveSlideIndex(remainingIndices[0]);

  await sleep(3000);

  return stepThroughSlides({
    remainingIndices:
      remainingIndices.length > 1
        ? remainingIndices.slice(1)
        : initialIndices
  });
};
stepThroughSlides({ remainingIndices: initialIndices });
```

There are a few prerequisites to this:

* We assume a slideshow essentially steps through an array of slides sequentially, by index.
* We assume that the indices for _all_ of the slides are stored in the `initialIndices` array.
* We assume we've used a `useState` hook to hold the index of the _current_ slide (`activeSlideIndex`).
* We assume that the function will receive an array of slides still waiting to be displayed (`remainingIndices`).

Given all of this is true, on invocation our `stepThroughSlides` function will:

1. Update the state to set the first index in the `remainingIndices` array as the active slide index.
2. Sleep for 3 seconds.
3. Call itself again with either:
  - The array of remaining slides indices, minus the one we've just made active.
  - The array of initial slides indices, if we've run out of slides and need to loop back.

With our state changes underway, we just need to update the actual display of our slides:

```javascript
{slides.map((slide, index) => (
  <div
    className={`slide ${activeSlideIndex === index && "active"}`}
  >
    {slide}
  </div>
))}
```

Nice and easy - I just map my slides and, if the `activeSlideIndex` state is equivalent to the index of the slide, I add a CSS class accordingly. Just a few lines of corresponding CSS and we're done:

```css
.slide {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.slide.active {
  opacity: 1;
}
```

I've glossed over some of the React nuance - like using `useEffect` to hook this all up - so it's worth having a proper look at [the full working example on JSFiddle](https://jsfiddle.net/vbktf9wm/). 

----

You might be thinking that I could have just used `setInterval` here - but using recursion:

* Removes the need for cleanup (ie. `clearInterval`).
* Encourages immutability by design - which in turn reduces the risk of bugs and race conditions.
* As a technique, can be used to much greater effect and applied to more demanding use cases.
Road to Genius: smart #19
Published: 2020-06-17 12:25:02

Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.

![coding challenge](https://dev-to-uploads.s3.amazonaws.com/i/9nt5q6bgv9i4yv1mnbnl.png)

Here's a new challenge with quite a lot of code, but only one bug that needs fixing 💧. You can solve this in several ways, the fastest method is by tracking variables, there are only a few potential variables that would fit the bug 💧. Both `LM and RM` are already used, and 💧 is unlikely to be any of these because those are arrays, and 💧 isn't used in an array-like fashion. The variable `max` appears to keep track of the max value, so 💧 isn't likely to be `max`, because `max` is no longer relevant at that stage.

The only remaining variable that's pretty much unused is `V`, it's also the value that the function returns, and since `A = 4`, then `V` cannot be zero; 💧 is very likely to be `V`.

![coding challenge answer](https://dev-to-uploads.s3.amazonaws.com/i/42mwshzhyps6lh9n0wgu.png)

You can take a few minutes to analyze the code closer, to understand what is going on. In a nutshell it's computing the sum of trap heights in a given array. A trap in this code, is identified by a value that's surrounded by two larger values (left and right of itself), as indicated by the arrow on the image below. In pseudo-code: `TRAPi = min(left, right) - height`. In this case there is only one trap, so `A = 4`, it is computed as such: `A= V= min(6, 6) - 2`

![coding challenge extra](https://dev-to-uploads.s3.amazonaws.com/i/u2dx7ewxjwjafsv8fuxd.png)

---

Join me on the Road to Genius and upgrade your programming skills, at https://nevolin.be/codr/
Cloud Native Applications: Creating a Mail Server Environment with Docker
Tags: docker, architecture, agile
Published: 2020-06-17 12:23:09

Here’s a little backstory: I was recently going over the process of converting a standard RPM package to a cloud application with a friend who’s a Software Engineer. He’d already read a lot of what’s out there about containerization and was ready to take the next step, to try to do it himself. 

That’s how we got here, experimenting and going over the basic steps of how to deploy a mail server application into a Docker container, and then into a Kubernetes cluster. We hope us sharing this real-time, intuitive experiment with our community piques your interest, as it did ours. 

We’re going to show you every step, what issues we encountered, and how we solved them.

We want to avoid switching to ‘cloud native’ just because it’s a trendy buzzword. So, as we examine the technology, we also take a look at who can benefit the most from this particular mail server approach.

**TL;DR**

If you’re a veteran Kubernetes user, this article may not add much value to your know-how.

However, the main objective is to bring together the typical steps that a user needs to follow when deploying a Dockerized mail server application to a Kubernetes cluster.

You can think of this article as a reference that you can get back to whenever you need a quick refresher about the most common resources used when deploying mail server applications with Docker and Kubernetes.

Through our discussion, we visit the conversion of the RPM to a Docker image, publishing to Docker Hub, creating and clustering in Google Cloud Platform, and deploying our image.

##The sample application — Axigen Mail Server

For this demonstration, we’re going to be using the Axigen Mail Server as a sample application. Why? I find that, while it’s specific to mail server technology, it shares a lot of modern web application requirements:

* A front end part where user requests are received.
* A backend that stores state.
* A static component that displays a nice user interface and connects to the front end.

This experiment can, therefore, be replicated with other applications as well.

**Note:** Axigen already provides a fully functional, ready-to use Docker image in Docker Hub. You can find all the information and try it out for yourself here.

A Kubernetes Helm chart will also be available very soon. Both are intended for actual production use and are adjusted as such. Stay tuned for more.

*This article is part of a series first published on [the Axigen blog] (https://www.axigen.com/articles/cloud-native-applications-creating-a-mail-server-environment-with-docker_69.html). If you want to see the full process, including converting the RPM to a Docker image, publishing to Docker Hub, creating and clustering in Google Cloud Platform and deploying the image, you can read the full article [here](https://www.axigen.com/articles/cloud-native-applications-mail-server-docker_69.html)*
How to rename your master branch to something else
Tags: webdev, git, github, codenewbie
Published: 2020-06-17 12:20:31

![GitHub Master to Main](https://dev-to-uploads.s3.amazonaws.com/i/25vcbehlghkzbmjpsm85.png)

Well, we all might have heard that GitHub will remove the `master` naming convention for default branch. 

Source: https://www.bbc.com/news/technology-53050955

GitHub's Twitter page posted that it stands with the black community and the fight against racism. 

{% twitter 1269664807977771008 %}

There are many people who might be looking to rename their branch to something more clearer and better.

## First of all let's understand what a master branch is?

In Git, "master" is a naming convention for a branch. After cloning (downloading) a project from a remote server, the resulting local repository has a single local branch: the so-called "master" branch. This means that "master" can be seen as a repository's "default" branch.

## Why we are doing this?

The master-slave relationship in technology usually refers to a system where one - the master - controls other copies, or processes.

The years-old campaign to replace such terms has been given fresh impetus amid the resurgence of Black Lives Matter protests in the United States.

Mr Friedman's announcement came in a Twitter reply to Google Chrome developer Una Kravets, who said she would be happy to rename the "master" branch of the project to "main".

"If it prevents even a single black person from feeling more isolated in the tech community, feels like a no-brainer to me," she wrote. (Excerpt from BBC Report)

## What are potential alternate names for master branch?

Alternate names can be:
- main
- edge
- release
- prod
- production
- live
- default
- head
- primary
- top

## How to rename master branch to some other name?

Let's name our `master` branch to `release`

i. Checkout your `master` branch

`git checkout master`

ii. Create your `release` branch and switch to it

`git branch release`
`git checkout release`

iii. Push that to the server

`git push origin release`

iv. Delete the `master` branch reference on the server

`git push origin :master`

v. Delete the local `master` branch

`git branch -d master`

## Your thoughts!

Let me know what can be a more better name for master branch?

Share your ideas in the comments section so that it's easier for new developers and programming community to decide the alternative or I must say original names for both terminologies.

## Thank you for reading


#🖤 #BlackLivesMatter 🖤
Daily Developer Jokes - Wednesday, Jun 17, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-06-17 12:00:08

---
title: "Daily Developer Jokes - Wednesday, Jun 17, 2020"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Wednesday%2C%20Jun%2017%2C%202020"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1258e0be565.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit.*

<!-- 
Joke text:
___Q:___ How did pirates collaborate before computers ?

___A:___ Pier to pier networking.
 -->
What's the difference?
Tags: gridlayoutsudoselector
Published: 2020-06-17 11:46:21

![+CSS](https://dev-to-uploads.s3.amazonaws.com/i/ym1iihioxg8vcj4lbf48.png)
![after applying css]

Sudo child elements became e@sy to manipulate when putting down on grid-layout parent.

        ## CSS

        ### .parent{display:grid; position:realtive}
        ### .child::before/after{ position:absolute; grid-column/row: x/y;}

Accept apology for inconvenience. It's En first DEV post.

[En Profile](https://enfollowen.netlify.app/)