teleren/devto huggingface dataset:
JavaScript Relative Time
Tags: javascript, typescript
Published: 2021-07-05 01:45:58

I've found that Day.js and Moment.js's relative time support to be buggy, especially when dealing with very recent timestamps.

Here's an implementation in TypeScript:

```ts
// much love https://stackoverflow.com/questions/6108819/javascript-timestamp-to-relative-time

const units = {
	year: 24 * 60 * 60 * 1000 * 365,
	month: (24 * 60 * 60 * 1000 * 365) / 12,
	day: 24 * 60 * 60 * 1000,
	hour: 60 * 60 * 1000,
	minute: 60 * 1000,
	second: 1000
};

const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });

export const getRelativeTime = (d1: Date, d2 = new Date()): string => {
	const elapsed = d1.getTime() - d2.getTime();

	// "Math.abs" accounts for both "past" & "future" scenarios
	for (const u in units) {
		if (Math.abs(elapsed) > units[u] || u == 'second') {
			return rtf.format(Math.round(elapsed / units[u]), u as Intl.RelativeTimeFormatUnit);
		}
	}
};

```

and raw JavaScript:

```js
// much love https://stackoverflow.com/questions/6108819/javascript-timestamp-to-relative-time

const units = {
	year: 24 * 60 * 60 * 1000 * 365,
	month: (24 * 60 * 60 * 1000 * 365) / 12,
	day: 24 * 60 * 60 * 1000,
	hour: 60 * 60 * 1000,
	minute: 60 * 1000,
	second: 1000
};

const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });

export const getRelativeTime = (d1, d2 = new Date()) => {
	const elapsed = d1.getTime() - d2.getTime();

	// "Math.abs" accounts for both "past" & "future" scenarios
	for (const u in units) {
		if (Math.abs(elapsed) > units[u] || u == 'second') {
			return rtf.format(Math.round(elapsed / units[u]), u as Intl.RelativeTimeFormatUnit);
		}
	}
};
```

## Credits

https://stackoverflow.com/questions/6108819/javascript-timestamp-to-relative-time
Coding Shorts: Dependency Injection Explained
Tags: dotnetcore, csharp
Published: 2021-09-19 20:04:40

---
title: Coding Shorts: Dependency Injection Explained
published: true
date: 2021-07-05 01:43:35 UTC
tags: dotnetcore,csharp
canonical_url: http://wildermuth.com/2021/07/05/Coding-Shorts-Dependency-Injection-Explained
---

Like most of you, I've been using Dependency Injection in my projects for quite a while. Whether it be the built-in .NET Core Dependency Injection layer, Ninject, StructureMap, Unity, MEF, etc. I've been using a DI layer to do this work for many years. But before I understood the benefit, I did so somewhat reluctantly.

For me, it seemed like a lot of boilerplate for little benefit. But once I started using it, it clicked why it was so important. In this new Coding Shorts video, I show you why Dependency Injection is so important and why you'll want to use it once you understand how it works:

<iframe src="https://www.youtube.com/embed/csBIhx94bts" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

If you like the video, don't forget to subscribe to be notified of new videos!

[Subscribe to my YouTube Channel](https://www.youtube.com/c/swildermuth)

[![Creative Commons License](http://i.creativecommons.org/l/by-nc-nd/3.0/88x31.png)](http://creativecommons.org/licenses/by-nc-nd/3.0/)

 This work by [Shawn Wildermuth](http://wildermuth.com) is licensed under a [Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License](http://creativecommons.org/licenses/by-nc-nd/3.0/).  
 Based on a work at [wildermuth.com](http://wildermuth.com).

* * *

If you liked this article, see Shawn's courses on [Pluralsight](http://shawnw.me/pscourses).
 ![](http://feeds.feedburner.com/~r/ShawnWildermuth/~4/0CbU1VJqwZ0)
Como adicionar um menu de contexto "abrir git-bash aqui ..." ao Windows Explorer?
Tags: gitbash
Published: 2021-07-05 01:21:20

Segue tutorial:

1) Abra um novo bloco de notas (notepad) e salva o documento com o nome **OpenGitBash.reg** e o tipo como **todos os arquivos**

![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/etfccpnavezj2f71hq9r.png)
 
2) Cole o seguinte script dentro desse documento em branco:

```
Windows Registry Editor Version 5.00
; Open files
; Default Git-Bash Location C:\Program Files\Git\git-bash.exe

[HKEY_CLASSES_ROOT\*\shell\Open Git Bash]
@="Open Git Bash"
"Icon"="C:\\Program Files\\Git\\git-bash.exe"

[HKEY_CLASSES_ROOT\*\shell\Open Git Bash\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%1\""

; This will make it appear when you right click ON a folder
; The "Icon" line can be removed if you don't want the icon to appear

[HKEY_CLASSES_ROOT\Directory\shell\bash]
@="Open Git Bash"
"Icon"="C:\\Program Files\\Git\\git-bash.exe"


[HKEY_CLASSES_ROOT\Directory\shell\bash\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%1\""

; This will make it appear when you right click INSIDE a folder
; The "Icon" line can be removed if you don't want the icon to appear

[HKEY_CLASSES_ROOT\Directory\Background\shell\bash]
@="Open Git Bash"
"Icon"="C:\\Program Files\\Git\\git-bash.exe"

[HKEY_CLASSES_ROOT\Directory\Background\shell\bash\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%v.\""
```

3) Clique no arquivo 2 vezes e execute:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g6f7gh3e8oeig2bgjjs3.png)

4) Feito isso será exibido a opção de "Open to GitBash" ao seu windows explorer:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wo89hkx1mlwzx8xm65qx.png)
My First Web Application Project at Flatiron School
Tags: javascript, html, css, beginners
Published: 2021-07-05 00:05:18

For my first project at Flatiron School, I was given a task to build a Single Page Application (SPA) by using only HTML, CSS, and JavaScript. The data had to be accessed from a public API. All communication would be through JSON fetch requests. Before coming up with a plan, we must understand what an API is. An API stands for Application Programming Interfaces. It provides an easier syntax to use by allowing difficult features to be more easy to use.
After carefully planning my project, I started building my HTML file. It is used to format my structure of the application. Unfortunately, you don’t get to see your work come alive yet.
Here’s where JavaScript comes in! JavaScript is an object orient programming language designed to allow users to create interactive and responsive web pages.
Now here comes the fun part! Creating the CSS file allows you to customize the HTML elements by defining styles that includes the layout, the design, and much more. You can play around with the features until the application is the way you want it to be!
Here is my full code: https://github.com/hanaxdo/phase-1-javascript-project-mode
Forms can have...nests?
Published: 2021-07-05 00:01:55

### What's the purpose of a nested form?

In Rails, forms allow a user to input information and persist or save that data to a table, in a database. This is great if the information in the form only pertains to one table or model. However, what if the user wants to save information to multiple tables within one form? Well, that's when nested forms come to the rescue. 

### How are nested forms built?

To better explain, we'll refer to my Rails application - CalenDOC (an app for users to track medical appointments with relevant information (i.e. appointment date & time, doctor, notes etc.)). 

With my app, I wanted to grant users the ability to create an appointment with the choice of:
1. Picking a doctor from an existing dropdown list
OR 
2. Creating a new doctor

In order to offer this functionality, I needed to utilize a nested form that would persist the information as a new appointment object and the information for the new doctor object, if he or she decided to create a new one. 

#### Nested Form Ingredients
* Proper associations

![Appointments Model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r06l1egpilc4hbtjcrdc.png)

Since an appointment belongs to a doctor, it has access to the `doctors_attributes` key which gives us access to the the method illustrated above; `accepts_nested_attributes_for :doctor`.

* `f.fields_for`

![Appointment Form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k33834cmbscu55tiae17.png)

![Doctor Nested Form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzofwtwv93p27uauq0h3.png)

Here, I utilized the `f.fields_for` line to include fields pertaining to the Doctor object even though this form is nested inside the Appointment form. 

* New Method - Appointment & Doctor

![Appointments Controller](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mbld5d572bu9bs4t3xfg.png)

Lastly, we use the `.build` method within our new appointment so we can persists information about the new Appointment when the form is submitted, along with the new Doctor (if applicable).

###Conclusion

Nested forms are just another way for developers to add realistic functionality for users as they interact with our applications.
How can I convince my boss to let me learn a shiny new technology?
Tags: learning
Published: 2021-07-09 21:14:49

---
title: How can I convince my boss to let me learn a shiny new technology?
published: true
date: 2021-07-05 00:00:00 UTC
tags: learning
canonical_url: https://jhall.io/archive/2021/07/05/how-can-i-convince-my-boss-to-let-me-learn-a-shiny-new-technology/
---

So you’ve been a Python programmer for a decade, and you want to try the shiny new Go language. Or maybe AWS has become second nature to you, but you want to skill-up to Kubernetes and Helm. How can you make the case to your boss to let you spend the time?

First, realize that introducing a new technology usually means taking on new risk. And risk is something most managers are trained to avoid. So your enthusiasm for the shiny new thing probably won’t translate to enthusaism from your boss.

So the key is to find some value that your new learning will provide to your boss. Of course there’s no guaranteed formula, but here are some suggestions.

- **Improved performance.** When I first learned Go, it was to speed up a task previously handled by an incredibly slow Perl script. Go’s concurrency features made it a great fit for the task at hand. What performance can be gained with your new tool/language of choice?
- **Simplified maintenance.** Is your team struggling with repetitive or fragile maintenance tasks? Can your tool help solve this problem?
- **Streamlined development.** Most new tools and languages slow down development in the short term as you and others learn how to use them. But if they have a proven track record in the industry, you may be able to make the case.
- **Easier hiring.** Sometimes adding a new tool, or even switching entirely to a new tool, can make hiring easier, especially if you’re currently using niche or outdated tools.

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
How to select HTML elements tags directly inside CSS?
Tags: css
Published: 2021-07-05 00:00:00

---
  title: How to select HTML elements tags directly inside CSS?
  published: true
  tags: CSS
  date: Mon Jul 05 2021 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/select-html-element-tags-directly-inside-css
  cover_image: https://melvingeorge.me/_next/static/images/main-a91aaf15543c6033d79c36076407fc3c.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/select-html-element-tags-directly-inside-css)
  
To select an HTML element tag directly inside the CSS stylesheet, you can use the name of the HTML element tag directly in the CSS. These selectors are also called `type selectors` in CSS.

For example, consider 2 `p` (paragragh) tags in HTML like this,

```html
<!-- Paragragh tags-->
<p>Hello World!</p>
<p>Hello Devs</p>
```

Now in the CSS stylesheet, we can select the `p` HTML tags by wrting the name of the HTML tag in the CSS like this,

```css
/* Select p tags from HTML */
p {
  /* Your styles */
}
```

Like this, you can select any valid HTML element tags.

Now, Let's set the `color` of all the text in the `p` tags to red like this,

```css
/* Select p tags from HTML */
p {
  color: red;
}
```

This rule will set all the `p` HTML tags text to have the color `red`.

The output will look like this,

![paragragh HTML tags having red color](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c6ari9kz3hgpvo20xlat.png)

See the above code live in [JSBin](https://jsbin.com/hasavabiye/2/edit?html,css,output).

That's all 😃!

### Feel free to share if you found this useful 😃.

---
TwilioQuest 3 日本語プレビュー版リリース!
Tags: twilio, twilioquest, japanese
Published: 2021-07-06 07:28:53

---
title: TwilioQuest 3 日本語プレビュー版リリース!
published: true
date: '2021-07-05'
tags: twilio, twilioquest, japanese
canonical_url: https://www.twilio.com/blog/twilioquest-jp-preview
---

![TQ - JP preview version](https://twilio-cms-prod.s3.amazonaws.com/images/TwilioQuest-JP-WebSite.width-1616.png)

Twilio Developer Evangelistの[池原](https://www.twilio.com/blog/author/dikehara)です。ゲームを遊びながらTwilio製品の利用方法に加えGitHubやPythonを学習できる[TwilioQuest 3の日本語プレビュー版をリリース](https://www.twilio.com/quest/ja)しました。

## TwilioQuestとは?

TwilioQuestはゲームをプレイするようにさまざまな開発スキルを向上できるチュートリアルです。2019年に最新バージョンである「TwilioQuest 3」がリリースされました。Twilio製品の利用方法だけでなく、Pythonのようなプログラミング言語や、GitHubの使い方などを学習できます。

より詳しい説明やミッションの進め方については以前こちらの記事で取り上げていますので、こちらもぜひご覧ください。

- [Game + Tutorial = TwilioQuest3のはじめかた](https://dev.to/twilio/game-tutorial-twilioquest3-40cb)
- [TwilioQuest 3: Basic Training その1 - ハッキングデバイスを活用しセキュリティを解除せよ](https://dev.to/twilio/twilioquest-3-basic-training-1-68b)
- [TwilioQuest 3: Basic Training その2 - Twilioアカウントの作成と電話番号の取得](https://dev.to/twilio/twilioquest-3-basic-training-2-twilio-m28)
- [TwilioQuest 3: Basic Training その3 - プロモーションコードを適用し無料クレジットをゲット](https://dev.to/twilio/twilioquest-3-basic-training-3-ida)

全編英語で作成されていますが、ゲーム好きな開発者には非常に人気のコンテンツです。日本でも多くのみなさんにプレイいただいていますが、「日本語版が欲しい」という要望を多くいただいたため今回、日本語版を開発しました。

## 日本語プレビュー版について

![TQ - JP preview version](https://twilio-cms-prod.s3.amazonaws.com/images/tkpUrdSf2WZc10W11P23Lag1kMgGyd7M7kuQ5R4mD52sdk.width-800.png)

今回のリリースでは下記4つのミッションコンテンツと **一部のUIを日本語化** しています。

- `基本トレーニング` - TwilioQuestのプレイ方法、ならびにTwilio製品の基本を学べるミッション
- `Voice: マラカイト鉱山` - Twilio Programmable Voice入門ミッション
- `Pythonic Templeの謎` - Python入門ミッション
- `オープンソースの炎` - Git、GitHub入門ミッション

基本的なプレイ方法については英語版と同じですが、ミッション内容については単純な翻訳だけではなく日本の皆さんに向けて加筆・修正を加えています。

![TQJP - Fog Owl](https://twilio-cms-prod.s3.amazonaws.com/images/Us7eG1miwxjs8oxB5YFLl809wBFkZtJu5tPw-Jj8tEMq0F.width-800.png) ![TQJP - voice](https://twilio-cms-prod.s3.amazonaws.com/images/trBmHPHVFoj3hyYZu1LTyLonyGUMW8x-q588nuVFse6J8c.width-800.png)

## ダウンロードおよびインストール方法

TwilioQuestは下記よりダウンロードいただけます。英語版をすでにお持ちの方は改めてダウンロードいただく必要はありません。過去にプレイされた記録はそのまま保持されます。  
  
[TwilioQuest - ダウンロード](https://www.twilio.com/quest/ja/download)

日本語プレビュー版の起動方法については[こちら](https://youtu.be/N9ySG7QiM-g)をご覧ください。

## Let’s Hack!

ぜひ、日本語版をプレイしてみてください!今後も日本語ミッションの追加、アップデートを予定しています。

日本語版の不具合や質問については下記までお問い合わせください。

- Twitter: [@neri78](https://www.twitter.com/neri78)
- Email: dikehara [@] twilio.com
Estado en componentes de Clase
Tags: react, webdev, spanish
Published: 2021-07-04 23:37:37

En los componentes de clase, el estado incial, se declara dentro del metodo constructor. 
Tenemos que hacer referecia con `this` a `.state` y le asignamos a un objeto los valores, dentro de  las llaves de éste, estos son los valores del estado.

![Ejemplo de método constructor: constructor(props){
		super(props);
		this.state = {
			valor1: 'Valor 1',
			valor2: 2,
		}
	}](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3l1damozb7rha0d5wtrv.png)

Podremos acceder en cualquier otro momento mediante this.state.valor1 , this.state.valor2 , etc.
Ejemplo:
![Aceediendo a los valores de estado](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vlsil0316c7erap9qic8.png)

`this.setState()` Es una función similar a `setName` , nos permite acualizar los valores del estado incial. `setState` es un elemento propio de `this` que recibe como argumento un objetos con los atributos que se vayan a actulaizar, inicializados dentro de `this.state`

NOTA IMPORTARTANTE! Nunca invocar el `setState` en el método constructor o en el método render porque la aplicación se romperá y entrará en un ciclo infinito.

## Declarando funciones en componenetes de Clase.

Si queremos declarar funciones dentro de nuestro componentes de clase, la manera de invocarlas para el manejo de valores de estado se debe tomar en cuenta la palabra reservada `this`. Por ejemplo:
![Imagen que muestra una funcion dentro de un componente de clase](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bp7idqb5w6002wl77dia.png)

En el ejemplo anterior this.state.name  y  this.state.lastName apuntan a los valores de estado de  nuestro componente e invocamos a esos datos  llamando a la funcion con this.getFullName , cabe resaltar que sin la palabra reservada this no podremos manejar los valores de estado en nuestro componente de clase ya que nuestro codigo se rompería.
On APIs and REST Architecture (Part 2)
Tags: node, restapi, crud, codenewbie
Published: 2021-07-10 20:12:08

---
title: On APIs and REST Architecture (Part 2)
published: true
date: 2021-07-04 23:30:05 UTC
tags: nodejs,restapi,crud,codenewbie
canonical_url: https://medium.com/@oaluna/on-apis-and-rest-architecture-part-2-5b5d5a9fa603
---

[![](https://cdn-images-1.medium.com/max/2600/0*tRxDziY_sfEJ5uDd)](https://medium.com/@oaluna/on-apis-and-rest-architecture-part-2-5b5d5a9fa603?source=rss-be00f566a88f------2)

Leveraging client-server communications using CRUD operations

[Continue reading on Medium »](https://medium.com/@oaluna/on-apis-and-rest-architecture-part-2-5b5d5a9fa603?source=rss-be00f566a88f------2)
How to display a user’s last login date in #WordPress admin
Tags: wordpress, php
Published: 2021-07-04 23:22:56

A few weeks ago when a WordPress site I managed crushed, I had the client ask to view stats of user login times. By default WP does not support this.

First quick fix for such solutions is to install a plugin. Great option - I found this plugin called [When Last Login](https://wordpress.org/plugins/when-last-login/). Its a lightweight plugin that allows you to see active users according to their last login time/date, with zero configuration - plug and play.

After installing it worked well. But being the developer I am, I was not settled having an extra plugin so I did some reading in the WP Codex and after a month I figured out a solution - plugin free.

If you’re familiar with adding code snippets to your site via functions.php or the code snippets plugin you can use this to add the user’s last login timestamp to the WP admin.

```php
//Record user's last login to custom meta
add_action( 'wp_login', 'capture_user_login_time', 10, 2 );

function capture_user_login_time( $user_login, $user ) {
    update_user_meta( $user->ID, 'last_login', time() );
}

//Register new custom column with last login time
add_filter( 'manage_users_columns', 'user_last_login_time_column' );
add_filter( 'manage_users_custom_column', 'last_login_column', 10, 3 );

function user_last_login_time_column( $columns ) {
	$columns['last_login'] = 'Last Login';
	return $columns;
}

// Output last login column onto WP Front end
function last_login_column( $output, $column_id, $user_id ){
	if( $column_id == 'last_login' ) {
        $last_login = get_user_meta( $user_id, 'last_login', true );
        $date_format = 'M j, Y';
        $hover_date_format = 'F j, Y, g:i a';
        $output = $last_login ? '<div title="Last login: '.date( $hover_date_format, $last_login ).'">'.human_time_diff( $last_login ).'</div>' : 'No record';
	}
	return $output;
}
```
LinkedList Questions: Reverse a Linked List - Iterative version
Tags: algorithms, cpp, codenewbie, linkedlist
Published: 2021-07-04 22:21:12

In this series of posts, I will discuss coding questions on the `LinkedList` Data structure.
The posts in this series will be organized in the following way,

1. Question Link ❓
2. Possible Explanation 📝
3. Documented C++ Code 🧹
4. Time and Space Complexity Analysis ⌛🌌

## The Question

Given the `head` of a singly linked list, reverse the list, and return the reversed list.

[https://leetcode.com/problems/reverse-linked-list/](https://leetcode.com/problems/reverse-linked-list/)

> 💡 Give yourself at least 15-20 mins to figure out the solution :)

> 💁🏻‍♂️ Tip: You need to be good at pointer manipulations.

## Explanation

We will go through every node and make it point to its preceding node. The idea is fairly simple, it's all about **pointer manipulations** and how you will do it. Here's the algorithm,

- Initialize three pointers, `prev = null`,  `nex = null`,  `cur = head`. At every iteration `cur` will point to the *current* node, `prev` will point to its *preceding* node and nex will point to its *succeeding* node.
- *while cur ≠ null* i.e until we haven't reversed every node
    - *nex = cur* ( Before we change `cur's` next, take hold of its succeeding node )
    - *cur → next = prev* ( Reverse the link )
    - *prev = cur* (Update `prev` for following iteration )
    - *cur = nex*  (Update `cur` for following iteration )
- Make `head = prev` ( prev points to the first node of reversed linked list )
- return `head`

Here's a dry run on a list of **5** elements to make things more clear, 

![Dry run of algorithm](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0br4kednpluc4g85qlk9.jpg)

## C++ Code

### Definition of LinkedList

```cpp
//Definition for singly-linked list.
struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

```

### Solution

```cpp
ListNode *reverseList(ListNode *head)
    {

        ListNode *prev = nullptr;
        ListNode *cur = head;
        ListNode *next = nullptr;

        //while cur is pointing to a node
        while (cur)
        {
            //get access to the node ahead
            next = cur->next;

            //break the forward link
            cur->next = prev;

            //moving prev ahead
            prev = cur;

            //updating current node
            cur = next;
        }
        //After the loop, prev will be pointed to the required node
        head = prev;
        return head;
    }
```

## Complexity Analysis

### Time Complexity: O(n)

We are traveling every node.

### Space Complexity: O(1)

We didn't use any extra space.

> 💡 Can you think of a *recursive* solution? I will answer this in the next post.
PhP Curl Basic code to scrape
Tags: php, codenewbie
Published: 2021-07-04 20:26:06

curl_init() : initialize a cURL session.

curl_setopt() : you can set all your options for the transfer.

curl_exec() : you can execute the session.

curl_close() : you finish off your session.

Using Above 4 Function, I will fetch [MovieBox Pro](https://movieboxpro.live) Website details.

<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://movieboxpro.live');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
echo $result;
?>