teleren/devto huggingface dataset:
Validate Binary Search Tree
Tags: leetcode, algorithms, bst
Published: 2020-09-24 04:12:56

---
title: Validate Binary Search Tree
published: true
date: 2020-05-11 15:04:00 UTC
tags: LeetCode,Algorithms,BST
canonical_url: https://coderscat.com/validate-binary-search-tree
---

## [Challenge Description](https://leetcode.com/problems/validate-binary-search-tree/)

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- Both the left and right subtrees must also be binary search trees.

## Recursive Algorithm

For checking the property of every node in search tree, we recursive traverse all the nodes.

We use a `rec` helper function with two more extra parameters as the left bounder and right bounder node.

```cpp
class Solution {
 public:

  bool rec(TreeNode* root, TreeNode* min, TreeNode* max) {
    if(root == NULL)
      return true;

    if ((min != NULL && root->val <= min->val) ||
        (max != NULL && root->val >= max->val))
        return false;

    return rec(root->left, min, root) && rec(root->right, root, max) ;
  }

  bool isValidBST(TreeNode* root) {
    return rec(root, NULL, NULL);
  }
};

```

## Traverse binary tree with inorder

For the property of BST, if we traverse the tree in the `inorder`, it will be a increasing sequence. Add a varaible name of `pre` to store the previous tree node.

If it is not a valid binary search tree, this property will not hold.

```cpp
class Solution {
 public:
    TreeNode* pre;

  bool in_order(TreeNode* cur) { 
    if(cur == NULL) return true;
    if(cur->left && !in_order(cur->left))
        return false;
    if(pre != NULL && pre->val >= cur->val)
        return false;
    pre = cur;
    if(cur->right && !in_order(cur->right))
        return false;
     return true;
  }

  bool isValidBST(TreeNode* root) {
    pre = NULL;
    return in_order(root);
  }
};

```

We can also use a `stack` to implement a iteractive algorithm:

```cpp
class Solution {
 public:
  bool isValidBST(TreeNode* root) {
    TreeNode* pre = NULL;
    stack<TreeNode*> stack;
    TreeNode* cur = root;
    while(!stack.empty() || cur != NULL) { 
        if(cur != NULL) {
            stack.push(cur);
            cur = cur->left;
        } else { 
            cur = stack.top();
            if(pre != NULL && pre->val >= cur->val)
                return false;
            pre = cur;
            stack.pop();
            cur = cur->right;
        }
    }
    return true;
  }
};

```

The post [Validate Binary Search Tree](https://coderscat.com/validate-binary-search-tree) appeared first on [Coder's Cat](https://coderscat.com).
How to Convert Canvas to an Image using JavaScript
Tags: html, canvas, javascript, image
Published: 2020-05-11 14:54:57


The **`HTMLCanvasElement`** has special method **`toDataURL()`** which returns a encoded data URI representing the image in the specified format(defaults to PNG).

* If the canvas height or width is 0 or larger than the canvas maximum size, then the string containing **`"data:"`** is returned.
* If the requested type is not **`image/png`**, but the returned value starts with **`data:image/png`**, then the requested type is not supported.
* Chrome also supports the **WEBP(`image/webp`**) type.

### Syntax:

```javascript
canvas.toDataURL(type, encoderOptions);
```

### Parameters:

##### type (optional)

* It indicates the type of image format.
* It will have the value of string type and is an optional parameter with default format type value **`image/png`**.

##### encoderOptions (optional)

* It indicates the type of image format.
* It will have the value of number type and is an optional parameter with default value **0.92**.
* The value ranges from **0** to **1** indicating the quality of an image to use for formats that use lossy compression such as **`image/jpeg`** and **`image/webp`**.
* Invalid value is ignored and default value is considered instead of it.

### Return value

It returns a DOMString containing the requested data URI.


### Example 1

```html
<canvas id="canvas" width="640" height="360"></canvas>
```

```javascript
var canvas = document.getElementById('canvas');
var dataURL = canvas.toDataURL();
console.log(dataURL);
```

```text
/*
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABa...5i/JyZmJr6v77XLtUjciSUnklJd29flKi1cAPKgw"
*/
```
### For more examples visit : [How to Convert Canvas to an Image using JavaScript](https://meshworld.in/convert-canvas-to-an-image-using-javascript)

Hope you learn something new. If this article was helpful, share it.

Happy coding
I developed a highly customizable dashboard tool with Electron
Tags: node, electron, javascript, beginners
Published: 2020-05-11 14:52:05

Hi, I am a Japanese beginner software engineer.
The name of tool I developed is "okadash".

![Actual window in use.](https://i.redd.it/elre9euk81s31.gif)
This is actual window in use.


## Why okadash?

My name is "okada" and this dashboard tool was created by me.

Okada is written as 岡田 in Chinese characters.
The icon for this tool is 岡+', which means oka-dash.
In Japan, it's called an old man's gag(Oyaji gag).


## How to use?

https://qiita.com/okadato623/items/c2f1ba554af0103bef91

More details are explained on the above page.
I used a lot of screenshots, and I hope my sloppy English will help you understand.

- https://github.com/konoyono/okadash
- [okadash-1.7.0-win.zip](https://github.com/konoyono/okadash/releases/download/1.7.0/okadash-1.7.0-win.zip)
- [okadash-1.7.0-mac.zip](https://github.com/konoyono/okadash/releases/download/1.7.0/okadash-1.7.0-mac.zip)


GitHub repository and ZIP files are here.

If you have any feedback, I'd be happy if you could comment or create issue!
And if you think okadash looks good, please star on GitHub.
I am REALLY overjoyed XD

Thank you very much! :D
Bootstrap Native. Bootstrap WITHOUT jQuery Today
Tags: javascript, webdev, beginners, opensource
Published: 2020-05-11 14:47:13

---
title: Bootstrap Native. Bootstrap WITHOUT jQuery Today
published: true
description: There is a jquery-less alternative to the popular framework
tags: javascript,webdev,beginners,opensource
cover_image: https://opticalcortex.com/app/uploads/2014/08/nojquery-670x376.jpg
---
We get it.  We all get it.  Bootstrap JavaScript is heavy because it requires jQuery.  You are right.  So here are the bare facts about an alternative I found a while ago:

**Bootstrap.Native:** https://github.com/thednp/bootstrap.native

## Size
**Bootstrap v4**

* Bootstrap v4: 60+ kb
* jQuery-slim v3: 60+ kb
* popperjs: 20+ kb

**Total: 140+ kb**

________
**Bootstrap.Native**

* Bootstrap.Native: 20+ kb

**Total: 20+ kb**

## Dependencies
**Bootstrap v4:**
* popperJS
* jQuery-slim

**Bootstrap.Native**
_NONE_

## What about Bootstrap v5?  Isn't that Vanilla?
Yes.  It will be.  But as of writing this, a stable version of that seems fairly far off (sometime later this year??).  Also, sometimes it's good to support a smaller library that works incredibly well.  Bootstrap.Native has 1.6k stars on GitHub and 8k download a week on npm. It's not feeble and it still leverages the CSS from Twitter Bootstrap.

## Conclusion
Give Bootstrap.Native a serious try.  Build a proof of concept with it and with Twitter Bootstrap. I guarantee you will find that Bootstrap.Native loads faster, performs smoother, and is just as easy to implement.  I use it.  It's honestly great.  The documentation is lacking at the moment but you can just read the original Bootstrap v4 docs.
Adding pseudo-elements on input elements 🚫
Tags: css, javascript, html, tutorial
Published: 2020-05-11 14:40:21


Before you sink hours into trying to work out why that `::after` pseudo-element isn't working on your text input, let me save you some time and tell you that you can't - without some extra work that is. 

_TLDR; Add the `::after` to a sibling `<span>` element._

The reason being is that pseudo-elements are only supported on container elements. 

W3C's specification states the following: 

> Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.

_But what does that mean!?_

**Pseudo-elements are rendered in your code as child elements of parent elements.**

This means that rendering an `::after` selector on a button is fine, because it can be rendered as a child within a `<button>` component without a problem because it's a container element, as shown below. 

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

However, the below code won't work, because `<input>` elements don't support children. It's not a container element, like `<button>` is. 

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

If you're not well acquainted with `<input>` elements, here's an example of _valid_ usage of an `<input>` element. Observe the fact that there's an immediate closing tag without any children within that element. 

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

See the problem? An `::after` pseudo-element can't render within an `<input>` because it's not a container element; it cannot support any children. So how do we get around this? 

The solution is to apply an `::after` pseudo-element on a sibling `<span>` element. 

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

Here, we are adding an `::after` selector when the `<input>` focus state is active. By targeting the focus state, we can append a pseudo-element to an empty adjacent `<span>` element and work around the `<input>`'s container issue. 

Here's a codepen to demonstrate this. 

{% codepen https://codepen.io/hannahblair/pen/KKdePgm %}

I hope you found this useful! Follow me on the bird app [@erhannah](http://www.twitter.com/erhannah) for more web dev shenanigans/virtual reality chat/dog pics. ✨ 

N.B: Yes, I know you could also get around this with jQuery. But it's 2020. 

--- 

_Hi! I'm Hannah. I'm a virtual reality developer, senior frontend developer, vrcalm cofounder helping dementia patients, and tech for good enthusiast._ 🌎
Publish a Package to NPM
Tags: npm, javascript
Published: 2020-05-11 14:14:23

---
title: Publish a Package to NPM
published: true
description: Publish your first package to NPM in 5 minutes or less.
tags: npm, javascript
---

Publishing a package to NPM is a quick and efficient way to re-use code across multiple projects.

## Prerequisites

Before we get going, make sure you have an [NPM account](https://npmjs.org/) and have NPM installed and updated by running `npm i -g npm@latest`. You'll also need [Node](https://nodejs.org/en/) installed.

## Create a Project

Let's get a project up and running. We'll build a small utility to catch and help us fix all our errors.

1. Create an empty directory: `mkdir super-error-handler && cd super-error-handler`
2. Generate a `package.json`: `npm init -y` This will produce some fine defaults.
3. Create your utility: `touch index.js`

```js
// super-error-handler/index.js

module.exports = function handleError(error) {
  const query = encodeURI(error.message)
  console.error(`https://stackoverflow.com/search?q=${query}`)
}
```

## Create a Test Environment

Now that we have some code, let's see if it works!

1. Create another empty directory outside of the original: `mkdir test-env && cd test-env`
2. Generate another `package.json`: `npm init -y`
3. Create a symbolic link to your utility so you can require it like other installed modules: `npm link /path/to/super-error-handler`
4. Create a file to test with: `touch index.js`

```js
// test-env/index.js

const handleError = require('super-error-handler')

function testErrorHandler() {
  try {
    throw new Error('something bad happened')
  } catch (error) {
    handleError(error)
  }
}

testErrorHandler()
```

Now that we have some test code written with our error handler, let's give it a try: run `node index.js`.

## Publish to NPM

Almost there! Since every NPM package needs a unique name, you'll need to namespace your package by setting the `name` field in your `package.json` to `@your_npm_username/super-error-handler`.

Finally, from the `super-error-handler` directory, run `npm adduser` to authenticate to NPM and then `npm publish`.

That's it! You've published your first NPM package! Head to [npmjs.org](https://npmjs.org/packages)
to search for it and check it out.

## Additional Tips

Now that your code is available on NPM, here are a few things you can and should do:

- Check out the [NPM docs](https://docs.npmjs.com/files/package.json) on `package.json` fields and fill them in appropriately.
- Create a GitHub repo for your project.
- Add an `.npmignore` file to keep some of your repo from being downloaded by users of your module. Here's a great [Stack Overflow question](https://stackoverflow.com/questions/25124844/should-i-npmignore-my-tests) detailing how you might use one.
- Use `np` to level up your NPM game. It helps to take care of a bunch of additional publishing steps, including creating a release on GitHub. [Read the docs](https://www.npmjs.com/package/np) on NPM.

---

Need some help or want to share your newly-uploaded NPM package? Feel free to [reach out](https://twitter.com/briansw).
Depois do Café - Episodio 10 - Edição Comemorativa: Conquistas em Tecnologia
Tags: podcast, programação, portugues
Published: 2020-05-11 14:14:00

---
title: Depois do Café - Episodio 10 - Edição Comemorativa: Conquistas em Tecnologia
published: true
description: Neste episódio comemorativo a gente conta histórias nossas e dos ouvintes de conquistas que sentimos orgulho de ter feito em tech, desde um olá mundo em uma linguagem nova, até mesmo um robô que resolve cubo mágico.
tags: podcast, programação, portugues
---

{% spotify spotify:episode:4KwDSMSFSkRGW77yoVKa75 %}

Você também pode ouvir no seu aplicativo preferido: [iTunes](https://podcasts.apple.com/br/podcast/depois-do-caf%C3%A9-com-airton-zanon/id1480842641), [Breaker](https://www.breaker.audio/depois-do-cafe-com-airton-zanon), [Google Podcasts](https://www.google.com/podcasts?feed=aHR0cHM6Ly9hbmNob3IuZm0vcy9lMGU0MDU4L3BvZGNhc3QvcnNz), [Overcast](https://overcast.fm/itunes1480842641/depois-do-caf-com-airton-zanon), [Pocket Casts](https://pca.st/bpyo3i4y), [Radio Public](https://radiopublic.com/depois-do-caf-com-airton-zanon-6r2oLq), [Spotify](https://open.spotify.com/show/4cqX5o40bClwqtYHv9X7Lp) e outros...

Neste episódio comemorativo a gente conta histórias nossas e dos ouvintes de conquistas que sentimos orgulho de ter feito em tech, desde um olá mundo em uma linguagem nova, até mesmo um robô que resolve cubo mágico.

De um jeito pratico, “Depois do Café” de ser, queremos falar das conquistas em tecnologia do dia a dia.

----------------------

**Participantes:**

Airton Zanon - [@airtonzanon](https://twitter.com/airtonzanon) (twitter)

Elisa Pedrosa Reis - [@liisapedrosa](https://twitter.com/liisapedrosa) (twitter)

----------------------

**Links Comentados:**

Projeto Robo que resolve cubo mágico: [https://www.hackster.io/andreangelucci/rubik-s-bot-858795](https://www.hackster.io/andreangelucci/rubik-s-bot-858795)

Edição da revista publicada: [https://hackspace.raspberrypi.org/issues/16](https://hackspace.raspberrypi.org/issues/16)

----------------------

 Para mais episodios e saber mais sobre o podcast acesse https://anchor.fm/depoisdocafe.

Siga-nos no twitter [@dpsdocafe](https://twitter.com/dpsdocafe)
ReactJS para Iniciantes 07 - Implementando um formulário de cadastro
Tags: react, javascript
Published: 2020-05-11 14:12:45

{% youtube Pnnkg9PysGk %}

Nesse vídeo nós implementamos um formulário de cadastro utilizando React e REST API.

✅ Me acompanhe nas redes sociais:

https://twitter.com/vinicius_dacal
https://www.instagram.com/dacaldev
https://www.linkedin.com/in/viniciusdacal

✅ Pull Request:
https://github.com/viniciusdacal/react-iniciante/pull/5

✅ Código Inicial:
https://github.com/viniciusdacal/react-iniciante/tree/feature-1

✅ Código Final:
https://github.com/viniciusdacal/react-iniciante/tree/feature-6
Day 16 of #100DaysOfCode: Design a Layout for Articles with Bootstrap Card
Tags: 100daysofcode, bootstrap, design, webdev
Published: 2020-05-11 14:10:42

## Introduction
For card style's design, we can use CSS Grid as I mentioned on Day 1.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hznp64w18f3xn8l3pooc.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/14mrl1jlc3su2do7nfkd.png)

* More detail: https://dev.to/jenhsuan/day-1-of-100daysofcode-design-a-layout-for-shopping-cart-template-with-css-grid-and-media-query-2hfn

However, we have to use *Media query* to complete the layout for the mobile version. One of advantages for using Bootstrap Card is that we don't have to write Media query additionally.

## Implementations
* Link
https://jenhsuan.github.io/ALayman/articles.html

* Screen shot for the desktop version
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/r0oqrmmivqgiew7f31jn.png)

* Screen shot for the mobile version
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q80x704zq1aeer0ldpj8.png)

## Code
* HTML
```HTML
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="views/js/articles.js" ></script>
...
<div class="container">
    <div id="medium" class="row item"></div>
</div>
```

* JavaScript (append child nodes dynamically by AJAX)

```javascript
...
function appendArticleChild(ele) {
    var div = document.createElement('div');
    div.className = 'col-md-6 col-xs-12'

    var card = document.createElement('div');
    card.className = 'card'

    var cardBody = document.createElement('div');
    cardBody.className = 'card-body'

    var cardTitle = document.createElement('h1');
    cardTitle.className = 'card-title'

    var cardBlock = document.createElement('div');
    cardBlock.className = 'card-block'

    cardBody.appendChild(cardTitle)
    cardBody.appendChild(cardBlock)
    card.appendChild(cardBody)
    div.appendChild(card)

}
```

## Articles
There are some of my articles. Feel free to check if you like! 
* My blog-posts for software developing: https://medium.com/a-layman
* My web resume: https://jenhsuan.github.io/ALayman/cover.html
* Facebook page: https://www.facebook.com/imalayman
How to prevent your app from crashing when working with a Google library
Published: 2020-05-12 15:13:23

---
title: How to prevent your app from crashing when working with a Google library
published: true
date: 2020-05-11 13:37:00 UTC
tags: 
canonical_url: https://coderamblings.dev/posts/how-to-prevent-your-app-from-crashing-when-working-with-a-google-library/
---

While debugging an issue in an app that I’m working on, I noticed some peculiar behavior which we couldn’t explain.

The app that I’m working in currently uses Firebase Remote Config to do A/B testing as well as to extract some configuration options which we want to change on-demand. We’ve been seeing quite a few errors when fetching the configuration so we decided to add a bunch more logging to figure out what was going on.

Firebase Remote config, like a lot of libraries by Google which do asynchronous work use the [Tasks API](https://developers.google.com/android/guides/tasks) to model the asynchronous work.

When we call the remote config SDK to fetch and activate our values, the SDK returns a `Task<Boolean>`. This is a `Task` which has a result which is of the type `Boolean`. In our logging we wanted to know what the result was, so we added this to the logs like so:

```
logger.error(
  "Firebase error occured",
  mapOf(
    "isResultSuccessful" to task.result?.let { if (it) "true" else "false" } ?: "null"
  )
)
```

The result can be nullable as well, so we check for that here, if it is defined we output the string equivalent of `true` or `false`.This looks pretty straight forward at first sight, right?

We released a new version of our app with this and suddenly we saw our crash rate dropping to almost 50% of our users. (We have quite a few non fatals occuring, but these never resulted in any crash).

After investigating for a couple of hours we found out that `task.result` _can_ throw an exception if there was an exception while executing the fetch and activate call. So adding a simple try-catch around this resolved our issue.

Looking at the declaration of `getResult` doesn’t show that it can throw an exception though.

[The documentation](https://developers.google.com/android/reference/com/google/android/gms/tasks/Task#getResult()) does show that it can indeed throw an exception, but who reads the documentation?

I hope that with this some people will prevent some of their crashes in their apps. I guess this is a note to myself to read the documentation a bit more. ¯\_(ツ)\_/¯
JSK meets friends #3: Reboot & Recruiting 
Tags: blog
Published: 2020-05-11 13:42:24


---
title: JSK meets friends #3: Reboot & Recruiting 
published: true
description: Here is the 3rd episode of #jskongress meets friends: We are excited to announce the guests for our next episode. Join us live on Tuesday, May 12th, starting 5:30 pm (CEST) on our channel youtube.com/jskongress We are so grateful, that Felicitas, Kristina and Aileen from Sinnerschrader will discuss with us: the recruiting process in these [&hellip;]
tags: Blog
canonical_url: https://js-kongress.com/2020/05/11/jsk-meets-friends-3-reboot-recruiting/
cover_image: https://js-kongress.com/wp-content/uploads/2020/05/JSKmeetsfriends_3.png
---

Here is the 3rd episode of #jskongress meets friends: We are excited to announce the guests for our next episode.

Join us live on **Tuesday, May 12th, starting 5:30 pm** (CEST) on our channel [youtube.com/jskongress](https://www.youtube.com/jskongress/?utm_source=blog&utm_medium=website&utm_campaign=20200511_jskmeets3&utm_nooverride=1)

We are so grateful, that **Felicitas, Kristina and Aileen** will discuss with us: the **recruiting process** in these challenging times, and which **opportunities** they developed from the crisis.

- - - - - -

First of all, everyone – attendee, speaker, sponsor and volunteer, as well as the team members – at the JS Kongress, have to agree to the Code of Conduct. You agree to comply by attending. Also, the organizers will enforce this code throughout the event. Finally, we are expecting cooperation from all involved parties to ensure a safe environment for everybody. In detail on <https://js-kongress.com/code-of-conduct/>

- - - - - -


[![JSKongress meets #3 – Reboot & Recruiting](https://js-kongress.com/wp-content/uploads/2020/05/JSKmeetsfriends_3-1024x696.png)](https://www.youtube.com/jskongress/?utm_source=blog&utm_medium=website&utm_campaign=20200511_jskmeets3&utm_nooverride=1)