teleren/devto huggingface dataset:
10 Laravel 7 Eloquent Tricks
Published: 2020-07-18 11:29:15

Laravel Eloquent ORM provides a whole lot of useful functionality which allows you to work with your database tables and relationships using an eloquent expressive syntax.

So, In here are some of the features which you might often reach out for ease of use and cleaner code in your laravel project.

## Finding first record or records

Here’s an example of finding a post with id.
```
// Instead of this
$post = Post::find($id);

if(!$post) {
   abort(404);
}

// Do this
$post = Post::findOrFail($id);
```
Or, you can even find multiple records at once by passing array of ids as second argument.
```
$posts = Post::find([1,2,3]);
```
Even specify id with the fields to select as the second argument.
```
$post = Post::find(1, ['title', 'description']);
$post = Post::findOrFail(1, ['title', 'description']);
```

## Model booted() method

In this method, you can specify what to do on different model events such as creating, updating, deleting etc by passing a closure function.
```
class User extends Model
{
    public static function booted()
    {
        static::creating(function ($user) {
            // delete comments
            // delete images
        });

        static::updating(function ($post) {
            // update comments
            // update images
        });
    }
}
```

## Change default model properties

These are only few of the default properties of an eloquent model you often would reach out. You can change the values according to your needs.
```
class Post extends Model
{
    // The table associated with the model.
    protected $table = 'posts';

    // fields that can be filled using mass assignment Post::create()
    protected $fillables = ['title' , 'description'];

    // Eager load relations everytime you fetch posts
    protected $with = ['comments'];

    // appends accessors to the model's array form.
    protected $appends = ['formatted_date', 'short_title'];

    // The primary key associated with the table.
    protected $primaryKey = 'post_id';

    // Indicates if the IDs are auto-incrementing.
    public $incrementing = false;

    // Indicates if the model should be timestamped.
    public $timestamps = false;

    // The storage format of the model's date columns.
    protected $dateFormat = 'U';

    // change the names of the columns used to store the timestamps
    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'last_update';
}
```

## Counting Related Models

you can retrieve the number of results from a relationship without actually loading them you may use the withCount method.

Define a relation comments():
```
public function comments() 
{
    return $this->hasMany(Comment::class);
}
```
Then, you can use like this:
```
$posts = Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;
}
```
If you find this useful, you can continue on https://laravelproject.com/10-laravel-7-eloquent-tricks/
A simple technique to promisify Chrome extension API
Tags: chrome, extensions, promise, beginners
Published: 2020-07-18 11:23:40

_Update:_
Now you can use `toPromise` from [crx-esm](https://github.com/hankchiutw/crx-esm#topromise)!

---


One of my pain when developing a Chrome extension is looking at the [callback-based APIs](https://developer.chrome.com/extensions/devguide). There are some polyfill promisified all the APIs. (e.g. [webextension-polyfill](https://github.com/mozilla/webextension-polyfill#using-the-promise-based-apis))

If you just want some light-weight solution, here you are.

The simple trick is to take advantage of the truth that the callback function is always the last argument, and you can create a simple helper function to promisify the chrome API:
```js
function toPromise(api) {
  return (...args) => {
    return new Promise((resolve) => {
      api(...args, resolve);
    });
  };
}
```
and use it like:
```js
toPromise(chrome.tabs.query)({}).then(...);
```
This just works for me most of the time.
How to add cloud layers to vts-browser-js 3D map?
Tags: gis, webgl, webdev, 3dglobe
Published: 2020-07-18 11:11:41

I want to add 3D clouds to an existing 3D map based on the [vts-browser-js](https://github.com/melowntech/vts-browser-js/) library to simulate weather conditions. I've added 3D 'obj' models to the map using the API. Also it has a built-in [skydome](https://github.com/melowntech/vts-browser-js/blob/0d3499025d888b1dea48430296cdefa6d5830276/src/core/renderer/geometry.js#L140) to show the air around the earth. I wonder is there a way to add 3d clouds to the map?
Any help would be appreciated
S2SL is back! But we need your help!
Published: 2020-07-18 11:09:36

Its been a long and hard year for us  all during  the COVID-19 pandemic, and that is why we are asking for your help!

We urge you to donate to charities on the scripting to save lives website, and code through github pull requests. But we need more support to help more people!

if at all possible, consider spreading the word across the coding community or your local area. Consider contacting people to put up advertisments or anything to ramp up support!

your support and feedback drives us on every day, keep on coding!

17lwinn - editor developer

-----------

<small>Scripting To Save Lives is a non for profit organisation made up of teenagers and developers wanting to make a change</small >
How to Build Reusable HTML Components Without Component-Based Frameworks
Tags: html, javascript, webdev, codepen
Published: 2020-07-18 11:07:43

Reusable components are common in component-based frameworks like React & Vue.

But what if we want to build components in pure HTML to keep it simple?

In this article I  showed how to build reusable HTML components without the frameworks.

Kindly read,comment and share.

https://www.freecodecamp.org/news/how-to-build-reusable-html-components-without-component-based-frameworks/
Comtonlizer
Tags: showdev, webdev, javascript
Published: 2020-07-18 11:05:16

Hello Everyone,

This is about the new project that I have been working on which is still in beta and I thought of sharing this with the community to get the valuable feedback and improve it.

When a content creator uploads a video to YouTube, he/she usually goes through the comments section to get an idea of how people are reacting to their video. It's obvious that we can get info from the like or dislike button, but they can't really get to know about the viewer's emotions unless we skim through the comments section.

Sometimes we don't really want to read all the comments either because we have a lot of work and no time or it's just we need something to analyze it. While I was looking at a video, I really want to know how other viewers have expressed their emotions for one particular video. That's how Comtonlizer has born.

Comtonlizer = Comment + Tone + Analyzer.

I have used YouTube's API to get the comment for a particular video and using those comments as an input to IBM Watson's tone analyzer API to get the tone score and the tone score is used to display the results.

I have hosted the application in netlify for which I've given the link at the end.

Here is the landing page of the application.

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

The input should be a valid YouTube URL and only when it's valid, the user is allowed to click the analyze button. The output of the popup screenshot is attached below.

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

Here we can see that the output is expressed in terms of emoji and percentage.

1. 😍 - Represents Joy percentage of comments. How much the user has enjoyed the video based on the comment given is analyzed here.

2. 🙄 - Represents the ok-ish percentage of comments. This means that the comments are neither good nor bad but in a neutral zone.

3. 😭 - Represents the sadness in the viewer's opinion. How sad they are based on the comment given by the viewers is represented in this emoji.

For now, I am analyzing only recent comments with a limited count since for a particular video there might be thousands and thousands of comments. So this application can be used to analyze the video with recent comments. I have plans to update this in the future to an extension where we can get the analysis on the same page without going to another page.

Link to the application: https://comtonlizer.netlify.app/

Please access the site using laptop or system. Even though it's accessible on mobile, the best experience is with a laptop or system.

If you have any suggestions or feedback to improve the application, please do let me know in the comments.
Spring Boot and Graceful Service Shutdown
Tags: spring, springboot, shutdown, exit
Published: 2020-07-18 10:24:20

Imagine your service running in Kubernetes, having the time of its life, and then suddenly you push a new version through the pipeline. Before starting the new version, Kubernetes needs to stop the old one. It first asks your service nicely to exit (SIGTERM), if your service doesn't respond to that it will be violently killed (SIGKILL) after several seconds. So if you want to close various resources correctly and exit gracefully, there are some steps you must take.

Below is an example of a generic skeleton for a Spring Boot Service that wants to handle shutdowns gracefully.

The main idea:
- Start a separate thread with main application logic
- Wait for application closing event (called upon SIGTERM)
- Interrupt the main application logic thread and exit
- PROFIT;

**P.S.** Don't forget to ~~eat~~ destroy your Beans, for Beans that implement the AutoClosable interface this is extremely simple:
`@Bean(destroyMethod = "close")`


{% gist https://gist.github.com/trexinc/336d6352aa584307d7742e5af81c734f %}
Which best practices can you afford in a Startup and which you cannot?
Tags: discuss, startup, bestpractices
Published: 2020-07-18 10:24:06

Even though what we understand as _Best Practices_ might vary person to person, team to team and company to company depending on their context, I will assume some of them during this post to create the debate 😊

---

Anyone working in a tech startup, without a huge budget at least, is familiar with some of the next situations:

- "We need this as soon as possible"
- "There's no time for testing, we need to work on this other thing"
- "Why dedicate two weeks to improve X, if we might need to close in next month?"
- etc.

It's true that those situations might be seen as tension between "product management" and "engineering", as an example, where someone wins and another loses.

I like to see them in another way, we are all collaborating to deliver a product to the customers, but we need to make tradeoffs in the different _delivery areas_. There's no I win you lose. We all win or we all lose.

A _Delivery area_ is engineering, UX, Product Design, Marketing, ..., anything needed to deliver the product.

That being said, everyone, in their own area of expertise, has an opinion about what's the best and what's not acceptable. 

Between that spectrum, __there are some best practices that we might consider required and others optional__. But which ones are required that really help in the product success and which didn't really help that much compared to others?

---

From the engineering point of view, I consider the next _Best Practices_ as required:

- __Test-Driven Development__: 

IMHO, the most important practice by far.

- __Continuous Delivery__: A simple Continuous Delivery pipeline really helps in

  - Faster Feedback Loop, the tests break sooner
  - No human factor to deploy the solution to production
  - Team can see the results of their daily work in the development environment
  - Be confident in releasing to production soon and often, being able to push fixes faster and without human factor most of times

![CD](https://dev-to-uploads.s3.amazonaws.com/i/5mwan877sju51bg3g0vp.png)

It at least requires some sort of testing, without testing the feedback loop is longer than it should be.

- __Trunk Based Development__

I consider that be working in one thing at a time, and always working in the trunk branch really helps in smaller iteration cycles.

- __Essential Monitoring__

Have a way to see how your system is behaving in terms of how many 2XX, 4XX and 5XX responses codes there are per day/week helps you react faster in case you broke something, without needing to constantly check the application in case it broke something.

---

And you? Do you consider some other best practices to be more crucial? Which is your opinion about it?

I do agree that it does depend on each case, but I do think there are some that really are required 😁
Use route model binding on Middlewares in Laravel.
Tags: laravel
Published: 2020-07-18 10:12:55

---
title: Use route model binding on Middlewares in Laravel.
published: true
description: How do you handle a route model binding on Middleware.
tags: Laravel
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/2gkj91aqrqtznh945eo7.png
---

# First you need a route:

On web.php

```php
Route::get('/users/{user}', 'UserController@show');
```

Then you have a route as "/users/1" for example, then in you controller:

## Add a show method in your controller

First add a controller of type resource with model User as a flag.

```php
php artisan make:controller UserController --model=User
```

Of course you can just add the controller and then add only the method that you want or even an invokable controller.

## Add the show method logic:

To get advantage of the route model binding you need to inject the model as type hint param in your show method:

```php
public function show(User $user)
{
    return $user;
}
```

In this example it only would return a json format of the model.


## How to use a middleware and get advantage of route model binding:

First we are going to create a middleware:

```php
php artisan make:middleware UserMiddleware
```

Then in your directory "App/Http/Middleware" you can view you r new middleware, there in this example we are going to validate if the user has a specific name, if not it will redirect to another route, the handle method:

```php
public function handle($request, Closure $next)
{
    //$condition = Route::current()
                   //->parameters()->name === 'John Doe';

    //$condition = $request
                   //->route('user')->name === 'John Doe';

    $condition = $request->name === 'John Doe';

    if ($condition) 
    {
         return redirect()
             ->back()
             ->with('status', 'user is not available');
    }
    return $next($request);
}
```

In this case it validates if user is John Doe, there are three different approaches, but all works pretty much the same.

***
JUST REMEMBER THAT ROUTE MODEL BINDING WILL WORK ONLY IF YOU INJECT THE EXPECTED MODEL ON THE METHOD THAT YOU EXPECT.
***

It returns back with a message that the user is not available, then if this is not the case it goes to the next part of the code to go to the controller.

## The route model binding on middleware you can access it by using the request method:

```php
$request->route('user')
```

Just remember the param string in route helper need to match to the url param.


Thanks for reading.
Your own local repository.  
Tags: linux, yum
Published: 2020-07-18 10:00:30

In this post, I will explain how to create your own local repository in Centos 7.

# 1.Attach and mount the iso
```
sudo su - 
mkdir /mnt/cdrom   #create a mount point            
mount /dev/cdrom /mnt/cdrom
df  -h            #verify if mounted 
```
# 2.Copy the Packages from iso
ISO comes with inbuilt packages.These packages must have .rpm extension. So, we copy those inbuilt packages to another directory and make it as a new repository.  
``` 
ls /mnt/cdrom
cp -R  /mnt/cdrom/Packages    /root
```
# 3.Create .repo file in /etc/yum.repos.d directory
Create a configuration file with .repo as extension and add these details into it.
```
vi /etc/yum.repos.d/local.repo
```
Filename - local.repo
```
[localrepo]
name=Prajwal Repository
baseurl=file:///root/Packages
gpgcheck=0
enabled=1
```
In the above file(ie., local.repo),
'name' is the name of the repo,
'baseurl' is the path to the package directory 
'gpgcheck' it takes 0 or 1. It's used for security. Only a user with gpgkey can access this repo if it's set to 1
'enabled' it also take 0 or 1. To activate this repo set it to 1.
#4.Building local repository
*createrepo* is the command to create a repository.
```
yum info createrepo
yum install createrepo
createrepo -v  /root/Packages 
```
#5.Verify if the repository is successfully created.
```
yum repolist all | grep -i prajwal  
```
Cool then!
Three Vim Features
Tags: vim, todayilearned
Published: 2020-07-18 09:56:43

To split a line at pattern:

     :5s/pattern/<c-v><cr>/g

`<c-v>`, or Ctrl-v, in terminal waits for the next character, and inserts it as a literal (verbatim). So upon pressing `<cr>` (carriage return a.k.a enter key), instead of executing the command, the literal carriage return character (would be shown as `^M`) is inserted at the cursor, which is then replaced into the file.

`^M` is the [caret notation](https://en.wikipedia.org/wiki/Caret_notation) of carriage return. Other control characters can be similarly inserted with their corresponding key in the caret notation. For example, cancel is `^Z`, so to insert it type

    <c-v><c-z>

To copy the whole file into clipboard:

    :%y+<cr>

To insert the content of a register, for example, clipboard:

    <c-r>+
Thwaites Conjecture - graphically
Tags: webdev, showdev, codepen, todayilearned
Published: 2020-07-18 09:43:43

What are **conjectures**? 

Wikipedia says _"In mathematics, a conjecture is a conclusion or a proposition which is suspected to be true due to preliminary supporting evidence, but for which no proof or disproof has yet been found"._

So, from one of these conjectures, I came across was the **Thwaites Conjecture**. 
The algorithm proceeds as below:
Think of a positive whole number,
if the number is odd, multiply by 3 and add 1,
if the number is even, just half it. 
Keep repeating this procedure, you'll eventually reach 1. 


{% codepen https://codepen.io/divyajyotiuk/pen/mdVGELx %}

So, to see why this is true, I thought of plotting every step on the graph to see if there is any pattern. You can go ahead and comment your observations. Unfortunately, I couldn't find any pattern but I understood how `canvas` was used. 


I am currently in the process of improving this project. 
The height and width need to be scaled properly to make all the points visible.


Any suggestions are welcome. 


Happy coding!
Have you made such an Application
Tags: php, programming
Published: 2020-07-18 09:40:35

Hello there, I hope you're doing well and are keeping safe.

I'm doing okay as well just occupied with trying to keep on self learning and my internship and I'm back with another question PHP related.

Has any of you ever made a message board kind of application: you have three columns, first column has a list of messages received from different platforms, second column has the area where you can chat with your client then the third column has profile information of the client you're talking to.

It's like a crm software but one you made yourself that fully works and can display messages from different platforms like Facebook, Twitter, gmail and such?
Free Online Photoshop Tool, Photopea
Tags: productivity, image, browser
Published: 2020-07-18 09:34:15

Hello Coders!
This is my first post, because I just started into this amazing social media like 2 weeks ago. Today I bring you a website that I discovered called: Photopea, a simple, free and account-less tool that you can use with only a browser! It has a lots of tools that will help you to do your job (Ex: editing photos, removing background, etc..). Finally, I have to ask that is similar to Photoshop but this is free!
https://www.photopea.com/
Hope you enjoy it!
Some popular Vim distributions
Published: 2020-07-18 09:33:39

# Links

https://vim.spf13.com/ (https://gist.github.com/SantoshSrinivas79/84bc4dc821fd0a453706)
https://github.com/bling/dotvim
https://github.com/carlhuda/janus
https://github.com/astrails/dotvim
https://github.com/vitaly/dotvim2
http://skwp.github.io/dotfiles/
http://vim.liuchengxu.org/ (https://github.com/liuchengxu/space-vim)
https://github.com/amix/vimrc
https://github.com/rust-lang/rust.vim
https://github.com/sheerun/vim-polyglot
http://moelove.info/vim/ (https://github.com/tao12345666333/vim)
https://github.com/wklken/vim-for-server
https://github.com/skywind3000/vim
https://github.com/chxuan/vimplus
https://spacevim.org/
How to verify Mail exchange records(MX) of DNS configuration
Published: 2020-07-18 09:13:25

This is a short note explaining how to verify your MX records configurations are correct or not using 'nslookup'

C:\Users\>nslookup
Default Server:  UnKnown
Address:  2a02:2788:fff0:7::3

> set q=mx
> example.com.
Server:  UnKnown
Address:  2a02:2788:fff0:7::3

Non-authoritative answer:
example.com     MX preference = 0, mail exchanger = (root)

example.com     nameserver = a.iana-servers.net
example.com     nameserver = b.iana-servers.net
a.iana-servers.net      AAAA IPv6 address = 2001:500:8f::53
b.iana-servers.net      AAAA IPv6 address = 2001:500:8d::53
a.iana-servers.net      internet address = 199.43.135.53

hope this helps.
The Github Archive Program is not frozen!
Tags: github, news, archive, code
Published: 2020-07-18 08:43:08

Yesterday, I read a tweet about a developer who had a badge on its Github's profile. Obviously, curiosity kills the cat and I checked my profile and boom! I see this 😮:
![screenshot of my badge on my github'profile](https://res-2.cloudinary.com/hok9n4wen/image/upload/q_auto/v1/ghost-blog-images/badge.jpg)
Then, I remember that I tweeted about the Github Artic Code Vault which is the core of all this project called Github Archive Program.
{% twitter 1245077490529456129%}
 To be short, the mission of the project is:
>>...to preserve open source software for future generations by storing your code in an archive built to last a thousand years...

That's it, a time capsule for the code on Github. A modern and high-tech capsule stored in the Arctic World Archive (AWA), a very-long-term archival facility 250 meters deep in the permafrost of an Arctic mountain. This is located in a decommissioned coal mine in the Svalbard archipelago (spoiler, near from Mr. & Mrs. Klaus) 🎅 🤶

One motivation is to learn from past experiences, specifically speaking I refer to the Library of Alexandria. If you do not know about what happened, I recommended you [a short lesson](https://www.youtube.com/watch?v=jvWncVbXfJ0) (less than 5 minutes) on Youtube made by TED-Ed's.
![artic code vault image of the frozen mountains](https://res-5.cloudinary.com/hok9n4wen/image/upload/q_auto/v1/ghost-blog-images/maxresdefault.jpg)

Github worked on this in conjunction with the Long Now Foundation, the Internet Archive, the Software Heritage  Foundation, Arctic World Archive, Microsoft Research, the Bodleian Library, and Stanford Libraries to ensure the long-term preservation of the world's open source software.

On February 2, 2020, Github took a snapshot of all active public repositories archive in the vault. This is about 21TB of data stored in 186 reels of digital photosensitive archival film 📽️

Is this a big step for humankind? For further information such as the description of the program and an official explanatory video, please go to [The GitHub Archive Program & Arctic Code Vault](https://github.com/github/archive-program) written on... wait for it, on Github 😆

Do you already verify if some of your repositories are in the Github's vault? In fact, if you have active public repositories, and commits between 11/13/2019 and 02/02/2020, and at least 1 star and any commits from the year before the snapshot (02/03/2019 - 02/02/2020), then you have the distinction! If your repository has at least 250 stars is also included.

Well, if you have the badge then enjoy it and share it! Congratulation. Otherwise, don't worry and enjoy this amazing project 👨‍🏫 👩‍🏫

*From a geek to geeks*

---
Originally published at [https://www.ecode.dev](https://www.ecode.dev) on July 18, 2020.