teleren/devto huggingface dataset:
Bash Notes
Tags: bash
Published: 2020-04-26 14:07:19

# Case Convertion
```bash
# Convert snake/kebab case to upper camel.  MacOS and Linux.
> echo 'snake_or-kebab-case' | sed -E 's/(-|_)/ /g' | awk '{for (i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) substr($i,2)} 1' | sed -E 's/ //g')"
# output: 
SnakeOrKebabCase
```

# Color output
```bash
color_some_output_light_blue() {
  while read line; do
    # If line has substring "environment"
    if [[ "$line" == *environment* ]]; then
      # Light blue color
      printf '\e[1;34m%s\e[m\n' "$line"
    else
      echo "$line"
    fi
  done
}

cat file | color_some_output_light_blue
```

# Arrays
## Create array from lines with spaces
```bash
# If you have file like this
cat file
# output:
foo bar
baz 
qux

# This doesn't work, because it breaks at both space and new line
arr=($(cat file))
printf "%s;%s;%s\n" "${arr[@]}"
# output:
foo;bar;baz

# This works
declare -a arr
while IFS='' read -r line; do
  var+=("$(line)") # Note the quotes
done <<<"$(cat file)"
printf "%s;%s;%s\n" "${arr[@]}"
# output:
foo bar;baz;qux

```
📖 New book: Using Gatsby and Netlify CMS
Tags: gatsby, react, books, showdev
Published: 2020-04-26 13:59:11

Hello DEV Community!

I'm so excited to announce that my new book, Using Gatsby and Netlify CMS, is finally available!

I'm excited and nervous as this is my first-ever book!

The book walks through building a sample project with Gatsby, using Netlify CMS as the backend. Some familiarity with Gatsby is helpful, but it gives a basic introduction as well for those who haven't used it before.

It walks through a complete example but isn't too long of a read.

You can get the book here: https://leanpub.com/using-gatsby-and-netlify-cms
How to add .env and use process.env to your typescript project
Tags: typescript, env, processenv, environmentvariables
Published: 2020-04-26 13:49:38

---
title: How to add .env and use process.env to your typescript project
published: true
description: This article shows you how to add .env and use process.env to your typescript project
tags: typescript, env, process.env, environment variables
---

I recently came across this problem in my project and the usual google search/Stackoverflow readings lead to partial and confusing solutions.
So i’m going to document my solution, hopefully someone finds it useful.

First install dotenv package
```
npm install dotenv;
 OR 
yarn add dotenv;
```

Import to the entry point of your code. This is usually your *index.ts, main.ts or app.ts*

```
import * as dotenv from 'dotenv';

//inside your starter code, do this
...
...
dotenv.config();
...
```

Now you are ready to use, process.env.ENVIRONMENT_VARIABLE with your project.

However, i will recommend creating a config module to put all your environment variables access. This approach has a lot of benefits such as:
  - ease of code refactoring: a single place to update, change any environment variable key or default value. This is better than doing All-files-search of a variable name.
  - ease of testing: you can mock or intercept this.
  - Clean code: this approach is modular and less typing.

Your config module could look like this. *endpoints.config.ts*

```
export default {
 UserBaseUrl: process.env.USER_SERVICE_URL ?? '',
 EtlUrl: process.env.ETL_SERVICE_URL ?? ''
}
```

Now in your code, you can do something like this

```
import endpoint from '../endpoints.config';
... 
...
const user = await axios.get(endpoint.UserBaseUrl, { params})
...
```

That’s it!. Feel free to leave a comment if i missed anything or you are having issues with this.
Thanks
The String#chars method
Tags: ruby, tutorial, todayilearned, codenewbie
Published: 2020-04-26 13:46:05

_Originally published on https://ali-ilman.com/blog/the-string-chars-method._

I was browsing the web and I noticed Ruby code that utilises a `String` instance method called `chars`.
Until today, I'd never used nor heard of `String#chars`. What does it do?

`String#chars` is used to return an array of characters within a string.
```ruby
name = 'Ali'
name.chars
=> ["A", "l", "i"]
```
Do note that it **does not** work similarly to `String#split`, although we can achieve the same result.
```ruby
name = "Ali"
name.split('')
=> ["A", "l", "i"]
```

So how are `String#chars` and `String#split` different to each other?

`String#split` uses a regular expression to divide characters within a string, thus returning an array.

`String#chars` parses the byte of each character within a string and then it returns an array.

Cheers for reading! 🤓
My portfolio 📜
Tags: webdev, html, css, saas
Published: 2020-04-26 13:37:36

##Hello 🤗

Hello everyone! This is my current portfolio I use and I made it a while back. It's fully made in HTML, CSS and a bit of javaScript for the form purposes. 

###What is the purpose of this post? 🤨
The purpose of this post is to get some feedback and to inspire some beginner front-end developers! I would appreciate if I would get some creative feedback on how it's currently looking! 🎉

Portfolio: https://salesmanunknown.github.io/
Git Talking - Manage Your github projects
Tags: twiliohackathon
Published: 2020-04-26 13:10:00

{% link https://dev.to/projectescape/submission-git-talking-35pa %}

For the hackathon, I'm building a platform that will help people have chat, checklist, code snippet sharing ( and maybe screen sharing too ) for their github projects.
User will be able to choose which of his own repository he want to create chat/list/snippet share for, and also choose different files which can have independent chat/list/snippet. Other users can then join these channels and interact.


#What I'll be using
1. PERN Stack
1. Github API
1. Twilio Chat API
1. Twilio Sync API

#Progress So Far
1. I've setup the backend with github oauth service
1. Setup Chat token generation
1. Initialized React Project with some styling

#Problems I'm Facing
1. Currently I'm not being able to  figure out how to to apply a search filter while retrieving all chat channels.I searched about it and found a post on stackoverflow saying it could be done using chat's REST API, but I wasn't able to find this in docs. As it was driving me crazy how the frontend will always have to fetch all channels every time, I've decided to keep track of all channels in my db and give frontend filtered results.
1. As the users will be sharing code snippets, I wanted the code syntax to be highlighted. I haven't still found some package which provides this by automatically detecting languages.
If anyone could help me with these problems, please do!

#Not exactly related to the project
1. Extra points if someone could suggest a better name for the project
1. Also, please someone do tell me how people are linking their articles together using that box links. :)

#Repository
{% github projectescape/twilio-hack %}
create docker hosted nodes using docker-machine
Tags: docker, dockermachine, linux, virtualbox
Published: 2020-04-26 13:05:21

***docker-machine*** is a component of *docker*, used to create docker hosted virtual nodes using different drivers like GCP, AWS, Azure, or Virtualbox. Docker hosted nodes are the machines running docker daemon and used to run the docker containers. The Docker machine tool is useful when you want to create a docker cluster on any of the drivers mentioned above using `docker swarm`.

Today, we will learn to create a virtual machine using ***docker-machine***

***Step 1:*** Check the latest release version available [here](https://github.com/docker/machine/releases/).
***Step 2:*** Run below command to install docker-machine (change the latest version you find from step 1)
```shell
$base=https://github.com/docker/machine/releases/download/v0.16.2 &&
curl -L $base/docker-machine-$(uname -s)-$(uname -m) >/tmp/docker-machine && 
sudo mv /tmp/docker-machine /usr/local/bin/docker-machine 
&& chmod +x /usr/local/bin/docker-machine
```
Click [here](https://docs.docker.com/machine/install-machine/
) for installation on Windows or Mac.

***Step 3:*** Check successful installation 
```shell
$docker-machine ls
NAME   ACTIVE   DRIVER       STATE     URL     SWARM     DOCKER     ERRORS
```
*Run last command `chmod +x /usr/local/bin/docker-machine` if you see any permission issue

***Step 4:*** Install Virtualbox driver for local installation of virtual machines
```shell
$sudo apt update && apt upgrade && apt install virtualbox
```
***Step 5:*** Create virtual machine on Virtualbox with name `dev` 
```shell
$docker-machine create --driver virtualbox dev
```
***Step 6:*** Now, the `$docker-machine ls` command should return with running machine 
```shell
$docker-machine ls
NAME   ACTIVE   DRIVER       STATE     URL                       SWARM   DOCKER  ERRORS
dev    -        virtualbox   Running   tcp://192.168.99.100:2376           v19.03.5   
```  
You successfully installed `docker hosted virtual machine using Virtualbox driver locally`, this node can be used for ***docker swarm*** worker nodes.

***Happy dockering! Keep Learning!***
Remove hash(#) at URL Angular and Still be able to refresh and Not Getting 404 Not Found !
Tags: angular, webdev, javascript
Published: 2020-04-26 12:47:39

recently i’m building a movie stream app and decide to use angular.

if you have 404 not found error when refreshing or you have ugly hash url on your web and projects
this article is really for you this article suited you if you use Angular 4 | 5 | 6 |7 |8 | 9 and older version

### **Problem** :
After i’m finished coding and deploying my angular app at shared hosting Server and found out if i am refreshing one of my movie detail component it Got error 404 Not Found,
And than i really trying to solve this for a while by adding this :
#### **To my project app-routing.module.ts**

scrollPositionRestoration: ‘top’, useHash: true,

#### **and this to my project app.module.ts**

providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],

And the results is my movie detail component can be refreshed and not getting 404 Not Found anymore but the url looks ugly ( for me ) it shows
www.example.com/#/movie-detail

### **Solutions**:
This is problem had me struggle about 2 days can’t be solved by me , i try to googling and search on youtube old video tutorial on angular JS but that’s not working.
And in the moment i got this article really helpfull content contains about angular lastest version routing , more deep explanation and trying to implement it on my projects

(https://gist.github.com/julianpoemp/bcf277cb56d2420cc53ec630a04a3566#new-generator)

The solution is simple you just need to make .htaccess (make sure it’s not txt format) on your Public_html that contains this :
.htaccess
{% gist https://gist.github.com/Anderies/fdd5909f2e8d8a4f72c0ee8678947d4e %}

and changes this on your angular projects

{% gist https://gist.github.com/Anderies/5712c600acdc4609efd2d846af25e922 %}

And boom your Angular project gets regular url like www.example.com/movie-detail without hash and *able to Refresh and not getting 404 Not Found anymore*

I know this is not a problem for senior developer but it’s kinda **BIG AND ANNOYING PROBLEM** for junior developer or engineer that first time using angular and i just want to them to have the lastest article , because sometimes developer more interest and believe lastest article.

i hope this article can be grow angular developer numbers around the world

if you can’t solve Angular Project problem just Send me messages
i’d love to help and answer it :) ✌️

just follow my github here maybe i’ll update more free projects 🎮 soon
(https://github.com/Anderies)
Using the Fluent Interface Pattern to Create JavaScript Objects
Tags: javascript, webdev, tutorials, patterns
Published: 2020-04-26 12:35:48

---
title: Using the Fluent Interface Pattern to Create JavaScript Objects
published: true
description: There are many ways to create new JavaScript objects. In this post, we use the fluent interface pattern.
tags: javascript, webdev, tutorials, patterns
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/dfwgw8o83ucsqvmty0fv.png
---

There are many ways to create new JavaScript objects. In this post, we'll use the _fluent interface_ pattern! In the fluent interface pattern, we use classes with defined methods to add attributes to our object.

In the following example, we create a `PersonBuilder` class. In the `constructor`, we create an empty `person` property. Then, we have some additional methods called `withName` and `withAge` that allow us to give our person a name and age, respectively.

Finally, we have a `build` method. This just returns our `person` object, signifying that we're done building.

```javascript
class PersonBuilder {
  constructor() {
    this.person = {};
  }
  withName(name) {
    this.person.name = name;
    return this;
  }
  withAge(age) {
    this.person.age = age;
    return this;
  }
  build() {
    return this.person;
  }
}
```

Note that we return `this` in the `withName` and `withAge` methods--this returns the current instance, allowing us to continue to chain methods. 

The implementation of our class ends up being something like this:

```javascript
const person = new PersonBuilder()
  .withName("Daffodil")
  .withAge(25)
  .build();
console.log(person);
// { name: "Daffodil", age: 25 }
```

And that's it, we now have a person object!

# Why Build Objects This Way?

The fluent interface pattern can definitely be verbose, but one nice thing about it is that it makes it pretty hard to set an incorrect property on your object--you can only set object props by using the methods on your class. This can be especially handy if your object has a lot of properties, or if you need a handy way to generate a bunch of different objects to a specification (e.g., for test case generation).
ignite 3.5.1 andross template (react-navigation error)
Published: 2020-04-26 12:01:38

If you see this error after creating a new project from ignite-cli (3.5.1) 

```
undefined is not an object (evaluating '_reactNavigation.ThemeColors.light')
```

you can fix it by update react-navigation to version 4.0.5 (or greater).

And after that, you will see next error like this
```
bundling failed: Error: Unable to resolve module ` react-native-screens` from XXX
```

you can fix it by reinstalling/updating these packages.
```
npm install --save react-native-gesture-handler react-native-reanimated react-native-screens
```

good luck ^^
Day-14 Reverse String
Tags: python, challenge
Published: 2020-04-26 12:00:35

##### Background
This problem statement is a part of Leetcode's learning card Array and Strings. Under the sub-heading two pointer technique.

##### Problem Statement
Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ASCII characters.

##### Example 1
```
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
```

##### Example 2
```
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
```
##### Solution Approach 1
Use python built-in methods. There are two ways of doing the same. Suppose s in the initial list. Then s.reverse() could be done or s[::-1] can be done.

Had reaching the solution by using the built-in methods been the aim. Probably the whole exercise would not have been worth the effort.

##### Solution Approach 2
1. Iterate over the list.
2. Swap the first element with the last element.
3. The list would be completely reversed when we are at the mid of the list. 
4. When the index of the current element is equal to mid of the list. Break.

```
class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        for x in range(0, len(s)):
            if x == int(len(s)/2):
                break
            else:
                temp = s[x]
                s[x] = s[len(s)-x-1]
                s[len(s)-x-1]=temp
```

##### Learnings
1. Time complexity - O(n), Space complexity - O(1).

A more elegant approach
##### Solution approach 3
1. Keep two variables. One at the starting of the list at index 0. Another at the end of the list. Index len(L)-1.
2. Keep swapping the elements until both the variables reach the mid of the list.

```
class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        start = 0
        end = len(s) - 1
        while start < end:
            temp = s[start]
            s[start] = s[end]
            s[end] = temp
            start += 1
            end -= 1    
```
##### Learnings
1. The solution is still time complexity O(n) and space complexity O(1).
2. Two pointer technique. Though in python there is no concept of pointer as such.
3. Built-in reverse method is also implemented the same way.
Daily Developer Jokes - Sunday, Apr 26, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-04-26 12:00:14

---
title: "Daily Developer Jokes - Sunday, Apr 26, 2020"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Sunday%2C%20Apr%2026%2C%202020"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1258a3e5534.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit.*

<!-- 
Joke text:
___Q:___ Why did the developer ground their kid?

___A:___ They weren't telling the truthy
 -->
Explain typeof operator in Javascript with example
Tags: javascript, codenewbie, webdev, todayilearned
Published: 2020-04-26 11:46:49


*This post first appeared on [hackinbits.com](https://hackinbits.com/practice/javascript-interview-questions/explain-typeof-operator-in-javascript-with-example)*

The **typeof** operator helps in finding the type of value that your variable is storing. It returns a string indicating the type of argument. It supports two syntaxes:

1. As an operator: typeof v.
2. As a function: typeof (v).

Example:

```javascript
var exp = typeof "Welcome to hackinbits.com";
 
//output: "string".
console.log(exp)
```  

You can also use **typeof** operator to check whether a value is undefined or not.  


```javascript
let testVar = undefined;
var typeVar = typeof testVar;
 
//output: "undefined".
console.log(typeVar)
```

----

### Related Article
- [Javascript Data Types Explained](https://hackinbits.com/articles/javascript-data-types-explained)
Looking for Promise.any? Let's quickly implement a polyfill for it.
Tags: beginners, typescript, javascript, async
Published: 2020-04-26 11:46:01

## The Problem
As we all know, we often write asynchronous code using Promise object, which is available since ES6 (ECMAScript 2015). It gracefully offers us several methods.
* `Promise.resolve` returns a value;
* `Promise.reject` rejects an error;
* `Promise.all` waits until list of promises is resolved or rejected;
* `Promise.race` waits until any of the promises is resolved or rejected.

There is also `Promise.any` method [(more details)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any), that could be very helpful for us. It returns the first resolved promise and stops execution, ignoring the other promises. It is an ECMAScript language proposal and is not supported by browsers yet.

## The Solution
Fortunately, we can implement such behaviour ourselves:

```typescript
const promiseAny = async <T>(
  iterable: Iterable<T | PromiseLike<T>>
): Promise<T> => {
  return Promise.all(
    [...iterable].map(promise => {
      return new Promise((resolve, reject) =>
        Promise.resolve(promise).then(reject, resolve)
      );
    })
  ).then(
    errors => Promise.reject(errors),
    value => Promise.resolve<T>(value)
  );
};
```
## Some details
Let's dive deeper into the process.

The main idea is transforming the passed promises list into a reverted promises list. When a reverted Promise resolves it calls `reject`, while when it rejects it calls `resolve`. Then the reverted promises list is passed to `Promise.all` method and when any of Promises rejects, `Promise.all` will terminate execution with reject error. 
However in reality this means that we have the successful result, so we just transform the result from reject to resolve back and that's all. 
We got first successfully resolved promise as a result without magic wand.

## More details
As a parameter we can pass an Array containing Promises or basic data types (number, String, etc.). To handle basic types we have to *promisify* them using `Promise.resolve(promise)`.
`PromiseLike` is built-in TypeScript data type that wraps and properly handles promises from different libraries that you can use (such as [jQuery](https://api.jquery.com/category/deferred-object/), [bluebird](http://bluebirdjs.com/docs/api-reference.html), [Promises/A+](https://promisesaplus.com/implementations), etc.)

Another interesting point is the `Iterable` type. It's usage means that we can pass in our function not only an Array but also a Map, a Set or even [a Generator Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*),  that's to say any object implementing [Iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol). Our polyfill handles that argument type out of the box using  `[...iterable].map` command.