teleren/devto huggingface dataset:
Graceful shutdown
Tags: go, gin
Published: 2021-06-24 18:13:17

If our server process gets signal to shut it down, we would like to finish the request currently handling before that happens. For that we will use graceful shutdown provided by Gin. This example is explained in detail on [Gin GitHub](https://github.com/gin-gonic/gin#graceful-shutdown-or-restart) with description in comments, so i will not go into details myself. Our `internal/server/server.go` will now look like this:

```go
package server

import (
  "context"
  "errors"
  "net/http"
  "os"
  "os/signal"
  "rgb/internal/conf"
  "rgb/internal/database"
  "rgb/internal/store"
  "syscall"
  "time"

  "github.com/rs/zerolog/log"
)

const InternalServerError = "Something went wrong!"

func Start(cfg conf.Config) {
  jwtSetup(cfg)

  store.SetDBConnection(database.NewDBOptions(cfg))

  router := setRouter()

  server := &http.Server{
    Addr:    cfg.Host + ":" + cfg.Port,
    Handler: router,
  }

  // Initializing the server in a goroutine so that
  // it won't block the graceful shutdown handling below
  go func() {
    if err := server.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
      log.Error().Err(err).Msg("Server ListenAndServe error")
    }
  }()

  // Wait for interrupt signal to gracefully shutdown the server with
  // a timeout of 5 seconds.
  quit := make(chan os.Signal)
  // kill (no param) default send syscall.SIGTERM
  // kill -2 is syscall.SIGINT
  // kill -9 is syscall.SIGKILL but can't be catch, so don't need add it
  signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
  <-quit
  log.Info().Msg("Shutting down server...")

  // The context is used to inform the server it has 5 seconds to finish
  // the request it is currently handling
  ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  defer cancel()

  if err := server.Shutdown(ctx); err != nil {
    log.Fatal().Err(err).Msg("Server forced to shutdown")
  }

  log.Info().Msg("Server exiting.")
}
```
3 Ways to Make Buttons more Enticing to Interact With
Tags: uiweekly, css, codenewbie, 100daysofcode
Published: 2021-07-30 18:49:53


Buttons are one of the most common elements in all of UI. It'll probably be the first thing you see when you open up a new component library or start working on a new project.

They can be surprisingly complex when you factor in all the different states and implications a button can have when pressed, clicked, or tapped.

Think about these differnt states you need to consider when designing a button:

- Full color, outlined, or "ghost" buttons
- Loading, disabled, and submitting states
- Button sizes like sm, md, and lg
- Hover, focus, and active states
- Buttons used as links, vs buttons used as... well, buttons

After all is said and done, you can still do more to make sure your button looks "clickable". Here are a couple ways you can enhance a button.

## Techniques for making buttons look more "clickable"

1. Overlap content sections

2. Add animations

3. Add `cursor: pointer`

## 1. Overlap content sections

An element that sits on top of 2 sections looks like it almost "floats", and looks like it could be clicked.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0b92akyskxx5zsmokzbf.png)
Material UI does this with their + buttons.

## 2. Add animations

Entrance animations, hover animations, and tap animations can all add to a button in subtle but important ways.

Consider scaling the button or text within it when you hover or click.

## 3. Add cursor: pointer

It makes a button obviously clickable to have a little finger pop up over a button! Consider adding it to something you know will be clicked.

You can't rely on this to signal a button is clickable though for users who navigate without a cursor.

<blockquote class="twitter-tweet"><p lang="en" dir="ltr">🔥 3 ways to make your button more enticing to click<br><br>1️⃣ Overlap content sections<br>2️⃣ Add animations<br>3️⃣ Add cursor: pointer<a href="https://twitter.com/hashtag/uifoundations?src=hash&amp;ref_src=twsrc%5Etfw">#uifoundations</a> <a href="https://t.co/Q47GPEKvk6">pic.twitter.com/Q47GPEKvk6</a></p>&mdash; Kyle Gill (@gill_kyle) <a href="https://twitter.com/gill_kyle/status/1420906363438260225?ref_src=twsrc%5Etfw">July 30, 2021</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
How I've added self-care and consistency to my daily routine
Tags: mentalhealth, productivity, burnout
Published: 2021-07-30 18:35:07

For a while now I have valued the following things:
1. Good physical health
2. Good mental health
3. Consistency

But I wasn't doing much to really live those values in my day to day life.

I knew that I *wanted* to embody those traits, but if I was being honest with myself, I wasn't.

One of the main things I learned from Nir Eyal's book, [Indistractible](https://www.nirandfar.com/indistractable/), is that it is important to align your values with the time you spend everyday.

Recently I started a new morning routine:

> 30 minutes every morning:
> 1. 10-12 minutes of yoga
> 2. 9-11 minutes of journaling
> 3. 8 minutes of meditation

### Yoga
Yoga is a great way to start your day by stretching and strengthening your body. I've found that if I don't exercise for 3-4 weeks, my body starts to get a lot of small aches and pains. I mix using videos from [Yoga with Adriene](https://www.youtube.com/watch?v=UEEsdXn8oG8) and also some basic self-guided routines.

### Journaling
If you are like me, then you may not always do a great job processing how you feel. Sometimes I would find myself feeling super stressed out, but not always understanding why. I've been really surprised by how much it benefits me to just sit down and write out what I am thinking or feeling.

### Meditation
I suck at meditation, but I keep practicing. One thing that changed my mindset was thinking about it as a practice to better be in control of your mind and thoughts. By practicing trying to clear your mind, you are building muscle to be more intentional with it. For me it has already helped with tempering my stress and emotions, while also helping me mindfully avoid distractions better.

### Don't give up!
I quit my job 4 months ago and have been trying to launch my own internet business. Mental health and consistency have probably been the two things I have struggled with the most. I hope this routine might help some of you overcome some of your own struggles!
---
If you liked this, consider following me on Twitter: [@jstnchu](https://twitter.com/jstnchu) (I tweet about my learnings around starting my own business)
Build a Python Web Scraper Step by Step Guide
Tags: python
Published: 2021-07-30 18:21:41

Web scraping with Python is a powerful way to obtain data that can then be analyzed. Python is one of the easiest programming languages to learn and read, thanks to its English-like syntax.

Because of Python’s popularity, there are a lot of different frameworks, tutorials, resources, and communities available to keep improving your craft.

What makes it an even more viable choice is that Python has become the go-to language for data analysis, resulting in a plethora of frameworks and tools for data manipulation that give you more power to process the scraped data.

So if you’re interested in gathering huge data sets and then manipulating and analyzing them, Python is exactly what you’re looking for.

In this article, we’re going to build a simple Python scraper using Requests and Beautiful Soup to collect job listings from Indeed and formatting them into a CSV file.

https://www.scraperapi.com/blog/web-scraping-python/
Entering a new space for Coding.
Tags: codenewbie, career, webdev, beginners
Published: 2021-07-30 18:07:51

So I've been absent for quite awhile again, maybe 2 weeks.
But Thats ok, I have decided as long as write at all is better than beating myself up about missing a few weeks.

I have been coding funnilly enough, maybe not as much as I would have liked but still some.

I continued to use in what I learned about Git to try and add more to my Git-hub repositories. I had some success and some snags along the way but that is to be expected. One thing I was trying to implement through out the week was designing my websites first before I started trying to build from scratch.

I was using Figma to create beautiful designs of projects I had imagined in my mind, and they came out fantastic. I then tried to switch that over to being able to code them. I though if I had all the code embedded so all I had to do was to really just use the code from figma and attach it to my script in vscode. Nothing but snags along the way and this made a major blow to my confidence again making me stifle the amount of time I put into coding.

So after a lot of thought I thought about it for a long while and decided it was time for me to get some real structure and guidance to be able to accomplish this.

If I want to be able to do this coding for real, for real. I need to put my all and extra and I feel like a bootcamp might be able to provide that structure I need. So I'm going for it.

Hopefully this should help me be able to get over the roadblocks alot quicker as I wont have a choice but to keep going. And this will make me a better coder.

Thanks for Reading.
Mika/Malcz.
How to install the psycopg2 Python package in WSL 2
Tags: python, wsl, linux, postgres
Published: 2021-07-30 17:51:13

---
title: How to install the psycopg2 Python package in WSL 2
published: true
description: Short post which describes what dependencies and packages are needed for WSL 2 to isntall psycopg2.
tags: Python, WSL, Linux, PostgreSQL
// cover_image: ![]()
---


This post is a quick note to all about how to install psycopg2 in Linux.  I used WSL 2 running Ubuntu 20.04.

## Background

I was trying to set up a toy project to learn Django using PostgreSQL.  When I tried to install the recommend psycopg2 package from pip, I received two error messages.

The first error I received was:  **error: invalid command 'bdist_wheel'** .  My second error was related to C / C++ and was in my log files:

In file included from psycopg/adapter_asis.c:28:

```C
./psycopg/psycopg.h:35:10: fatal error: Python.h: No such file or directory
  35  |  #include <Python.h>
      |           ^~~~~~~~~~
```
compilation terminated.


## The Steps


1.  I installed the following dependencies:  `python-dev` , `python3-dev`.
2.  I installed wheels using  `pip3 install wheel` .  
3.  I installed `python[your version]-dev` using Ubuntu's `sudo` command.



## Explanation

The root cause of the problem was that psycopg2 was looking for headers for Python 3.8.5.  Since I am using Python 3.9.5, the headers could not be located and psycopg2 could not install.  After installing `python3.9-dev` , psycopg2 successfully installed on my system.

I hope that this short post saves people time and energy.

Additional references:  

[SO - Invalid command bdist wheel on Travis CI](https://stackoverflow.com/questions/34819221/why-is-python-setup-py-saying-invalid-command-bdist-wheel-on-travis-ci)
[SO - How to fix `error: invalid command 'bdist_wheel'`](https://stackoverflow.com/questions/65273035/how-to-fix-error-invalid-command-bdist-wheel)
UPDATED: Bootstrap v5.0.2 Navbar with Multi-Level and Mega Menu
Tags: bootstrap, navigation, css, frontend
Published: 2021-07-30 17:48:38

In February 2021, I published this article: "Bootstrap v5 Navbar Component with Multi-Level and Mega Menu". 

https://dev.to/typo3freelancer/bootstrap-v5-navbar-component-with-multi-level-and-mega-menu-1218

Due to the many requests, I just rebuilt the pen to make the example compatible for Bootstrap 5.0.2.

## No more custom JavaScript required!
The JavaScript is completely dropped thanks to the new features in Bootstrap. You can create arbitrary dropdown menus with infinite levels using the "data-bs-auto-close" attributes and "data-bs-toggle", as well as the "dropend" and "dropstart" classes.

{% codepen https://codepen.io/typo3-freelancer/pen/poEvyGj %}
.NET 5 with RavenDB Series -1
Tags: dotnet, csharp, ravendb
Published: 2021-07-30 17:20:01

##Knowing RavenDB
RavenDB is an open source document-oriented NoSQL designed for the .NET / Windows platform. It has a free edition available for open source projects, but it must be requested. It also has its commercial version.

RavenDB supports multiple databases. RavenDB can easily handle hundreds or thousands of databases on the same instance, explicitly designed with multi-tenancy in mind. This allows RavenDB to manage a large number of databases, but at any one time only one database is active and consuming resources.

Each RavenDB database contains a set of documents that can be divided into collections. A Collection is a logical way to group documents, similar to a table in relational databases. In a Collection, documents share the same entity name.

Following are links to the official RavenDB documentation as well as the book written by Oren Eini, CEO of RavenDB.

[Oficial documentation](https://ravendb.net/docs/article-page/5.2/csharp)
[Book Inside RavenDB 4.0](https://ravendb.net/learn/inside-ravendb-book)

There is also a bootcamp for beginners that you can apply through this link.
[Bootcamp RavenDB](https://ravendb.net/learn/bootcamp)

##Why RavenDB?
RavenDB was produced not only to solve some problems but also to meet the needs of a better environment. Every year developers become better and more demanding, with better environments, better tools, and simpler, more straightforward methods to achieve a wide variety of goals.

With this in mind, users considering adhering to a NoSQL solution should choose the appropriate database management system that best suits their needs and their applications.

But why does RavenDB make data management with NoSql easier? Here are the main advantages of adopting RavenDB:

- RavenDB is made in C #, .NET and as we know this platform has one of the best learning curves currently.
This is a big plus. Data can be efficiently queried using .NET LINQ queries or using RESTful APIs.

- In RavenDB, the database schema is no longer fixed, data is stored without schema like JSON documents, so documents can have arbitrary structures and attributes associated with them.

- RavenDB is extremely fast, it has an automatic cache management that identifies the queries already performed and manages to make the least possible effort in the database, which generates an incredible speed in queries.

- Highly scalable and designed for web scale. It offers out-of-the-box replication and fragmentation support.
RavenDB is fully transactional with ACID Support.

- It has the RQL (Raven Query Language) which is very similar to the SQL SERVER syntax, which makes it much easier for quick database queries by the user.

In this first lesson we learned a little about RavenDB and why using it is a good idea.
In the next lesson we will install it through the docker and access your dashboard locally.
Open Mobile Camera With HTML
Tags: html, webdev, css, javascript
Published: 2021-07-30 16:56:56

The HTML Capture attribute open device camera to capture image followed by accept attribute

The capture attribute takes as it's value a string that specifies which camera to use for capture of image or video

1 `capture="user"` - Open Front Camera
2 `capture="environment"` - Open back camera

### Open Front Camera
![Front camera](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dh5y0i7rmm0okknqb93r.png)

### Open Back Camera
![Back Camera](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xleanr7aj7idihq8nj3w.png)

Output: 
![Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hx0xeiqshh3c8yi2x4ux.PNG)

To record video pass `video/*` to accept attribute

Reference:- https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/capture

Visit Blog:- https://beginners-developer.blogspot.com

Portfolio:- https://ejaazrkhan.github.io/portfolio
What is System Design?
Tags: systemdesign, software
Published: 2021-07-30 16:55:51

<strong>System design</strong> is the phase that bridges the gap between problem domain and the existing system in a manageable way. This phase focuses on the solution domain, i.e. “<em>how to implement?</em>”

It is the phase where the SRS document is converted into a format that can be implemented and decides how the system will operate.

In this phase, the complex activity of system development is divided into several smaller sub-activities, which coordinate with each other to achieve the main objective of system development.

#Inputs to System Design
####System design takes the following inputs −

<ul>
<li>Statement of work</li>
<li>Requirement determination plan</li>
<li>Current situation analysis</li>
<li>Proposed system requirements including a conceptual data model, modified DFDs, and Metadata (data about data).</li>
</ul>

#Outputs for System Design

#####System design gives the following outputs −

<ul>
<li>Infrastructure and organizational changes for the proposed system.</li>
<li>A data schema, often a relational schema.</li>
<li>Metadata to define the tables/files and columns/data-items.</li>
<li>Actual or pseudocode for each module in the program.</li>
<li>A prototype for the proposed system.</li>

</ul>


Credits: https://www.tutorialspoint.com/
Will you consider your carbon footprint when configuring your compute workloads?
Tags: cloud, discuss
Published: 2021-07-30 16:49:12



At Google, engineers get to spend 20% of their time on internal projects of their own design and Steren built a free public-facing customer tool to help you consider the carbon footprint when provisioning your resources in a specific region.

{% tweet 1384542442536333315 %}

{% tweet 1384542442536333315 %}

![Screen Shot 2021-07-30 at 12.12.57 PM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqp8fbtt6asgw795gbo1.png)

If you expand the cards you get a bit more detail.

![Screen Shot 2021-07-30 at 12.25.53 PM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vjl37utvy0bomict80fn.png)

Try the [Google Cloud Carbon Footprint Region Picker](https://cloud.withgoogle.com/region-picker/) yourself.

- Do you think you will ever consider your carbon-foot print when using cloud services?
- Would you ever want to see a carbon-foot print as part of the cost and usage reporting within your cloud service provider (CSPs)? 


-----

Did you know there is a Forem server just for just the cloud? [www.thedev.cloud](https:///www.thedev.cloud)

[![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8nxmzmstl05jouj4ws0t.png)]((https:///www.thedev.cloud))
Color Flipper Using RGB color
Tags: javascript
Published: 2021-07-30 16:28:50

## Hello Dev Friends,
Today i am showing how you can flip background color of screen infinitely using simple javascript, html and CSS.

- Html
    - Create Simple Span to show which Color is Present
    - A button which changes the color


- Javascript
    - Add event listener on button
        - in this function generate a random number between 0 to 256(rgb values).
    - We know that body.background-color in RGB format accept 3 values as number so we need to generate 3 number randomly.
    - Put these 3 numbers in rgb() by using string concat or template.

For More Information you can visit my GitHub Code :-
https://github.com/piyushmbm45/JavaScriptProject/tree/master/color%20flipper

There You will find other color flippers also.

### Thanks guys.
Stop Serving Context Soup with Your React Testing Library Tests
Tags: react, testing, webdev
Published: 2021-07-30 16:11:48

If you've worked on a production [React](https://reactjs.org/) app for any amount of time, you've probably noticed the accumulation of [`Provider`](https://reactjs.org/docs/context.html#contextprovider) components that wrap the top level component. When it comes to writing tests, these contexts become an extra hurdle to set up new test files.

We have to make sure all [`useContext`](https://reactjs.org/docs/hooks-reference.html#usecontext) usages in the component are covered. One missing `Provider`, and we get failing tests.

```javascript
// don't forget one!
render(
  <GlobalCacheProvider>
    <I18nProvider i18n={i18n}>
      <NotificationProvider>
        <UserScreen />
      </NotificationProvider>
    </I18nProvider>
  </GlobalCacheProvider>
);
```

And what happens when there's a new global context added?

We have a couple options:
1. Add it it to all the test suites hoping we don't miss one.
2. Go the lazy route and only add it to the test suite using it. This creates a landmine for our coworkers (or our future selves), so when they use the new context, the tests are missing the `Provider` and fail. Gee, thanks!

We can solve both of these problems with one solution.

## The Context Wrapper

Let's create a wrapper component called `GlobalTestProvider` that includes all our global context `Provider` components.

```javascript
function GlobalTestProvider({ i18n, children }) {
  return (
    <GlobalCacheProvider>
      <I18nProvider i18n={i18n}>
        <NotificationProvider>
          {children}
        </NotificationProvider>
      </I18nProvider>
    </GlobalCacheProvider>
  );
}
```

Then the line to render the component becomes much more palatable:

```javascript
render(
  <GlobalTestProvider i18n={i18n}>
    <UserScreen />
  </GlobalTestProvider>
);
```

Not to mention, when we add a new context, there's only one place to do it, and all test suites get updated together. Boom.

## Summary

- Reduce friction in creating new tests and make them more maintainable by creating a wrapper component that includes all global context providers.
How to create server of files with FastAPI
Tags: fastapi, python, backend, nelsoncode
Published: 2021-07-30 16:09:04

In this example I will show you how to upload, download, delete and obtain files with FastAPI

### Upload files by Form Data using FastAPI

In the following code we define the file field, it is there where we will receive the file by Form Data

```python
from fastapi import FastAPI, UploadFile, File
app = FastAPI()

@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    with open(file.filename, 'wb') as image:
        content = await file.read()
        image.write(content)
        image.close()
    return JSONResponse(content={"filename": file.filename},
status_code=200)
```
### Download files using FastAPI

```python
from fastapi import FastAPI
from os import getcwd
from fastapi.responses import FileResponse
app = FastAPI()

@router.get("/download/{name_file}")
def download_file(name_file: str):
    return FileResponse(path=getcwd() + "/" + name_file, media_type='application/octet-stream', filename=name_file)
```

### Get files using FastAPI

```python
from fastapi import FastAPI
from os import getcwd
from fastapi.responses import FileResponse

app = FastAPI()

@router.get("/file/{name_file}")
def get_file(name_file: str):
    return FileResponse(path=getcwd() + "/" + name_file)
```

### Delete files using FastAPI

```python
from fastapi import FastAPI
from os import getcwd, remove
from fastapi.responses import JSONResponse

app = FastAPI()

@router.delete("/delete/file/{name_file}")
def delete_file(name_file: str):
    try:
        remove(getcwd() + "/" + name_file)
        return JSONResponse(content={
            "removed": True
            }, status_code=200)   
    except FileNotFoundError:
        return JSONResponse(content={
            "removed": False,
            "error_message": "File not found"
        }, status_code=404)
```