teleren/devto huggingface dataset:
Advanced TypeScript Exercises - Question 5
Tags: typescript, javascript
Published: 2020-02-28 10:06:30

--- series: Advanced TypeScript Exercises ---

We have function `getUser` which gets `Config` object, the object defines what fields of `User` function will return. If for example config says `{ name: true, lastname: false }` it means returned object should have `name` field non-optional but no field `lastname`. Current `User` type is very broad type of the return, we need to narrow it down depending on the config passed as argument of `getUser`. Solution should be done only at the type level, no value level code should be written. Only function declaration `getUser` is to be changed.

```ts
// Here types should remain the same ❄
type Config = {
  name: boolean;
  lastname: boolean;
};
type User = {
  name?: string;
  lastname?: string;
};

// Here declaration to be changed 🔥
declare function getUser(
     config: Config
): User;

// test cases
const user = getUser({ name: true, lastname: false })
user.name // this field should be non-optional
user.lastname // this field should not be there and we should have compile error 🛑

const user2 = getUser({ name: true, lastname: true })
user2.name // this field should be non-optional
user2.lastname // this field should be non-optional

const user3 = getUser({ name: false, lastname: true })
user3.name // this field should not be there and we should have compile error 🛑
user3.lastname // this field should be non-optional

const user4 = getUser({ name: false, lastname: false })
user4 // user4 should be empty object {}
```
Full code can be found [in the playground](https://www.typescriptlang.org/play/index.html?ssl=30&ssc=41&pln=1&pc=1#code/PTAEAkFMCdNAXAngB0gZ1GgFgewK4A2AJqLALYCGAlgHYJZxoVlyAi5AFBKqgDCONAMyoBzUAF5QAb3ahQNZpABcoAEY4cBSBRoBuGaAIU08eS2VqNW3ewC+ernACqaGOKn7TkAPzLj0WsJ6sobGnj6Y8P40gbZ67CAQMHBEkADGhtAU8FT8CDiqcKlY2sKQJIC8G4Cku+wp6RSwoAJ4NKnZuaXwzjAAFPqyoKn8QsLKfIIi7ACUyl3QcQnw6PADRujsgzTGoHgu0G4ds92ScgrKkXiQADQGRianjRQELqA2k+w7MAB0nqALWFQYISQYiYXCEEgqOA0fgAWhwyDa8gI712nxCdxYvzA8H+gKowJI2HwIOhy0h9CSoG0JAA7owwSDigA3Qo4MjIKiaUAwaA4PblQCLe+x1vwth9oAAmfaQTq7I4nMwIaAXa7ozxnZVwV4omAS74KLH0AGNfEgonggpyWHwxGPHWStG3H5-Y1As0MiFQ60InJI4UbMW7ADM0tlPWO6oeTyuN1C93OWre4qD+sxLrxBNBxJIpMtOMp1NAdKzFuZrPZnLgPL5oEF9pTaoN6ZNmfNIPJ0JocJ9-DtIs2y3FABZQ4cI-cBI8XKqnROp4n7SOEsOS+2q+ykKAcCoAFZpZaSGxAA).

Post your answers in comments. Have fun! Answer will be published soon!

**This series is just starting**. If you want to know about new exciting questions from advanced TypeScript please follow me on [dev.to](https://dev.to/macsikora) and [twitter](https://twitter.com/macsikora).
Labelling form inputs
Tags: a11y, html
Published: 2020-02-26 09:15:15

## Semantic HTML and accessibility
Most of the times, when it comes to HTML and accessibility, all boils down to semantic HTML, that is using the correct HTML elements for their purpose as much as possible. This ensures that screen readers can infer as much information about the intent behind your page structure and announce the content in a meaningful way for the users. 


### Going the extra mile
There are scenarios where you'll need to put extra work to make sure the content is accessible to everyone. An instance of this are form inputs and their associated labels.

Let's take as an example a text input:

```html
<input type="text"/>
```


All users, whether they're using a screen reader or not will have a hard time figuring out what information are they supposed to enter in the input. The natural thing is to add a label next to the input:

```html
<label>First Name:</label>
<input type="text"/>
```

That gives context to sighted users but is not of much help when we use a screen reader. Voice over is not able to infer the context in which we use the input.


Let's make it clear for the screen readers:

```html
<label for="first-name">First Name:</label>
<input id="first-name" />
```

The input element is identified by an `id` which we can use to tell the label to which element it's associated using the `for` attribute.


### Other methods of labeling form controls

Using the `for` attribute to associate a label with the form control is not the only way to achieve accessible form controls.

Just as well, you could set the `aria-labelledby` attribute to the `id` of the label

```html
<label id="first-name">First Name:</label>
<input aria-labelledby="first-name" type="text"/>
```

Using an `aria-label` attribute or wrapping the input element by a label will also do the job.
JavaScript and CSS progress bar
Tags: javascript, css, widget, dom
Published: 2020-02-26 10:34:39

I recently created a simple progress bar with vanilla JavaScript and CSS.

It's not really a big deal. But someday when you might need something like this, instead of spending time building again, just remember one exists here already:



https://frontend-io.github.io/Vanilla-JS-and-CSS-progress-bar/



Your use case might be different however, but I think same logic may apply. 

```html
	<div class="cont">
		<div class="loader">
			<label class="counter">Profile is <span>0%</span> complete</label>
		</div>
	</div>
```

Adding css- there isn't really much here, just some styling and some tweaks with CSS psuedo class.
The darker pulse that follows later after the bar is loaded is fine with the CSS psuedo ::after class

```css
	.cont{
		margin-top: 30px;
		height: 20px;
		width: 100%;
		background: rgba(0, 200, 0, .3);
		border-radius: 50px;
	}	
	.cont .loader{
		height: 20px;
		position: relative;
		box-sizing: border-box;
		width: 0%;
		background: rgba(0, 200, 0, .8);
		border-radius: 50px;
		transition: width 1.5s linear
	}
	.cont .loader:before{
		content: "";
		position: absolute;
		top: 0;
		left: 0;
		height: 100%;
		border-radius: 50px;
		width: 100%;
		background: linear-gradient(to  right, rgba(0, 200, 0, .3), rgba(0, 100, 0, .8));
		animation: purge 4s infinite ease-out
	}

	@keyframes purge{
		0%{
			opacity: 0;
			width: 0%;

		}
		50%{
			opacity: .5
		}
		100%{
			opacity: 0;
			width: 100%;
		}
	}
	.cont .loader label{
		font-size: 12px;
		position: absolute;
		right: -10px;
		text-align: center;
		top: -25px;
		font-weight: 600;
		transition: .3s;
	}
	.cont .loader:after{
		content: "";
		position: absolute;
		top: -10px;
		right: 0px;
		height: 50%;
		width: 2px;
		background: rgba(0, 200, 0, .8);
	}
	.cont:hover .loader label{
		transform: scale(1.5);
		transition: .3s;
	}
```

And lastly our JavaScript

```javascript
window.addEventListener("load", loadProgress)

  function loadProgress(){
   
  	// Get DOM element
  	const target = document.querySelector(".loader")
	const counter = target.querySelector("span");

	// Sample form data
	const details = {
	    name: "Jefferson",
	    age: 12,
	    weight: 70,
	    level: 30,
	    relationship: "",
	    contact: "",
	    email: "",
     friends: 459
	}


  	function getProgress(board){
	  	let maxLength = 100;
	  	// Put them into array to get length of form
	  	let lengthOfBoard = Object.values(board).length;

	   	// Get possible mark of each field
	  	let jumps = maxLength/lengthOfBoard;
	  	let progress = 0;
	  	for (let field in board){
	  		// If field is filled add it's mark to progress
	  		if (board[field]) {
	  			progress += jumps
	  		}
	  	}
	  	return progress
	}

	// Utilise value calculated from loader
  	function implimentLoad(){
	  	// Simulate a delay
	  	setTimeout(()=>{
	  		let progress = Math.round(getProgress(details))
	  		counter.innerText = `${progress}% `;
	  		target.style.width = `${getProgress(details)}% `
	  	}, 1000)

	}
	implimentLoad()
  }


```


I hope you find this useful...
Creating Extension for VS-Code
Tags: vscode, javascript, tutorial, 100daysofcode
Published: 2020-02-26 11:46:57

Originally posted on Medium.com. I am sharing the medium embedded link here, if you want me to repost the entire article on dev.to then let me know by the comments section.

{% medium https://medium.com/@avishekpatra.1986/creating-extension-for-vs-code-741a26fa0f74 %}
Web Application Firewall - Friend of your DevOps pipeline?
Tags: security, webdev
Published: 2020-02-26 13:01:56

A [MyDevSecOps live session](https://www.mydevsecops.io/post/web-application-firewall-friend-of-your-devops-pipeline) from Jan 30 2020 by [Franziska Buehler](https://twitter.com/bufrasch)

Web Application Firewalls (WAF) often raise concern about false positives, latency and other potential production problems. In addition, it is often said, that DevOps and WAF do not fit together. That is a pity since the WAF helps to protect us from web application attacks, like those described by the OWASP Top Ten. But what if you could ensure that introducing and using a WAF went smoothly? 


I will show how to integrate a WAF with WAF testing automation into a continuous integration (CI) pipeline. This pipeline ensures that developers receive early and often feedback about their WAF, saves them time and headaches down the line. In fact, DevOps, testing and automation only make sense if all components are part of the process. 


Needless to mention, I as an [OWASP Core Rule Set (CRS)](https://coreruleset.org) developer and enthusiast introduced the CRS to [Puzzle ITC](https://www.puzzle.ch/) when I joined them in 2019! By providing YAML templates, we want to make it easy for developers to introduce WAFs into projects.


{% youtube YhfGeV9XWlo %}
React CREATE_REACT_APP Error**
Tags: react, npm
Published: 2020-02-26 16:45:24

I am getting error on creating-react-app. Is there any one to help me out. I am also sharing picture with comment


:::::ERROR IS::::::
There might be a problem with the project dependency tree.
It is likely not a bug in Create React App, but something you need to fix locally.

The react-scripts package provided by Create React App requires a dependency:

  "webpack-dev-server": "3.10.2"

Don't try to install it manually: your package manager does it automatically.
However, a different version of webpack-dev-server was detected higher up in the tree:

  /Users/apple/node_modules/webpack-dev-server (version: 3.10.3) 

Manually installing incompatible versions is known to cause hard-to-debug issues.

If you would prefer to ignore this check, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.
That will permanently disable this message but you might encounter other issues.

To fix the dependency tree, try following the steps below in the exact order:

  1. Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder.
  2. Delete node_modules in your project folder.
  3. Remove "webpack-dev-server" from dependencies and/or devDependencies in the package.json file in your project folder.
  4. Run npm install or yarn, depending on the package manager you use.

In most cases, this should be enough to fix the problem.
If this has not helped, there are a few other things you can try:

  5. If you used npm, install yarn (http://yarnpkg.com/) and repeat the above steps with it instead.
     This may help because npm has known issues with package hoisting which may get resolved in future versions.

  6. Check if /Users/apple/node_modules/webpack-dev-server is outside your project directory.
     For example, you might have accidentally installed something in your home folder.

  7. Try running npm ls webpack-dev-server in your project folder.
     This will tell you which other package (apart from the expected react-scripts) installed webpack-dev-server.

If nothing else helps, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.
That would permanently disable this preflight check in case you want to proceed anyway.

P.S. We know this message is long but please read the steps above :-) We hope you find them helpful!

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
apples-MacBook-Pro-2:react1 watto$ node --v
node: bad option: --v
apples-MacBook-Pro-2:react1 watto$ node -V
node: bad option: -V
apples-MacBook-Pro-2:react1 watto$ node
Welcome to Node.js v12.15.0.
Type ".help" for more information.
> 
(To exit, press ^C again or ^D or type .exit)
> 
apples-MacBook-Pro-2:react1 watto$
How to use Swapper in Golang?
Tags: go, tutorial
Published: 2020-03-03 14:41:31


[Swapper](https://golang.org/pkg/reflect/#Swapper) is a function defined in the [reflect](https://golang.org/pkg/reflect/) package. This function takes a slice and returns a swap function. This swap function takes 2 indexes as arguments and swaps the values at index position in the slice. 

> Originally published on [schadokar.dev](https://schadokar.dev/to-the-point/swapper-in-golang/)

### Function Definition

```go
func Swapper(slice interface{}) func(i, j int)
```

Let's try

```go
package main

import (
	"fmt"
	"reflect"
)

func main() {
	s := []int{1, 2, 3}
	fmt.Printf("Before swap: %v\n", s)

	swapF := reflect.Swapper(s)

	swapF(0, 1)

	fmt.Printf("After 1 swap: %v\n", s)

	swapF(0, 2)

	fmt.Printf("After 2 swap: %v\n", s)
}
```
[Try it](https://play.golang.org/p/pljUgJ0mEnJ)

Output
```
Before swap: [1 2 3]
After 1 swap: [2 1 3]
After 2 swap: [3 1 2]
```

**Swapper panics if the provided interface is not a slice.**

```
panic: reflect: call of Swapper on <Type> Value
```

### Reverse a slice using Swapper

Swap first element with last element, the second element with second last and so on.  

```go
package main

import (
	"fmt"
	"reflect"
)

func main() {
	s := []int{1, 2, 3, 4, 5, 6, 7}

	fmt.Printf("Before swap: %v\n", s)

	swapF := reflect.Swapper(s)

	for i := 0; i < len(s)/2; i++ {
		swapF(i, len(s)-1-i)
	}

	fmt.Printf("After swap: %v\n", s)
}

```
[Try it](https://play.golang.org/p/yFtphVvgvBN)

Output

```
Before swap: [1 2 3 4 5 6 7]
After swap: [7 6 5 4 3 2 1]
```

### Use Swapper in Bubble sort

```go
package main

import (
	"fmt"
	"reflect"
)

func main() {
	s := []int{1, 2, 6, 3, 8, 0, 7, 9, 5, 4}

	fmt.Printf("Before swapper: %v\n", s)

	swapF := reflect.Swapper(s)

	for i := 0; i < len(s)-1; i++ {
		for j := i + 1; j < len(s); j++ {
			if s[i] > s[j] {
				swapF(i, j)
			}
		}
	}

	fmt.Printf("After swapper: %v\n", s)
}
```
Output

```
Before swapper: [1 2 6 3 8 0 7 9 5 4]
After swapper: [0 1 2 3 4 5 6 7 8 9]
```

---
PnP Tips - Credentials
Tags: productivity, powershell, sponline, office365
Published: 2020-03-03 16:01:24

This is the first post of several articles with tips for working with PnP PowerShell commands for Office 365. Today, I will show you how to save your time when connecting to the site collections you want to work with.

If you usually work with PowerShell and Office 365 you'll notice that it is tedious work when several site collections are involved in the tasks you have to do. You normally have to call the `Connect-PnPOnline` command passing the site collection URL and you have to do this for each of the site collections. A new popup window will appear asking you for the credentials you want to use to connect to the site.

```PowerShell

# PnP command for working with a specific site collection
Connect-PnPOnline -Url https://<tenant name>.sharepoint.com/sites/<site collection url>
# It will ask you for the credentials

```
So, let's imagine you have to collect the features for 3 of your site collections. You may think about creating a script and ask for credentials as the first step and, then these credentials will be used for connecting to the site collections. Well, you are wasting much time coding the script than running manually all these actions.

There is another solution, an easy solution let me say. PnP provides with cmdlets that work with your local __Credential Manager__ application. If you don't know what is this think of a repo that makes relationships between URLs and credentials, avoiding writing the credentials, again and again, you want to access the site. In other words, PnP allows you to store your credentials for each of your site collections easier than you think and save your time when manual actions have to be done.

What is the way to use these commands? Let me show you by example:

```PowerShell

Add-PnPStoredCredential -Name https://<tenant name>.sharepoint.com/sites/<site collection url> -Username <user name>
# It will ask you the password

# You can now run this command the number of times you need without asking for credentials
Connect-PnPOnline -Url https://<tenant name>.sharepoint.com/sites/<site collection url>

```

It seems easy, right? Yes, it does. Let me go further and share with you this script, [_Add-StoredCredentials.ps1_](https://raw.githubusercontent.com/codingbugs-code/Learning-PnP-PowerShell/master/scripts/fundamentals/Add-StoredCredentials.ps1), that makes your life even better. I implemented it to automate my tenant tasks, so it stores the same credentials for all the site collections of the tenant even the admin site.

```PowerShell

# Run once and credentials will be saved for all your site collections
Add-StoredCredentials.ps1 -TenantName <tenant name> -UserName <user name> -Password $(ConvertTo-SecureString <password> -AsPlainText -Force)

```

Give it a try and let me know your thoughts.
On.NET Episode: Finding parking spots with Custom Vision and IoT
Tags: dotnet, azure, iot, machinelearning
Published: 2020-03-03 16:04:23

As developers, we have the ability to us machine learning to our applications to create very unique experiences and solve difficult problems for our customers.

In this episode, Martina and Bruno Capuano sit with Scott to show us how we can use Custom Vision and IoT devices to recognize objects in the real world. This is a great demo of how to get started with ML without having to train a model, and also how to get our children interested in technology.


{% youtube B2aX4g_sTUQ %}

If you liked this video and would like to see some more of our .NET content, please subscribe to our [.NET Developers YouTube Channel](https://www.youtube.com/channel/UCvtT19MZW8dq5Wwfu6B0oxw).


## Useful Links
* [Custom Vision](https://www.customvision.ai/?WT.mc_id=ondotnet-c9-cephilli)
* [Custom Vision Documentation](https://docs.microsoft.com/en-us/azure/cognitive-services/custom-vision-service/home?WT.mc_id=ondotnet-c9-cephilli)
* [Identify faces and expressions by using the Computer Vision API in Azure Cognitive Services](https://docs.microsoft.com/en-us/learn/modules/identify-faces-with-computer-vision/?WT.mc_id=ondotnet-c9-cephilli)
Paying attention: the mental cost of development
Tags: programming, codequality, attention, productivity
Published: 2020-03-09 06:24:22

---
title: Paying attention: the mental cost of development
published: true
description: Everyone's very busy, but the results are weak. The product is buggy and unreliable; the codebase is messy; people are frustrated. Sounds familiar? Let's talk about focus and attention.
tags: #programming #quality #attention #productivity
cover_image: https://www.datocms-assets.com/22772/1583227076-photo-1519012121217-3c6d687335c8.jpg?auto=compress%2Cformat&dpr=1&fm=jpg&w=1024
---

Writing software requires long periods of uninterrupted concentration. Developers need to consider complex ideas in detail, imagine and experiment with various solutions to discover the one that works. Finding answers often requires research and learning about new concepts. All this is impossible without paying attention.

For this reason, attention is [the most precious](https://thekarel.gitbook.io/best-practices/the-big-picture/principles/attention) resource in a software project. Once depleted, no amount of determination, money or time will deliver the desired outcomes. Without focus, all other resources go to waste. 

> There is no such thing as multitasking. You can do one thing well or many things wrong in parallel.

But, attention is also a very fragile thing. Successful developers work in attention-friendly environments without external interruptions. They also learn how to manage and direct their focus on what's relevant: they are disciplined. 

A significant source of distraction is often the codebase and the tooling itself. Teams need to avoid unnecessary complexities in the code and all unproductive practices while writing it. There are some [recommendations you can follow](https://thekarel.gitbook.io/best-practices/).

Of course, there are other things to do in a project than writing code. But all activities must be organized in a way that encourages and supports periods of deep concentration and thinking. Focus and care always manifest in more reliable, performant, refined and more enjoyable products. Your customers will be grateful!

Building up a focus-friendly climate takes effort and care, but it's an essential requirement to achieve anything substantial.

You can find out more about the importance of concentration and focus [in my Best Practices on GitBook](https://thekarel.gitbook.io/best-practices/the-big-picture/principles/attention)
How to clean your git history
Tags: git, github, vim
Published: 2020-03-16 12:31:04

Hi!
I want to share you a short instruction on how to remove wrong or mistaken commits from a remote repository when you don't want to make a revert.

Check changes and find what commits you want to remove.

```sh
$ git log --stat
```
Use the interactive rebase command.

```sh
$ git rebase -i HEAD~X
```

Put the number of commits instead of **X** which you want to remove. Better to add a bit more to view the previous ones also. So, you need to remove 1 commit add number 3.

You will see something like this:

```text
pick a0b45b373 Dynamic field featured image url fixed
pick 8e8d27747 Update render condition for feedback popup component
pick 843770a32 Add dev.to version

# Rebase 680ac7c26..843770a32 onto 680ac7c26 (3 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
```
I use Vim as default text editor for Git.

Replace the word `pick` with the word `drop` or `d` for those commits that you want to remove. I remove only one, but I also checked and see that previous commits not related to my changes.

```text
pick a0b45b373 Dynamic field featured image url fixed
pick 8e8d27747 Update render condition for feedback popup component
d 843770a32 Add dev.to version
```
Save and exit from your editor.

Check git status.

```sh
$ git status
On branch master
Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.
  (use "git pull" to update your local branch)

nothing to commit, working tree clean
```
In some cases, there can be merge conflicts after rebase. Follow instructions to solve them.

The next step is to push it to your remote repository. You need to force this push because the remote repository will think that your current branch is behind.
```sh
git push -f
```
Go and check your remote repository.

That it. Thanks and Good luck :rocket:

Cover image by [Diana Mounter](https://www.flickr.com/photos/broccolini/5597043374)