teleren/devto huggingface dataset:
iOS 13: launchOptions always nil? This is the reason & solution
Published: 2020-04-18 17:32:30

So today I spent quite some time puzzling over why I was always getting `nil` `launchOptions` argument in `func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?)` and then finally found a solution.

## The reason

The culprit is the new project structure for iOS 13 and above. In the past we were used as `AppDelegate` as the only class to handle app lifecycle events and responding to shortcuts, URL schemes and what not.

But with iOS 13 and more specifically iPadOS came the push to better support multiple screens for apps we got the `SceneDelegate` where most of the events now moved.

So even though the `didFinishLaunchingWithOptions` still looks the same:

```swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
}
```

You don't get any `launchOptions` here. It would be better if Apple simply changed the signature but for some reason (lets hope there at least is a reason) the argument is still present but always `nil`.

## The solution

The solution to correctly getting `launchOptions` in iOS 13 and above is 
to use `SceneDelegate` and the `willConnectTo session` which is automatically there with some basic code.
The full signature looks like this:

```swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
```

And the `connectionOptions` is new "reincarnation" of the trusty old `launchOptions`. To be fair to apple, this is much better to work with.

Say you want to respond to launch from shortcut item (the quick action available with long press on app icon). Previously you would have to reach into the options dictionary and do a cast. 

Now it looks like this:
```swift
if let shortcut = connectionOptions.shortcutItem {
	// handle shortcut here
}
```

What about reacting to URL scheme? We have `urlContexts` set available and can simply pull the first item for basic implementation:
```swift
if let firstUrlContext = connectionOptions.urlContexts.first {
	// handle firstUrlContext.url
}
```
And that is it!

Hope this will save you some time when implementing this and you won't have to go full Sherlock 🕵 finding what is wrong...

### One last thing

Since I have shown you how to react to shortcuts and URLs, let's see how to do these tasks when app is already running in the background.

We have this method to handle shortcuts:

```swift
 func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
}
```

And this one to handle URL launch:

```swift
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
}
```

Once again, this is much better than prior to iOS 13 changes. 🙂

_Thanks for reading!_
Calculating A Rolling 18 Months
Tags: javascript, date, webdev, beginners
Published: 2020-04-18 17:24:56

---
title: Calculating A Rolling 18 Months
published: true
description: Basically, they wanted me to filter the events list so that only events within the last 18 months showed.
tags: JavaScript, Date, WebDev, Beginners
series: JavaScript Tips
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/uxvfa2wdwp0nt81s18u4.png
---

On a recent project, I was tasked initially with modifying an `events.js` file that loaded data from JSON.

## Rolling 18 Months

Basically, they wanted me to filter the events list so that only events within the last 18 months showed.

### The Data

The data looked something like this ...

```javascript
[
  {
    "name": "A Conference",
    "type": "conference",
    "displayDate": "April 1, 2020",
    "sortDate": "2020/04/01"
  },
  {
    "name": "Another Conference",
    "type": "conference",
    "displayDate": "March 24, 2020",
    "sortDate": "2020/03/24"
  }
]
```

### The Solution

The original code looked like this ...

```javascript
module.getEvents = function () {
  return $.getJSON('events.json', function (data) {
    module.events = data.sort(sortByProperty('sortDate')).reverse();
  });
};
```

At some point in time, I added a function (`deltaData`) to my inventory. If anyone out there knows where this came from I would be happy to attribute it here. To fit this functionality, it became ...

```javascript
module.deltaDate = function (start_date, days, months, years) {
  var date = new Date(start_date);
  date.setDate(date.getDate() + days);
  date.setMonth(date.getMonth() + months);
  date.setFullYear(date.getFullYear() + years);
  return date;
};
```

From here, I needed to calculate back 18 months ...

```javascript
module.setFilterDate = function () {
  var today = new Date();
  var dayChange = 0;
  var monthChange = -18;
  var yearChange = 0;
  return module.deltaDate(today, dayChange, monthChange, yearChange);
};
```

Then, the original `getEvents` function transformed as follows. This function now filters, then sorts the incoming JSON data ...

```javascript
module.getEvents = function () {
  var filterDate = module.setFilterDate();
  return $.getJSON('\\events.json', function (data) {
    var filtered = data.filter(function(item) {
      return new Date(item.sortDate) > filterDate;
    });
    module.events = filtered.sort(sortByProperty('sortDate')).reverse();
  });
};
```

## Conclusion

While this change was relatively simple, I wanted to document this functionality for my own future use. I hope you found this article interesting.
Using the reduce method to sequentially execute a promise queue
Tags: javascript, ecmascript5
Published: 2020-04-18 17:23:39

Hello friends!

In this post, I decided to share with you one of the uses of the `Array.prototype.reduce` a method, namely, using the method to consistently fulfill `promises`.

In one of the works ([AnimationJS](https://github.com/olton/animationjs), [m4q](https://github.com/olton/m4q)), I needed to perform sequentially some (total number is unknown) number of animations. Each animation is a `Promise`.

**Animation definition**
```javascript
function animate(args){
	return new Promise(function(){
		...
	})
}
```

**Chain definition**. Each argument for `chain` is a plain object, who describe animation.
```javascript
chain([{...}, {...}, ...])
```
#### async/await
The first thing that came to mind was to solve the problem using **async/await**:
```javascript
async function chain(arr) {
    for(let i = 0; i < arr.length; i ++) {
        const a = arr[i];
        a.loop = false;
        await animate(a);
    }
}
```
This works fine, but was not suitable for my [m4q](https://github.com/olton/m4q) library written for [Metro 4](https://metroui.org.ua) on ECMAScript 5.1 due to lack of **async/await** support.

> for Promise, I use polyfill

Finding a solution made it possible to use the `reduce` method.
```javascript
function chain(arr, loop = false){
    const reducer = function(acc, item){
        return acc.then(function(){
            return animate(item)
        });
    }

    arr.reduce(reducer, Promise.resolve());
}
```
How to `reduce` works? The `reduce()` method reduces the array to a single value. The `reduce()` method executes a provided function for each value of the array (from left-to-right). The return value of the function is stored in an `accumulator` (result/total). For initial value, I use empty `resolve`. In next, on all iteration reducer execute `Peromise` and call a next animation in resolver. Since the resolver is executed after the end of the promise, we get sequential animations when each next animation is executed only when the previous one is completed.

Now I can execute `chain` of animations:
```javascript
var ball = document.querySelector(".ball");
chain([
	{
		el: ball,
		draw: {
			top: [h - ball.clientHeight]
		},
		dur: 2000,
		ease: "easeOutBounce"
		},
	{
		el: ball,
		draw: {
			left: [w - ball.clientWidth]
		},
		dur: 2000,
		ease: "easeOutBounce"
	},
	{
		el: ball,
		draw: {
			top: 0
		},
		dur: 2000,
		ease: "easeOutBounce"
	},
	{
		el: ball,
		draw: {
			left: 0
		},
		dur: 2000,
		ease: "easeOutBounce"
	}
]);
```
#### Result
<img src="https://pimenov.com.ua/demo/animate-chain.gif">
Understand "this" keyword in JavaScript
Tags: javascript, react, angular, vue
Published: 2020-04-18 17:22:15


Most of the time we confuse with this keyword in JavaScript. So lets simplify it.
"this" is just used to create a reference to any object.

Let say we have a two object "studentFirst" and "studentSecond".
```javascript

const studentFirst = {
    name:"ritik",
    age:"21"
}

const studentSecond = {
    name:"gaurav",
    age:"45"
}

```
And a function "getDetails" which will log the student details in console.

```javascript

function getDetailsFirst(){
    console.log(`${studentFirst.name} is ${studentFirst.age} years old.`);
}

function getDetailsSecond(){
    console.log(`${studentSecond.name} is ${studentSecond.age} years old.`);
}

getDetailsFirst();
getDetailsSecond();

//ritik is 21 years old.
//gaurav is 45 years old.

```
Above we are using two seperate function and using object properties by calling their Object seperatly.
It can be done more efficiantly using "this". Lets see:

```javascript

const studentFirst = {
    name:"ritik",
    age:"21"
}

const studentSecond = {
    name:"gaurav",
    age:"45"
}

function getDetails(){
    console.log(`${this.name} is ${this.age} years old.`);
}

getDetails.call(studentFirst); //this gets a reference to studentFirst Object //A
getDetails.call(studentSecond);//this gets a reference to studentSecond Object //B

//ritik is 21 years old.
//gaurav is 45 years old.

```
Here "call" method is used to create a reference for "this" in "getDetails" method.
At position A "this" creates a reference to "studentFirst".
At position B "this" creates a reference to "studentSecond".

Now lets see how does "this" behave in different scopes.

Open Chrome Dev-Tool and in console just log "this".

```javascript

console.log(this);
//Window {parent: Window, opener: null, top: Window, length: 4, frames: Window, …}

```
So in global scope "this" is refering to "window" object.

Now lets try "this" inside a object.

```javascript

const student = {
    name:"ritik",
    getDetails(){
        console.log(this);
    }
}

student.getDetails();
//{name: "ritik", getDetails: ƒ}

```
Inside a Object "this" refers to scope of same Object in which it is defined.

```javascript

const student = {
    name:"ritik",
    getDetails(){
        console.log(this.name);
    }
}

student.getDetails();
//ritik

```
or you replace "this" with Object name "student" like this:

```javascript

const student = {
    name:"ritik",
    getDetails(){
        console.log(student.name);
    }
}

student.getDetails();
//ritik

```
Most of the time "this" is seen inside a constructor which is one of the usecase of it.

Hope you get the basic of "this" in JavaScript.
{This post is also available on [ritikrana.netlify.com](ritikrana.netlify.com)}
About Ruby Hash#assoc
Tags: ruby, hash, documentation
Published: 2020-04-18 17:15:30

---
title: About Ruby Hash#assoc
published: true
description: 
tags: ruby, hash, documentation
---

Get more information and more examples at my AboutRuby project:
* [AboutRuby project](https://github.com/BurdetteLamar/AboutRuby/blob/master/core/Hash/api/markdown.md#assoc)

Here's the write-up over at the Ruby project:
* [Ruby project](https://ruby-doc.org/core-2.7.0/Hash.html#method-i-assoc)

My main page is [here](https://github.com/BurdetteLamar/AboutRuby#about-ruby).

TL;DR

I've been working on enhancements to the documentation for the Ruby project.  Getting these enhancements posted to the Ruby project has been very slow.  They're not actually meeting resistance;  I know because my many PRs for enhancing class ENV were accepted (though not rapidly).  It's just that everyone is busy.

Anyhow, I'm stashing all this stuff on in my own project, called AboutRuby.  The piecemeal migration from there to the Ruby project is not going to be completed in my lifetime (I'm 77 years old).

So:  I'm going to blow my own horn here on DEV, to encourage you to use the enhanced documentation.
100daysofcode Flutter
Tags: 100daysofcode, flutter
Published: 2020-04-18 16:56:39

day 40/100 of #100daysofcode #Flutter
Learning Flutter , courses Udemy from
@maxedapps

Today implements validating form, focusnode ,addlistener, about dispose and implement some constructor,
https://github.com/triyono777/100-days-of-code/blob/master/log.md
Taking Pixel-Perfect Screenshots Every Time Using Chrome Devtools
Tags: webdev, design, productivity, programming
Published: 2020-04-18 16:55:22

---
title: Taking Pixel-Perfect Screenshots Every Time Using Chrome Devtools
published: true
description: While most operating systems ship with built-in screenshotting tools, it's often desired to grab pixel-perfect screenshots. In this post, I'll show you how to do so.
tags: webdev, design, productivity, programming
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y1pdb45kzy0ncbcu15ad.png
---

While most operating systems ship with built-in screenshotting tools, it's often desired to grab pixel-perfect screenshots. In this post, I'll show you how to do so using Chrome Devtools.

# A Test Case -- The Dev.to Sidebar Nav

To use Chrome Devtools to take screenshots, we'll want to be screenshotting something in the browser. Today's test case will be the Dev.to sidebar nav (yes, that thing on the left of your dev.to home page). The following is a pixel-perfect example of what we'll be grabbing:

![Dev sidebar nav screenshot](https://dev-to-uploads.s3.amazonaws.com/i/dvta7ar1ktvidwpqh25w.png)

# The Steps

The steps we need to take are as follows:

1. Find the right node in Chrome Devtools "Elements" panel
2. Open the Run Command prompt
3. Select "capture node screenshot"

## 1. Finding the right node

To find the right node, I usually right-click on the element I'm looking for and click "inspect." This will take you to the "Elements" panel in devtools, at which point you can browse around to make sure you're selecting the right node. In this case, the `div` we're targeting has an `id` of `sidebar-nav`. When you have it correctly selected, your screen should look something like this:

![Choosing the right node](https://dev-to-uploads.s3.amazonaws.com/i/y1pdb45kzy0ncbcu15ad.png)

## 2. Open the Run Command prompt

Once we have the right node selected, we need to open the Run Command prompt. There area couple ways to do this:

1. Click on the vertical ellipsis (...) in the upper-right corner of devtools and click "Run command"
2. (My preferred method) Just hitting ctrl + shift + p

You should now see something like this:

![Run Command prompt](https://dev-to-uploads.s3.amazonaws.com/i/p0bjufbrspv7nxr4h7ds.png)

## 3. Select "Capture node screenshot"

Type "capture node screenshot" and hit enter once the right option is selected. 

![Capture node screenshot](https://dev-to-uploads.s3.amazonaws.com/i/zgkdmofsctatig60qejd.png)

You should see your screen take the screenshot and download the image!

# That's It

You now know how to take pixel-perfect screenshots! Hopefully this helps you with all sorts of tasks, from working on design mocks to capturing bug reports.
Feature Engineering in Machine Learning
Tags: machinelearning, featureengineering, prediction, analysis
Published: 2020-04-18 16:46:46

### **Why Feature Engineering?** 
The most important step in every machine learning process is the creation of features that allow us to create a model capable of predicting well. In the majority of the machine learning projects we face, the initial features we get are minimal in comparison with the ones we can create from our dataset.

Keep in mind that feature engineering is a creative process and the way of validating if a certain feature is useful is to test our model with that feature.

Here are some techniques to help you with feature engineering:

## New features
Say you have a dataset that includes a timestamp. You may enumerate all the properties of a timestamp and consider what might be useful for your problem, for example:
* Weekend or not
* Night or not
* Business quarter of the year
* Public holiday or not

You could also include, for a numeric column in your dataset, statistical features: mean, median, standard deviance, max, min.

## Transform features
Transformation of a feature is the application of a deterministic mathematical function to each point in a dataset. Say you have a numeric column of data **X**. You could apply one of the following transformations:

* Log(**X**)
* 1/**X**
* **X**^(1/2)
* Normalizing **X** in the range [-1, 1]

The motivation behind transformations is better visualization and interpretability of the data.

## Encoding
Encoding is the process of transforming a categorical variable into a continuous variable and using them in the model. There are many encoding possibilities, for example, **One-hot encoding**:
* In this method, we map each category to a vector that contains 1 and 0 denoting the presence of the feature or not. The number of vectors depends on the categories which we want to keep.

If you think encoding could help, also check out other encoding techniques: Mean Encoding, Label Encoding, Target Guided Ordinal Encoding. 

##Interaction between features
Getting a little more creative you could sum, multiply, concatenate the data of 2 columns.
The possible interactions could be a big number, so my recommendation to find useful ones is to place them in a loop and keep the ones with the best results.

##**Finally, how to test my features?**
As explained in the beginning, the way to test your features is by placing them in your model and make a prediction with it.
* A cool tip! Place them in a **Random Forest** model. After you predict with it, you can get each feature importance.
Your Own Personal 'Device specific' Notepad: lives in your device not on any server.
Tags: css, javascript, html, beginners
Published: 2020-04-18 16:43:37

I was exploring something about indexdb ( a database inside browser). 

However, we all know a local storage is also available on browsers apart from indexdb.

Most of the times , I want to use a volatile notepad in my mobile phone without uploading contents to any server . Also, I don't want to download any app.

So here is what I have created. You can try too. 

https://devicenotepad.imfast.io

Your all contents are inside your browser's local storage. Nobody knows.

Also this site is hosted on Google drive using fast.io . 

What else you can add: A service worker to catch the index HTML file and make it available when you are offline.
Export WordPress Posts to Nuxt
Tags: nuxt, javascript, webdev, showdev
Published: 2020-04-18 16:23:11

---
title: Export WordPress Posts to Nuxt
published: true
description: A simple CLI to suck your WordPress posts down into 
tags: nuxt, javascript, webdev, showdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/wf9547xob7n5vybkiimn.png
series: "WordPress to Nuxt"
---

If you're reading this, you might have a blog on WordPress right now.

Have you ever had the dream of having your blog on something much faster like a static site generator?

I'm building a Nuxt.js site right now, and I have to import around 800 historical posts going as far back as 2015.

If you've tried to export posts from WordPress, you'll have found there are very little plugins to help you. And, the format of the official export tool seems only designed for importing back into WordPress.

So, I'm building my own little exporter.

## What You'll Need

- A WordPress Blog with WP REST enabled (I don't know how to enable it, it was already enabled! Try it out https://yoursite.com/wp-json) - GET requests are public, no auth required.
- Some JavaScript/Node Knowledge
- Node Installed

## Creating A Little Exporter

First, a new project directory (and change into it)!

```bash
mkdir wp-exporter && cd $_
```

Create a blank file to use as a little CLI.

```bash
touch index.js
```

Initiate the NPM project.

```bash
# -y to skip the questions
npm init -y
```

Install [`wpapi`](https://www.npmjs.com/package/wpapi) the official node SDK for the `wp-json` API.

```bash
npm install wpapi
```

Now for some coding. Edit `index.js` and add all of this code.

```js
const WPAPI = require('wpapi')
const fs = require('fs')
const wp = new WPAPI({ endpoint: 'https://yoursite.com/wp-json' })

const wpExportToJson = async () => {
  let page = 1
  let data = {}
  const posts = []

  do {
    try {
      data = await wp.posts().perPage(20).page(page)

      posts.push(...data)
      page++
    } catch (err) {
      console.error(err)
    }
  } while (!!data._paging.links.next)
 
  fs.writeFile("output.json", JSON.stringify(posts), 'utf8', (err) => {
    if (err) {
      return console.error(err);
    }
    console.log("JSON file has been saved.");
  });
}

wpExportToJson()
```

By the time you `fs.writeFile`, the `posts` variable contains an array of all of your WordPress posts.

If you have a lot of content, this could take a little while to run. The `output.json` is likely to be big, too. For me, it was over 30MB–and it doesn't even include the images...

From here, you could neatly chop it up into individual JSON files in a [Netlify CMS](https://www.netlifycms.org/) friendly format, or pre-process it before sending it over to a headless CMS like [Sanity.io](https://www.sanity.io/).

![Screenshot of WordPress post fetcher CLI](https://dev-to-uploads.s3.amazonaws.com/i/bzavrbrxf4qem5mus9rz.png)
Transforming Teaching with Teachingo - Update #2
Tags: twiliohackathon, postgres, node, javascript
Published: 2020-04-18 16:17:19

_This is an update on our #TwilioHackathon project progress - you can see the original post here: {% link https://dev.to/chloemcateer3/transforming-teaching-with-teachingo-4lc5 %}_

---

## Data is the new oil 🛢

When thinking about the different user flows for an application like this, it is clear to see that there are a lot of different data points being generated, which meant we had to think about adding a persistence layer to our application.

So we initially spent some time thinking about what the best way to store this data was. Both of us have previous experience working with NoSQL, so we considered using [MongoDB](https://www.mongodb.com/) since it is quick & easy to get up and running. 

However, we took the time to understand what all data we would be working with, we realised we would need to store all of the following:

* Users email address, password, name, mobile and if they where a student or teacher.
* Class names, teacher that teaches it, students that attend it
* Lesson time/date, number of questions asked in lesson, lesson feedback etc.

![Brooklyn Nine Nine, There is another way](https://media.giphy.com/media/XoM3WIZDHMYwQKlXsC/giphy.gif)

From seeing this, it was clear that it made more sense for us to opt for a more structured database approach, the relationships between the different data points were more complex than we initially thought. We had a quick brainstorm about the database platform, ultimately settling on [PostgreSQL](https://www.postgresql.org/).

### Integrations.js ✨

Having decided on the platform, we needed to understand how our Node.js service could interact with a Postgres instance. I came across [Knex.js](https://knexjs.org/) which is an SQL query builder that can be used with Postgres!

It allowed me to be able to define schemas for each table within the code and create functions for getting, adding and removing data from the db - I was amazed by how powerful it was and how much of the heavy lifting it could do out of the box.

![Brooklyn Nine Nine, Boyle holding Terry](https://media.giphy.com/media/5qFQhmVkF0mfDoymL5/giphy.gif)

It also meant that once someone else pulled down the repository, they could run the database migrations, to get all the tables set up the correct way!

Knex also allowed me to define and generate seed data for the application, which meant I could put large amounts of dummy data into the database.

We now have our database up and working, but we did face some problems along the way, when it came to actually modelling it. For example: duplication of data and over complicated tables.