teleren/devto huggingface dataset:
Insert Delete GetRandom O(1) - LeetCode
Tags: array, hashtable, design
Published: 2020-06-13 09:52:50

---
title: Insert Delete GetRandom O(1) - LeetCode
published: true
description: Design a data structure that supports all following operations in average O(1) time.
tags: array, hashtable, design
---

Design a data structure that supports all following operations in average O(1) time.

1. insert(val): Inserts an item val to the set if not already present.
2. remove(val): Removes an item val from the set if present.
3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Algorithm:

The intuition here is whenever you want to achieve in less time, you have to sacrifice space. So we are gonna use extra space with hash table.

![Delete from set](https://i.imgur.com/v7lw0wW.png)

``` JS
/**
 * Initialize your data structure here.
 */
var RandomizedSet = function () {
  this.nums = new Array();
  this.locs = new Object();
};

/**
 * Inserts a value to the set. Returns true if the set did not already contain the specified element.
 * @param {number} val
 * @return {boolean}
 */
RandomizedSet.prototype.insert = function (val) {
  if (!(val in this.locs)) {
    this.nums.push(val);
    this.locs[val] = this.nums.length - 1;
    return true;
  }
  return false;
};

/**
 * Removes a value from the set. Returns true if the set contained the specified element.
 * @param {number} val
 * @return {boolean}
 */
RandomizedSet.prototype.remove = function (val) {
	if(val in this.locs) {
		let loc = this.locs[val];
		let lastEl = this.nums[this.nums.length - 1];
		this.nums[loc] = lastEl;
		this.locs[lastEl] = loc;
		this.nums.pop();
		delete this.locs[val];
		return true;
	}
	return false;
};

/**
 * Get a random element from the set.
 * @return {number}
 */
RandomizedSet.prototype.getRandom = function () {
	return this.nums[Math.floor(Math.random() * this.nums.length)];
};
```
Optimize Twitch stream browsing - just see dev streams you like
Tags: twitch, adblock, programming, streams
Published: 2020-06-13 09:48:16

If you are like me and browse the Twitch "[Science & Technologie](https://www.twitch.tv/directory/game/Programming)" section from top to bottom to find some interesting dev streams you are familiar with this image:

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

animal cams, rocket launches, radio stations,...nothing bad about them but it makes it hard for me to find streams I'm interested in. 
Yes, you can use tags or a search but I like to find new dev streams and like to scroll to the bottom!

Luckily you can tweak the page with uBlock a bit! Add a custom block filter:
```
##[data-a-id="card-channel_name"]
```
and remove the cards you don't want to see! 
It won't free the space unless you have a whole row but still it makes it way easier to find awesome streams - even if they are at the bottom of the list!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yxkoxz6bkh2cfee43js4.jpg)
How to read Medium articles for free?
Tags: medium, articles, premium, paid
Published: 2020-06-13 09:15:01

You all know Medium right where you can publish articles and read articles from various authors. We can say that Medium platform is like a Social Journalism. Many authors are earning from Medium based on time spent on the article by the user. Medium encourages to create the larger articles which is know for the content.

Many people want medium for free there is one trick to get the medium for free life time I think if it works forever.

I will give you a YouTube video link so that you can access for free.

Youtubelin: https://www.youtube.com/watch?v=LrdfscqIGfI
Reuse component functionality with the Vue wrapper component pattern
Tags: vue, components, designpatterns
Published: 2020-06-13 09:09:52

---
title: Reuse component functionality with the Vue wrapper component pattern
published: true
description: A component design pattern to extend and reuse base component functionality
tags: 
 - vue
 - components
 - designPatterns
---

When building Vue components I often need to create a component that has similar functionality to an existing base component. I want to re-use the base component and extend it to create a new one.  A good pattern for this is the wrapper component.

Think of a `BaseButton.vue`. It takes some props and emits some events:

```
<template>
  <button
    :class="`btn btn-${theme}`"
    :disabled="disabled"
    @click="handleClick"
  >
    <slot />
  </button>
</template>

<script>
export default {
  name: "BaseButton",
  props: {
    theme: {
      type: String,
      default: "info",
      validator: val =>
        [
          "info",
          "success",
          "error"
        ].indexOf(val) !== -1
    },
    disabled: {
      type: Boolean,
      default: false
    }
  }
  methods: {
    handleClick() {
      this.$emit("click");
    }
  }
};
</script>

<style scoped>
.btn {
  outline: none;
  border: none;
  color: white;
}
.btn-info {
  background: blue;
}
.btn-success {
  background: green;
}
.btn-error {
  background: red;
}
</style>

```

I now have a need to build a button that shows a loading state with some text and disables the button when passed a prop of `loading`. I could cram this new functionality into the BaseButton, but a much cleaner solution is to use a wrapper component pattern. Let's create a `LoadingButton.vue`.

```
<template>
  <BaseButton v-bind="{ ...$props, ...$attrs }" v-on="$listeners">
    <template v-if="loading">Loading...</template>
    <slot v-else />
  </BaseButton>
</template>

<script>
import BaseButton from "~/components/BaseButton";
export default {
  components: {
    BaseButon
  },
  props: {
    ...BaseButton.props,
    loading: {
      type: Boolean,
      default: false
    }
  }
};
</script>
```

A couple of this are happening here:
* Pass all the components instance details down to the base components via `$props`, `$attr`, `$listeners`. [See more Vue in the docs](https://vuejs.org/v2/api/#vm-attrs).
* Use `BaseButton.props` to maintain the same props passed down but add additional `loading` prop to create the new functionality.

A great little pattern for component reusability &#128293;

Originally posted on [https://matthewblewitt.com/posts/vue-wrapper-component](https://matthewblewitt.com/posts/vue-wrapper-component)
Laravel Eloquent Relationships Tutorial with Examples From Scratch
Tags: laravel, laravel7, php, laraveleloquent
Published: 2020-06-13 08:51:44

The Eloquent ORM that comes with Laravel makes it incredibly easy to interact with a database. It is like Eloquent models themselves; relationships also serve as an essential query builders, representing the relationships as methods provide powerful method chaining and querying capabilities.

Today we'll look at how we can use Eloquent to interact with our database.

## How Does Eloquent Work?


A `Article` model will correspond to a 'articles' table in the database. Since we have convention when creating our models and database tables, we can easily call data from our database.

For example, to get all articles from a 'Article' model, all you would do is `Article::all()`. Using this function would query the database and generate the proper SQL command. Here are some quick examples:

| Description   |      Function      |
|----------|:-------------:|
| Find all articles |  Article::all() |
| Find a record |    Article::find(id)   |
| Delete a record | Article::delete(id) |

## Types of Eloquent Relationships in Laravel
* One To One
* One To Many
* Many To Many
* HasOne & HasMany Through
* Polymorphic Relations

## One to One Relationship with Example
One to one relationship is one of basic relationships. For example, a User model would be associated with a Address model. To illustrate this relationship, we can create a address() method within the User model and call the hasOne() method to relate the Address model.
{% youtube  m0IsbkfONL4 %}

## One to Many Relationship Example
One of many relationships determines a relationship where one single model owns the number of the other model. For example, a blog author may have many post.
{% youtube  rb2Tf8zByRU %}

## Many to Many Relationship Example
Each post have many tag and each tag can have many post.To define many to many relationships, we use belongsToMany() method.
{% youtube  JQ01o10Mva4 %}

**Adding & Retrieving Pivot Table Columns in Many To Many Relations**
{% youtube  HoPol7IBo3g %}

**Handle events on attach, detach or sync in Many To Many Relations**
{% youtube  zt2DuEVht1M %}

## HasMany Through
The “has-many-through” relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. For example, a Country model might have many Post models through an intermediate User model. In this example, you could easily gather all blog posts for a given country. Let’s look at the tables required to define this relationship:
{% youtube  UMRaECFcvCM %}

**has-many-through relation using Pivot model**
{% youtube  67dzvpebcgA %}

## Polymorphic Relationship
A polymorphic relationship is where a model can belong to more than one other model on a single association.

**One to Many & One to One Polymorphic Relationships**
{% youtube  QAfTYrDhdHE %}

**Many to Many Polymorphic Relationship**
{% youtube  tdCw3mW1ccQ %}
drow name generator and meanings
Published: 2020-06-13 08:50:44

I have assembled four random name generators for Drow characters and their noble homes. I started with a wide variety of resources, including the Forgotten Realms wiki; my book, Drow or Porphyra; an older but wonderful article in Dragon magazine; and drow dictionaries online. I then added new meanings and adjusted as best I could. There are now three different ways to use the generators.
https://drownames102.blogspot.com/
Making Sense of the Web (Introduction)
Tags: webdev, design, computerscience
Published: 2020-06-13 08:48:26

####Welcome to "Making Sense" 🌈

I've been learning web development for close to 3 years now.
It has been quite a challenge , like climbing a mountain. I've not reached the summit yet , but in my hike so far , I've made many mistakes that had almost even halted my progress. I've had to retrace my steps , hike back up but I think I'm beginning to see the horizon , albeit having not reached the summit yet.

This full-stack web development bootcamp is intended to help others hike up , and while doing so , avoid the mistakes I've made.

This course will be delivered bi-weekly in 10-15min long reads starting all the way from the beginning to HTML and CSS ,then through Javascript , Databases and Frameworks like React, Node etc. Each post will be labelled in sequential order as MS [number].

There will also be bonus articles , detailing over UI design , font choices , code editor setups , learning methodologies and so on. 

####Why Should I learn Web Development? 🌈

Before you start learning anything , you need to understand if it checks the right boxes for you.

If you're artistic or like building things and tinkering with them, Web Development might be for you. A Web page , starts out as a blank canvas , an empty document and if you're enthused at all by the fact , that you have the potential to fill it with beautiful functionality , Web Development's for you.

Web Development is in fact a great career choice too. It's a great freelancing option , and with the sudden explosion of demand for Full-stack web developers since the introduction of NodeJS , the indicators for web development to be a well-paid career choice is stronger than ever. 

It's also a great starting point for Computer Science students who are just starting out with college. Web development is a great way to express your ideas. 
It's also a great introduction to real-world programming. JavaScript is somewhat of a de-facto language for the web. It's tricky but it's very powerful , but most importantly , it's never going away. It will always stay relevant.

####What's next? 🌈
The next part of the course , will introduce you to the mentality that you should adopt while learning to code.
Avoid CORS in Nuxt.js with @nuxt/proxy
Tags: nuxt
Published: 2020-06-13 08:46:08

In a modern web application, we separated between front-end and back-end for flexible work. But *CORS* always happened on development if you don't know about `CORS`, please check [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)   

In this case, we gonna take look '@nuxt/proxy' module to avoid CORS.

# Let's start !
I assume you already have a nuxt.js project then you just install '@nuxt/proxy'  

```
npm i @nuxt/proxy
or
yarn add @nuxt/proxy
```

Add `@nuxt/proxy` to moduless in `nuxt.config.js`

```javascript
{
  modules: [
    '@nuxtjs/proxy'
  ]
}
```
then add key you want to be a proxy like this
```javascript
{
  proxy: {
  '/api/v1': { target: 'API_URL', pathRewrite: {'^/api/v1': ''} }
  }
}
```
now, when you call API you just add prefix to path in this case I'm gonna use `axios` to send request HTTP to my server like this 
```javascript
const PATH_API = '/service'
axios.get(`/api/v1${PATH_API}`);
```

Done !! 

If I missed anything, please let me know Thank you :)
What is React JS - Introduction
Tags: react, javascript, codenewbie, webdev
Published: 2020-06-13 08:36:20

React is a Javascript library used for building fast and interactive user interfaces. It is developed by Facebook in 2011. Today, React is very popular with **144k** stars on [Github](https://github.com/facebook/react).

> **React** is a Javascript library used for building fast and interactive user interfaces.

React is used to build single-page applications or mobile applications. You can create complex user interfaces using small isolated pieces of code called components.

## Components in React

Components are building blocks of a React App. A component represents a piece of User Interface like buttons, textbox, etc. It is a javascript function or class which accepts properties(props) and returns a react element that describes how a section of UI should appear.

![React Component](https://firebasestorage.googleapis.com/v0/b/hackinbits.appspot.com/o/react.png?alt=media&token=381453c0-293b-4e14-ab83-a3c43c52af03)

> A Component is a javascript function or class which accepts properties(props) and returns a react element that describes how a section of UI should appear.

## Props and State

There are two types of "**modal**" data in React:
- props and,
- state

**Props:** Props are used to send data to the component, it is equivalent to the arguments of the javascript function. Parent component can pass data to the child component using props.

**State:** State is a javascript object that is initialized and managed by the component. It is like a data store for the react component.

# Virtual DOM

When the state or props of a component change, react renders the component using new data(props and state). However, react does not work on the DOM directly. Instead, it creates a virtual DOM in the memory and compares it with the original DOM. If there is a difference, react updates the real DOM to sync with the virtual DOM.

![Real and Virtual DOM](https://firebasestorage.googleapis.com/v0/b/hackinbits.appspot.com/o/react2.js.png?alt=media&token=bd69b0c6-8c57-43ee-b9fc-e6dc1c8de78f)

React updates only the part of DOM which is modified instead of rendering the whole page again.

In the next article, we will discuss some of the core features of React JS.

## Additional Resources
- [**Intro To React (reactjs.org)**](https://reactjs.org/tutorial/tutorial.html)


----

**If you liked this article, please upvote and recommend it. Feel free to ask any questions in the comments below.** 

----
**This article was first published on [hackinbits.com](https://hackinbits.com/articles)**
**We publish articles on web development and technology frequently. Consider subscribing to our newsletter or follow us on our social channels ([twitter](https://twitter.com/hackinbits), [Facebook](https://www.facebook.com/hackinbits/), [LinkedIn](https://www.linkedin.com/company/hackinbits)).**
How to calculate dot product in perceptrons?
Tags: machinelearning, datascience, neuralnetowrks, numpy
Published: 2020-06-13 08:07:15

Neural networks are a collection of individuals nodes called as artificial neurons or **perceptrons**.
Each perceptron takes in an input array, multiples it with weights array and add a bias value to create a computed sum.
This computed computed is passed to an activation function to compute the final output value of a neuron.
We can see the basic parts of a perceptron below:
![Example of a perceptron](https://res.cloudinary.com/dk22rcdch/image/upload/v1592035333/Blogimages/Perceptron.001_mw0jtq.jpg "Example of a perceptron")
We can calculate the summation value of neuron inputs, weight and bias in the for a sample neuron as explained in example below:
```python 
#Example of dot product using bumpy
import numpy as np
#Sample input to perception
inputs = [1.2, 2.2, 3.3, 2.5]
#Weights passed to perception
weights = [0.4,0.6,-0.7, 1.1]
#bias for a particular perception
bias = 2
#Take dot product between weights and input 
#and add bias to the summation value
output = np.dot(weights, inputs) + biasprint(output)
#Output:-4.24
```
Here **np.dot** function is used to calculate dot product between the input and the weights. 
Internally it works as follows:
![Calculation of Dot Product](https://res.cloudinary.com/dk22rcdch/image/upload/v1591670631/Blogimages/Screenshot_2020-06-09_at_8.11.53_AM_fyqgqd.png "Calculation of Dot Product")
The output value from above function is fed to an activation function to calculate final value of a perceptron. I will cover various activation functions and their working in another article since it is a vast concept requiring it's own article.
That's it for today's short tutorial on dot product using bumpy.
You can follow me on [Twitter](https://twitter.com/saurabhnative) or [LinkedIn](https://www.linkedin.com/in/saurabh-mhatre/)  
Reference:[Neural  Networks from Scratch by SentDex](https://www.youtube.com/watch?v=tMrbN67U9d4&t=807s)
10 Phone skins in CSS
Tags: css, html, imageless, purecss
Published: 2020-06-13 08:28:08

![Phones in CSS](https://dev-to-uploads.s3.amazonaws.com/i/6szjz96pz5tn59oqnb0z.jpeg)

A while ago after I did an [iPhone](https://zubach.com/iphone) and [Lumia](https://zubach.com/lumia) in CSS and a touch of JavaScript (for basic functionality like `lock` & `unlock` the device), I was contacted by one company to re-create 10 specific android skins in CSS. I did the order quickly in my spare time but never had a chance to share them publicly.

Now I guess is a time, ~8 years after the work was done 🤪

So, here's the list:

> You can check the entire collection page on Codepen - [Imageless Devices in CSS](https://codepen.io/collection/nVyxOk).

## Default Android Device Skin 4"

{% codepen https://codepen.io/vasyl-zubach/pen/MWKyBeP %}

## Galaxy S4

{% codepen https://codepen.io/vasyl-zubach/pen/vYLGzQV %}

## Galaxy S3

{% codepen https://codepen.io/vasyl-zubach/pen/rNxeZPy %}

## Galaxy Note 3

{% codepen https://codepen.io/vasyl-zubach/pen/OJMNoqe %}

## Nexus 5

{% codepen https://codepen.io/vasyl-zubach/pen/KKVzxLz %}

## HTC One

{% codepen https://codepen.io/vasyl-zubach/pen/dyGMqEj %}

## Sony Xperia Z1

{% codepen https://codepen.io/vasyl-zubach/pen/jOWqvjW %}

## Lenovo VIBE X

{% codepen https://codepen.io/vasyl-zubach/pen/ExPKeBb %}

## Ascend Mate 2

{% codepen https://codepen.io/vasyl-zubach/pen/gOPrdNJ %}

## Xiaomi Mi3

{% codepen https://codepen.io/vasyl-zubach/pen/yLeOxmV %}

Which one do you like more? ;)
MLB Draft '20 by the Numbers
Tags: javascript, dataviz
Published: 2020-06-13 08:01:13

With no baseball being played so far in 2020, there hasn't been anything incredibly interesting to analyze or look at besides historical data (in the MLB at least). On June 10th and June 11th, however, we finally got our first bit of new MLB information to play around with - the draft. I've taken data from Rounds 1-5 and compiled them into some (hopefully) interesting visuals.

<h1>Picks by State</h1>

Let's start with a simple question. What state produced the most sought after baseball talent this year? California. The values used for the visual below may not reflect where a player was born and raised, rather it is the location of the high school or college the player was drafted from. This also excludes Owen Caissie and David Calabrese of Ontario, Canada.

{% codesandbox 9h3b5 %}

---

<h1>Picks by Position</h1>

Next, let's look at draft picks by position. This includes every single pick - all 159 of them. As you can see in the chart below, pitchers were definitely shown some love while first basemen lagged behind (Although the #1 pick Spencer Torkelson played 1B, his primary position was marked as OF on MLB. This is likely the case for many utility players).

{% codesandbox z3g7e %}


So who <strong>didn't</strong> take any pitchers? Only <em>three</em> teams! The Detroit Tigers, Tampa Bay Rays, and Milwaukee Brewers.


---

With all of these pitchers being picked, let's see how the top 5 picks compare to one another using WHIP, ERA, BB/9, HR/9, and H/9. Not that these metrics alone tell you the sole offensive value of a pitcher, I just chose them for fun. (FYI for non-baseball fans, for all of these metrics a lower number is preferable).

<h1>Top 5 Pitcher Metrics Heatmap</h1>
{% codesandbox kwx6p %}

I'd love to do many more draft visualizations and maybe even dip into some KBO numbers, but for now I'm going to call it a night! Thanks for stopping by.
My first attempt at using python's selenium
Published: 2020-06-13 07:58:50

- This post below will be about what my experience was like using python's selenium. 

### Reason for wanting to learn selenium in the first place
I love automation, it's really cool when you can become more productive by allowing a bot to do repetitive work for you. I had a great project idea that I wanted to implement that involved selenium and youtube. In my subscription feed I had channels where i would watch all their videos everyday. Everyday I would add the videos to either a watch later playlist or add it to queue. I wanted a way for a program to do this for me.

### Results of using selenium
The selenium docs are pretty clear and straight forward. My first task was to setup selenium and chrome webderiver. This took some time because I had to configure the path to my downloaded chrome webdriver and set a path to my chrome location. If you have your chrome in it's default location (where it usually would be when you finish downloading it) this wouldn't be a problem for you. After configuration, I was able to open a site using selenium. I soon realized that I couldn't sign in to google because google was protecting my account from selenium. I scrapped my project idea, but it was fun just openning up a website page automatically. 

### Future
In the future I plan to use selenium for testing, a new project, or some simple task where I click something everyday.

[Resource I used to setup and use Selenium](https://www.youtube.com/watch?v=Xjv1sY630Uc)

Thanks for reading.