teleren/devto huggingface dataset:
Sweet & Sour mongoose.js methods 
Tags: javascript, mongodb
Published: 2019-09-08 22:32:46

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/7stgzy0pd027w7ssm85k.png)

I’ve been using Mongoose (ODM library for MongoDB) quite a bit for the authentication project. NoSQL databases like MongoDB do seem more flexible for web apps which depend quite a bit on user interaction. Example a user might decide to login with a social media account or register with their email, a password and secret question-answer.

I find it way easier to write a mongoose method that deal with updating app.js, user.js, routes.js every time a user decides to do something a bit different!

Here is a short mongoose.js method which is a pre-save hook. It will check if a username exists in your schema. If the username exsists it will return an error, if not then the method will facilitate the saving of the username to the db: The method is essentially a function unto your user schema.

<pre>
UserSchema.pre("save", function(next) {
    const self = this;
    User.find({
        name: self.name
    }, function(err, docs) {
        if (!docs.length) {
            next();
        } else {
            console.log("user exists: ", self.name);
            next(new Error("User exists!"));
        }
    });
});
</pre>

ps: I'll keep editing this document & add in more functions
Cycling, Javascript and Saving the Planet
Tags: cycling, javascript
Published: 2019-09-09 13:35:32

---
title: Cycling, Javascript and Saving the Planet
published: true
tags: cycling,javascript
canonical_url: https://ohryan.ca/2019/09/08/cycling-javascript-and-saving-the-planet/
---

A few weeks ago I bought a basic road bike with the intention of cycling to work. And I’m totally hooked! Addicted maybe? I think I finally _get_ it.

My primary reason for biking to work is to level up the amount of exercise I get in every week, but I’m aware that leaving the car at home has some obvious side effects. By burning less gasoline I’m obviously saving some money and I’m keeping some amount of carbon out of the air.

Meanwhile, I’ve been looking for a good practical way to level up my vue.js skills. So I challenged myself to build a simple tool in vue.js to help me quantify just how much CO<sub>2</sub> I’m leaving in the tank and how much money I’m leaving in my wallet.

The result [biketoworkcalculator.com](https://biketoworkcalculator.com)

[![](https://i1.wp.com/ohryan.ca/wp-content/uploads/2019/09/Screenshot_2019-09-08-Bike-To-Work-Calculator.png?w=1100&ssl=1)](https://biketoworkcalculator.com)

It’s a dead simple tool that allows you to roughly calculate CO2 and dollars you save by riding a bike. Check it out for yourself.

I was actually quite surprised that biking only one day per week would save me around $10 in gasoline over the course of a month.

* * *

If you’d like to look at the code or correct my math or whatever, it’s up on github: [https://github.com/ohryan/biketoworkcalculator](https://github.com/ohryan/biketoworkcalculator)

Oh and if you’re in to cycling, follow me on [Strava](https://www.strava.com/athletes/41148252).

The post [Cycling, Javascript and Saving the Planet](https://ohryan.ca/2019/09/08/cycling-javascript-and-saving-the-planet/) appeared first on [ohryan.ca](https://ohryan.ca).
Hello World, I work with Jack Bauer and create my own content and products
Tags: css, html, webdev, teespring
Published: 2019-09-08 22:15:18

This is just a quick hello world post I've just joined Dev to leave a comment. I'm leaving a comment on a post about ruby on rails web scraping... Might as well take this opportunity to say hello, I get as much satisfaction from data analysis as I do from producing videos and analysing markets for viable internet marketing opportunities. 

Paid client work is (sometimes) great, but self sufficiency is my trajectory. So I've spent 25+ years intensely immersed in anything involving a CPU, mouse, keyboard or screen in order to create and market content of value, be it a social media campaign promoting a network of livestreaming gamers, a Wordpress Plugin to address a need of my own or compiling footage in Premiere, producing it in After Effects and publishing it in YouTube, with all the associated SERPs relevant work that accompanies it (audience research, hashtag and keyword analysis, psychology driven profiling to inform everything from content presentation to timing posts for maximum impact in accordance with the intent of the potential visitors).

I'm a Microsoft Certified Professional, Adobe Expert, Amazon Influencer and BSc Hons Games Programmer. I use automation to reduce the neccesary for outsourcing in order to scale.

I run 360fov, AndGamers, the recruitment helper and my latest web dev and SEO client is Kiefer Sutherland.
A simple way to keep your Vue page title in sync with the router
Tags: javascript, vue, beginners, webdev
Published: 2019-09-08 22:11:10

---
title: A simple way to keep your Vue page title in sync with the router
published: true
description: a short guide how to set up sync between router and page title using watcher and router meta fields
tags: javascript, vue, beginners, webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/3ejj191ton9gleio8xpk.jpg
---

I have noticed in quite a few projects that developers forget to keep page title updated with the router or maybe think that they will do it tomorrow as it is such a small feature :). It always makes sense to keep the title synchronized with the contents for several reasons:
- helps users with more than one tab 
- important for website analytics


I will show you how to do it with the standard [vue-router](https://github.com/vuejs/vue-router).

## Step 1: Declare route meta in your router config

First things first, let's add some additional metadata to our standard routes:

```javascript
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomePage,
      meta: {
        auth: true,
        title: 'Dashboard'
      }
    }, {
      path: '/login',
      name: 'login',
      component: LoginPage,
      meta: {
        auth: false,
        title: 'Login'
      }
    }, {
      path: '/buckets',
      name: 'buckets',
      component: BucketsPage,
      meta: { auth: true, title: 'Buckets' }
```

More docs on the router package can be found [in the official vue router website](https://router.vuejs.org/guide/essentials/dynamic-matching.html#reacting-to-params-changes).

## Step 2: Add $route watcher in your App.vue

Go to your Vue main .vue file (it should have a `<router-view></router-view>` component) and add a watcher:

```javascript
    watch: {
      '$route' (to, from) {
        document.title = to.meta.title || 'Your Website'
      }
    },

```

This will set a title as your page title (if you specified a meta field for that route). I have tried to achieve the same with router navigation guards but `$route` watcher seemed like the simplest solution. 

Looks easy, right? :) Feel free to experiment and define more fields in the router meta like page description and anything else you want to be set for that page. Then modify the watcher to also use them. 

Hope this helps!
How to handle a nodeback in ReasonML
Tags: ocaml, reason, bucklescript, node
Published: 2019-09-08 22:07:59

---
title: How to handle a nodeback in ReasonML
published: true
description: A technique for using type-safe functions in place of NodeJS callbacks
tags: ocaml,reason,bucklescript,node
---

NODEJS callback-style programming entered the JavaScript developer's toolbox a few years ago and brought with it the term 'nodeback', short for (I guess) 'node callback'. The idea of this callback is that it gets called with upto two arguments: an error value xor a success value, representing that the previous operation failed or succeeded and letting the programmer decide what to do next. [For example](https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_readfile_file_options_callback):

```javascript
fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});
```

Although the nodeback style of programming has mostly been superseded in the JavaScript world, thanks to the advent of promises and async/await, developers still occasionally have to deal with it.

The problem with this callback is that either of the parameters might be `undefined`, and you have to, every time, manually implement the logic of the callback in such a way that the `data` is not accessed if there is a non-empty `err`, and vice-versa.

In strongly, statically-typed languages like ReasonML, we have the ability to wrap up this unsafe API, with a slight runtime overhead, in a much more type-safe and ergonomic API. Here's the wrapper:

```ocaml
let nodeback(f) = (. err, result) =>
  switch (err, result) {
  | (Some(err), None) => f(Js.Result.Error(err))
  | (None, Some(result)) => f(Ok(result))
  // Throw if APIs break nodeback 'guarantee':
  | _ => invalid_arg("Nodeback arguments invalid")
  };
```

You can use this like so (with a hypothetical `Node.Fs.readFile` binding):

```ocaml
Node.Fs.readFile("/etc/passwd", nodeback(fun
  | Error(err) => raise({j|$err|j}) // Can't access data in this branch
  | Ok(data) => Js.log(data)), // Can't access err in this branch
);
```

The way `nodeback` works is, it takes as input a type-safe `result`-handling function and converts it into a nodeback (formatted to highlight the input and output):

```ocaml
let nodeback:
  (Js.Result.t('a, 'e) => 'b)
  =>
  (. option('e), option('a)) => 'b;

```

You can use the `nodeback` wrapper to get its type-safety benefits, while passing the JavaScript side the nodeback that it expects.

[EDIT: see correction and full working example in the [comment below](/yawaramin/comment/ge32)]
Series: How YOU can build a Serverless GraphQL API leveraging microservices
Tags: webdev, graphql, tutorial, docker
Published: 2019-09-08 22:01:02

---
title: Series: How YOU can build a Serverless GraphQL API leveraging microservices
published: true
cover_image: https://thepracticaldev.s3.amazonaws.com/i/fectyfh3w86dwdxtovp3.jpg
description: A series describing how you can build a GraphQL API that pulls in data from microservices. This API is then hosted as a serverless function in the Cloud
tags: webdev, graphql, tutorial, docker
---
Follow me on [Twitter](https://twitter.com/chris_noring), happy to take your suggestions on topics or improvements /Chris

> I've written a two-part series explaining a quite common situation. You have 1 or more services where there is a team maintaining each service and it thereby lives its own life. 

Sometimes you might need to build an app that needs to read from a few of these services. Instead of doing a bunch of HTTP calls, wouldn't it be great if we had something like GraphQL in front of these services so the builder of the new app can query for just the data they need? The GraphQL ends up using the URL of these services, as we Dockerize them and thereby we have a very loosely coupled approach between the GraphQL API and the Services. It's loosely coupled in the sense that the services don't know about the GraphQL API and the GraphQL API can easily replace a data source for another that conforms to the same schema, after all, it's just a URL. 

I'm assuming in this series that we won't be using the GraphQL API so often, so it doesn't make any sense to give it the same uptime and thereby the same cost as the other business-critical services. Also, the GraphQL can be seen as a computation of the results it pulls in and doesn't really need to have a state of its own. Thereby it's an ideal candidate to make Serverless. 

These are the two parts:

- [Building the services and the GraphQL API](https://dev.to/azure/learn-how-you-can-build-a-serverless-graphql-api-on-top-of-a-microservice-architecture-233g)
Here we are showing how we build the services and containerize them with Docker and thereby makes them ready to easily be pushed to the Cloud. We also show how we pull in the Dockerized services, and their URLs, and build our GraphQL API
- [Sign up for a free Azure account](https://azure.microsoft.com/en-us/free/?wt.mc_id=devto-blog-chnoring)
To create Serverless Azure Functions you will need a free Azure account
- [Moving to the Cloud](https://dev.to/azure/learn-how-you-can-build-a-serverless-graphql-api-on-top-of-a-microservice-architecture-part-ii-deploy-it-to-the-cloud-26b6)
Here we are pushing each of the services to a Container Registry in the Cloud and we also create a service endpoint from each of the services. We also create a Serverless app and a function and call our GraphQL API from it. Then we bring the Serverless app to the Cloud using VS Code.
Is Ruby worth learning in 2019? 
Tags: ruby, webdev, discuss, career
Published: 2019-09-08 21:43:02

---
title: Is Ruby worth learning in 2019? 
published: true
description: Is it a bad investment if you dedicate all your time and money to learning Ruby along with Ruby on Rails?
tags: ruby, webdev, discuss, career
---

##Is Ruby worth learning in 2019? 

A subscriber asked me this, and it's a great question for numerous reasons. Firstly, some bootcamps still teach it, despite its decreasing adoption rates in enterprise development settings.

Secondly, Ruby on Rails (RoR) is one of the earliest backend web frameworks to hit the scene in late 2005. Despite its OG status, it seems to be falling off the popularity chart. Does that mean you should avoid it, along with the language that was used to build the framework? 

Is it a bad career investment if you dedicate all your time and money to learning this language along with RoR?

###Let’s see what the developers say. Over 200 devs responded to my poll, but what do YOU think? Should you learn Ruby this year?
Learning Xojo - episode 1
Tags: xojo, learning, beginners
Published: 2019-09-08 20:41:27

---
title: Learning Xojo - episode 1
published: true
description: A log of me learning Xojo
tags: xojo,learning, beginner
cover_image: https://thepracticaldev.s3.amazonaws.com/i/627enjy10myu461tjxut.png
---

I recently starting working for a company who have decided to migrate their platform, bit by bit into Xojo from a Node/React platform. 

Those of you who have never heard of Xojo, It's a cross platform development environment that ports out to Web, Windows, Mac, Linux and IOS.

if you want to know more go have a read yourself at [Xojo.com](https://xojo.com)

## The visual dilemma

When writing a web application, I at least expect to write some HTML and CSS. With Xojo this is not the case. When you download Xojo it comes with it's own editor. The editor has a WYSIWYG editor. So all the UX is done with drag and drop and styling is achieved by clicking buttons and adjusting sliders. you'll see what I mean by that when I start to show you screen shots. 

## Coding in Xojo *forget the semi-colon*

When I first started learning how to code, one of the first languages I started with was Visual Basic. But I quickly changed to C# never expecting to ever really use the VB syntax ever again! well...**How wrong was I??**

The Xojo coding syntax is pretty much and exact copy of VB. Adding click code is done in the same way as visual studio. You double click an Element in your designer and it opens up an event handler in a code editor. This reminds of using the VBA Editor in Excel too. 

## The point of this blog series

I'm hoping to document my learning process as I go. I'll make a real life application and share the journey on here. Hopefully it'll be fun for all!!

orrrrrrr.....I'll make an ass of myself.
How to display observable of an object in angular
Tags: observable, rxjs, typescript, angular
Published: 2019-09-08 20:34:57

---
title: How to display observable of an object in angular
published: true
description: A simple way to display observable of an object in angular.
tags: Observable, rxjs, typescript, angular
---

It is very easy to display observable in angular using the async pipe.

For example,

If you wanna display an observable of string in angular, it will go like this =>

demo.component.ts
```
import { Component, OnInit } from '@angular/core';
import { Observable, of } from 'rxjs';

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.scss']
})
export class DemoComponent implements OnInit {
  astring$: Observable<string>;
  
  constructor() { }

  ngOnInit() {
    this.astring$ = of("Hello Observable!!!")
  }

}
```

demo.component.html

```
  <p *ngIf="astring$">
    {{ astring$ | async }}
  </p>
```
#### Results

Hello Observable!!!

## Display an observable of object

Similar way, we can display observable of the object also.

demo.component.ts

```
import { Component, OnInit } from '@angular/core';
import { Observable, of } from 'rxjs';

export interface Person {
  name: string;
  place: string;
}

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.scss']
})
export class DemoComponent implements OnInit {

  myself$: Observable<Person>;
  
  constructor() { }

  ngOnInit() {

    this.myself$ = of({
      name: 'Amrish',
      place: 'Bangalore'
    })
  }

}

```

demo.component.ts

```
<div *ngIf="myself$">
  <p>Name: <span>{{ (myself$ | async).name }}</span></p>
  <p>Place: <span>{{ (myself$ | async).place }}</span></p>
</div>
```   

Result is

Name: Amrish
Place: Bangalore

---

And also the most efficient way to display it will be

demo.component.ts
```
<div>
  <div *ngIf="myself$ | async as myself">
    <p>Name: <span>{{ myself.name }}</span></p>
    <p>Place: <span>{{ myself.place }}</span></p>
  </div>
</div>
```
Manage metadata in JSON (for instance for visualizations)
Tags: discuss, json, java
Published: 2019-09-08 19:03:05

Hi all,

I just thought about how best to add metadata to for instance object keys in JSON.

For instance as I'm engineering an Open Source temporal document store, I'm storing some metadata in the binary encoding for each node. Optionally SirixDB for instance stores the number of descendants of objects, object keys and arrays, it optionally stores hash-codes for integrity checks and speeding up diff-computations and so on. Furthermore it would be great to be able to serialize the unique, stable 64 bit integer node identifiers.

Now, I want to serialize this additional data into the serialized JSON format. In the XML serialization I simply added attributes in a special namespace for the elements.

However, how would you serialize this stuff in a JSON document?

Kind regards
Johannes
Schedule Live
Tags: conference, schedule
Published: 2019-09-08 18:47:51

The DevFest WI schedule is ready! We're excited to share it with you. Visit [Schedule](https://devfestwi.com/schedule) to read about our speakers and presentations.

A few highlights:

- [Easy Machine Learning for Software Developers](https://devfestwi.com/schedule/2019-09-28?sessionId=DNQi5YvkXQdk6nnX9IkI) with Dale Markowitz
- [11 ways to make your website #a11y compliant](https://devfestwi.com/schedule/2019-09-28?sessionId=zvDJuXsExKdiPatJ10JB) with Riya Dashoriya
- [Salary Negotiation for Tech Careers](https://devfestwi.com/schedule/2019-09-28?sessionId=C5cnDTRcZRnwQoSnsvb7) with Ashley Quinto Powell

Thanks to our sponsors, including [Google](https://www.google.com), [Propeller](https://www.propellerhealth.com/) and [Bendyworks](https://bendyworks.com), for making this event possible.
Handling OS-level Authentication Dialogues in Internet Explorer using Selenium + AutoIt
Tags: testing, selenium, csharp, beginners
Published: 2019-09-08 18:09:24

For a few weeks, I've been working on a Selenium project and I'd to figure out a way to handle authentication dialogues in Internet Explorer (IE). The dilemma is that IE dialogues are non-browser dialogues, i.e., Windows-based dialogues. Therefore, they can't be handled using Selenium since Selenium doesn't recognize OS-level dialogues. I'll walk you through my solution which consists of two parts.

I used Selenium C# WebDriver. For other programming languages users, the concepts in this article are still applicable. You may need to import or use AutoIt package in a different way but nothing is really hard.

1- IE Settings:

I want IE to prompt the users to enter their credentials each time they open the browser because I'd like to run my tests against different users.

In your IE browser, click on Settings > Internet options > Security tab > check Enable Protected Mode > click on Custom level… > check Prompt for user name and password. Repeat the last three steps on all four zones (Internet, Local internet, Trusted sites, Restricted sites).

![IE settings demo #1](https://thepracticaldev.s3.amazonaws.com/i/6fkhtr536xgbnj2tah4c.png)

![IE settings demo #2](https://thepracticaldev.s3.amazonaws.com/i/7xqdy8eyfhei8mu3cj8m.png)

After applying the previous steps, IE should prompt the user to enter their credentials every time they open it.

2- C# code

To tackle the problem of Windows-based dialogues, I utilized a scripting language called AutoIt. By integrating AutoIt with Selenium, I was able to handle Windows- based dialogues smoothly. Let's dive into the C# code.

First step is to add AutoIt NuGet Package in Visual Studio. [Refer to Microsoft Documentation](https://docs.microsoft.com/en-us/nuget/quickstart/install-and-use-a-package-in-visual-studio). After referencing AutoIt NuGet Package (`` using AutoIt; ``), you will get a class named AutoItX with static methods ready to be used.

I created a method that takes the user credentials and handles the windows-based dialogues.  
```csharp
public static void SetAuthenticationCredentials(string UserName, string Pws)
        {
            AutoItX.WinWaitActive("Windows Security");
            AutoItX.Send(UserName);
            AutoItX.Send("{TAB}");
            AutoItX.Send(Pws);
            AutoItX.Send("{ENTER}");
        }
```

A number of people ran into an exception after this step, so here's one way to use the previous method properly.
```csharp
Parallel.Invoke(() => driver.Navigate().GoToUrl("https://YourWebsite.com"), () => SetAuthenticationCredentials("usertest2", "password2"));
```
In this way, you'll navigate to your website and invoke the SetAuthenticationCredentials method simultaneously.



Congratulations!!! right now you should be able to handle Windows-based dialogues easily. If you have any question, please don't hesitate asking me.
My first experience learning programming
Tags: beginners, html, javascript
Published: 2019-09-08 18:02:22

Hello!

This is my first post and I still don't have much experience as a developer, so I would like to share with you my experience so far.

I am studying a programming bootcamp in the company Hack a Bos, we have started learning html and now we are with javascript. 

The company are really fantastic! Start by saying that the teachers are lovely and the attention they give us is enormous and they make everything great but at the same time they teach us the effort we must make and how hard we have to work to reach our goal.

They not only train us in technical skills but also in soft techniques.
They teach us the contact with companies like Softtek and allow us to learn from professionals like Marta Falcón.

We still have a long way to go, but to say that the beginning has been spectacular and I would recommend it to anyone who would like to start in this world!



Regards!