teleren/devto huggingface dataset:
React Hooks useState tutorial in 10 minutes
Tags: react, javascript
Published: 2020-10-10 18:29:08

Hey there!

I've just released my 5th youtube video, and decided to get started on a React series, in no particular order as it'll build up over time. I've started with the useState hook, which we can use with functional components in React.

Let me know what you think!
{% youtube icrrnFSjg8c %}
Use fancy imports with path mapping in tsconfig
Tags: angular, typescript
Published: 2020-10-10 17:50:00

In typescript or Angular apps, we can avoid having ugly paths like the next example.

```typescript
import { BookMark } from 'src/app/models/bookmark';
import { BookmarksState } from './../../../state/bookmarks.state';
import { GetBookMark } from './../../../state/bookmarks.actions';
```
To fancy paths like:

```typescript
import { BookMark } from '@app/models/bookmark';
import { BookmarksState } from '@state/bookmarks.state';
import { GetBookMark } from '@state/bookmarks.actions';
```
##How ?
All magic is part of the TypeScript compiler, it supports declaration mappings using ["paths" property](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping) in tsconfig.json files.

First define your base path, if you are in angular applications, into the compiler options change the baseurl from "./" to "src".

```typescript
"compilerOptions": {
    "baseUrl": "src",
....
```

Define shortcut for each area for example components or state, page etc.

```typescript
 "paths": {
      "@app/*": ["app/*"],
      "@pages/*": ["app/pages/*"],
      "@components/*": ["app/components/*"],
      "@state/*": ["state/*"]
 },
```

Done! Then change your code in components or files, and vscode will detect the new paths from tsconfig.

> Sometimes you need to reopen it to  detect new paths automatic.

## Before and after.

![Differences between code](https://dev-to-uploads.s3.amazonaws.com/i/5w4h5419l4oncy4n50tc.png)

## That's it!
Hopefully, that will give you a bit of help to write clean paths in Typescript or Angular apps. If you enjoyed this post, share it!
Creating custom manage.py commands for Django
Tags: django
Published: 2020-10-10 17:40:27

For my recent project [**pyremote**](https://www.pyremote.com), I needed to run a script every night to remove old job postings from the database. I decided to implement it as a **custom manage.py** command so that I can easily run it from the command line and add it to a nightly cron job on the server.

To create a custom command you need to add a `management` directory to your Django app. In there create another directory called `commands` and in that one add a Python file and call it the way you want the command to be called. In my case I called it `purge_old_jobs.py`:

``` bash
pyremote/
    __init__.py
    management/
        commands/
            purge_old_jobs.py
    models.py
    views.py
    ...
```

The Python file you create must define a class called `Command` that inherits from `BaseCommand`. Create a method named `handle` in your `Command` class. The actual logic of the command goes in this method. 

You can also define `add_argument` method where you specify any command line arguments you would like to pass to the custom command when you invoke it. These arguments are then available to the `handle` method in a dictionary called `options`.

``` python
# purge_old_jobs.py
import datetime
from django.core.management.base import BaseCommand
from pyremote.models import Job


class Command(BaseCommand):
    help = 'Cleans database from job posts older than the given number of days.'

    def add_arguments(self, parser):
        parser.add_argument('days', type=int, help='Retention period in days.')

    def handle(self, *args, **options):
        retention_period = datetime.timedelta(days=options['days'])
        expiry_date = datetime.date.today() - retention_period
        number_deleted, * _ = Job.objects.filter(creation_date__lt=expiry_date).delete()
        self.stdout.write(f'Number of expired jobs: {number_deleted}')
```

Now I can run this command to clean the database from jobs that are added to the page more than 30 days ago:

``` bash
$ python manage.py purge_old_jobs 30
```

<a href="https://chipper-musician-9131.ck.page/71c2932d23">![signup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rx6dciscpdwtk3z6j4u6.png)</a>
✨ Github-feed-cli : Github feed right at your terminal.
Tags: showdev, github, productivity, javascript
Published: 2020-10-10 17:36:42

**✨ Github-feed-cli** is a cli app that brings your GitHub feed right to your terminal.

{% github rocktimsaikia/github-feed-cli no-readme %}

Most of the time while I am coding I have this habit of quickly checking my GitHub feed for no reason. 
So I thought it would really cool if I could take a quick look at my GitHub feed right from my working terminal. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/uz5qsvpveonho12owv4l.gif)
<br>

Well, that idea alone was enough for me to fork my [my extended boilerplate](https://github.com/RocktimSaikia/my-module-template) and start coding at 1.20 AM at the morning for the cli app that does exactly the job that I mentioned which is ***Bringing GitHub feed to my your terminal***

Here is how to get strated with this tool:

## Installation
```sh
$ npm install --global github-feed-cli
```

## Usage

```bash
Usage
	$ feed <options>

Options
	--username, -u Github username to fetch the feed [default: Your own git username]
	--page, -p Page number of the results to fetch [default: 1]
	--version, -v Get the current version
		
Examples
	$ feed
	$ feed --page 2
	$ feed --username rocktimsaikia
	$ feed --username rocktimsaikia -page 2
```

- When you simply run `feed` without any flags/input it will fetch and show your current GitHub feed.

- You can also see any other GitHub users feed too by adding the `--username` flag following the `github username` of the person you wanna check.

- If you want to go to the next page of the feed, you can simply pass in `--page` following by the page number. Default is 1.<br><br>

[ PS: This was a fun little project and I had an awesome time coding it. I thought someone else might find it interesting too so made a quick post on it. 
Also leave a star at [the repo](https://github.com/RocktimSaikia/github-feed-cli) 🌟 if you like this project. Thanks for reading 🦄 👋]
Day 4: Hoisting in JS
Tags: 100daysofcode, javascript, webdev, codenewbie
Published: 2020-10-10 17:34:57

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qr5zqovwv8oisdrg5qjm.png)
Hoisting is the mechanism where the JS interpreter scan the code and hoists the variables and functions at the top so that they can be accessed before declaring them.

Javascript handles hoisting of variables and functions differently. 

**Variable Hoisting**

**var**

`console.log(name) // undefined
var name = "xyz"
console.log(name) // "xyz"`

After hoisting, the above code looks like the code snippet written below

`var name;
console.log(name) // undefined
name = "xyz"
console.log(name) //`

Hence the first line of `console.log(name)` outputs undefined instead of throwing an error.

**let and const**
They way hoisting is handled with let and const is different than how var is handled. We wont be able to access the variable until it is declared.

Lets look at the previous example with let keyword

`console.log(name) // throws error
let name = "xyz"
console.log(name) // "xyz"`

This happens because, in case of var, before executing the code line by line, variables are declared and initialised with *undefined*. But, let/const doesn't get initialised until it finds the initialisation in the code. So, when we try to access the variable, it throws an error.

**Function Hoisting**

In JS there are three ways of in which we create function.

1. Function Declaration
2. Function Expression
3. Arrow functions

**Function Declaration**
Ex of regular function declaration

`function addNum(a, b){
    return a+b;
}`

*When the interpreter scans the JS code, regular function definitions are hoisted at the top and made available at all other places*

`console.log(addNum(4, 5)) //prints 9
function addNum(a, b){
    return a+b;
}`

Once this code is hoisted it looks as below 

`//Hoisted function definition
console.log(addNum(4, 5)) //prints 9
    ...
    ...
   Rest of the code follows`

**Function Expression**

`console.log(add(4, 5)) //throws error add is not a function
var add = function (a, b){
    return a+b;
}`
functions Expressions are not completely hoisted in JS, Instead only declarations are hoisted bcz, it is only recognised as variable.

In the same way, when a function is referenced using *let* keyword, hoisting behaves the same way as that of regular let.
Ex: 

`console.log(add(4, 5)) //throws error
let add = function (a, b){
    return a+b;
}`

**Arrow functions**

Just like function Expressions, arrow functions are not hoisted in JS
Should I leave my first dev job to be a support engineer at my dream company and then move into a dev role from there? 
Tags: career
Published: 2020-10-10 17:33:01

I started my first jr. software dev position about 8 months ago. I made the transition from tech support. However, I feel that the role isn’t helping me grow and I feel less and less motivated to be there.  I’m not really doing any projects but I am growing in other areas - like research, problem solving & presenting ideas, which is good. 

I have to engage in side projects outside of work just to keep my skills up.  It’s also a contract position which means IF they have the budget they’ll renew my contact after a year.  I’m also very underpaid for the market where I am. 

Basically my dream company is hiring senior devs (they hire jrs to but no avail positions right now) but I don’t feel like I’d pass the coding tests (just yet). However they are hiring support engineers and I applied and they’re interested.  I was thinking I could have a foot in as a support engineer while continuing my projects on the side and practice their stack, even make some contributions and then apply from within once I feel confident enough.  

The dream company aligns more with my values and provides more freedom & opportunity as a whole. I could see myself being there long term way more than where I am now even if I have to start in support. The support role is also $25k more than what I make now - actual market rate. 

The support role involves helping people with their websites so it’s not completely left field and I’m already familiar with the product and tools. 

I’m just thinking long term. I’m not a bad coder just very new but I could do better just building some stuff on the side and just regroup from there and then give it another shot. 

My current job will not provide me with enough hands-on experience.  I’m afraid it might stagnate me and plus it’s draining me and making me feel slightly trapped. Just feel I need to move on. 

I feel stuck on what to decide. 

I don’t want to feel like I’m back tracking but I don’t like the idea of wasting my time anywhere. 

Is this a bad move? Would this hurt me career wise as a developer?
Include FactoryBot in RSpec
Tags: todayilearned, ruby
Published: 2020-10-11 07:24:55

---
title: Include FactoryBot in RSpec
published: true
date: 2020-10-10 14:43:34 UTC
tags: TIL,Ruby
canonical_url: https://andreligne.io/include-factorybot-in-rspec/
---

When using `FactoryBot` for generating random data in my `RSpec` tests for my Rails app, I had to keep prefixing my call to `create` with `FactoryBot`.

This caused my specs to look a bit cluttered.

```
trace = FactoryBot.create :trace
parent = FactoryBot.create :trace_field, trace: trace
child = FactoryBot.create :trace_field, trace: trace
```

It is possible to include the `FactoryBot` methods into RSpec so it will automatically find the methods from there.

To get that working, you could properly set up RSpec, [as per the documentation](https://github.com/thoughtbot/factory_bot/blob/5c071d42fda1682282461978923a2bd89f2ad27d/GETTING_STARTED.md#rspec), but if you didn’t you can add this to a file named `spec/support/factory_bot.rb`.

```
# spec/support/factory_bot.rb
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end
```

Also, make sure that you also uncomment this line in `spec/rails_helper.rb` so that RSpec includes any files you put in `spec/support/`.

```
Dir[Rails.root.join("spec/support/**/*.rb")].sort.each { |f| require f }
```

Now that we’ve fixed that we can remove the `FactoryBot`  prefix from the `create` calls to clean the whole thing up.

```
trace = create :trace
parent = create :trace_field, trace: trace
child = create :trace_field, trace: trace

```
Another Hacktoberfest post 
Tags: hacktoberfest, opensource, github
Published: 2020-10-10 17:04:07

Hi I am new to DEV and Hacktoberfest this is my first time in a fest. I learned many new things like we have to write github readme file in markdown. 
You don't need to be a programmer to participate in this fest if you are a content created you make documentations of github repos. This year hacktoberfest tries to decrease spams by make selective github repos eligible for this fest The repos with Hacktober tag or the issues with hacktoberfest-eligible tag is eligible for this fest. All the best to all of you.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7bf39sc3jyqazbl1ezf7.JPG)
I many more than 4 PRs
1. requirements.txt of a python project it was easy
2. readme.md file of a project and I also used some emoji in it
3. fixed a issue in a minor project
4. again created a readme.md file this time with images
and did some PRs for some minor issues in projects.
Should we use shorthand?
Tags: shortcut, shorthand, readability, style
Published: 2020-10-10 16:50:48

When I say shorthand, what I mean is "statements that combine multiple lines into one." These exist in every language. For instance, the ternary operator, null coalescing operator, and optional chaining operator.

They exist because they're sometimes easier to write and take up fewer lines of code. Readability is always more important than lines of code though. Are they as readable?

Let's take the ternary operator vs its non-shorthand version:
```js
let isFull = glassState ? "Yes" : "No";

let isFull;
if (glassState)
    isFull = "Yes";
else
    isFull = "No";
```

If I'm completely honest, I like the ternary expression better. Micheal Feathers talks about the idea of "tunneling," which is having multiple nested if statements. Tunneling is bad for code readability. With a ternary operator, there's less chance for tunneling. Getting ride of all your if statements creates code that reads like a series of assignments. An assignment series is way easier for me to read than nested, scoped blocks. 

On the flip side, you have to remember more syntax. One of my role models mentioned to me that unless you use the ternary operator a lot, it's hard to remember whether the true case goes first or second. I feel like this is also valid argument for readability. At this point I'm in favor of short hand because I've seen tunneling have an effect on readability and even performance. But I could be wrong, or this could be a style issue. What are your thoughts?

<sub>Note: if you're viewing this on https://winstonpuckett.com, you can scroll to the bottom and click "This post is also available on Dev." That will give you the option to respond to the post.</sub>
What I Learned Series - 01
Tags: beginners, tool
Published: 2020-10-10 16:38:03

This post is published originally : [simsekhuseyin.com](simsekhuseyin.com)

I readed a post about what should a software developer write. If you are a senior software developer, you can find a lot of topics. However, if you are a junior software developer like me, you are able to write what you learned or how did you solve your encountered problems. Thus, I have been started to write posts. This post is first post in this series. My aim is that writing weekly in `what I learned`. I intend to share on topics such as programming, tools or algorithms.

Let's Begin!

## Programming
I have been learned bitwise operators. As you know, there are two basic bitwise operations "AND" and "OR". 
#### Bitwise AND Operator
E.g. Given two integers i = 10 and j = 6, calculate t= i & j = 2
```csharp
int i = 10      // 0000 1010
int b = 6;      // 0000 0110
int c = a & b;  // 0000 0010 -> 2
```
#### Bitwise OR Operator 
E.g. Given two integers i = 10 or j = 6, calculate t= i & j = 14
```csharp
int a = 10;     // 0000 1010
int b = 6;      // 0000 0110
int c = a | b;  // 0000 1110 -> 14
```
Maybe you can use these operators solving algorithm problems.  

----
### Tool - Uptime Robot
I discovered a new tool, Uptime Robot. Uptime Robot is a monitoring tool which you can control  web services is up or not. It is not free but 50 monitors with checks 5-minute is free. You can get notification some of resources such as mail, Slack or Telegram, when your service is down. You can set these alert resources from "My Settings" dashboard. You can create a new monitor easily with "Add New Monitor" button. Finally, You are able to show statistic from main dashboard.
Create and Manage Cloud Resources
Tags: googlecloud, beginners
Published: 2020-10-10 16:37:39

**Virtual machines**
Dividing a big server into multiple instance where each of them works exactly like a regular server. Each of this divided part is a Virtual machine.


**What is a Compute engine?**
A google Compute engine is a customizable VM, Google provide both pre-defined and custom-type compute engine.

Pre-defined machine-types are general(best for web, and small applications), Compute Optimized and Memory Optimized.


**What is Ngnix?**

Its a Http and [reverse proxy server](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwjToZWV2KvsAhXKfH0KHUzRC8gQFjAHegQICBAC&url=https%3A%2F%2Fwww.nginx.com%2Fresources%2Fglossary%2Freverse-proxy-server%2F&usg=AOvVaw24bB3UWQJZLV0OSxtxu66Q).

**Creating a VM using Google Cloud Console**

1. Open cloud Console.
2. Navigation menu > Compute Engine > VM Instances.
3. Name your VM, and also select Region, Zone, Series, Machine type, Boot-Disk and Firewall
4. Click on Create.

**Creating a Vm using Command Line**

1. Open Cloud terminal
2. Use gcloud command
```
gcloud compute instances create <vm_name> --machine-type <machine-type> --zone <your_Zone>
```
3. Eg
```
gcloud compute instances create gcelab2 --machine-type n1-standard-2 --zone us-central1-c
```
4. to Ssh into your instance
```
gcloud compute ssh gcelab2 --zone us-central1-c
```
What is Google Cloud ?
Tags: googlecloud, beginners
Published: 2020-10-10 16:33:35

Google Cloud Platform provides computer resources (servers) which runs on a well optimized infrastructure.

It helps you in deploying applications(web, mobile app, Ml models, ...)

By using Cloud Solutions many top companies solve their business problems like hosting, managing traffic load, security and analytics. 

To get started - [Gcloud](https://cloud.google.com/)

Google Cloud provides 100+ products.


Few Best courses to get started with Cloud Computing - 

1. [Introduction to Cloud Computing](https://www.coursera.org/learn/introduction-to-cloud#about)
2. [Cloud Computing Basics (Cloud 101)](https://www.coursera.org/learn/cloud-computing-basics#about)

Books -

1. Cloud Computing: Concepts, Technology & Architecture
   by _Thomas Erl_
2. Cloud Computing: From Beginning to End
   by _Ray Rafaels_
3. Cloudonomics: The Business Value of Cloud Computing
   by _Joe Weinman_



In upcoming posts I'll Blog my learning process with key points to remember from Google Qwiklabs Cloud Engineering Track

**Cloud Engineering Track**

1. Getting Started: Create and Manage Cloud Resources

2. Perform Foundational Infrastructure Tasks in Google Cloud

3. Setup and Configure a Cloud Environment in Google Cloud

4. Deploy and Manage Cloud Environments with Google Cloud

5. Build and Secure Networks in Google Cloud

6. Deploy to Kubernetes in Google Cloud


These are the Skill badges required to finish Cloud Engineering track, around 54hr of practice is required.


I'm a Complete beginner trying to learn cloud engineering,If you find anything wrong or improvements in my posts, let me know in the comments 

thank you
Using Avalara’s AvaTax with Stripe Subscriptions
Tags: stripe, avalara, subscriptions, payments
Published: 2020-10-10 16:14:58

## It’s supposed to be easy. Eventually, it is.

If you use [Stripe](https://stripe.com/) to charge users and plan on using [Avalara’s AvaTax](https://www.avalara.com/us/en/products/sales-and-use-tax/avatax.html) for charging sales tax, you’re probably looking for a simple plug & play solution. It very much is this type of solution, but it isn’t very well documented. 

This post is all about laying out the required steps to making it work quickly and easily.

_Examples are written in node.js but can easily be converted to any language Stripe’s API supports._

### First Step: Ask Stripe to Allow Your Account to Use The `pay_immediately` flag
Contact Stripe’s support and ask them to enable the usage of the `pay_immediately` flag for you for the purpose of integrating AvaTax.

For AvaTax to integrate with Stripe, you have to give AvaTax to a chance to catch new invoices and add the sales tax to the invoice. You do this by sending the attribute `pay_immediately = false` upon subscription creation. **This flag is not well documented anywhere and is disabled by default**. 
Avalara do [mention it in their documentation](https://help.avalara.com/FYHP/AvaTax_for_Stripe_Invoicing/Install_and_Configure_Avalara_AvaTax_for_Stripe_Invoicing#Configure_sales_tax_calculation_for_subscriptions), but it’s easy to miss.

### Second Step: Update Address Details in The Customer’s Metadata
Add address details that AvaTax will use to calculate the tax for future invoices. This can happen at any time prior to creating the subscription.
Only `Address_PostalCode` and `Address_Country` are mandatory but you can add [more details](https://help.avalara.com/FYHP/AvaTax_for_Stripe_Invoicing/Install_and_Configure_Avalara_AvaTax_for_Stripe_Invoicing/Metadata_Specifications#Customer_metadata) to make the tax calculation more accurate.

```js
const stripe = require('stripe')(STRIPE_KEY);

const customer = await stripe.customers.update(
  CUSTOMER_ID,
  { metadata: {
	  'Address_PostalCode': '10001', // Valid Postal Code
	  'Address_Country': 'US' // ISO-3166-1 alpha-2 Country Code
	}		
  }
);
```

### Third Step: Add The `pay_immediately = false` to Your Subscription Creation Request
When you create the subscription, add the attribute `pay_immediately` with the value `false`.

```js
const stripe = require('stripe')(STRIPE_KEY);

const subscription = await stripe.subscriptions.create({
  customer: CUSTOMER_ID,
  items: [
    {price: PRICE_ID},
  ],
  pay_immediately: false
});
```

### Fourth Step: Wait for Webhook Events
Your invoice will not be charged immediately (as you requested), and AvaTax will pick it up. This could take a couple of seconds.
[Avalara’s webhooks](https://help.avalara.com/FYHP/AvaTax_for_Stripe_Invoicing/Install_and_Configure_Avalara_AvaTax_for_Stripe_Invoicing#Connect_AvaTax_to_Stripe_Invoicing) will allow you to know what happened with your invoice under their care.

That’s it. It’s fairly easy and straightforward, but it’s rather hard to find good documentation for it.