teleren/devto huggingface dataset:
Example: Imperative vs. Functional
Tags: beginners, tutorial, javascript, webdev
Published: 2019-11-09 10:51:07

---
title: "Example: Imperative vs. Functional"
published: true
description: "Example: Imperative vs. Functional"
tags: ["Beginners", "Tutorial", "JavaScript", "Webdev"]
---

Lately, I got a lot of questions about functional programming.

So here's a small example about the different approaches.

```js
// list of my friends
const friends = [
  { name: "Erwin", drinks: ["beer", "coffee"] },
  { name: "Peter", drinks: ["beer"] },
  { name: "Heidi", drinks: ["water"] }
];

// what do we want to search?
const itemToSearch = "beer";

/***********************************
 * imperative approach
 */

// a place to store the results
let resultImperative = [];

// go over every friend
for (friend of friends) {
  // check if the person drinks this
  if (friend.drinks.includes(itemToSearch)) {
    // add it to the results
    resultImperative.push(friend.name);
  }
}
console.log(resultImperative); // [ 'Erwin', 'Peter' ]

/***********************************
 * functional approach
 */
const resultFunctional = friends
  // check if the person drinks this
  .filter(friend => friend.drinks.includes(itemToSearch))
  // only give me the name
  .map(friend => friend.name);
console.log(resultFunctional); // [ 'Erwin', 'Peter' ]
```

I like the second approach more:
- less complexity,
- increased readability
- constant level of abstraction

**How do you feel about that?**
Gridsome + Eslint: the complete Guide
Tags: gridsome, eslint, productivity, vue
Published: 2019-11-09 09:16:21

While VueJS has the great [Vue Cli](https://cli.vuejs.org/guide/) tool, Gridsome has "not yet" the equivalent.

To install and configure Eslint, we must install our dependencies by hand.

## Install dev dependencies

This article assumes that you already have a Gridsome project installed. If not, you can consult the list of starters on this page: [Gridsome Starters](https://gridsome.org/starters/).

As Gridsome is based on Vuejs, we will use the same recommended tools:

+ [eslint](https://eslint.org/)
+ [prettier](https://prettier.io/)
+ [@vue/cli-service](https://cli.vuejs.org/guide/cli-service.html)
+ [@vue/cli-plugin-eslint](https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-eslint)
+ [@vue/eslint-config-prettier](https://github.com/vuejs/eslint-config-prettier)
+ [eslint-plugin-vue](https://github.com/vuejs/eslint-plugin-vue)
+ [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier)
+ [babel-eslint](https://github.com/babel/babel-eslint)

```shell
yarn add eslint prettier @vue/cli-service @vue/cli-plugin-eslint @vue/eslint-config-prettier eslint-plugin-vue eslint-plugin-prettier babel-eslint -D
```

You have time to have a coffee during the installation !

## Configurations files

In your root directory, create two files: `.prettierrc.js` and `.eslintrc.js`

```js
// .prettierrc.js
module.exports = {
  singleQuote: true,
  semi: false
}
```

And:

```js
// .eslintrc.js
module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/essential',
    'plugin:prettier/recommended',
    '@vue/prettier'
  ],
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
  },
  parserOptions: {
    parser: 'babel-eslint'
  },
  overrides: [
    {
      files: [
        '**/__tests__/*.{j,t}s?(x)',
        '**/tests/unit/**/*.spec.{j,t}s?(x)'
      ],
      env: {
        jest: true
      }
    }
  ]
}
```

Now, you have to add a script in your `package.json` file:

```json
// package.json
"scripts": {
    "build": "gridsome build",
    "develop": "gridsome develop",
    "explore": "gridsome explore",
    "lint": "vue-cli-service lint"
  },
```

And just run:

```shell
yarn lint
```

Happy coding !
Prefer Model.DoesNotExist over ObjectDoesNotExist in Django
Tags: django, python
Published: 2019-11-09 09:00:06

In Django it's very common to see code like this:

```python
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from myproject.apps.teams.models import Team

try:
    user = User.objects.get(pk=1337)
    phone = Team.objects.get(pk=1337)
except ObjectDoesNotExist:
    logging.error("User or Team does not exist")
```

The code will try to fetch an auth user and a team from the database and if either of those does not exist, we'll just log an error. This is so common that I never thought twice when seeing or writing it.

But it turns out that there is a slightly better way to accomplish the same result. I didn't know this before recently, but the Django Model class has its own `DoesNotExist` exception! We can use it like this:

```python
from django.contrib.auth.models import User
from myproject.apps.teams.models import Team

try:
    user = User.objects.get(pk=1337)
    phone = Phone.objects.get(pk=1337)
except User.DoesNotExist:
    logging.error("User does not exist")
except Phone.DoesNotExist:
    logging.error("Phone does not exist")
```

This is better for a couple of reasons:

1. The two except blocks are now more explicit and will only catch exceptions when the specific model does not exist. 
2. This is minor, but you don't have to worry if ObjectDoesNotExist is already imported in the current scope or not.

`MultipleObjectsReturned` exception is implemented the exact same way and if you are curious to learn how Django implements a new Exception type for every subclass that you make, you can check out [the source code here](https://github.com/django/django/blob/85efc14a2edac532df1a9ad4dd9b6d4a4dcf583e/django/db/models/base.py#L124-L141).

My day job codebase currently has 231 occurrences of except ObjectDoesNotExist. I'll slowly start replacing them with model.DoesNotExist 😊
Real-World JavaScript Interview Questions: A New Repo
Tags: javascript, jobs, career, webdev
Published: 2019-11-09 08:22:49

---
title: Real-World JavaScript Interview Questions: A New Repo
published: true
description: A new GitHub repo consisting of JavaScript questions asked at real interviews.
tags: javascript, jobs, career, webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/ugo8zbnmunlh5nra69mu.jpg
---

##There are plenty of random coding challenges and prep questions out there, but wouldn't it be cool to have a list of things that were asked at real developer interviews?

That's the idea behind [Real World JavaScript Interview Questions](https://github.com/RealToughCandy/real-world-javascript-interview-questions).

Whether you're a new developer interviewing for your first job or a battle-hardened senior dev, you can help simply by sharing what JavaScript questions you were asked during your interview(s). 

##There are lots of ways to contribute. Leave a comment here and I'll add it to the repo, create a pull request, DM me...Whatever is easiest for you!

You may also add contextual information such as: how much time you were given to solve the problem, whether or not you were allowed to use additional resources to solve the problem (i.e. Google), the job title, etc. 

I want this to be the go-to repo for people seeking real-life JavaScript interview questions, so if you have any suggestions for improvement please let me know. Thank you!

https://github.com/RealToughCandy/real-world-javascript-interview-questions
Dependency Injection in NetCore
Tags: netcore, csharp, dotnet, beginners
Published: 2019-11-09 08:00:20

---
title: Dependency Injection in NetCore
published: true
description: Brief explanation about dependency injection
tags: netcore, csharp, dotnet, beginners
---

# Dependency Injection in NetCore

Dependency Injection [DI] is a pattern that gives the implementation of a class to an object without needing a Factory or the object knowing how to instantiate it with the intent to decoupling these objects.

We are going to describe the purposes of the three types of patterns available in NetCore: “Singleton”, “Scoped” and “Transient”.

The purpose of Singleton is to instantiate your object only once and then whenever you need that object, you will use the same implementation. This is useful for example for caching.

Then, we have Scoped. When it is applied your object will be instantiated once per request lifecycle. This is useful for example for Repositories or Services.

Lastly, we have Transient. This is the most common of the three because it is going to be instantiated whenever it is invoked.

In NetCore you define your DI inside Startup.cs on ConfigureServices method. Now, let’s see how you can define this.

Singleton:

```
services.AddSingleton<Interface, ImplementationClass>();
```

Scoped:

```
services.AddScoped<Interface, ImplementationClass>();
```

Transient:

```
services.AddTransient<Interface, ImplementationClass>();
```

You can read more about this pattern on:

https://martinfowler.com/articles/injection.html

If you have any doubt don’t hesitate to leave your comments or asking me ​​via [Twitter](https://twitter.com/jpblancodb).
Difference between traditional media and live media in lovesick game
Published: 2019-11-09 07:16:15

After all, Love Sick game is a sunrise industry that is going against a sunset industry. Their trend comparison is reflected in the increasing and decreasing trend of attention (it is predicted that by 2020, the number of live broadcast Love Sick users will exceed 80 million), as well as in the salary and treatment of employees, as well as in the identity dilemma of traditional media. After all, live broadcast in Love Sick game can interact, attract money, and satisfy Qianqi For the entertainment needs of ios support, what's more sad is that many users choose to stay away from the "high-quality content" that some traditional media people cherish by themselves. After all, it's sunny and snowy. They prefer to watch the hot dance performances of the three popular hosts. I believe that everyone here has understood why in the past few months, traditional media for Love Sick game have been so frequently challenged by live broadcast, because it has been promoted by some media people. In a variety of senses, the competition between the host and the group is actually Darwinian without the help of [Love Sick Interactive Stories hack](https://lahasoft.com/love-sick-interactive-stories-cheats/), and the focus of competition is attention, which is an indispensable core resource in the media circle. In contrast, the poor management of traditional media: paper media has been suspended, and the credibility of portal websites has become the target of public criticism. In order to compete for eyeballs, some media Love Sick players have constantly updated the lower limit. This means that, in addition to facing the cold data, all the writers who pretended to be noble in the past have to be questioned and even attacked by users - this kind of comparison is like a siege hammer, hitting the psychological defense line of "the old and the young" all the time.
365 Days of Coding Challenge: Day 7
Tags: codingphase, coding365challenge, beginners
Published: 2019-11-09 05:52:28

---
title: 365 Days of Coding Challenge: Day 7
published: true
description: Day 7 of my attempt to complete 365 days of coding
tags: #CodingPhase #Coding365Challenge #beginners
---

<p>Today is the <strong>seventh</strong> day of my journey to complete <a href="https://codingphase.com">Joe Santos Garcia's (aka CodingPhase.com) Coding365Challenge</a>.</p>

<p>I'm sorry for the late post.  I decided to take a more structured approach for my daily projects.  I began today by starting <a href="http://www.freecodecamp.com">FreeCodeCamp Responsive Web Design Certification course</a>.  I just finished up the section on HTML forms and decided to do a project that would incorporate a <em>little</em> of what I learned.</p>

![#CodingPhase #Coding365Challenge: Idrissa Lemaire Thiam's screenshot on FreeCodeCamp Day 7](https://thepracticaldev.s3.amazonaws.com/i/7xyf1z8ekkfxvv5tw0ut.png)

<p>I thought it would be cool to build a <strong>*simple*</strong> user registration form.  I saw that renowned PHP/MySQL instructor <a href="https://johnmorrisonline.com/">John Morris</a> had a tutorial on this so I decided to watch it and try to implement the code on my own shared server instance.</p>
<a href="https://www.youtube.com/watch?v=n35Jn2nP9iU">
![Excellent tutorial by John Morris (aka www.johnmorrisonline.com) demonstrating database submission from HTML to MySQL database](https://thepracticaldev.s3.amazonaws.com/i/4ysi2jmiohkgcqqh4u08.jpg)</a>

<p>It took a little of bit of debugging some initial database connection errors--hence the late post--but I was able to get it working for use here: <a href="http://www.tech-roi.com/codepen/form.php">http://www.tech-roi.com/codepen/form.php</a>.</p>

<p>Feel free to review the <a href="https://github.com/idrissathiam01/codingphase-coding365challenge/tree/master/day-7">code repository on Github</a> and browse a screenshot of the code below:</p>

![#CodingPhase #Coding365Challenge: Idrissa Lemaire Thiam's code screenshot for Day 7](https://thepracticaldev.s3.amazonaws.com/i/yhxitecs9kasjkq3cy47.jpg)
Recursion - what, why & how
Tags: javascript, recursion, webdev, tutorial
Published: 2019-11-09 04:29:48

**tl;dr** Recursion has real-world benefits, not just to impress interviewers with recursive fizz-buzz or Fibonacci answers. 

# Recursion Overview - The What 
One way I have heard recursion explained is looking into a mirror and with another mirror behind you, visually showing you a reflection, reflecting a reflection...so on Ad Infinitum. 

The metaphor aside, we can just think of recursion for this article's situation as a function that will call itself until a condition is met.
We will eventually show some examples of how to implement recursive functions. 


# Recursion Benefits & drawbacks - The Why

**Some Pros:**
- One of the benefits of recursion is it can potentially reduce [Big O of time, here is a table with different levels of time complexity](https://en.wikipedia.org/wiki/Time_complexity#Table_of_common_time_complexities). In other words, it can potentially increase performance. (Edit: Caveat to this is utilizing memoization when possible.)

- So one of the things I like about recursion is its ability to reduce the surface area of code being executed especially if the inputs are uncomplicated. This can simplify the code at times and even make debugging and testing a bit less challenging. 

- Uncomplicated inputs with repetitive tasks can be distinctly expressed and self-contained. 

**Some Cons:**
- So as I mentioned recursion uses memory, in JavaScript, in particular, the call stack is utilized, in which maximum call stack can be reached. 
So while a recursive function is running it will retain the values in memory until it is completed. 

- If unsuccessfully implemented then it can be slower than iterative approaches. 

- Too many inputs can lead to more complicated termination conditions and recursive inputs. 

# Examples - The How

This recursive function finds an element in an array then constructs an object that gives the index of the found element in the array and a copy of the original array.
```javascript
const numAr = [1, 2, 3, 4, 5, 6];
function numCheck(termN, arrCh, i) {
  console.log(i); // 0, 1, 2, 3
  if (termN !== arrCh[i]) {
    return numCheck(termN, arrCh, i + 1);
  }
  return { number: arrCh[i], indexOf: i, copyArr: [...arrCh] };
}
console.log(numCheck(4, numAr, 0)); 
// { number: 4, indexOf: 3, [1, 2, 3, 4, 5, 6] } 
```

This is a great mathmatical operation that can be expressed with recursion, since there are not very many inputs. 
```javascript
// GCD = Greatest Common Denominator 
 function gcd(x, y) {
  if (y === 0) {
    return x;
  } else {
    console.log(x); // 123432, 120, 72, 48
    console.log(y); //  120, 72, 48, 24
    return gcd(y, x % y);
  }
}
console.log(gcd(123432, 120)); // 24
```

**I might figure out a nice example of tree traversal, nodes or some other structure searching**
Visit to DFW this Winter
Tags: career
Published: 2019-11-09 03:49:50

I'm needing to go back to Dallas, TX this winter to visit family. I want to pair that trip with some learning/networking related events (that would be applicable to someone who doesn't live in the area). I've not yet had the opportunity to do any in-person dev interaction as I live in a rural area. 

If you know of anything going on that might be of interest to me, please let me know. I can flex my travel around any event date.
Robot Class vs Robot Framework vs Robotic Process Automation
Tags: testing, automation, todayisearched
Published: 2019-11-09 02:51:39

In this article i am going to talk about the buzz words around Robot. So, now a days in Software Test Automation we are coming across Robot Class, Robot Framework and Robotic Process Automation frequently. They are all different. Let me explain how.

Robot Class
------------
This is coming from Java AWT package. It is used to trigger the input events like mouse move, mouse click, keypress, etc during test automation. 
An Example:
public class robotic 
{ 
    public static void main(String[] a)
    { 
        String command = "wordpad.exe"; 
        Runtime run = Runtime.getRuntime(); 
        run.exec(command); 
        //instance of Robot class 
        Robot myrobot = new Robot(); 
        // keypress will make the virtual keyboard press 
        myrobot.keyPress(KeyEvent.VK_S); 
        Thread.sleep(100); 
        robot.keyRelease(KeyEvent.VK_S);
        myrobot.keyPress(KeyEvent.VK_O); 
        Thread.sleep(100); 
        robot.keyRelease(KeyEvent.VK_O);
        myrobot.keyPress(KeyEvent.VK_N); 
        Thread.sleep(100); 
        robot.keyRelease(KeyEvent.VK_N);
        myrobot.keyPress(KeyEvent.VK_U); 
        Thread.sleep(100); 
        robot.keyRelease(KeyEvent.VK_U);
    }
}

Wordpad will be opened and Output will be- SONU

There are some of the drawbacks of this class. So not extensively used in test automation. If you use Robot class, you need to make sure that no other window is open during test execution, because Robot class will work on active window. 
This makes parallel running not possible if using this class in code.

Also, if you use keyPress event of this class then you should use keyRelease event if not then it will remain pressed and consume memory in the background.

Robot Framework
----------------
Robot Framework is an open source automation framework for acceptance testing and robotic process automation (RPA). The core framework is implemented using Python and runs also on Jython (JVM) and IronPython (.NET). This is very easy to learn and implement. But, not that popular in market. So,only few people know this framework.

Robotic Process Automation 
--------------------------
Robotic means any entity which is capable of mimicking human action. Process means sequence of steps and Automation means without human intervention. This is new type of automation tools which needs no/ less programming skills. Mostly used for process automation. Most of the things are drag and drop in RPA tools. Market trends shows down the line this will get more popularity. There are many popular RPA tools like UI Path, Automation Anywhere and Blue Prism.

I hope i was able to give you some useful information. You can connect to me at LinkedIn-  https://www.linkedin.com/in/raghwendra-sonu
Understanding the TODOs in your Codebase
Tags: codequality, productivity
Published: 2019-11-09 02:39:06

I've been working on a side project called [tickgit](https://github.com/augmentable-dev/tickgit), which is an experiment in code-based project management.

I put together a small UI which can present the TODOs in public github repos, see `facebook/react` for instance: [https://todos.augmentable.dev/?repo=https://github.com/facebook/react](https://todos.augmentable.dev/?repo=https://github.com/facebook/react)

I'm wondering if this is a useful point-of-view into a codebase, as a way of summarizing items that need to get done. What do you think? Could you see it being useful for the codebases you work on?

I'm thinking about adding some search functionality and parsing out the age of TODOs as well, to have a sort order available...
Where do my saved dev.to articles/blogs go?
Tags: help
Published: 2019-11-09 02:16:13

Hello, dev.to Community

I'm a huge fan of dev.to, I read all sorts of tech articles but unfortunately sometimes because of time constraints I cannot read all the interesting blogs/articles I find on my feed. So I tend to click on the save option with the intent to read them later.

My question, where do I find those saved blogs/articles?

I have looked everywhere.

Help!!!
418 HTTP Status Code: Im a teapot!
Tags: http, webdev, html
Published: 2019-11-09 01:46:27

---
title: 418 HTTP Status Code: Im a teapot!
published: true
description: The http status code 418 is real, and it means "The server refuses the attempt to brew coffee with a teapot"
tags: #http #webdev #html
---

I was building an API, and consulting some http status codes when i saw the 418 status code on the MDN documentation.

> `418 I'm a teapot`
The server refuses the attempt to brew coffee with a teapot.

And this is what the MDN says about it:

> The HTTP 418 I'm a teapot client error response code indicates that the server refuses to brew coffee because it is a teapot. This error is a reference to Hyper Text Coffee Pot Control Protocol which was an April Fools' joke in 1998.

You can check the documentation here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

And here is the RFC:
https://tools.ietf.org/html/rfc2324#section-2.3.2

Then i asked myself: WTF?
Most of you devs may already known this staus code and even its history, but many dont. So, there it goes:

"So, what’s the "418 I'm a teapot" all about? Well, the group of people who make these codes and set the standards is the IETF or "Internet Engineering Task Force". To propose new standards, the members release RFC’s or "Requests for Comments" to the community. Every year since 1989, they release a few humorous RFC’s for April’s Fool Day and on April 1st, 1998, RFC 2324 introduced the "Hyper Text Coffee Pot Control Protocol" or (HTCPCP/1.0). This was a brand new protocol for controlling, monitoring, and diagnosing coffee pots. Now, the RFC is pretty funny with lines like "Coffee pots heat water using electronic mechanisms, so there is no fire. (...) Now, you may be asking, if this is a COFFEE protocol, why the "teapot" code? This is answered in Section 2.3.2. in that "Any attempt to brew coffee with a teapot should result in the HTTP error code 418 I'm a teapot and the resulting entity body MAY be short and stout". And just like that the "418 I’m a teapot" code was born! Since then, it's been used in all sorts of wacky ways. Google even referred to "418" as a different error in their 2013 April Fool's Joke "Google Nose" saying that "418: Scent transfer protocol error" indicates system congestion; please try again later".

from: https://sitesdoneright.com/blog/2013/03/what-is-418-im-a-teapot-status-code-error

So, its just a joke.
Personally, i found it very cool ;P
Java Deep Learning Cookbook released!
Tags: java, machinelearning, books, github
Published: 2019-11-09 00:44:54

Hi All! 
I have posted about my "work in progress" book sometime back:
https://dev.to/rahulraj/java-deep-learning-cookbook-9p4

It's my pleasure to announce that the book is finally released.
https://www.packtpub.com/in/data/java-deep-learning-cookbook


If you have basic knowledge in deep learning & some understanding on DL4J, jump straight to my GitHub repository, clone it and play with it!

GitHub: https://github.com/rahul-raj/Java-Deep-Learning-Cookbook