teleren/devto huggingface dataset:
How far can we go with web components [Part-1]
Tags: svelte, webcomponenets, webdev
Published: 2020-04-06 15:20:30

Web components are reusable custom elements that have a shadow dom attached to it.   
Any web component can basically be divided into 3 main parts;
* **Custom element**: The javascript API's responsible for creating the element-tag and defining its behavior
* **Shadow DOM**: The main element tree that is used to render the custom element to the main-DOM
* **HTML templates**: The `<template>` and `<slot>` tags are used to define the HTML present inside the shadow DOM   
To read more about web components click [here](https://developer.mozilla.org/en-US/docs/Web/Web_Components)

## Pre-requisites
To follow along you should know javascript and a bit of [svelteJS](https://svelte.dev/) or any other front-end framework which supports web components.
> You don't need to know svelte or any other framework to create web components but a framework makes it a bit easier to create them

## Why svelte?
Svelte compiles your code directly into vanilla javascript so if you write your web component in vanilla javascript the bundle size would be very similar and svelte comes with some cool features which we would be using.

## Setup
### Step 1
Get the svelte web component template and install the dependencies

``` bash
npx degit sveltejs/component-template my-new-component # name of your component goes here
cd my-new-component
npm i # or yarn
```
### Step 2
Once downloading the template is done there are minor changes required to make it work properly
1.  Add the `customElement` property in the `rollup.config.js`
``` javascript
    plugins: [
        svelte({
            customElement: true,
        }),
        resolve()
    ]
```
2. Add `<svelte:options tag="your-tag-name"/>` at the top of the `Component.svelte` file in the `src` directory and you should be good to go.

## Hello World web component
To create a web component you need to write some code in the `Component.svelte`, something like this
``` html
<svelte:options tag="hello-world"/>
<script>
    export let name
</script>
<main>
<h1>Hello { name }!</h1>
</main>
```
clearly `name` is a prop and we will see how to send data into the component but for now just run `npm run build`. This will create two files in the `dist` folder namely `index.js` and `index.mjs`. That's it your web component is created

## Use the hello-world component
To the hello-world component that we just created we need to import the `index.js` into a html and run it on a server
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Web components</title>
    <script src="./index.js"></script>
</head>
<body>
    <hello-world name="world"></hello-world>
</body>
</html>
```
clearly the prop `name` that needs to be passed is sent as an attribute to the web component and the web component recieves it and displays it, however if we don't pass anything it will display `undefined`.  

### Thanks for reading :smile:
How to make a JSON Linter / Validator with Vue
Tags: showdev, webdev, vue, javascript
Published: 2020-04-06 15:20:19

---
title: How to make a JSON Linter / Validator with Vue
published: true
description: A simple linter, validator & formatter using Vue.js
tags: showdev, webdev, vue, javascript
---

![Vue Lint JSON](https://dev-to-uploads.s3.amazonaws.com/i/ykaznigy63dhsbywxa3z.png)

Here's my latest in a series of helpful snippets I've made on [Vue](https://www.codeply.com/tagged/vue) . As a developer, one of my favorite go-to tools is [jsonlint.com](https://jsonlint.com/). I use it so much that I decided to make my own 🙂 JSON Linter using Vue.js.

The Vue App
===

This turned out KISS. Just 2 vars for the JSON as a string, and displaying errors. I used a computed `prettyFormat` method that handle the validation logic.

The `prettyFormat` method attempts to parse the JSON string, and on error displays the line &amp; position of the problem. To highlight the error position within the JSON, I grab a ref to textarea element, and find the position, and finally use `setSelectionRange` to highlight the problem text.

```

const app = new Vue ({
  el: '#app',
  data: {
    jsonstr: '',
    jsonerror: ''
  },
  computed: {
    prettyFormat: function() {
        // reset error
        this.jsonerror = ""
        let jsonValue = ""
        try {
            // try to parse
            jsonValue = JSON.parse(this.jsonstr)
        }
        catch(e) {
            this.jsonerror = JSON.stringify(e.message)
            var textarea = this.$refs.jsonText
            if (this.jsonerror.indexOf('position')>-1) {
                // highlight error position
                var positionStr = this.jsonerror.lastIndexOf('position') + 8;
                var posi = parseInt(this.jsonerror.substr(positionStr,this.jsonerror.lastIndexOf('"')))
                if (posi >= 0) {
                    textarea.setSelectionRange(posi,posi+1)
                }
            }
            return ""
        }
        return JSON.stringify(jsonValue, null, 2)
    }
  }
})
```

The HTML / Vue Markup
===

The keep the UI clean and responsive I included Bootstrap 4. This gives you some color classes to make the error and success text contextual.

```
<div id="app" class="container py-3">
    <div class="row">
        <div class="col-sm-10 mx-auto py-3">
            <h4 class="font-weight-light">JSON Validator / Linter / Formatter with Vue2</h4>
            <div id="vueapp">
              <div class="text-danger" v-if="jsonstr && jsonerror">{{ jsonerror }}</div>
              <div class="text-success" v-if="!jsonerror">Valid JSON ✔</div>
              <textarea 
                v-model="jsonstr" 
                rows="10" 
                class="form-control" 
                ref="jsonText" 
                placeholder="paste or type JSON here..."></textarea>
              <pre>{{ prettyFormat }}</pre>
            </div>
        </div>
    </div>
</div>
```

Voila, [check it out for yourself](https://codeply.com/v/2sHU0s6aLC)😉 and let me know what you think.

Full source: https://codeply.com/go/932bxkCVow
Machine Learning, Tutorial Hell, Work-Life Balance & More: ZTM Instructor AMA
Tags: machinelearning
Published: 2020-04-06 15:03:44

<br>

[ZTM Academy](https://zerotomastery.io/academy?utm_source=devto&utm_medium=danielama) Instructor, [Daniel Bourke](https://zerotomastery.io/about/instructor/daniel-bourke?utm_source=devto&utm_medium=danielama) answers the most upvoted Zero To Mastery student community questions in this AMA style video. Daniel answers questions about life, machine learning, business, getting a job and more.

Daniel is a self-taught Machine Learning Engineer that has worked at one of Australia's fastest-growing artificial intelligence agencies, Max Kelsen, and is now using his expertise to teach thousands of students data science and machine learning.

**Just a few of the topics covered:**
1. **Life** (work-life balance, daily routine, music while working, working on solo projects)
2. **Career** (getting hired in data science, getting out of tutorial hell, freelancing, how do I make money)
3. **Machine Learning** (data structures and algorithms, do you need a GPU to train and deploy ML models, the missing component of a CS degree)

**Additional resources:**
1. [Daniel's course -- Complete Machine Learning and Data Science: Zero to Mastery](https://links.zerotomastery.io/mlds_academy)
2. [The missing semester of your CS degree](https://missing.csail.mit.edu)
3. [Cunningham's Law](https://meta.wikimedia.org/wiki/Cunningham%27s_Law)
4. [Master the Coding Interview: Data Structures + Algorithms](https://links.zerotomastery.io/datastructures_academy)

If you enjoy this AMA and want to get more like it in the future, make sure to subscribe on [our blog](https://zerotomastery.io/blog?utm_source=devto&utm_medium=danielama). If enough people subscribe, we'll keep making them!

**Without further ado... (click the image below to watch the full AMA on YouTube)**

[![Zero To Mastery Instructor AMA: Tutorial Hell, Work-Life Balance, Machine Learning & More](https://images.ctfassets.net/aq13lwl6616q/6HonjbXKa6qndbGrHfASS6/50dab66b7515934926cbcfde69a01c7b/AMA_DanielBourke_MachineLearning_GettingHired.png)](https://www.youtube.com/watch?v=8X9sxi_0azI)
Performance auditing an eCommerce site
Tags: performance
Published: 2020-04-08 00:51:12

---
title: Performance auditing an eCommerce site
published: true
date: 2020-04-06 15:00:00 UTC
tags: performance
canonical_url: https://jeffy.info/2020/04/06/live-site-audit.html
---

## Alan's weekly eCommerce livestreams

My teammate [Alan](https://alankent.me/)'s been running a weekly livestream on [his YouTube channel](https://www.youtube.com/channel/UCyQwDaXnT7wMBBqIaAfmY7g), focusing on topics of interest to eCommerce websites. He asked me to come on this week and perform a site performance audit.

Since I'm currently homebound due to Coronavirus concerns in NYC, I haven't had the chance to perform any [in-person site audits](https://dev.to/jeffposnick/cds-perf-review-clinic-takeaways-2267) in a while. Going through the process via a livestream was a great opportunity!

## The site review

The review process took about 50 minutes (I'd recommend watching at 2x playback speed...) and covered some relevant findings from WebPageTest.org and Lighthouse.

We choose the site, [https://threddies.com/](https://threddies.com/), "at random" based on folks who [volunteered](https://twitter.com/akent99/status/1245466347502333952). I think it ended up being fairly representative of the types of issues a lot of sites encounter.

{% youtube l4bIT3CXCpc %}

_Lightly edited from the notes I took during the review._

### Tools used:

- ["Easy" mode on WebPageTest](https://webpagetest.org/easy) ([site results](https://webpagetest.org/result/200402_FD_f791a96a04046aaa9d7583914ba1c952/))
- [Lighthouse](https://developers.google.com/web/tools/lighthouse)

### Observations

- 11 seconds for main content to load — what's loaded beforehand?
- How many of the widgets/analytics tools can be [lazily-loaded](https://web.dev/native-lazy-loading/) (or potentially removed, if appropriate)?
- HTTP cache expiration [best practices](https://web.dev/reliable/).
- Use the [Coverage panel](https://developers.google.com/web/tools/chrome-devtools/coverage) in Chrome Dev Tools to evaluate how much of your JS/CSS in the critical request path is being used
- Q: Can they get away with loading Google Maps static images instead of Google Maps widget? Answer: [yes, they can](https://developers.google.com/maps/documentation/maps-static/intro).
- Always click on the "Learn More" link in Lighthouse for additional context!
- Zach Leatherman's [guides to loading web fonts](https://www.zachleat.com/web/comprehensive-webfonts/) are great.
Do you use flashcards? - my first react project
Tags: showdev, learning, discuss
Published: 2020-04-06 14:46:51

![flashcards](https://raw.githubusercontent.com/slavcoder/flashcards/master/src/assets/screenshot-1.png "main view")

I created this project to take a closer look at **react** (it might contain a lot of bad practices - **I warn**)

I would love to hear some feedback if you have a minute.  
And if you do, try out **test mode** (button in footer) - noone have time to create cards just for testing app :)

[flashcards](https://slavcoder.github.io/flashcards/)

[repository](https://github.com/slavcoder/flashcards/)

## Are flashcards a good learning method?

But this post is not only to show that not everyone is making coronavirus dashboards right now `</badjoke>`, but also to ask about your thoughts on flashcards as a learning method.

- Do you use flashcards? Or why not?
- What apps can you recommend?
- or maybe you are using a different method?

Recently I found [this article](https://www.yearlyglot.com/dont-use-flashcards) against flashcards in learning language. If you are using them, do you see a progress which you expected to have? Or maybe the author have some points? What do you think? Are flashcards overrated?

One post, millions of questions...
Code Snippets 👨🏾‍💻 New Series
Tags: codenewbie, tutorial, javascript, webdev
Published: 2020-04-06 14:56:20

Hey Dev Nation!👋🏽

I'm starting a new series where I will post easy to understand code snippets💻 on a regular interval or repost some of my work from other platforms here. 

I promise that the snippet will be **visually aesthetic** and will convey a critical bit of information in **less than 30 seconds**. For example:

{% twitter 1247129460660297728 %} 

Tag along for more to come! All feedback appreciated!

Cheers!
The 7 Most Popular DEV Posts from the Past Week
Tags: top7
Published: 2020-04-06 14:50:39

---
title: The 7 Most Popular DEV Posts from the Past Week
published: true
description: A round up of the most-read and most-loved contributions from the community this past week.
tags: icymi
cover_image: https://thepracticaldev.s3.amazonaws.com/i/sfwcvweirpf2qka2lg2b.png
---
Every Monday we round up the previous week's top posts based on traffic, engagement, and a hint of editorial curation. The typical week starts on Monday and ends on Sunday, but don't worry, we take into account posts that are published later in the week. ❤️

#1. Not a Nightmare

While powerful, Git can often be a nightmare to figure out. In this post, Lydia helps us understand the most common and useful git commands through visualizations.

{% link https://dev.to/lydiahallie/cs-visualized-useful-git-commands-37p1 %}

#2. Single Source

Sven introduces us to Eclipse Theia, the vendor-neutral open-source IDE platform that runs in browsers and on desktops.

{% link https://dev.to/svenefftinge/theia-1-0-finally-a-good-browser-ide-3ok0 %}

#3. Lego Castle

Angad takes us through and explains a typical linux desktop: display manager, window system, window manager, desktop environment.

{% link https://dev.to/l04db4l4nc3r/the-linux-desktop-deep-dive-1jh3 %}

#4. Do Not Call (all the time)

Martín shares two great techniques to avoid extra function executions.

{% link https://dev.to/otamnitram/throttling-and-debouncing-avoiding-unnecessary-api-calls-2god %}

#5. Not alone

Caitlyn shares their experience of being a new developer during a pandemic. This is a very relatable post, regardless of whether or not you're new to the industry.

{% link https://dev.to/thecaitcode/being-a-junior-dev-in-the-time-of-covid-n0b %}

#6. Mobile First

Want to make your life easier? Adopt a mobile-first mindset to simplify your journey towards a responsive site. 

{% link https://dev.to/kevinpowell/stop-making-responsive-websites-the-hard-way-kgb %}

#7. Optimize Operations

Linda explains "The Why" behind learning data structures and algorithms. The short answer? DS & A are superpowers!

{% link https://dev.to/the__dauntless/what-data-structures-and-algorithms-should-mean-to-you-9kn %}

_That's it for our weekly wrap up! Keep an eye on dev.to this week for daily content and discussions...and if you miss anything, we'll be sure to recap it next Monday!_
Scala - Funções de Ordem Superior, Anônimas e Currying
Tags: scala, functional
Published: 2020-04-06 14:48:33

* [Funções de Ordem Superior](#hof)
* [Funções Anônimas](#lambda)
* [Currying](#currying)

Em linguagens funcionais, funções são tratadas como valores de primeira classe, permitindo a existência das **funções de ordem superior**.  

## Funções de Ordem Superior <a name="hof"></a>

Funções de ordem superior são funções que aceitam outras funções como argumento ou as retornam como resultado. Isso faz com que programas sejam compostos de uma forma mais flexível.  

Dado as funções
~~~scala
def sum(f: Int => Int, a: Int, b: Int): Int = 
  if (a > b) 0
  else f(a) + sum(f, a + 1, b)
~~~
~~~scala
def cube(x: Int): Int = x * x * x
~~~

É possível compôr uma função que soma os cubos de um número  

~~~scala
def sumCubes(a: Int, b: Int): Int = 
  sum(cube, a, b)
~~~

>**A => B** é o tipo de uma função que recebe um argumento do tipo **A** e retorna um resultado do tipo **B**. Sendo assim, **Int => Int** recebe um argumento do tipo Int e retorna um resultado do mesmo tipo.


## Funções Anônimas <a name="lambda"></a>

O problema de passar funções como parâmetro é que isso leva à criação de diversas funções pequenas. Para evitar que isso aconteça, podemos criar funções sem dar um nome a elas. Essas funções são chamadas de **funções anônimas**.

~~~scala
(x: Int) => x * x * x
~~~

Na função acima, `(x: Int)` é o parâmetro da função, e `x * x * x` é o seu corpo.
O tipo do parâmetro pode ser omitido caso o compilador consiga inferir pelo contexto.  

Uma função anônima `(x1: T1, ..., xn: Tn) => E` pode muito bem ser expressada utilizando `def`:
~~~scala
def F(x1: T1, ..., xn: Tn) = E
~~~
Se pode dizer então que funções anônimas são  [açúcares sintáticos](https://www.guj.com.br/t/acucar-sintetico/22309). 

Usando uma função anônima para reescrever a função `sumCubes`, ficaria da seguinte forma:
~~~scala
def sumCubes(a: Int, b: Int): Int = 
  sum(x => x * x * x, a, b)
~~~

## Currying <a name="currying"></a>

A definição de funções que retornam funções é tão útil na programação funcional que existe uma sintaxe especial em Scala:
~~~scala
def sum(f: Int => Int)(a: Int, b: Int): Int = 
  if (a > b) 0
  else f(a) + sum(f)(a + 1, b)
~~~

Essa *sintaxe especial* se chama **Currying**.

O que o Currying faz é pegar uma função que recebe múltiplos parâmetros e transformar em uma cadeia de funções, cada uma recebendo 1 parâmetro.  
Essa técnica facilita a criação de funções anônimas, e deixa mais fácil de passar uma função como objeto de primeira classe.  

Além disso, ela abre a possibilidade de aplicá-la parcialmente a função, tornando-a mais flexível, da seguinte forma:
~~~scala
val sumCubes = sum(x => x * x * x)(_, _)

sumCubes(2, 5)
~~~
---
Esse post é o primeiro de uma série sobre Scala, que pretendo escrever a partir de anotações sobre as aulas do curso [Functional Programming in Scala](https://www.coursera.org/specializations/scala).
Apache Kafka tool evaluation related queries
Published: 2020-04-06 14:45:22

Hello All,

I need below information about Apache Kafka tool for data integration and ETL needs:

Development effort:

The development effort , time and  complexity is more in general?

Maintainability:

Is it less maintainable?

Error Handling:

Only possesses  a single log file? or possesses a log and  error port in every transform?
What kind of errors can be handled?

Various teams needed:

Separate Administration team or Unix or NT Admin will suffice needed works. hence it does not need a dedicated administer?

File Structure:

Only able to  read record with single type of delimiter?

Data Integration Capability:

ODI boasts comparatively lesser range of  Data Integration Products and capability which includes many related functions such as profiling and data quality ? Also, if it offers these capabilities then these are  more mainstream in nature?

Market Segments:

Serves medium to large scale companies?

Debugging:

Is it offer easy debugging? Example -just place some  watchers on required places  and intermediate data will be  saved in temporary files for easy viewing. or complex debugging process through debugger?

Company Strategy:

You can download a scaled down free version of their software and plenty of free documents available on internet?

Go live rate:

High “GO Live” success? any know issue during deployment?


Scalability:
Is there any issue with stability? If yes then why is the issue and what is impact?
Which kind of scalability is supported- horizontal, vertical?

Performance:
Can it supports High volume of data movement, transformation and integration (ETL operations)?
How about parallelism - mapping level parallelism, session level parallelism, supports multiple parallel source and multiple target data loads?

Heterogeneous system:
It integrates data from various heterogeneous systems like multiple variety of databases (SQL server, Oracle, DB2 etc), files (XML, XLS, CSV, text etc)?
Targets can be any type of DB , file etc.?

Big Data support:
It can be integrated and used for Big Data?

On cloud solution:
It is available for both- on cloud and on premises platforms?

Pricing:
Is it free ware - open source? Does it come in basic, standard and enterprise editions flavors? If yes , all flavors are free?

Repository:
Does it offers repositories ? Those repositories are for metadata? 
Host for repositires should be relational database?

Push down mechanism:
Do we have pushdown optimization concepts, where it can generate SQL   statements from the   workflow/mapping which   can be directly executed on   database?
It is ETL or ELT tool?

Job scheduling:
Does it come with in-built scheduler?

Version controlling:

Does it offer version controlling?
If yes then it is tightly controlled or moderate?

Tool Bugs:
Any known tool bugs? Any issue due to those bugs?


Anything else you want to highlight?


Thanks,

Rajneesh
Trying to Land the Job?
Tags: beginners, career, promotion
Published: 2020-04-06 14:38:43

---
title: Trying to Land the Job?
published: true
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/3b94jiw9xtum8n0u5djh.jpg
description: 
tags: [beginner, career, promotion]
---
Hey everyone. I'll keep this pretty quick.

I know a lot of people are struggling with COVID. That means there are people who might be graduating from various schools and entering the job search. There are also people who have lost their jobs and need to find a new one quickly.

I published a book, Land the Job, back in January that helps developers navigate the entire process including negotiating a higher salary.

In these trying times, I've decided to give my book away for free. 

You can use this coupon that [I've set up on Leanpub](http://leanpub.com/landthejob/c/gk1zLUeLA5c7). If that doesn't work out, reach out to me and I'll get you a digital copy.

If you need help in your search reach out to me. I'm here to help.
Converting a sorted array to binary search tree in Javascript
Tags: javascript, algorithms, interview, career
Published: 2020-04-06 14:28:12

<h2>Question: given a sorted array, convert it to a binary search tree.</h2>

Let's start by understanding what's a binary search tree is? 

<h3>Binary Search Tree </h3>
<p>A binary search tree is a type of tree in which at any root, the elements in it's left subtree are strictly decreasing and elements in it's right subtree are strictly increasing.</p>

So we've to figure out a way to choose elements from array such that the binary search tree constraints are followed.

This leads to an intuition of picking element at the middle index of a subarray.

Let's understand this:

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

so based on this let's write our solution:

```javascript

var sortedArrayToBST = function(nums) {
    return traverse(nums,0,nums.length-1); // recursively parse through array
};

function traverse(nums,start,end){
    if(start>end){                        // if start>end means left tree or right subtree is not possible so return null
        return null;
    }
    let mid = Math.floor((start+end)/2);       // get the mid index
    let root = new TreeNode(nums[mid]);        // make a new node
    root.left = traverse(nums,start,mid-1);    // now recursively generate left subtree
    root.right = traverse(nums,mid+1,end);     // similarly generate right subtree
    return root;                               // return the root
}

```

That's it ! 

github: https://github.com/AKHILP96/Data-Structures-and-Algorithms/blob/master/problems/convertSortedArrayToBST.js