teleren/devto huggingface dataset:
Preventing a Windows PC from adjusting the screen's brightness automatically
Tags: windows, setup
Published: 2020-05-05 23:09:45

---
title: Preventing a Windows PC from adjusting the screen's brightness automatically
description: I noticed huge changes in the screen's brightness (which causes me to get distracted). I hated it, so I removed it.
slug: windows-brightness
series: windows-web-dev
tags: windows, setup
cover_image: https://zellwk.com/images/2020/windows-brightness/change-brightness-checkbox.png
published: true
---

Mac changes the brightness of your screen automatically. It brightens up when you're in a bright place. It dims when you're in a dark place. They do it elegantly and slowly. Most of the time, their brightness adjustment is great.

The same cannot be said for Windows. I noticed huge changes in the screen's brightness (which causes me to get distracted). I hated it, so I removed it.

Turns out, it's not as easy as you think it should be.

## Step 1: Turning off the option

This is the easy part. Search for "display" in the Start menu and select "Change brightness level".

<figure role="figure">
  <img src="https://zellwk.com/images/2020/windows-brightness/change-brightness-level.png" alt="Shows how to find the setting to change brightness .">
</figure>

Then, uncheck the checkbox.

<figure role="figure">
  <img src="https://zellwk.com/images/2020/windows-brightness/change-brightness-checkbox.png" alt="Uncheck the change brightness automatically checkbox.">
</figure>

This should be it, right?

Nope. Not for every Windows computer.

If your PC is built on a Windows system, you still need to turn off adaptive contrast.

## Step 2: Turning off adaptive contrast

Adaptive contrast is a feature that **changes the brightness of a screen depending on how bright the screen is**.

I discovered it when I was working in a room with the lights turned off. (I know, bad for my eyes, but I still do it occasionally). I set the display brightness to the lowest level, but adaptive contrast brought it back up...

Super irritating!

You need to dig into the Window's Register to change this. [Follow this article][1] to do so.

:::note
The article says to change `TestFeatureControl` from 2440 to 2450. The original value of my `TestFeatureControl` was 200. I still changed it to 2550 and it worked.
:::

The article also said Windows updates can change the registry back to its original value, so you might need to do this once or twice a year. It's not fun, but there's nothing much we can do about it. At least we can disable the feature!

[1]: https://www.windowscentral.com/how-disable-adapative-contrast-surface

<hr>

Thanks for reading. This article was originally posted on [my blog](https://zellwk.com/blog/windows-brightness). Sign up for my newsletter if you want more articles to help you become a better frontend developer.
Using a Modal in React
Tags: beginners, react, modals
Published: 2020-05-05 23:09:13

For my final project at Flatiron, I built an app that allowed users to fill out forms and submit information on different pages.  Because I didn't want to keep rendering an entire page with a form and then going back to the previous page to display the information, I decided to use a modal.  A modal is just a design term for a pop-up form that appears when a user clicks on a button.  I also used some of react bootstrap to style and render the modal.

To get the modal to display a showModal state can be set in the parent component.
```react 
state = {
  showModal: false,
}
```  
Also in needed in the parent component are two methods to change the state of the modal.  One method to set the showModal state to true when a button is clicked, and another method to set the showModal state back to false when the user clicks the x in the corner.

```react
 closeModal = () => {
    this.setState({ showModal: false });
  };

  openModal = () => {
    this.setState({ showModal: true });
  };
```
Next you will create a button with an onClick event handler that will call the openModal method and set the state to true.  The component that is being rendered as a modal should open on the page of the parent component.  The modal component itself will need the state of the modal as well as the closeModal method passed to it in props.  Any other props that modal component needs should be passed to it as well.

In the component that I wanted to render as a modal, I imported from react-bootstrap.
```react
import { Modal, Form } from "react-bootstrap";
```
Then in the modal component, I wrote the form to show in a method called renderAddGift.

```react
renderAddGift = () => {
  return (
  ...all the form labels and inputs...
  )
}
```
In the render method of the modal component, I used the Modal wrapper imported from react-bootstrap to render the above form depending on the state of the modal.

```react
 render() {
    return (
      <div>
        <Modal show={this.props.showModal} onHide={this.props.closeModal}>
          <Modal.Header closeButton={true} style={{ color: "#3e6b89" }}>
            <h3>Add A Gift Idea</h3>
          </Modal.Header>
          {this.renderAddGift()}
        </Modal>
      </div>
    );
  }
}
```
I found this to be an easy beginners  approach to set up a working modal and understand how it was rendering to my page. It also made the page it was rendering on cleaner with only necessary information displayed.  A common place to use modals is on the login and sign-up on a home page.
Introducing stimulus-image-grid
Tags: stimulus, javascript
Published: 2020-05-05 22:28:50

---
title: Introducing stimulus-image-grid
published: true
description: A Stimulus controller for beautiful image grids
tags: stimulus, javascript
cover_image: https://svbtleusercontent.com/oCfEKyCfwps3Ebogfwpm5x0xspap.jpg
---

I published my first npm package today!

https://www.npmjs.com/package/stimulus-image-grid

With only three optional parameters, this is a simple, drop-in, backend-agnostic, code-free solution that is completely free of CSS opinions. It's responsive and scales to whatever bounding container you give it. 

It's also performant AF: stimulus-image-grid uses the ResizeObserver so there's zero screen flicker. It's compatible with Turbolinks by design and free for personal and commercial use.

{% youtube e08sFfBYoiE %}

## Built for StimulusJS

This [Stimulus](https://stimulusjs.org/) controller allows you to make any configurations for the image grid directly with data attributes in your HTML. Once registered in your Stimulus application, you can use it anywhere you like.

Here is a simple example:

```html
<div data-controller="image-grid">
  <img src="https://placehold.it/350x300/EEE04A/ffffff">
  <img src="https://placehold.it/420x320/5cb85c/ffffff">
  <img src="https://placehold.it/320x380/5bc0de/ffffff">
  <img src="https://placehold.it/472x500/f0ad4e/ffffff">
  <img src="https://placehold.it/540x360/FF3167/ffffff">
</div>
```
<tiny>Yes, that's really it.</tiny>

## Setup

Add an import to your main JS entry point, and then register it:

```js
import { Application } from 'stimulus'
import ImageGrid from 'stimulus-image-grid'

import { definitionsFromContext } from 'stimulus/webpack-helpers'
const application = Application.start()
const context = require.context('../controllers', true, /\.js$/)
application.load(definitionsFromContext(context))

// Manually register ImageGrid as a Stimulus controller
application.register('image-grid', ImageGrid)
```

And you're done! Note, this package relies on the alpha preview of Stimulus v2, which is stable and available [here](https://github.com/stimulusjs/stimulus/pull/202).
Refactoring: Try-Catch for Variable Assignment in JS
Tags: refactoring, express, javascript
Published: 2020-05-05 22:22:06

---
title: Refactoring: Try-Catch for Variable Assignment in JS
published: true
description: 
tags: refactoring, express, javascript
---

I was refactoring an Express application when I came across a curious bit of code:

```js
let email;

try {
  email = req.body.email;
} catch (err) {}

```

I believe this code is attempting to throw an error if the "name" property is missing in `req.body` – if `req.body.name` did not exist the assignment would cause an error and it would stop execution of the rest of the code.

However, that's not what happens! `req.body.email` is `undefined`, so it is perfectly possible to assign `undefined` as the value for the `name` variable.

I think `hasOwnProperty` is more reliable way to make sure `req.body` container an `email`:

```js
if (!req.body.hasOwnProperty("name")) {
  const err = new ReferenceError("no name in request body.");
  throw err;
}

const {email} = req.body
```

PS: For Express specifically, I'm interested in learning more about [validating the req.body using JSON Schema or Joi](https://stackoverflow.com/a/16819689/5578727).
Windows in NCurses (Part 3)
Tags: cpp, ncurses, linux
Published: 2020-05-05 22:18:01

Hey there, if you haven't read [Part-2](https://dev.to/tbhaxor/playing-with-ncurses-cursor-part-2-1gil) yet, I would suggest you read it first.

Ncurses provide one main window known as _Standard Screen_ by default, defined as `stdscr`. It also allows you to make windows that divide the stdscr i.e Main Window.

A window may be as large as entire stdscr or as small as a single character

To declare a window you will have to use `WINDOW` typed object defined in ncurses.h. and  `newwin(int height, int width, int starty, int starty)` function to initialize

For example, 

```cpp
WINDOW *win = newwin(10, 20, 1,10);
refresh(); // this will refresh "all" the screens
```

In the real world, you would be working with different windows. So if we want or refresh a specific window, we will be using `wrefresh(WINDOW *)` function of ncurses.h that takes a window and refresh memory contents related to that window only. 

Like `mvprintw()` (_in part 2_) is for `stdscr`, you will have to use window specific function to print in particular window `mvwprintw(WINDOW *, int y, int x, “String”, ….);`

Ok now everything is done, except one, and that is borders. To add borders to screen there are two functions

+ **`box(WINDOW*, int v, int h)`**: Function to add borders to window
   + `v` is the value for vertical borders. Default is 0
   + `h` is the value for horizontal borders. Default is 0
+ **`wborder(WINDOW*, int leftChar, int rightChar, int topChar, int bottomChar, int topLeftCorner, int topRightCorner, int bottomLeftCorner, int bottomRightCorner)`**: The most precise function to add borders to a window


```cpp
#include <ncurses.h>
using namespace std;

int main(int argc, char **argv)
{
	initscr();

	// creating a window;
	// with height = 15 and width = 10
	// also with start x axis 10 and start y axis = 20
	WINDOW *win = newwin(15, 17, 2, 10);
	refresh();

	// making box border with default border styles
	box(win, 0, 0);

	// move and print in window
	mvwprintw(win, 0, 1, "Greeter");
	mvwprintw(win, 1, 1, "Hello");

	// refreshing the window
	wrefresh(win);

	getch();
	endwin();
	return 0;
}
```

![](https://i.ibb.co/Th7523w/image.png)
TailwindCSS with Webpack Encore
Tags: tailwindcss, css, webpack, symfony
Published: 2020-05-05 22:10:23

---
title: TailwindCSS with Webpack Encore
published: true
description: 
tags: TailwindCSS, css, webpack, symfony
---

Tailwind CSS is a highly customizable, low-level CSS framework that gives you all of the building blocks you need to build bespoke designs without any annoying opinionated styles you have to fight to override.

> Use Tailwind to increase your development speed

## Installing Tailwind

Tailwind, like any other framework, is available on a CDN, but you can configure it yourself, Simply by running this command

```javascript
# Using npm
npm install --dev @symfony/webpack-encore autoprefixer postcss-loader tailwindcss
# Using Yarn 
yarn add --dev @symfony/webpack-encore autoprefixer postcss-loader tailwindcss
```

Next, we need to generate the `tailwind.config.js` file:

```javascript
npx tailwindcss init
```

Here you can add colors, edit font stack, and much more
Use the @tailwind directive to inject Tailwind's base, components, and utilities styles into your CSS:

```css
@tailwind base;
@tailwind components;
@tailwind utilities;
```

I use Symfony for most of my projects, so for compiling my assets I always use Webpack. Here’s how you would set up Tailwind with webpack-encore:

You’ll want to add Tailwind as a PostCSS plugin in your build chain.

Generally, this means adding Tailwind as a plugin in your `postcss.config.js` file:

```javascript
module.exports = {   
     plugins: [     
          require('tailwindcss'),   
     ] 
}
```
and in `webpack.encore.js` we need to enable the PostCSS loader

```javascript
// ...
.enablePostCssLoader()
// ...
```

You can also pass options into the PostCSS loader by passing a callback, as per the Encore PostCSS docs:

```javascript
Encore.enablePostCssLoader(function(options) { 
  options.config = {     
     path: 'postcss.config.js'   
  } 
})
```

That’s it. Now you can just run it as always.

```javascript
npm run watch
```

## In conclusion

Tailwind provides a great developer experience and with webpack-encore it is especially easy to set up.
I made a Game with vanilla HTML CSS and JavaScript
Tags: gamedev, html, css, javascript
Published: 2020-05-05 22:04:01

Recently I have not been writing posts. The reason is I had been developing a simple game using vanilla HTML, CSS and JavaScript (no framework used). The game is available as a PWA at [https://oddneven.netlify.app/](https://oddneven.netlify.app/) 

If you want to check out the frontend code go to [https://github.com/AyushmanBilasThakur/Odd_N_Even](https://github.com/AyushmanBilasThakur/Odd_N_Even)

I will write posts about my experience developing this game if I get positive responses. Also, there is a small backend managing the leaderboard. I will be unveiling that code after editing some things out. 

Comment your high scores and what do you want to learn about the project.
Make Your Objects Unchangeable with Object.freeze()
Tags: javascript, const, objectfreeze, frozen
Published: 2020-05-05 21:59:42

---
title: Make Your Objects Unchangeable with Object.freeze()
published: true
description: Achieve immutability with Object.freeze().
tags: javascript, const, object.freeze, frozen
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/tali1zhnr3wag4hjic85.png
---
One of the things that confused me initially during my JavaScript learning journey was the `const` keyword.  I thought it was akin to `const` in C++ where the declared variable would be immutable. 

This is not the case in JavaScript.

The `const` keyword does not create immutability as the name would imply (i.e. no changes allowed), but actually prevents reassignment.

So how do you make JavaScript objects immutable?

That's where `Object.freeze()` comes in.  It is a way to **freeze** an object and as it implies, a frozen object can not be changed.

Let's look at an example in our browser console.

```
>> const myinfo = { name: "Liz", title: "Frontend Engineer" }
```

Now let's change my title via property access:

```
>> myinfo.title = "Elephant Trainer"
>> myinfo
Object { name: "Liz", title: "Elephant Trainer" }
```

No problem, as long as we not reassigning anything to `myinfo`, my `name` and `title` are mutable for all to change.

Let's say we do something like this:

```
>> const myinfo2 = Object.freeze(myinfo)
```

`Object.freeze(myinfo)` returns the frozen version of `myinfo` to `myinfo2`.  

Now before you break out into a song of "Let it Go", it might not be totally obvious that `myinfo2` is frozen.

`myinfo2.title = "Ballet Dancer"` doesn't throw any errors but upon inspection, you will see nothing has changed.

```
>> myinfo2
Object { name: "Liz", title: "Elephant Trainer" }
```

In conclusion, if you are looking for a way to make objects unchangeable in JavaScript, `const` is not the keyword your are looking for.  Use `Object.freeze()` for your immutability needs.
Getting data from Hasura onto your Next.js app
Tags: hasura, nextjs, graphql, javascript
Published: 2020-05-05 21:56:24

---
title: Getting data from Hasura onto your Next.js app
published: true
description: 
tags: Hasura, Nextjs, graphql, javascript
---
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zpqphxi8mosdwub36dka.jpeg)

## Hasura

Hasura is an open-source engine that gives you realtime GraphQL APIs on new or existing Postgres databases, with built-in support for stitching custom GraphQL APIs and triggering webhooks on database changes.

## GraphQL

GraphQL gives you the ability to fetch the exact data you need for your UI and is great for building UIs with encapsulated data requirements.
> You get exactly what you ask for!

## Next.js
Next.js is an isomorphic react framework that that has server-side rendering, hot module replacement, automatic code-splitting, static page exporting and so much more.

> Next.js + Hasura + next-apollo = SSR react apps with GraphQL!

Let’s start, by creating a next project
```javascript
npx create-next-app <app-name>
```
we need to add some dependencies
```javascript
yarn add next-apollo apollo-boost graphql graphql-tag next-apollo react-apollo
```
then, add this code and remember to replace the endpoint with the endpoint you get from Hasura
```javascript
// config.js
import { withData } from 'next-apollo'
import { HttpLink } from 'apollo-link-http'

const GRAPHQL_URL = 'http://localhost:8080/v1/graphql' // url from Hasura 

export default withData({
    link: new HttpLink({ uri: GRAPGQL_API }),
});
```
In your component import the Books query
```javascript
import gql from 'graphql-tag'

const BOOKS_QUERY = gql`
    query Books {
        books {
            id
            title
            author{
                id
                name
            }
        }
    }
`

export default BOOKS_QUERY
```
That’s all you need. You should now have your Hasura endpoint and your application making a query to view the data which you can now display in your template.
```javascript
<Query query={BOOKS_QUERY}>
  {({loading, data, error}) => {
    if (error) {
      return <div>Error {JSON.stringify(error)}</div>
    }
    if (loading) {
      return <div>Loading..</div>
    }
    return (
      <ul>
        {data.books.map((book) => {
          return (
            <li key={`book__${book.id}`}>
              <h3>{book.title}</h3> <small>{book.author.name}</small>
            </li>
          )
        })}
      </ul>
    )
  }}
</Query>
```
That’s it! Now run the server by running the following command:
```javascript
npm run start
```
### In conclusion
Using Hasura to increase your development speed, you don't need to spend time setting up your GraphQL server.
NGRX | Use effects and router-store to isolate route related side 🧙🏼‍♂️ effects
Tags: ngrx, angular, rxjs, typescript
Published: 2020-05-05 21:52:41

One of the major advantages of `ngrx` is that we can isolate side effects from the components.

When we need to have router related data on the component we'll usually use the `ActivatedRoute` service from the component itself. For example, we can get the id from a route using this technique:

```typescript
export class MyComponent {
  id: string;
  id$ = this.activatedRoute.params.pipe(
    map(params => params.id),
    tap(id => this.id = id),
  );
}
```

Let's isolate this using `@ngrx/effects`. The first goal is to get the route param from the URL.

## How not to do it

We might be tempted to try using the `ActivatedRoute` service on the effects, but it's useless. It's only accessible on the "associated with a component loaded in an outlet", quoted from https://angular.io/api/router/ActivatedRoute.

Another thing we might think of is to use the `Router` service. But again we won't have the url parameter accessible in a clear, easy to use way.

What we can do, is to use `selectRouteParam` state selector from `@ngrx/router-store`.

Let's dive into the example. (stackblitz link at the bottom of the article)

## How it's done right

Setting up the effect:

```typescript
  setCurrentCourse$ = createEffect(() => this.store$.pipe(
    select(selectRouteParam('id')))
      .pipe(
        map((id: string) => setIds({id})), // dispatch a new action to set the selected id
      ),
    {dispatch: true},
  );
```

_Kudos for @timdeschryver for the simplified version 🤘🏼_

Then our component can be as simple as:

```typescript
import { Store, select } from '@ngrx/store';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `{{selectedId$ | async | json}}`,
})
export class HomeComponent {
  selectedId$ = this.store.pipe(select((state: any) => state.featureName.selectedId));
  constructor(
    private store: Store,
  ) { }
}
```

## The takeaways

That a basic example showing just how to get a param. The real power comes when we need to use that param and fetch some data with it. Then we'll have an effect where we'll use the `mergeMap` operator to fetch the data using this id from the URL. On the component, we'll just subscribe to the fetched data, and that's it.

{% stackblitz ngrx-effects-router-store view=preview %}

If you liked it, please show me some love here or on my twitter @AdamGenshaft.
Day 131 : It Makes You Forget
Tags: hiphop, code, coding, lifelongdev
Published: 2020-05-05 21:39:04

_liner notes_:
- Professional : Had a couple of test runs set up for people using the tutorial we are working on. Got some really good feedback. There was a wide range between the people who took the tutorial today. Did some work rewriting a demo I'm working on for another team to see if I can get a feature working.

- Personal : So last night, before I went to sleep, I thought of a way to get a feature for a demo for another team to work. Other than that, basically sat if no power for a couple of hours. haha. I was able to do a little design work for a side project.

![Aerial shot of the mountain side coast of Kalalau, Hawaii](https://dev-to-uploads.s3.amazonaws.com/i/cf60swn6bzwtpm8rn0m1.png)

Going to see if I can get the feature working for a couple of more hours. After that, maybe some more design work for my side project. Also, I've been slowly getting back into studying Japanese. With so much time passed, I figure it makes you forget a lot! I remembered a lot more than I thought.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube SlbVgjFvE3I %}