teleren/devto huggingface dataset:
Fix developer path after upgrade to MacOS Catalina
Tags: macos, shell, git
Published: 2021-01-20 18:16:08

After MacOS system upgrade to [Catalina](https://www.apple.com/macos/catalina/), on my computer **git** did not work anymore. If you happened the same, the following steps resolve it for me!

Running any of git commands, you would probably got this error

```shell
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
```

To fix it, you had to run

```shell
xcode-select --install
```

The "xcode-select" command requires the command line developer tools.

A prompt will appear asking you to install it now.

<img loading="lazy" src="https://res.cloudinary.com/giuliachiola/image/upload/v1585479297/super-blog/012-mac-os-catalina/xcode-prompt_n6obrx.jpg" alt="xcode-prompt" width="1146" height="604">

When installation is completed, git should work as expected! 😎

> 📚 More info
>
> [Invalid active developer path](https://apple.stackexchange.com/questions/254380/why-am-i-getting-an-invalid-active-developer-path-when-attempting-to-use-git-a)
Add items to an array in Nunjucks
Tags: nunjucks, twig
Published: 2021-01-20 18:13:00

To add items in Nunjucks, use the `.push()` function.

  ```twig
  {% set arr = [1,2] %}
  {% set arr = (arr.push(3), arr) %}
  ```

Final array:

```md
arr = [1,2,3]
```

Unfortunately, I did not found any references in the official [Nunjucks documentation](https://mozilla.github.io/nunjucks/templating.html) for this useful function 🤷🏻‍♀️

  ```twig
  {% set animals = ['cat 🐱', 'dog 🐶', 'lion 🦁'] %}
  {% set domesticAnimals = [] %}
  {% for animal in animals %}
    {% if animal !== 'lion' %}
      {% set domesticAnimals = (domesticAnimals.push(animal), domesticAnimals) %}
    {% endif %}
  {% endfor %}
  ```

Final array:

```md
domesticAnimals = ['cat 🐱', 'dog 🐶']
```

> 🧨 **!important**
>
> If you use `{% set .... %}` inside a for-loop block, pay attention to have defined it **outside** before entering the loop.
> I wrote a post about it: [📒 Nunjuks scoped variable declarations](https://giuliachiola.dev/posts/nunjucks-scoped-variable-declarations/)

<br> 

> 📚 _More info_
> 
> Docs about [Twig 'push' filter](https://www.branchcms.com/learn/docs/developer/twig/filters/item/push). Note that this filter is not present into the official [Twig documentation](https://twig.symfony.com/doc/3.x/) 🤷🏻‍♀️
CLI tools: Replace snake by camel in a text file
Tags: devops, beginners, perl
Published: 2021-01-20 18:12:49

---
title: CLI tools: Replace snake by camel in a text file
published: true
description: Perl is very powerful on the
tags: DevOps, Beginners, Perl
---

I have a file that has the word "snake" in it 

```
There is a snake in the first line.
No such word in the second line.
Another snake in the 3rd line.
There is a blue snake and a red snake here.
```

This one-liner that you can run on the command line will replace the word "snake" by the word "camel" in the file:

```
$ perl -i -p -e 's/snake/camel/g' snakes_or_camels.txt
```

This one-liner will create a backup of the original file before making the changes.

```
$ perl -i.bak -p -e 's/snake/camel/g' snakes_or_camels.txt
```

* `-i` means "inplace editing"
* `-i.bak` means "copy to .bak then inplace editing"
* `-p` means (in rough terms) "What ever you do, do it on every line of data."
* `-e` means "execute the following code".
* `s/snake/camel/g` is a substitution. The `g` at the end means globally. Without that only the first snake would be replaced.

The result is

```
There is a camel in the first line.
No such word in the second line.
Another camel in the 3rd line.
There is a blue camel and a red camel here.
```

If you'd like to learn more about Perl check out my [Perl Tutorial](https://perlmaven.com/perl-tutorial)
CSS Lint for Target _blank, noopener and noreferrer
Tags: css, security, html
Published: 2021-01-20 18:09:56

If you have been developing websites for some time, you may know that adding a target of _blank to a link can have some unintended consequences. I sometimes find myself wondering which of these to add and and having to look them up.

**Summary:**
Use **rel="noreferrer noopener"** at minimum. There is also a **nofollow** that you may want to use but this has less to do with security and more about passing “link juice” along to the site that you are linking to. When you do not use **nofollow** you are basically vouching for the site that you link to and this can also affect your SEO. So, just make sure to use **nofollow** when linking to sites that may not be as reputable.

## WHY ARE WE DOING THIS?
>The threat associated is called Reverse Tabnabbing. The issue is the webpage that we are linking our existing page to gains a partial access to the linking page, or in other words, the target page or url gains a partial access to our parent page from where the user is redirected to a new url.

>This happens through the window.opener object of Javascript. The attacker can change the window.opener.location to some malicious page and also the parent page. In case the parent page has the same look and feel of the user intended page, he might end up sharing credentials or secure information assuming that the webpage is secure.

>*Hackernoon – https://hackernoon.com/unsafe-use-of-target_blank-39413ycf*

## WARNING MYSELF AND OTHERS WHEN WE FORGET…
WordPress does a pretty good job with adding these in the editor and I can add a linting rule for my own code. But, sometimes there are places where code or content can be added by site admins or editors in places where this may not get caught. To help find these, I am playing with the idea of this CSS linting rule.

[Read More About CSS Lint for _blank targets](https://rainey.dev/target-_blank-noopener-noreferrer-and-nofollow/)
Add HTML classes to 11ty markdown content
Tags: 11ty, eleventy
Published: 2021-01-20 18:08:44

[11ty](https://www.11ty.dev/docs/) comes with some useful plugins for markdown manipulation, one of these is [markdown-it-attrs](https://github.com/arve0/markdown-it-attrs).

This plugin should be used combined with its big brother, the markdown parser [markdown-it](https://github.com/markdown-it/markdown-it), which is already added in 11ty basic installation.

**markdown-it-attrs** uses `markdown-it` and add the possibility to add attributes to HTML nodes generated from markdown.

To use it, add this plugin to the `.eleventy` configuration file:

- require `markdown-it`

```javascript
const markdownIt = require('markdown-it')
```

- require `markdown-it-attrs`

```javascript
const markdownItAttrs = require('markdown-it-attrs')
```

- define basic `markdown-it` configuration options

```javascript
const markdownItOptions = {
  html: true,
  breaks: true,
  linkify: true
}
```

- set `markdown-it-attrs` as `markdown-it` usage options

```javascript
const markdownLib = markdownIt(markdownItOptions).use(markdownItAttrs)
```

- set as eleventy configuration the new markdown configuration

```javascript
eleventyConfig.setLibrary('md', markdownLib)
```

To sum up:

```javascript
// .eleventy.js

const markdownIt = require('markdown-it')
const markdownItAttrs = require('markdown-it-attrs')

const markdownItOptions = {
  html: true,
  breaks: true,
  linkify: true
}

const markdownLib = markdownIt(markdownItOptions).use(markdownItAttrs)
eleventyConfig.setLibrary('md', markdownLib)
```

### Example of usage

```md
# This is a title {.c-article-section__title}
This is a paragraph with data-state {data-state=important}

Another text with attributes {.c-article-section__disclaimer #articleId attr=value attr2="spaced value"}

![Alt text](image.jpg){.u-shadow}

[Link in a new tab](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a){target="_blank" rel="noopener"}
```

will output

```html
<h1 class="c-article-section__title">This is a title</h1>
<p data-state=important>This is a paragraph with data-state</p>
<p class="c-article-section__disclaimer" id="articleId" attr=value attr2="spaced value">Another text with attributes</p>

<img class="u-shadow" src="image.jpg" alt="Alt text">
<a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a" target="_blank" rel="noopener">Link in a new tab</a>
```

> 🧨 **!important**
>
> Note the last line where I added the `target="_blank"` attribute to the link to open it in a new browser tab. It's ok open a link in a new tab, but for security reasons it has to have also the `rel="noopener"` attribute.

Side note: unfortunately, I did not find a way to add attributes to markdown _tables_ and _blockquote_ 😢

> 📚 More info
>
> - [11ty Markdown Attributes](https://dev.to/iarehilton/11ty-markdown-attributes-2dl3)
> - [When to use target="_blank” by Chris Coyer](https://css-tricks.com/use-target_blank/)
> - [rel="noopener" - MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types/noopener)
Pre-compiled pytorch versions
Tags: python, pytorch, cuda, gpu
Published: 2021-01-20 17:51:25

---
title: Pre-compiled pytorch versions
published: true
description: Pytorch official repo with many pre-compiled versions of pytorch library.
tags: python,pytorch,cuda,gpu
cover_image: https://upload.wikimedia.org/wikipedia/commons/9/96/Pytorch_logo.png
---

I had just found about a repository that just saved my bacon so I decided to share it with you guys.

If you go to pytorch's website, you'll be given a lot of choices to install it:

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

The thing is, if you want to install a different version than the one listed (1.7.1 as of today) you'll begin a not very pleasant treasure hunt.

There's a repo that somehow took me quite a while to find here:

```console
https://download.pytorch.org/whl/torch_stable.html
```

But you don't need to click on it! You can ask `pip` to fetch it for you:

```console
pip[3] install pytorch==1.6.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html
```

And voilá, your package will be installed automagically!

Now some extra tips:

1. Some `cuda` versions are considered "default". For instance if you look for `1.6.0+cu102` you won't find it, that's because installing `pip install cuda==1.6.0` will automatically fetch cuda's `10.2` version.

2. If you're a masochist and need the CPU-only version: `pip install 1.6.0+cpu`

3. To save this repo on your `requirements.txt`, just add this as the first line of it:

```console
-f https://download.pytorch.org/whl/torch_stable.html

...
torch==1.6.0+cu110
...
```

Happy torching!
Human-readable Numbers
Tags: webdev, javascript
Published: 2021-01-20 17:38:02

---
title: Human-readable Numbers
published: true
description: Convert a JavaScript number to a human-readable number the easy way
tags: webdev, javascript,
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/x5f3z70h8lqa489cmm7m.jpeg
---

I recently came across a situation where I was required to add two numbers before displaying them on the frontend.

Here is a (very) simplistic example…
```javascript
  const valueA = 12300
  const valueB = 45.67
  const numberToDisplay = valueA + valueB // 12345.67
```

The trouble was, the client didn't like the way the number was displayed - `12345.67` felt _"too computer-y"_ :joy:

I'm old enough to remember having to write a function that counted the number of digits in the string and insert commas (or fullstops) in the relevant places but I thought to myself: "Hey, it's 2021! JavaScript is better now! There must be an easier way!"

So, a little bit of searching later - [`Number.prototype.toLocaleString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString)!!! :tada:

This handy method will convert a given `Number` into a human-readable `String` based on a given language.

In this handy utility function, we format the given value based on the `lang` attribute on the `<html/>` element unless one is explicitly provided.

```javascript
const humanReadableNumber = (value, lang = null) => {
  if (!value) return;
  const locale = lang || document.documentElement.lang || 'en'
  const number = parseFloat(value, 10)
  return number.toLocaleString(locale);
}
```

So, using our example from before…

```javascript
  const valueA = 12300
  const valueB = 45.67
  const numberToDisplay = humanReadableNumber(valueA + valueB) // 12,345.67
```

If you want to have a play around, I made a [CodePen](https://codepen.io/thomasxbanks/pen/PoGLMdE)

Hope this is as useful for you as it was for me! 😎
Welcome Thread - v108
Tags: welcome
Published: 2021-01-20 17:31:22

---
title: Welcome Thread - v108
published: true
description: Welcome to DEV! A thread of hellos and intros.
tags: welcome
canonical_url: 
---

![Yay](https://media.giphy.com/media/l4pTfqwRupvNCiEa4/giphy.gif)

### Welcome to DEV!

1. Leave a comment below to introduce yourself! You can talk about what brought you here, what you're learning, or just a fun fact about yourself.

2. Reply to someone's comment, either with a question or just a hello. 👋 

**Great to have you in the community!**
How to update object or array state in React
Tags: javascript, typescript, react
Published: 2021-01-20 17:27:41

Ever tried to update object or array state directly in React?
I did that, the state of my component didn't change.
Destructuring the object/array was the solution.

When you update the state, create a new array/object by destructuring the one in the state, manipulate it then set it as a new value in the state.

## Object

```javascript
import React, { useState } from 'react';

const States = () => {

  const [objectValue, setObjectValue] = useState({});

  const updateObjectValue = (key, value) => {
    // Destructure current state object
    const objectvalue = {
      ...objectValue,
      [key]: value,
    };
    setObjectValue(objectvalue);
  };

  return <Component/>;

};

export default States;
```

## Array

```javascript
import React, { useState } from 'react';

const States = () => {

  const [arrayValue, setArrayValue] = useState([]);

  const updateArrayValue = (value) => {
    // Destructure current state array
    const arrayvalue = [ ...arrayValue ];
    arrayvalue.push(value);
    setArrayValue(arrayvalue);
  };

  return <Component/>;

};

export default States;
```

### Happy Hacking!
Why Little Boat <3 Prismic
Tags: prismic, gatsby, cms
Published: 2021-01-20 17:21:01

Here at Little Boat Digital, we've tried all different types of headless (and not so headless!) CMS's. and we've decided to back Prismic. 

Whilst this doesn't mean we won't use the others, everything has its merits, we're using Prismic for [our website](https://littleboat.digital) and will offer it to future clients.

Now. Enough about **us**, why did we pick it?!

## Why Prismic?

### Gatsby support for previews
![The preview button](https://dev-to-uploads.s3.amazonaws.com/i/qfqt3sq32fj7qaomrfo8.png)

A lot of issues we had with other headless options, is a lot of our clients wouldn't want to wait for a staging site to rebuild before seeing their content where it'll actually live.

With Prismic, and a little magic & configuration, we were able to set up support against **our live site**, getting rid of the need to have a staging server. 

### WYSIWYG schema editing

![Custom blocks](https://dev-to-uploads.s3.amazonaws.com/i/uomdcdoqdhho1r4p7pe7.jpeg)

Whilst not essential, it's super nice to be able to drag a few content types out from an interface and call it a day.

Our clients can essentially make a new page/content type on the fly, pass it over to us as requirements and then we can build around a page with the data they're wanting. _Mindblowing!_

### Slice Machine

![Slice Machines](https://dev-to-uploads.s3.amazonaws.com/i/0297gd6qrvgigdty19qq.jpeg)

Whilst this isn't a feature for Gatsby (yet), using slice machines in Next is next level. In the past, we've had to create a `BlockBuilder` component to wrap our slices, loop over them, and a whole tonne of markup to get there.

With slice machines, they abstract a lot of that away, giving you a one line option to run instead.


I hope this list, despite being short, gives you some thought for your next CMS. I feel I ought to say, Prismic didn't pay for this post, no sponsorship etc. I just love what they're doing over there and I'm excited to see what happens next.
Easy way to use Dark Mode in Next.js + Tailwind
Tags: nextjs, css, react, javascript
Published: 2021-01-20 17:13:35

Yesterday I was working on my personal website, and I really wanted to add a dark mode toggle.
I already converted my site to use Tailwind before, so how do I enable dark mode now?

It's simple: in Tailwind v2 dark mode is built in (https://tailwindcss.com/docs/dark-mode).

To be able to toggle the dark mode, you should put `darkMode: 'class'` in your `tailwind.config.js`. 
This configuration implies that a class called `dark` will be added to the `<html>` tag. 
Once this class is active, your `dark:{class}` classes will become active.

To link this functionality up with Next.js I used the lightweight <b>next-themes</b> library (https://github.com/pacocoursey/next-themes). 

After installing this library, simply change your _app.js to include the ThemeProvider:
```react
import { ThemeProvider } from 'next-themes'

function MyApp({ Component, pageProps }) {
  return (
    <ThemeProvider attribute="class">
      <Component {...pageProps} />
    </ThemeProvider>
  )
}

export default MyApp
```

<b>Including the `attribute="class"` is very important, since this tells the library to use the Tailwind dark theme class.<b>

For the toggle button I used the following:
```react
import {useTheme} from 'next-themes'

const {theme, setTheme} = useTheme()

<button
  aria-label="Toggle Dark Mode"
  type="button"
  className="p-3 h-12 w-12 order-2 md:order-3"
  onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
>
```

An example of the `dark:{class}` code, this will use a purple background color for light mode and a darkgrey color for dark mode:
```react
<nav className="fixed bg-purple dark:bg-darkgrey h-16 w-full z-50">
```

And that's it! The theme is being switched when you click the button. 
Live example can be found here: https://www.thomasledoux.be/
Github source: https://github.com/thomasledoux1/website-thomas
Inspired by: https://leerob.io
The end of LibSass
Tags: css, saas, webdev
Published: 2021-01-20 17:12:12

As someone who doesn't consider himself as a designer, discussions around different sass compilers never caught my attention as the differences were too minor for my use cases.
However, recently I noticed that more and more packages have problems compiling modern Sass & SCSS.
I finally looked into the topic and was shocked:

## Since October of 2020 LibSass is deprecated

This is huge as npm packages like node-sass with roughly 5 Million downloads a week are basically deprecated as well, without the packages themselves being marked as such! While the deprecation warning is stated in the readme, not setting these packages themselves to the deprecation state means that any packages having it as a dependency will not produce any warning when installating or updating your dependencies. And last time I checked, VSCode uses libSass to compile Sass as well as a built in compiler.

## What you should do

When starting projects, make sure to use packages based on DartSass. For node, this means using the package sass instead of node-sass. If you use your IDE to compile, make sure to check out if there are plugins/extensions that use dartSass instead of libSass (as usual, if you are using Webstorm you are already fine)

Happy coding!
How to test AWS services locally with Moto library?
Tags: python, testing, aws
Published: 2021-01-20 17:04:26

Currently, I'm working on coding Python services that work with AWS S3 buckets. However, for unit testing parts of these services, I don't want to create a separate AWS S3 bucket just for my unit tests. 

It would require managing AWS credentials and it would take a bunch of time to set up for multiple team members. What if there is a way to Mock AWS S3 service on local that does not require any steps from the above?

That's how I found [Moto library](https://github.com/spulec/moto) for Python.

- Run the example below on [Replit](https://repl.it/talk/share/Examples-of-using-moto-to-develop-for-AWS/116066).

```python
import os
from moto import mock_s3
import boto3
import pprint

BUCKET_NAME = "test_bucket"

os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing'
os.environ['AWS_SECURITY_TOKEN'] = 'testing'
os.environ['AWS_SESSION_TOKEN'] = 'testing'


with mock_s3():
    client = boto3.client('s3', region_name='us-east-1')
    client.create_bucket(Bucket=BUCKET_NAME)

    def write_value_to_s3(key, value):
        s3 = boto3.client('s3')
        key = key.split("/")
        bucket_name = key[0]
        key_in_the_bucket = "/".join(key[1:])
        s3.put_object(Bucket=bucket_name, Key=key_in_the_bucket, Body=value)


    path_1 = f"{BUCKET_NAME}/a/d"
    path_2 = f"{BUCKET_NAME}/b/c"

    write_value_to_s3(path_1, "")
    write_value_to_s3(path_2, "")

    client = boto3.client("s3")

    object_page = client.list_objects_v2(
        Bucket=BUCKET_NAME,
        Prefix="a",
        Delimiter="/"
    )

    pprint.pprint(object_page)

    object_page = client.list_objects_v2(
        Bucket=BUCKET_NAME,
        Prefix="",
        Delimiter="/"
    )

    pprint.pprint(object_page)

    path_3 = f"{BUCKET_NAME}/a"
    write_value_to_s3(path_3, "")

    object_page = client.list_objects_v2(
        Bucket=BUCKET_NAME,
        Prefix="",
        Delimiter="/"
    )

    pprint.pprint(object_page)

    path_4 = f"{BUCKET_NAME}/a/b"
    write_value_to_s3(path_4, "")

    object_page = client.list_objects_v2(
        Bucket=BUCKET_NAME,
        Prefix="a/",
        Delimiter="/"
    )

    pprint.pprint(object_page)


    path_5 = f"{BUCKET_NAME}/a/b/c"
    write_value_to_s3(path_5, "")

    object_page = client.list_objects_v2(
        Bucket=BUCKET_NAME,
        Prefix="a/b",
        Delimiter="/"
    )

    pprint.pprint(object_page)
```
And here you go 💪