teleren/devto huggingface dataset:
🕵️‍♀️ "hygen" first impressions
Published: 2020-09-06 04:06:53

A couple of days ago I stumbled upon a new tool called hygen [hygen.io](https://www.hygen.io/) on github as [jondot/hygen](https://github.com/jondot/hygen). 

Here's what the description from the repo says:

> hygen is the simple, fast, and scalable code generator that lives in your project.

The bottom line is it's a cli-based scaffolding tool. It uses an odd combination of [`ejs`](https://ejs.co/) and [front-matter](https://jekyllrb.com/docs/front-matter/). 

## How does it work?

First you install the CLI tool globally using npm.

```bash
npm install hygen -g
```

Then call `hygen init self` to generate a scaffold, for generating scaffolds, kind of meta right?

This will allow you to run `hygen generator new component`. 

By now you should have a `_templates` folder with a `generator` and a `component` directory inside.

You'll see a temporary file inside `_templates/component/hello.ejs.t` which you can customize to be be the new component. I would rename `hello.ejs.t` to `simple.ejs.t` and put this inside:

```ejs
---
to: src/components/<%= name %>.tsx
---
import React from 'react'

export function <%= name %>(props) {
  return <h1>Hello, {props.name}</h1>;
}
```

Then you can run:

```bash
hygen component new --name Example
```

And voila! You will have easily created a new component.

## Using Prompts

One super-cool feature is the prompt functionality, just by adding in a `prompt.js` file to the generator directory you can get prompted when you run the command for different `ejs` variables rather then supplying them as flags to the command.

## The Shell

One nice addition is an option to execute a shell command from the front-matter of a generator. This allows better pipelining of side-effects. 

```ejs
---
sh: echo "hi"
---
```

## Open Questions

#### Is it possible to get `.ejs.t` vscode syntax with front matter support? Perhaps just use `.ejs`?

One possible workaround for vscode picking up the `.t` file- type is to add a file association in the vscode preferences:

```jsonc
{
  "files.associations": {
    // @see https://dev.to/reggi/using-hygen-3g3i
    "*.ejs.t": "html"
  }
}
```

## Conclusion

I love it so far! It's greatly improved my workflow and I continue to find new use cases. ❤️❤️❤️❤️❤️
DNS Explained. The RRR Model
Tags: dns, networking, rrr, domain
Published: 2020-09-06 04:05:01

> This is an article in the *DNS Explained.* series. Click [here](https://dev.to/blake/dns-explained-introduction-history-1an7) to read the introduction post. 

DNS isn't all technical. At its core, there is a lot of policy and thus jargon created. The intent of this post is to clear up some of the most commonly used jargon relating to entities in DNS.

![Diagram of the RRR model.](https://i.imgur.com/K41K3cR.png)

There are three main stakeholders in the DNS ecosystem. Together, they form the RRR (triple-R) Model.

**Registrants** are the individuals and organizations that register a domain name. 

They obtain a domain name from a registrar by paying the price that that particular registrar sets. If a potential registrant thinks that a registrar's price is too high, they can look at another registrar (competition!).

If Alice registers the domain name “alice.rocks”, then Alice is considered as the registrant for the domain name “alice.rocks”.

**Registrars** are third-party organizations that "sell" domain names to registrants. 

Domain names are not really sold but rather rented on an annual basis. The maximum length of a registrant’s active registration depends on the policy of the specific TLD, but usually is 10 years. 

Registrars are also the bridge between registrants and registries, because they have to interface with the specific TLD's registry to submit the domain creation. 

Before registrars were established, a TLD’s registry would act as the registrar. This didn’t permit much competition, so the concept of a registrar was adopted.

Some notable registrars include:

- GoDaddy
- NameCheap
- 101domain
- Network Solutions

**Registries** operate the backend infrastructure for a top-level domain and process domain creations, renewals, expirations, deletions, and transfers. 

Their customers are registrars, who then sell to registrants. Since registries need to make money too, there is a wholesale cost for new domain creations, among other fees that are charged to registrars.

There is a single registry for each TLD. The organization ICANN [designates via contract](https://www.icann.org/resources/pages/registries/registries-agreements-en) the sole registry for each TLD.

Some notable TLDs and their corresponding registries are:


| TLD        | Registry           |
| ------------- |:-------------:|
| .com      | Verisign |
| .net      | Verisign      |
| .org | Public Interest Registry      |
| .gov | General Services Administration |
| .coffee      | Donuts |
| .tv      | Verisign |
| .site      | Radix |
| .me | DoMEn d.o.o |


## Conclusion

Registrants, registrars, and registries make up the RRR model within DNS. Registrants are end-customers leasing a domain name. The organizations that offer the means to obtain a domain name are registrars. Registrars have to communicate with the backend systems of each TLD they want to offer, which are managed by the TLD's registry.
Enough to be dangerous - is dangerous.
Tags: beginners, webdev
Published: 2020-09-06 03:19:39

> "For the last 10 years - I’ve been hearing all about what people want - and seeing first-hand, how they are going about getting it."

Check out this latest post [https://sheriffderek.substack.com/p/enough-to-be-dangerous-is-dangerous](https://sheriffderek.substack.com/p/enough-to-be-dangerous-is-dangerous) from our own [@sheriffderek](https://sheriffderek.consulting)

Many people want to “learn to code.” They want a job that’s easier and provides them a lot more money. They feel like it’s attainable - and everyone says it’s easy. You can make lots of money - and they say you can learn it all for free. Now, if you know me - then you’ll know the second I hear the word “free,” I start looking for the hidden cost.

When you send someone surfing across The Web to find books and free courses to teach them ‘to code’ (as fast as possible), what do you think happens? There are hundreds of thousands of tutorials and videos and opinions and everything you can imagine.

It wasn’t always that way. There used to be some books and some publishers that acted as gatekeepers and created reliable teaching materials. But the market is now completely flooded and it’s yesterday’s novices who are pointing today’s newest students to the worst of the educational materials with great enthusiasm.

Full post [here](https://sheriffderek.substack.com/p/enough-to-be-dangerous-is-dangerous)
Display online/offline pdf files in React using react-pdf
Tags: pdfjs, react, reactpdf
Published: 2020-09-06 03:13:04

react-pdf is a great package for react it's based on the pdf.js from Mozilla.
* Install
`npm i react-pdf`
* Import
```
import { Document, Page, pdfjs } from 'react-pdf'
// right after your imports
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`
```
* Use
```
<Document
  file={{ url: urlPdf }}
  onLoadSuccess={onDocumentLoadSuccess}
>
  // pages here, we will get back to that later
</Document>
```
in above code urlPDF is url to pdf. Remember this resource must not be blocked by CORS. Or pdf will not render.
If the resources is not available for cross origins use this instead (just a temporary solution, don't use it in production).
```
file={{ url: `https://cors-anywhere.herokuapp.com/${urlPdf}` }}
```
* onLoadSuccess is invoked when the file has loaded use this to set total pages in pdf
const [totalPages, setTotalPages] = useState(null)
const onDocumentLoadSuccess = ({ numPages }) => setTotalPages(numPages)
* Now we have totalPages, let's display the pages now
```
<Document
  file={{ url: attachment.url }}
  onLoadSuccess={onDocumentLoadSuccess}
>
  {
    Array.apply(null, Array(totalPages))
     .map((x, i) => i + 1)
     .map((page) => <Page pageNumber={page} />)
  }
</Document>
```
* Turn off IDM extension module in your browser or it will prompt to download the file and you'll see and error "faild to load" in the browser.
* References
https://github.com/wojtekmaj/react-pdf
Upload files to S3 buckets from react
Tags: s3, react, upload, multipart
Published: 2020-09-06 03:06:57

*Disclaimer - When uploading files to s3 directly from front end, your AWS credentials are exposed in the network tab. Refrain from uploading files to protected S3 buckets directly from FE. Always use a server to upload files.*

You need to install `aws-sdk` npm package in order to upload files to s3 buckets.

`npm install aws-sdk --save`

Make sure the bucket has following policy
```
<?xml version="1.0" encoding="UTF-8"?>
 <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedMethod>DELETE</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <ExposeHeader>ETag</ExposeHeader>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>
```
The ETag header must be exposed or bigger uploads will not complete.


---

Let's write some React
`import AWS from 'aws-sdk'`

in the component constructor set the AWS access key and the secret keys. You get them straight from the aws console.
```javascript
AWS.config.update({
  accessKeyId: AWSAccessKeyId,
  secretAccessKey: AWSSecretKey
})
```
Create the bucket in the constructor as well
Always double check bucket's name and region.
```javascript
this.myBucket = new AWS.S3({
  params: { Bucket: 'video-bucket-xyz'},
  region: 'ap-south-1',
})
```
Now when ever you want to upload a file to the bucket call the following function and pass the selected file as function argument.
```javascript
uploadFile = (file) => {
  const params = {
    ACL: 'public-read',
    Key: file.name,
    ContentType: file.type,
    Body: file,
  }
  this.myBucket.putObject(params)
    .on('httpUploadProgress', (evt) => {
      // that's how you can keep track of your upload progress
      this.setState({
        progress: Math.round((evt.loaded / evt.total) * 100),
      })
    })
    .send((err) => {
       if (err) {
         // handle the error here
       }
    })
}
```
you can read more about putObject [here](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property).


---

References
[aws-sdk](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property)
Leetcode: Best Time to Buy and Sell Stocks II Python Solution With Explanation
Tags: python, datastructures, algorithms
Published: 2020-09-06 02:55:22

[Link](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) to leetcode question.

##Full Solution
```python
def maxProfit(self, prices: List[int]) -> int:
    if not prices or len(prices) is 1:
        return 0
    profit = 0
    for i in range(1, len(prices)):
        if prices[i] > prices[i - 1]
    return profit
```

##Edge Cases
```python
if not prices or len(prices) is 1:
    return 0
```
We need to check if anything is in the input. If nothing is in the input or if there is only one item in there, then we cannot make any profits. Therefore, we would return 0.

###Keeping Track of our Results
`profit = 0`
This should be pretty self explanatory where we would keep track of what we want to return at the end.

##Going Through the Input
`for i in range(1, len(prices)):`
You can do this part in many ways, but the way I solved this was iterating the input array starting from the second index so we can compare the current to the previous. 
If we compared the current to the previous and started at the beginning of the array, then we would hit an error.

```python
if prices[i] > prices[i - 1]:
    profit += prices[i] - prices[i - 1]
```

So if our current price is greater than the previous stock, then that means we will make a profit which is what we want. So we will add to our `profit` the difference between our current stock price and the stock price before it.

If the price of the stock is smaller than the previous stock price, then we will not make a profit so we will continue iterating through the input array.

Finally we can return the resulting profit.
Why use Redux?
Published: 2020-09-06 02:51:45

Well for first it helps you manage your state better, its actually quite a handy tool. What it does is gather all your state data of your application, saves it to a store, and then you can easily access it from any component. 
Now you might think it is not helpful or not needed. But as your application gets bigger, managing state becomes a lot harder and annoying.
I use react overall, and so I will be using it for this example. In react a state is managed inside a parent component, and you can pass it through sibling components as prop. And so you see that managing state gets messy, and this is why you need a tool like redux.
How does redux work? It has three main section to it. The first is action, this is how you send your data to the redux store. Then you have the reducers, that take the state and perform some action to that state and then return it. And last we have the store which holds all the state stored. With redux there is one store and all components have access to it. It also makes it a lot easier to test it and debug it.
How do you deal with information and learning overload?
Tags: productivity, discuss
Published: 2020-09-06 02:43:26

As people working in an ever-evolving discipline, we're encouraged to continuously learn and take in new information. We also know how information has proliferated so much and everyday there's just new information (or articles, blogs, topics) that keep popping up.

Personally, in addition to trying to keep up with software topics I also try to keep up and learn non-software fields too. But I find myself often getting sucked to click hell, using my time opening multiple links to materials that I find interesting or beneficial, but then never really getting to go over them earnestly.

Do you experience information/learning overload? If so how do you manage it?
I ️❤️ GitHub's Template Repository Feature
Tags: github, repository
Published: 2020-09-06 02:33:51

I've recently fell in love with a new [GitHub feature called "Github Template Repository"](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-template-repository). It allows you to set any GitHub repository as a "Template Repository". 

![Template Repository Checkbox](https://dev-to-uploads.s3.amazonaws.com/i/okhr6szx8bfvd4vfo7b6.png)

This will change the "Code" button to be "Use This Template".

![Use this template](https://dev-to-uploads.s3.amazonaws.com/i/8au2pnz7nynccjkfc415.png)

When you click it it will open up a page similar to when you create a brand new repo except instead it will start with the files in the template.

![Create from template page](https://dev-to-uploads.s3.amazonaws.com/i/mf7ed2rk7ipxrejm8exo.png)

This simple but powerful feature allows you to stop writing repetitive starter code, and dive right into creating.
Let's play a game Frontend Vs Backend devs ⚔⚔
Tags: javascript, backend, jokes, database
Published: 2020-09-06 01:52:29

Here goes mine joke for backend devs: 

> You know why frontend devs have lunch alone?
>.
>.
> because they don't know how to join tables 😅

 

**One special for MS developers** 😂
 
> You know why Microsoft devs wear glasses
>.
>.
> because they need to C sharp. 🤣

 
It's your turn fellas show devs what you got 💬💬👇👇
Day 97 : #100DaysofCode - Building a Single Page Application and Regex (FCC)
Published: 2020-09-06 00:30:39

Today I reviewed a video on how to build a single page application using <a href="https://github.com/typicode/json-server"> json server </a> as a database and javascript. I was able to practice making a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"> fetch request</a>, using <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">addEventListeners </a>, and using <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset"> data-sets</a>. I will be completing the application tomorrow and then I will attempt to build one without any help.

{% github SincerelyBrittany/js-fetch-review %}

In addition, I began to review FreeCodeCamp's regex video. I did not complete it yet but hope to soon so that I can complete that section on the website.

{% youtube ZfQFUJhPqMM %}

As always, thanks for reading!

Sincerely, 
Brittany
Generating UTC Timestamps for Postman Requests
Tags: postman, javascript, time
Published: 2020-09-06 00:26:32

---
title: Generating UTC Timestamps for Postman Requests
published: true
description: Put an end to manually creating timestamps for use in your Postman requests with Moment and JavaScript.
tags: postman,javascript,time
//cover_image: https://direct_url_to_image.jpg
---

**Update: Evidently using `new Date().toISOString()` works just fine and avoids all this moment lib nonsense. Much <3 to Josh & Liv for the update to my brain.**

You're using Postman, like you do, to test your API endpoints before you get into the code. You're going through the POST request and building that JSON when you get to the part where it wants a timestamp in UTC. Hmm, alright, well you probably don't want to have to create a fresh timestamp every time.

Enter JavaScript and Postman's excellent choice to give us access to the Moment library which you can read more about at www.momentjs.com.

For this particular request we need two things: the current UTC timestamp, and a later UTC timestamp (7 days later, for this example). First we'll import the library and then we'll use it, setting two environment variables using the built-in `pm.environment.set` function.

```javascript
var moment = require('moment');

pm.environment.set("now", moment.utc().toJSON());
pm.environment.set("later", moment.utc().add(7, 'days').toJSON());
```

That's all there is to it! Drop that into the pre-request script area of your request and that'll run before the request is submitted to the endpoint.

To make use of the timestamps, embed them where appropriate in your JSON request with double curly-braces around them.

```json
{
  "nodes": [1, 2, 3, 4],
  "unmanageFrom": "{{now}}",
  "unmanageUntil": "{{later}}",
  "relativeTime": false
}
```

If you're using a relatively recent version of Postman, the variable will turn orange even though they're inside a string. if they're red, you've either misspelled them in your JavaScript or in your request. Give it a closer look.
Learning Tries in Javascript
Tags: beginners, algorithms, javascript, computerscience
Published: 2020-09-06 00:12:16

In this weeks article I'm going to be discussing Tries. A Trie is a data structure thats main purpose is re<b>trie</b>val. Tries are most often used to store and retrieve strings in O(L) time, where L is the length of the string. A common use of a Trie data structure is to do prefix searching, such as an autocomplete form.

 ![Trie Example](https://dev-to-uploads.s3.amazonaws.com/i/w4a3d5r11urr07335wwx.png)

As you can see in the example above, each node contains a letter. Each chain of nodes will result in a string. In theory we could use a trie to store every word in the dictionary, but that would use an incredible amount of memory. For this reason Tries are often replaced by other data structures when a prefix search isn't necessary.

Tries have two main functions: 
* Insert
* Search

But before we dive into those, let's first start with implementing the overall structure.

![Node and Trie Classes](https://dev-to-uploads.s3.amazonaws.com/i/w8ph392f2sagdbhercem.png)

We need to create two classes, a node class and our tree class. Each node will contain a value, which is the letter it represents, a boolean representing if it's the last letter in a word, and an object for holding the nodes children. The Trie will only need the root, which is initialized as an empty node.

![Insert](https://dev-to-uploads.s3.amazonaws.com/i/161lb9v4aqt3tc7y00bk.png)

For our insert method we need to traverse through our tree. So to start we initialize a node variable representing the node we are currently on, and set it to the root. For each character in the passed in word, we see if our current node is holding the character as a child, if it isn't we add it as a child. We then change our current node to that character and repeat until we've gone through the word. After our traversal we set the last node's status to show it is the last character of a word.

![Search](https://dev-to-uploads.s3.amazonaws.com/i/4sxyiuqrl43faog3l0kn.png)

Our search method is similar to our insert method in that we are doing another traversal. However, all we do in the loop is check if each letter is present in the word. If all of the characters are there and the last character's status shows it's the last character of a word then we return true, otherwise we return false.

Thanks for reading! You can find the code for this post [here](https://github.com/123JackCole/Tries).