teleren/devto huggingface dataset:
Share functions between Vue and Node
Tags: vue, node, javascript, tutorial
Published: 2020-07-24 08:52:31

**Vue and Node make a powerful and versatile team, but aside from the API — via Express for me — Vue doesn't _talk_ to Node, or vice versa, and I had to fix that.**

So there I was, building the front end, writing the code for a _utilities_ mixin to store functions to handle common string and number operations. But then I realized that I had also written much the same code in a controller for Node.

What if I could use the same functions in Node _and_ Vue?

So, first I created a file in Node that would contain the _core_ functions I'd be using in the mixin in Vue:

```
// "utilities.js" in Node.

let utilities = {}

utilities.stripTags = (note, hellip = false) => {
  let removeHTML = note.replace(/(<([^>]+)>)/ig, "")
  let removeHTMLEntities = removeHTML.replace(/&#{0,1}[a-z0-9]+;/ig, "")
  let removeLineBreaks = removeHTMLEntities.replace(/\r?\n|\r/g, " ")
  let removeNonbreakingSpaces = removeLineBreaks.replace(/&nbsp;/ig, " ")
  let removeEmojies = removeNonbreakingSpaces.replace(/[\u1000-\uFFFF]+/g, " ")
  let string = removeEmojies
  return (hellip) ? string.concat('&hellip;') : string
}

module.exports = utilities
```

… then, I returned to the mixin:

```
// "utilities.js" in Vue.

'use strict'

// Core modules.
import CoreUtilities from 'path_to/utilities'

export const Utilities = {
  data () {
    return {
      // Reactive variables...
    }
  },
  methods: {
    stripTags (note, hellip = false) {
      // Utilizing a method in core utilities.
      return CoreUtilities.stripTags(note, hellip)
    }
  }
}
```
Now I have one definitive source of functions that both Vue and Node are able to access.

If anyone knows a more efficient method of replacing HTML, please share!

Image by <a href="https://pixabay.com/users/Dyanap-1633410/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1039483">Dyanap</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1039483">Pixabay</a>
Preview selected image (input type="file") using JavaScript
Tags: javascript, css, tutorial
Published: 2020-07-24 08:51:39

*** [CodePen Demo](https://codepen.io/michaelburrows/pen/ZEQPveq) ***

By default only the file name is displayed when a user uploads an image using a file input field.

Wouldn’t it be better if the user could preview the image before continuing?

Fortunately with a little JavaScript we can display the selected image in the browser.

Let’s get started by setting up the HTML form and file upload field:

```html
<form>
  <div>
    <div id="img-preview"></div>
    <input type="file" id="choose-file" name="choose-file" accept="image/*" />
    <label for="choose-file">Choose File</label>
  </div>
</form>
```

It’s important to add `"accept="image/*"` so only image uploads are allowed.

Next comes the JavaScript functionality to preview the image.

Step 1 is to define variables for the input field and `<div>` that display’s the image.

```javascript
const chooseFile = document.getElementById("choose-file");
const imgPreview = document.getElementById("img-preview");
```

Step 2 is to add an event listener that detects a value change on the input field.

When this is detected we’ll call the function that get’s the image data:

```javascript
chooseFile.addEventListener("change", function () {
  getImgData();
});
```

The `getImgSrc()` function inserts an image into the page with the base64 data of the selected image:

```javascript
function getImgData() {
  const files = chooseFile.files[0];
  if (files) {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(files);
    fileReader.addEventListener("load", function () {
      imgPreview.style.display = "block";
      imgPreview.innerHTML = '<img src="' + this.result + '" />';
    });    
  }
}
```

Now for some CSS to contain the image size and prevent large image uploads breaking the layout:

```css
#img-preview {
  display: none; 
  width: 155px;   
  border: 2px dashed #333;  
  margin-bottom: 20px;
}
#img-preview img {  
  width: 100%;
  height: auto; 
  display: block;   
}
```

Lastly we’ll style the input field so it doesn’t look so boring:

```css
[type="file"] {
  height: 0;  
  width: 0;
  overflow: hidden;
}
[type="file"] + label {
  font-family: sans-serif;
  background: #f44336;
  padding: 10px 30px;
  border: 2px solid #f44336;
  border-radius: 3px;
  color: #fff;
  cursor: pointer;
  transition: all 0.2s;
}
[type="file"] + label:hover {
  background-color: #fff;
  color: #f44336;
}
```

Styling file fields is limited so what we’re actually doing here is hiding the field and styling the label.

This works because the file selector is also triggered when the associated label is clicked.
Avoid The Native In React Native
Tags: reactnative, react, javascript
Published: 2020-07-24 08:51:06

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

In times where there are multiple technologies like React Native and flutter, we often tend throw the word cross platform app loosely. I saw many react native applications that have been said to be cross platform until you start looking at the amount of platform specific codebase been written -

<ul>
<li> Cause certain UI components are platform specific like DrawerLayoutAndroid</li>
<li> There was a limitation within the React Native API, or performance limitation so native bridge had to be written</li>
</ul>

### **Try avoiding it as long as you can**
Dropping some native code in React Native codebase brings multiple complexities -

<ul>
<li> Now anyone in future who needs to manage the codebase requires knowledge of native app development which means having understanding of three domains - Android, iOS and React Native 😦</li>
<li> Just shipped a new feature in Android, great now also ship it in iOS. Now you suddenly realise you're losing the very point of choosing React Native</li>
</ul>


### **Native can be hard to avoid for certain use-cases unfortunately** 
Yes we talked about what's the right way to do but now let's talk what's practical.  

<ul>
<li> Want to do some background syncing, well unfortunately that requires multi-threading. In JavaScript land multi-threading isn't possible. 😐</li>
<li> Need your app to talk to a native mobile feature but React Native doesn't support it, its time to write a native bridge which involves coding in native language along with javascript.</li>
</ul>

### **So how does one force themselves from not diving into native code -**

Start of your green field app in [expo](https://expo.io/) cause it allows you to build app and test it on real device simultaneously. So no surprises of moving the app from emulator to real device. You loose this cool feature the moment you add native code since native code doesn't compiles in run time.

### **But do you practice what you preach**
Absolutely 🙂, I have been building a commercial [B2B SaaS mobile app](https://www.airplug.xyz/) following the same development model. As a developer choose the easier path cause even that often ends up being lot more harder than you thought.
We built an OpenAI powered Tailwind CSS code generator using GPT-3
Tags: showdev, webdev, tailwindcss, html
Published: 2020-07-24 08:42:52

A couple of days ago we got access to the OpenAI’s Beta API platform and I had the occasion to play around with it. After the first couple of minutes I couldn’t really understand how it works, but after going through some tutorials and other examples I got a hang of it.

[![Tailwind CSS GPT-3 Code Generator](https://themesberg.s3.us-east-2.amazonaws.com/public/posts/gpt-3-tailwind-css-code-generator.jpg)](https://gpt-tailwind.com) 

<abbr title="Generative Pretrained Transformer 3">GPT-3</abbr> (Generative Pretrained Transformer 3) is an unsupervised Transformer language model and the successor to GPT-2 containing over 175 billion parameters. The interesting thing about this AI is that it can very quickly learn only from a few input parameters before giving it a job to do.

Because we work in web development specifically with front-end frameworks such as Bootstrap, Tailwind CSS, React, Angular, Vue and so on we thought it’s worth giving a shot to use the AI to generate code. We just did that and I must say I am very surprised by the results.

Effectively I built a local React app where I can give a text based input, send it over to the OpenAI API and then it will give me the results (the HTML code) that you see below. Mind. Blown. 🤯

Here’s the video:

{% youtube QGlDuy67ROA %}

Of course I had to train the AI before it can give such good results and there is so much more work to be done to optimize the results. As you can see the first example was perfect, however the second one had some extra garbage results as well.

## How can GPT-3 Tailwind CSS Code Generator help developers?

So I want to make it very clear - because many developers are scared that they will lose their jobs after this - that GPT-3 will not affect the jobs of front-end developers because it can only effectively return results for at most a couple of components. Besides, the results are almost never perfect, but that doesn’t matter.

The way I imagine this tool being used is sort of a smart snippet or a code assistant that can save you time writing boilerplate code. We already purchased over 40 domains related to GPT-3 and AI in web development and you will see Themesberg being more and more active in this field.

Either way, if you are interested in getting early access to this builder please let us know by joining the waiting list on the official [GPT-3 Tailwind CSS](https://gpt-tailwind.com/) website.
JAMstack comments
Published: 2020-07-24 08:32:05

[My site](https://tsvbits.com) is a [Jamstack](https://jamstack.org/) site. It is built using [GatsbyJS](https://www.gatsbyjs.org/) powered by [ReactJS](https://reactjs.org/). In this post I gonna show how you can add a free comments to your site with the following pretty simple steps.

1. Use [Reddit](https://www.reddit.com/) as a service that stores comments.
1. Implement React component that shows reddit Comments.
1. Integrate component to the blog post template

## React Component

We gonna use [NextJS useSWR](https://github.com/vercel/swr) hook to fetch comments from reddit re-post.
Here a code snippet of this component.

```jsx
import React from 'react';
import useSWR from 'swr';
import moment from 'moment'; // to render relative time of the comment
import ContentLoader from 'react-content-loader'; // to render nice loader

export default function RedditComments({ reddit }) {
  if (!reddit) {
    return null;
  }
  const { data, error } = useSWR(reddit, fetcher);
  if (error) {
    // TODO render error
    return null;
  }
  const comments = data ? (
    data.map((item, i) => <Comment key={i} data={item.data} level={0} />)
  ) : (
    <Loader />
  );
  return (
    <div className="reddit">
      <a className="heading" href={reddit} target="_blank">
        Comments
      </a>
      {comments}
    </div>
  );
}
```

The full source code is available [here](https://github.com/tsvbits/tsvbits.github.io/blob/dev/src/components/Reddit.js).

## Component Integration

I've added a `reddit` metadata to each post having a reddit re-post.
After that I've extended [a blog post template](https://github.com/tsvbits/tsvbits.github.io/blob/dev/src/templates/blog-post.js#L197) to render comment block. 

```jsx
// ...
import Reddit from '../components/Reddit';

const BlogPostTemplate = ({ pageContext }) => {
  let {
    // ...
    // new metadata
    reddit,
  } = pageContext;

  // ... computing more state like translations

  return (
      <Layout>
        {/* main content is omitted */}
        <footer>
            <Reddit reddit={reddit}/>
            {/* other footer blocks */}
        </footer>
      </Layout>
  );
};
```

And voila it amazingly works.

Enjoy! EOF :smile:

[Link to original post](https://tsvbits.com/jam-comments/)
THANK YOU: Riding the CodeLand Wave
Tags: devjournal, codenewbie, womenintech, codeland
Published: 2020-07-24 08:12:20

_This post was originally published on July 24, 2020 on [my blog] (https://alexlsalt.github.io/blog)._

Guys! Gals! CodeLand was yesterday, and so was my talk and panel discussion, and I am most definitely still riding a wave of utter elation.

As I've mentioned, this was my first time giving a conference talk to a large audience, and I think it's safe to say that *I am hooked*.

Wow.

Just, all the good feelings. All the inspiration from connecting with others.

Everything.

It was everything.

Thank you from the deepest and most sincere recesses of my heart to everyone who reached out after watching the talk, who connected, who shared bits of their own journey with me.

I'm continuing to read and absorb every single note I've received, and I so thank you for it.

*This* is getting out there and getting after it. *This* is being seen. *This* is putting one foot in front of the other and erring on the side of taking action, always.

Thank you.

P.S. If you missed my talk, Being Utterly Fearless in Your Pursuit of Learning to Code, you can find it [right over here >>] (https://dev.to/alexlsalt/being-utterly-fearless-in-your-pursuit-of-learning-to-code-with-alex-morton-5o0)


----------

Thanks so much for reading along! [Now let's be friends over on Twitter >>] (https://twitter.com/alexlsaltt)

P.S. Did you know I have a podcast with new episodes each Wednesday? Go listen [right over here >>] (https://www.ladiescodecollective.com/)

![The Ladies Code Collective Podcast art](https://dev-to-uploads.s3.amazonaws.com/i/nl20jdyk6b9ec2w1lms7.png)
glitchchord updates
Published: 2020-07-24 08:05:39

Wow, since we started we now have over 100 users! thanks to all those who helped us get to where we are now!

We are unveiling some new features!:

- statuses- show how you feel! look for 'status' in your profile!

- load profile pic from URL- if your having issues uploading an image, then load one from a remote source! look for this under 'upload a profile picture'

- user-specific admin- admin is granted through boolean logic, to prevent users getting powers we only load resources needed for admins where they are wanted. 

Some users may have witnessed the birth of markdown support, we have had to discontinue this for now until we can fix an ongoing issue.

Again, thank you to all the devs who offered their help and to you (the user) for staying with us!
What is NGINX?
Tags: webdev, beginners, node, codenewbie
Published: 2020-07-24 07:42:41

This article was originally published at https://www.blog.duomly.com/6-most-popular-backend-questions-and-answers-for-beginners/#what-is-nginx-tutorial-for-beginners

--- 

### What is NGINX?

{% youtube 9sTGRDRWPZc %}

NGINX started to be known as an open-source web server, but now it’s also used as a reverse proxy, HTTP cache, and load balancer. As a web server, It was designed for maximum performance and stability.

To make it simple and understandable, let me explain how the web server works. When you try to open a website, the browser sends a request to the server, then the server looks for the requested sources and returns it to the browser. Of course, requests are usually much more complicated. 

The process described above is a single thread, and usually, the web server creates a thread for every request, but NGINX makes it a different way. 

NGINX manages similar threads as a one process worker, and each process workers have smaller units, called worker connections. Process connections deliver the request to the worker process, and the worker process delivers it to a master process, and the request is returned to the browser.

NGINX can process thousands of requests.

Let’s visualize the usage of NGINX in the application.

![Nginx Web Server](https://dev-to-uploads.s3.amazonaws.com/i/3k9wms6e52ekmmtk32zy.png)

<a href="https://www.duomly.com/?code=lifetime-80">![Duomly - Programming Online Courses](https://dev-to-uploads.s3.amazonaws.com/i/k00bacsgkavhcziauwrg.png)</a>

Thank you for reading, 
Anna from Duomly
Getting Started with Angular Reactive Forms
Tags: typescript, javascript, angular, node
Published: 2020-07-24 07:27:59

---
title: Getting Started with Angular Reactive Forms
published: true
description: Getting Started with Angular Reactive Forms
tags: TypeScript, JavaScript, Angular, Node
---

In Angular, There are two ways to create forms.

1) Template Driven
2) Reactive Forms.

Here in this video- I have explained what are the advantages and disadvantages of using reactive forms in the angular application.

I have also created a sample application and demonstrate how we can create reactive forms and also validate the same.

Following is video for the same.

{% youtube -7vVgM0tU2Q%}

If you like this video and wanted to see a similar kind of video then, please subscribe to my youtube channel at - https://bit.ly/codewithjv.

Also, Do let me know what more content you wanted to see in for Angular
Nobody likes to wait in a Queue
Tags: sre, devops, productivity, computerscience
Published: 2020-07-24 07:25:21

Nobody likes to wait in a queue. Almost everyone in a queue at immigration or in a road traffic has considered

- What if I move to the other queue? Thats going faster
- Why haven't they added more servers / units / lanes to service?
- This is just the bad time of the day. Should have started early.

Its a science! These things can be answered by formulas and you can study these systems formally.

The mathematical field of studying queues is called Queueing Theory.


## Queueing Theory 101

### Definitions

![Queueing Theory Terminology](https://dev-to-uploads.s3.amazonaws.com/i/nd0me6l7c48klaejbnm8.png)

### System Structures

![Queueing Systems](https://dev-to-uploads.s3.amazonaws.com/i/gk6b0umtt6fq43fdr3r2.png)

### Key Concepts

* Arrivals
   How things arrive? Stream, Batch
   Is there a normal arrival distribution?
   Are the arrival times finite / infinite?

* Service
   Kind of resources needed to service
   How long does it take ?
   Number of servers available
   How many can be serviced?
   Parallel / Serial?
   Single / Multiple Queues 
   Preemption (Priority)

* Queue Characteristics
   Balking (people/things don't join, if queue is long)
   Reneging (queue too long, leave mid way)
   Jockeying (switch queue)
   Finite / Infinite (queue lengths)


### Questions we are interested in

1. How long does a customer (*request) have to wait
2. What is the probability of customer having to wait longer
3. Average length of queue
4. Expected utilisation of the server at any given point

#### To Decide

1. Is it worthwhile to improve on service times
2. ‘Auto Scale!’
3. Should we introduce priorities
4. Is waiting area adequate

### Little's Law

L = ƛW

ƛ = Arrival Rate
W = Waiting times
L = Total being serviced

[Presentation](https://docs.google.com/presentation/d/13rJWsZzPdDBfZr-alKFQZ10UcijVOsefe2bOq8Ibcx8/edit?usp=sharing)

[SRE Platform](https://blog.last9.io)
How to Send Pair with Open MPI
Tags: cpp, mpi
Published: 2020-07-24 07:24:07

Hey guys.
I'm a beginner of Open MPI.
When I wanted to send some std::pair onjects from a node to another, I found out the fact that there are no Datatype of std::pair.
You can use only the datatypes in Open MPI as bellow.

|MPI Datatype|C++ Datatype|
|:----|:----|
|MPI::CHAR|char|
|MPI::SHORT|signed short|
|MPI::INT|signed int|
|MPI::LONG|signed long|
|MPI::LONG_LONG|signed long long|
|MPI::SIGNED_CHAR|signed char|
|MPI::UNSIGNED_CHAR|unsigned char|
|MPI::UNSIGNED_SHORT|unsigned short|
|MPI::UNSIGNED|unsigned int|
|MPI::UNSIGNED_LONG|unsigned long int|
|MPI::UNSIGNED_LONG_LONG|unsigned long long|
|MPI::FLOAT|float|
|MPI::DOUBLE|double|
|MPI::LONG_DOUBLE|long double|
|MPI::BOOL|bool|
|MPI::COMPLEX|Complex<float>|
|MPI::DOUBLE_COMPLEX|Complex<double>|
|MPI::LONG_DOUBLE_COMPLEX|Complex<long double>|
|MPI::WCHAR|wchar_t|
|MPI::BYTE| |
|MPI::PACKED| |

You can see only basic types and it's natural to do so because developers use variety of custom types and Open MPI can't prepare for all types of them.

I think the most flexible one is MPI::BYTE.
So, I used it to send std::pair<int,int>.
You can easly calculate the total size of pairs in 1 byte increments by using the "sizeof" function.

Here is the example code.
```cpp
#include "mpi.h"
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char **argv) {
  int rank, numprocs;
  int namelen;
  vector<pair<int, int>> send_buf = {make_pair(0, 1), make_pair(2, 3)};
  vector<pair<int, int>> recv_buf(2);

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
  if(rank == 0){
    MPI_Send((void*)send_buf.data(), sizeof(pair<int,int>)*2, MPI_BYTE, 1, 0, MPI_COMM_WORLD);
  }

  if(rank == 1){
     MPI_Recv((void*)recv_buf.data(), sizeof(pair<int,int>)*2, MPI_BYTE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
     cout << recv_buf[0].first << ":" << recv_buf[0].second << endl;
     cout << recv_buf[1].first << ":" << recv_buf[1].second << endl;
  }
  MPI_Finalize();
  return 0;
}
```

Enjoy hacking!
15 Essential Node.js Packages To Improve Developer Productivity
Tags: node, webdev
Published: 2020-07-24 07:21:44

Node.js is a pioneer in the asynchronous framework markets and used to create quick and scalable network applications. It supports a huge pool of startups and businesses that earn hundreds of millions of dollars in revenue. Node.js is the greatest disclosure of modern server engineering that we use and is not showing any sign of stopping. A new release of Node.js secures some loopholes in OpenSSL, and supports languages like C and C++

Node.js packages helps you to use an event-driven, non-blocking I/O model. These important features makes it efficient, lightweight and totally adept for data-intensive real-time applications. It helps in achieving many purposes like back-end, front-end, APIs and robotics, improvement of development workflow and work model.

#Significance of NPM-
NPM is a JavaScript node package manager. It is a default method to manage packages in Node.js runtime environment and supports use cases like publish, discover, install and develop node programs. By using NPM, javascript developers can easily share the code that they have compose to solve specific issues and other developers can reuse this code for their application.

**Three specific components-**

* Website
* Command Line Interface (CLI) known as the NPM client
* Registry (it is the directory of information about packages)

Registry includes more than 1 million Node.js Packages. These packages help developers to code by bringing simplicity to work. They can just install many NPM packages, copy few snippets and get ready with a decent demo for a JIT presentation.

#Top 15 Node.js Packages To Improve Productivity-
**1. Browserify-**
This package allows developers to develop organised, systematic and easy to navigate client-side codebase. With the use of Browserify, you can develop components that assign dependencies according to their use in different conditions. Generally, Node.js projects have many Node.js Packages, libraries and scripts. At such cases this package helps you to organize and give proper structure.

JavaScript libraries are complicated to manage and you have to continuously check the templates to analyse which script is used by which libraries. As soon as you go deep into a project, script increases and hence it becomes difficult to tab on libraries and widgets. 

**2. Express-**
One of the fastest ways to get a programming language to serve your needs is through a framework. Most of the common programming languages have similar structures. It is a widely used framework to create and publish applications, and APIs rapidly. This framework has a minimal structure and by using Express generator, you can immediately launch a functional application. Also you can combine it with other Node JS packages for better performance.

**3. Socket.io-**
Know more at- [https://solaceinfotech.com/blog/15-essential-node-js-packages-to-improve-developer-productivity/]