teleren/devto huggingface dataset:
Flash messages with Hotwire
Tags: rails, hotwire, turbostream, tutorial
Published: 2020-12-30 10:59:54

Last week Basecamp released their NEW MAGIC aka [Hotwire](https://hotwire.dev) and I finally had the time to have a look at it.
The first thing that come to mind was forms and flash messages. There's already a ton of videos showing how to use Turboframes with forms so I don't want to go into too much detail on that topic. But what I would like to show you is how you can add flash messages that pops up like an alert.

A simple form:
![1](https://dev-to-uploads.s3.amazonaws.com/i/shsywmn6lypnkn8e60a9.png)

A simple form with an alert on top when submitted 🎉
![2](https://dev-to-uploads.s3.amazonaws.com/i/7238tseebjukvs1u5fxf.png)
  

The first thing I do is to wrap my flash message partial in a `turbo_frame_tag`. By doing this, we can replace this part of the page on its own later on.

app/views/layouts/application.html
```erb
<%= turbo_frame_tag "flash" do %>
  <%= render "flash" %>
<% end %>
```

app/views/layouts/_flash.html.erb
```erb
<% flash.each do |type, message| %>
  <% if type == "notice" %>
    <%= message %>
  <% end %>
<% end %>
```

I also added a turbo_frame_tag around my form partial
app/views/places/edit.html.erb
```erb
<%= turbo_frame_tag "admin_place_form" do %>
  <%= render 'form', place: @place %>
<% end %>
```

My form is just a regular form partial using a `form_with` helper and a `dom_id` helper. The `dom_id` sets a unique ID that can be replaced.
app/views/places/_form.html.erb
```erb
<%= form_with model: place, id: dom_id(place)  do |form| %>
  <%= form.text_field :name %>
  <%= form.submit %>
<% end %>
```

And now the controller code. There's probably a better way to do this. If you know how, please let me know in the comments. I'm just learning this 😊 But here it is:
app/controllers/place_controller.rb
```ruby
class PlacesController < ApplicationController
  def update
    @place = Place.find(params[:id])
      
    if @place.update(place_params)
      respond_to do |format|
          flash.now[:notice] = "Place was updated!"
          format.turbo_stream { render turbo_stream: turbo_stream.replace("flash", partial: "layouts/flash", locals: { flash: flash }) }
          format.html         { redirect_to edit_admin_place_path(@place.id) }
        end
    else
      render turbo_stream: turbo_stream.replace(@place, partial: "places/form", locals: { place: @place })
    end
  end
end
```
In the code above, in the case that the `update` action is succesful: 
1. Create a flash message to be used in the same request with the message "Place was updated".
2. Use turbo_stream to replace the dom id `flash` with the partial containing the flash message.

In case of an unsuccessful update, eg. validation failed, I simply replace the form partial with some validation errors.

That's it 🎉
🔥 Changing Your Git Repository From Master To Main 🔥
Published: 2020-12-30 11:17:30

---
title: 🔥 Changing Your Git Repository From Master To Main 🔥
published: true
description: 
tags: 
cover_image: https://images.unsplash.com/photo-1556075798-4825dfaaf498?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&dl=yancy-min-842ofHC6MaI-unsplash.jpg
---
It has become imperative for us to remove the master/slave terms from our codes.

I will be showing you how I did that for my local git repository.

Simply get into your project directory from the terminal and run the following command:
```
git branch -m master main
```

For this command to work as expected, make sure you have made some commits on the branch.

And viola! 💥 that is it. You can now push to your remote.
Javascript Games
Tags: game, pac, udemy, javascript
Published: 2020-12-30 11:16:54

Primera incursion con javascript, curso realizado atraves de udemy, nivel inicial, falta seguir agregando mas funciones, detalles al juego pac.
Alguna sugerencia sobre libros game programming javascript?...
 Que tengan un buen fin de año, saludos cordiales!

https://josealz.github.io/html_jsGame/
Cost to develop website like Udemy
Tags: udemy, cloneofudemy, websitedevelopment, wordpress
Published: 2020-12-30 11:08:51

Udemy is a marketplace for e-learning and teaching online. With the help of udemy students can learn and master new skills by learning from a huge library of over 55,000 courses taught by different expert instructors.

So having these much amount of potential market many wants to develop this kind of website. Let me tell you it’s not an easy task to get all features in first phase of website development. One needs to do continuous development and need to add new feature to enrich the user experience.

Here is the least of basic functionality one need, based on each page when he wants to launch a website like Udemy:

Home Page:

This Page will have Logo of the company. (Logo will be provided from client)

The development of page will have below details:

=> 3 full screen banners
=> Top Courses List
=> Big button for browsing different courses
=> Sign up or Registration button
=> Log In Option in Header Part with tutor registration and
sign up for students:
>Student or Trainee Registration: Name, e-mail, Password
>Tutor Registration: Name, e-mail, Password

About Us Page:

In the development process of About Us Page will have details of the company.

This Page will have subpages which are mentioned below:

=> Mission and Vision
=> Team
=> Career
=> Press

Training Page:

Development of training page in which details for training service for any business will be given.

Affiliates Page:

Development of Affiliates page will be done in which details for affiliate program will be given.

Blog Page:

Development of blog page which will have list of different blogs.

Support Page:

Development of support page in which details for support will be given.

Tutor Dashboard:

Tutor Dashboard will have below details which needs to be developed:

=> Course Creation panel in which basic information of course and summary of course will be added
=> Images
=> Promo video
=> Test Video
=> Add Lectures
=> Add Quiz
=> Add Project or Exercise
=> Price and Coupons
=> Manage Instructors
=> Student message
=> Analytics of Student Satisfaction
=> Manage student

Project submitted who applied for certification
Assessments of student who applied for certification
Provide Certificate

Student Dashboard:

Student Dashboard will have below details which needs to be developed:

=> List of registered courses
=> Download attachments or documents
=> Open Discussion
=> Project/Exercise submission
=> Take a quiz
=> Check Assessments
=> Apply for Certificate if tutor provides
=> Account setting

Admin Side Features:

=> Menu Hierarchy Management
=> Banner Management
=> Content Article Management
=> User Management
=> Tutor Management
=> Category Management
=> Courses Management
=> Static Page Management
=> Blog Management
=> Contact Us
=> Payment Management

Vibidsoft has expertise to develop this kind of website in the timeline of 2-3 months. The cost will totally depend on the features you are selecting. So don’t wait if you want to design and develop a clone of Udemy mail us on inquiry@vibidsoft.com.
Image BlueScreen
Published: 2020-12-30 11:03:19

Imagine you started watching a movie and you see protagonist introduction immediately. If you think about special effects in the background, Did they shot everything that you are seeing right now ? or it also includes some post shoot editing work. Before going further, let me remind you video is just a series of still images, In most of the cases 20 to 60 per second.


BlueScreen algorithm is basically combining two or more images to get the desired result for example aligning protagonist with a background. We have to detect the every pixel of our original image, let's say the pixels other than the protagonist in our example. Then, there is a background image you have to embed in the original to acquire the result. You have to consider the same pixel in the background image and copy over that pixel to the original. That's it and you are done.

Imagine Monkey as a protagonist and Apollo 8 as background in the following images.


![Alt text of image](https://live.staticflickr.com/65535/50778794847_46af16c6c9_z.jpg)
![Alt text of image](https://live.staticflickr.com/65535/50777926363_8ef343b633_z.jpg)

Think of eliminating the blue background in the original and embed apollo 8 background to acquire special effect. Here goes the javascript code for bluescreen algorithm ...


*image = new SimpleImage("stop.jpg");*
*back = new SimpleImage("leaves.jpg");*

*for (pixel: image) {*
  *avg = (pixel.getRed() + pixel.getGreen() + pixel.getBlue())/3;*
  *if (pixel.getBlue() > avg * 1.5) {*
    *x = pixel.getX();*
    *y = pixel.getY();*
    *pixel2 = back.getPixel(x, y);*
   *pixel.setRed(pixel2.getRed());*
    *pixel.setGreen(pixel2.getGreen());*
    *pixel.setBlue(pixel2.getBlue());*
 *}*
*}*
*print(image);*

Ok, let me explain ,

For every pixel in image we have to detect the blue portions , the average of all the three works better because the brown colour on monkey also includes a small(x) portion of blue then it also changes it's pixel's colour if we do if(pixel.getBlue()>x). Here, 1.5 is just a margin of that average to detect the pixel. There is no rocket science behind that, the simple formula is to chase the correct margin, it basically lies in between 1 to 3. If you can remember how to detect the current pixel you are accessing, then you are good to go (co-ordinates of x and y of image gets you the current accessible pixel).

Then, searches for the same pixel in background and copies over RGB values to the original. If you are curious to know how the special effect image looks like. Here you go.

![Alt text of image](https://live.staticflickr.com/65535/50778895327_bd2ef11e64_n.jpg)

This may not give you the clear picture but you can sense how it works because I wasn't able to grab and paste the whole picture in here.

          Hopefully you enjoyed reading this Blog.
Laravel One to Many relationships with CRUD example
Tags: laravel, webdev, beginners, javascript
Published: 2021-01-12 17:01:09

---
title: Laravel One to Many relationships with CRUD example
published: true
date: 2020-12-30 11:02:35 UTC
tags: laravel,webdev,beginners,javascript
canonical_url: https://medium.com/backenders-club/laravel-one-to-many-relationships-with-crud-example-c52b13e598c4
---

[![](https://cdn-images-1.medium.com/max/800/1*OFwvVzfOiiscWUOSucwkFQ.jpeg)](https://medium.com/backenders-club/laravel-one-to-many-relationships-with-crud-example-c52b13e598c4?source=rss-8b0955f01559------2)

Laravel One to Many relationships is used to define situations where one entity in our database is related to many entities of the same…

[Continue reading on Backend Developers »](https://medium.com/backenders-club/laravel-one-to-many-relationships-with-crud-example-c52b13e598c4?source=rss-8b0955f01559------2)
React update 2020
Tags: react
Published: 2020-12-30 10:57:44

React 2020 is here! Here are two new features I have noticed so far:


## 1. You no longer have to import React and ReactDOM.

I quite liked this for some reason; less code. Also, my js files have the extensions **js** and my jsx files have the extension **jsx**. 


## 2. reportWebVitals.js

reportWebVitals has replaced serviceWorker. serviceWorker.js is used to make the react app a progressive web app. However, it has been replaced with reportWebVitals.



-----------



Have you started using the new react update? Do you like it? What new features have you noticed? Let me know in the comment section below 👇🏾
html2pdf.js generated pdf attach with laravel Mail
Tags: html2pdfjs, laravel, vue, javascript
Published: 2020-12-30 10:47:40

I am trying to convert my html dom into pdf and send that pdf as an attachment with email.

I am using Vue2 in frontend along with html2pdf.js. I am using this to download the dom as pdf and sending the pdf as email attachment. The pdf which is directly downloading is opening correctly but the pdf I am receiving on email is unable to open showing error `Failed to load pdf document` on chrome and `unable to open document , File type plain text document (text/plain) is not supported`.

This is my html2pdf code on frontend:

```
let opt = {
   margin:       1,
   filename:     'summary.pdf',
   image:        { type: 'jpeg', quality: 0.98 },
   html2canvas:  { scale: 2 },
   jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
};

let canvas = document.querySelector("#summary-block");

html2pdf().from(canvas).toPdf()
.output('datauristring')
.then(function (pdfAsString) {
    const data = {
        pdf: pdfAsString,
        emails: this.emails
    }
    console.log("promise-2-1");
    console.log(this.selectedListing);
    HTTP.post(`api/listings/${this.selectedListing.id}/share`, data)
    .then((response) => {
        this.btnLoading = false;
        this.tagError = false;
        this.emails = [];
    })

}.bind(this));
```

This is my php code in my Laravel controller.

```
$request = $this->request;
$b64file = trim( str_replace( 'data:application/pdf;base64,', '', $request->pdf ) );
$b64file = str_replace( ' ', '+', $b64file );
$decoded_pdf = base64_decode( $b64file );

if(!empty($request->emails))
{
    foreach ($request->emails as $recipient)
    {
        $user = User::find($recipient["key"]);
        $__NAME__ = 'User';
        $__MAIL_FROM_NAME__ = "Repylot";
        $__ADMIN_EMAIL__ = "support@repylot.com";
        $search = ['__NAME__', '__MAIL_FROM_NAME__', '__ADMIN_EMAIL__'];
        $replace = [$__NAME__,$__MAIL_FROM_NAME__, $__ADMIN_EMAIL__];
        Mail::to($user)->send(new EmailNotificationWithAttachment($request->pdf, $search, $replace, "offer_summary"));
    }
}
```

and EmailNotificationWithAttachment have handle
```
return $this->subject($subject)->html($template)->attachData(
        $attachment, 'summary.pdf', [
        'mime' => 'application/pdf',
    ]);
```
Getting Black and isort to agree on formatting
Tags: python, black, isort, formatting
Published: 2020-12-30 10:46:08

---
title: Getting Black and isort to agree on formatting
published: true
description: A working configuration file for isort that makes it easy to use both isort and black on the same project
tags: python, black, isort, formatting
---

We have been using [Black](https://github.com/psf/black) for a while to standardise our code formatting and reduce unproductive time in code reviews discussing syntax.

When we introduced it we had disabled our [isort](https://pycqa.github.io/isort/) formatting due to an issue but when it came time to reintroduce it I found that `black` and `isort` were engaged in a formatting war both trying to change the formatting of a few files whenever they were run.

isort now has [some advice on compatibility](https://pycqa.github.io/isort/docs/configuration/black_compatibility/) that wasn't available at the time (and which as a result I haven't tried).

This is the configuration file I ended up using for our code.

{% gist https://gist.github.com/rrees/0ae4b684a051e618fce9f1414b24d0ff %}

Automated code formatting has been a massively time saver in terms of code review and consistency across the codebase. If you're not already doing it then it is definitely one of the better new year resolutions you could make.
Tips to make Python Code faster
Tags: python, programming, faster, facts
Published: 2020-12-30 10:34:39



At this time we need everything fast and this thing also applies to programming. So we can talk here about how can we make the python program run Faster.

The first way to make a program faster is to understand the Data Structure that which one is fast and which is slow. So let's talk about python `list` and `dict`. For searching an element, which one is Faster?

When we searching an element in a list then we have only one way that is by accessing each item from the 0th index to the last index but the dictionary utilizes a data structure called a hashmap (Python dictionaries are optimized versions), and a key will be converted using a hash algorithm from a string (or whatever) into an integer value, and it is a couple of very simple calculations to take that integer and find the right place in the dictionary to look. So the `dict` Data Structure is faster than `list` for searching elements and by using a faster data structure we can make our code faster.

Another way to do reduce the run time of a python code is by reducing `Memory footprint`.
For example:
 ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ogh98pykqsuolt5xd9aj.png)
This is inefficient because a new string gets created upon each pass. Use a list and join it together:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gis63kbpnbd496wz1bx5.png)
Similarly, avoid the + operator on strings:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pq6ubvir1tmeesotiby3.png)



The next way to speedup python code is by using built-in functions because built-in functions like sum, max, any, map, etc are implemented in C. They are very efficient and well tested. These functions reduce the runtime of the code and make the program Faster.
Let's be fancy with a console signature
Tags: webdev, javascript, tutorial, beginners
Published: 2020-12-30 10:31:47

Create a stylized console message and say hello to your fellow developers.

![Console log signature](https://dev-to-uploads.s3.amazonaws.com/i/26uszeuue02c1wi4gblo.PNG)

## Let's get started

First you should know that a console message, which is the first argument of a `console.log`, can be formatted using other arguments. 

```js
console.log("I'm the message");
```
There are different ways to format a console message but the only one that is useful in this specific case is the `%c` formatter.

```js
console.log("%cI'm the message");
```

`%c` applies to the console message CSS rules that are defined by the second argument. 

```js
console.log("%cI'm the message", "background: red;");
```

And that's already all you need to know to create your own console signature. 

**Example**

```js
var consoleSignatureStyle = "font-size: 16px;" +
  "background: linear-gradient(to right, #e66465, #9198e5);" +
  "color: white;" +
  "text-align: center;" +
  "padding: 10px 15px;" +
  "width: 100%;" +
  "border-radius: 20px;";

var consoleSignatureText = "%cDon't steal my cookies! 🍪";

console.log(consoleSignatureText, consoleSignatureStyle);
```
![Console signature example](https://dev-to-uploads.s3.amazonaws.com/i/ggtdnhr33fhd9s4hnucb.PNG)

Note: *It is also possible to print images into the console by using the `background-image` CSS property.* 

***

If you like my posts follow me on [dev.to](https://dev.to/basilebong) and [twitter](https://twitter.com/basilebong/)!
Do you track your achievements?
Tags: watercooler, motivation, inspiration, career
Published: 2020-12-30 10:14:37

---
title: Do you track your achievements?
published: true
description: 
tags: watercooler, motivation, inspiration, career
cover_image: https://i0.wp.com/coverlettersandresume.com/wp-content/uploads/Key-Achievements-for-Teacher.gif?fit=640%2C406&ssl=1
---
Keeping track of your progress can be a huge motivation booster.
When you get stuck or out of inspiration, you can look back to what you have achieved and be grateful for that.

A nice example: [Florin Pop's timeline](https://www.florin-pop.com/timeline).

Currently, I'm tracking my achievements in Notion. Do you track your achievements, too? What do you use for that?
Python3 Programming - Exercise 8 - String formatting
Tags: python, programming, tutorial, beginners
Published: 2020-12-30 10:09:31

## String formatting

There are a couple of ways to format our output, making our output more readable. We would go with the `f"... {some_value}"` approach known as string interpolation (f-strings).
The `{}` provides the means to insert values into our string as we write it out. `some_value` is the value we pass into the string, whereby `f` means format. The string must begin with the `f` followed by string delimiters (double or single quote).

## Example

```Python
# Consider a simple program to take the users
# name and age and then print them to the screen

name = input("Enter name: ")
age = input("Enter age: ")

print(f"User name: {name}\nUser age: {age}")

# Another sample code
# A program to find the area of a triangle
# The area of a triangle is half the product of the base
# (length) and height of the triangle

height = float(input("Enter height of triangle: "))
base = float(input("Enter base of triangle: "))
area = 0.5 * base * height

print(f"The area of a triangle of height, {height}")
print(f" and base, {base} has an area of {area}")
```

When we have a float, such as, `3.14159` we could round it with the `round(number, digit)` function to `2-decimal` places then print it out.

```Python
pi = 3.14159
rounded_pi = round(pi, 2)
print(f"pi, {pi}, rounded to 2d.p is {rounded_pi}")
```

There is a simple way to do that using f-strings.

```Python
pi = 3.14159
print(f"pi, {pi}, rounded to 2d.p is {pi:.2f}")
```

## Practicals

Using the new concept in this exercise and the white space character, newline - `\n` and one `print` function. Write a program that takes users full name and their favourite number. Print to the screen the string, `<full name> thinks <num / 3> is special`.

Given `<full name>` as, `Daniel` and `<number>` as `23`, print, `Daniel thinks 7.667 is special`. Divide the `<number>` by `3` and round it to 3 decimal places.

## Summary

- One may use `f"... {}"` to format a string
- `f` - means format
- `{}` allows us to insert values directly into the string
How do you come up with the product names?
Tags: watercooler
Published: 2020-12-30 09:59:56

---
title: How do you come up with the product names?
published: true
description: 
tags: watercooler
cover_image: https://miro.medium.com/max/5200/0*EbZGz-rd5dpnePpo.jpg
---
Choosing a proper name for your product is equally important as naming variables, functions, classes, etc for code readability and future maintainability.

Is it hard for you to come up with the product name and where do you get your ideas from? Have you ever changed the product name afterward?
How to Start/ Run Angular application with pm2 in aws ec2

Tags: angular, pm2, ec2, aws
Published: 2020-12-30 09:54:35

I have configuration in directory /etc/nginx/conf.d

server {
    listen 80;
    root /var/www/html/owner/dist/browser;
    server_name stagingapp.company.com;


location / {
    proxy_pass http://127.0.0.1:8002;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

I Built the app from my local system and pushed to Git. Then pulled the same from Ec2 Server from app directory. Now I want to run the application. Do we have any command for this with PM2.