teleren/devto huggingface dataset:
What is Defensive Coding?
Tags: codenewbie, beginners, computerscience
Published: 2020-02-08 08:19:13

Defensive coding is a way of ensuring your program or code continues to function under unforeseen or unintended circumstances. Imagine a hacker or malicious user is trying to find vulnerabilities in your program, such as seeing the contents of a database, you want your program to not reveal any secure information or break in such a way that reveals vulnerabilities. Another reason to write defensive code is to prevent a normal user from accidentally making your program halt or perform in an unintended manner.

Let's look at a simple example and how we can write some defensive code around it to protect it against unintended usages. The below code snippet shows a simple function that takes two parameters and returns the multiplication of those two parameters. This function obviously should take two numbers as the parameters, but what would happen if a string or a boolean is passed into the function instead?

```javascript
function multiply(a, b){
  return a * b;
}
```

We could add an if statement to the function to ensure that both parameters are above the number 0, this would ensure that they're number variable types. This change to the code is shown below, if the parameters are not numbers (e.g. booleans or string) or are not positive numbers, they are not above the number 0, the function will return the number 0 otherwise it will return a multiplication of the two parameters. The two numbers passed into the function. This if statement does include defensive code but it stops the function from returning the multiplication of numbers below or equal to the number 0.

```javascript
function multiply(a, b){
  if(a > 0 && b > 0){
    return a * b;
  }
  return 0;
}
```

We can change the function by checking the variable type of the two passed in parameters. The code below ensures that both parameters are of the variable type 'number' and if they are it returns the multiplication of the two numbers otherwise it returns the number 0. This would allow negative numbers or decimal/floating-point numbers to be passed in and the multiplication of those returned.

```javascript
function multiply(a, b){
  if(typeof a == 'number' && typeof b == 'number'){
    return a * b;
  }
  return 0;
}
```

Defensive coding is a way to prevent your program from 'acting up' under strange or unforeseen circumstances, such as the wrong parameter variable types being passed into a function. The example shown on this page is very simple and defensive coding can become more complicated or include checking other things and not just numbers. For example, if you are processing a file you may want to check that the file exists and you have permission to access the file before trying to process it. Try catch blocks can be used to attempt a process and then catch any errors or exceptions, and run a different code path if any errors occur.

This post was originally published on https://acroynon.com
TypeScript settings for modern projects
Tags: typescript, esmodules
Published: 2020-02-08 07:13:41

---
title: TypeScript settings for modern projects
published: true
description: Configure TypeScript and Node to generate modern code, while still being able to use legacy modules
tags: TypeScript, ES modules
---

# Modern TypeScript project template

Even though ES modules have been no longer experimental for a few months, many TypeScript users still generate old ES3 code. While that may make sense for browser compatibility, it doesn't make any sense for server-side Node projects! On your server, you control your version of Node, and Node has been supporting modern `import`/`export` code natively since version 8.5.0, released in 2017!

At the same time, you want to be able to import npm packages that still (ಠ_ಠ) haven't published native ES modules (e.g. [`apollo-server`](https://github.com/apollographql/apollo-server/issues/1356#issuecomment-565277759), [`node-influx`](https://github.com/node-influx/node-influx/issues/298)).

So here's a [minimalistic example](https://github.com/dandv/typescript-modern-project) of configuring TypeScript and Node to do that, and a bit more:

* emit modern ES modules code
* import modules that don't have named exports (the ones I linked above)
* import modules that use Node built-ins
* import your own modules without specifying an extension
* run the resulting JavaScript code

Here's how each of these is done.

# Emit ES modules code

In `tsconfig.json`, set this in `compilerOptions` (don't mind the syntax highlight error here, `tsc` supports comments in JSON):

```json
{
    "target": "esnext",
    "module": "esnext",  // Output `import`/`export` ES modules
}
```

# Import modules that use Node built-ins (`http`, `url` etc.)

* run `npm install --save-dev @types/node`
* in `tsconfig.json` under `compilerOptions`, set
  * `"moduleResolution": "node"`, so `tsc` can find modules [when targeting ES6+](https://github.com/Microsoft/TypeScript/issues/8189) 
  * `"types": ["node"]` to avoid errors related to Node built-in modules  

# Import modules that don't have named exports

Set `"allowSyntheticDefaultImports": true` in `tsconfig.json`. In our code,
instead of `import { InfluxDB } from 'influx` we have to write:

```js
import Influx from 'influx';
const influx = new Influx.InfluxDB();
```

# Import your own modules without specifying an extension

When transpiling, [TypeScript won't generate an extension for you](https://github.com/microsoft/TypeScript/issues/16577). Run Node with the `node --experimental-specifier-resolution=node` parameter:

    node --experimental-specifier-resolution=node run.js
    
Otherwise, [node mandates that you specify the extension](https://nodejs.org/api/esm.html#esm_mandatory_file_extensions) in the `import` statement.

# Run the resulting JavaScript code

Add `"type": "module"` to `package.json`, because [TypeScript can't generate files with the .mjs extension](https://github.com/microsoft/TypeScript/issues/18442#issuecomment-581738714).

Enjoy using modern TypeScript!
Import once Browser Module
Tags: angular, materialdesign, refactoring
Published: 2020-02-08 07:02:28

#### Problem Statement

In one of the existing projects i worked on, i was given a task of improving the performance of an Angular App. 

First thing i looked on is if the major routing modules are lazily loaded or not. Sometimes developers make basic mistakes. 

As i was navigating through the code found, i found none of the modules are lazy loaded due to some x reason. This was the chance to improve upon as client would be un-necessary downloading the code he would never want to go on.

As i extracted the components and created a lazy module, i imported *MaterialDesignModule* from the codebase which would imply it had all the material library related modules. Once imported my app would stop working and below error could be see on console.

>Error: BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.**

This error is self explanatory and tells us that BrowserModule has already been loaded and it does not need to be loaded again. if its needed in any other module or a lazy loaded module then *CommonModule* should be imported. 

#### Solution

I tried to find the BrowserModule, but it had been imported only once. So there is another module [BrowserAnimationsModule](https://angular.io/api/platform-browser/animations/BrowserAnimationsModule) which exports BrowserModule with additional providers useful for animations.

Importing BrowserAnimationsModule in your app module will mean that all your module will have animation enabled and you are ready to use.

To solve the error remove BrowserAnimationsModule from any other modules and import it in AppModule.

AppModule
```javascript
@NgModule({
  imports:      [ BrowserModule, BrowserAnimationsModule, FormsModule, AppRoutingModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
``` 

LazyModule
```javascript
@NgModule({
    declarations: [LazyComponent],
    imports: [
      LazyRoutingModule,
      // Dont import BrowserAnimationsModule inside child module
      // BrowserAnimationsModule
    ],    
})
```

Other problem was that the MaterialDesignModule in codebase had mixed responsibilities as it imported BrowserAnimationsModule too. 

> A bit of refactoring and cleaning the code is a part of developer journey.

Code was refactored to have MaterialDesignModule just consisting of Material modules and main AppModule has BrowserModule, BrowserAnimationsModule.

Also *CommonModule* needed to be imported in Lazy module as it required *ngIf directive. 

Though if you feel that any of your module does not need animation, Angular provides a clean way of disabling it by importing [NoopAnimationsModule](https://angular.io/api/platform-browser/animations/NoopAnimationsModule)


I will post more on [Animations](https://angular.io/guide/animations) in Angular in my upcoming posts
Connect/debug android with adb (Android Debug Bridge) commands in terminal easily, with one or many devices/emulators.
Tags: android, adb, androiddebugbridge, bashscript
Published: 2020-02-08 06:11:13

---
title: Connect/debug android with adb (Android Debug Bridge) commands in terminal easily, with one or many devices/emulators.
published: true
description: connect/debug android with adb (Android Debug Bridge) commands in terminal easily, with one or many devices/emulators.
tags: Android, adb, "Android-Debug-Bridge", "bash-script"
---
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/as0aqpiiq9vf19a1dgq3.png)

If you are developing/debugging an android app, sometimes you may want to run some commands from the terminal (using `adb`). If you have one device/emulator attached, then you are okay to run commands like `adb install -r app.apk`.

But when you do have several devices attached, that command will not work. You would have to specify the `ID` of the specific device you want to run a command on: `adb {deviceid} install -r app.apk`. Now, to get a list of attached devices, you simply run the command: [`adb devices`](https://developer.android.com/studio/command-line/adb#devicestatus)
```
$ adb devices
List of devices attached
emulator-5556 device product:sdk_google_phone_x86_64 model:Android_SDK_built_for_x86_64 device:generic_x86_64
emulator-5554 device product:sdk_google_phone_x86 model:Android_SDK_built_for_x86 device:generic_x86
0a388e93      device usb:1-1 product:razor model:Nexus_7 device:flo
```
[This is why I wrote below bash script:](https://gist.github.com/McKabue/ac124f736085e9650fdbf63b1d9ca5ab)
{% gist https://gist.github.com/McKabue/ac124f736085e9650fdbf63b1d9ca5ab %}
This script allows you to connect/debug android with `adb` commands in terminal easily, with one or many devices/emulators.

```
bash <(curl -s https://gist.githubusercontent.com/McKabue/ac124f736085e9650fdbf63b1d9ca5ab/raw/ccfba9fad913baebc1f08cbcd7e525cc3827dd5a/debug-android-from-terminal.sh) install -r app.apk
```
This will prompt you to run the command on a specific device, or all of them.
Help me decide on a meta attribute for dev bookmarks
Tags: watercooler, discuss, opensource, bookmarks
Published: 2020-02-08 06:08:09

---
title: Help me decide on a meta attribute for dev bookmarks
published: true
description: Help me decide whether to add a level (beginner, intermediate and advanced) attribute to dev bookmarks
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/sjk6ksm6qcieq69m1rkc.png
tags: watercooler, discuss, opensource, bookmarks
---

Dear community,

I need your help making up my mind whether to add an optional **level** attribute to bookmarks on [www.bookmarks.dev](https://www.bookmarks.dev). There is a [Github issue](https://github.com/CodepediaOrg/bookmarks.dev/issues/21) for the topic for quite some time. 

Thus you could search for public articles marked for *beginners*, *intermediates* or *advanced* for example. And even with your private bookmarks, it might help you decide which one to read when you bookmarked more links to the same topic.

My biggest concern is it will "bloat" the [Save bookmark form](https://www.bookmarks.dev/personal/new), also used by the [Google Chrome Extension](https://chrome.google.com/webstore/detail/save-to-bookmarksdev/diofdblfhjbpgackifolmboaiccmebjb) with a new field:
![to level or not to level](https://dev-to-uploads.s3.amazonaws.com/i/bmm7sjjlwfge2avldi8s.png)

that might not get used. But hey, we are agile and can easily undo it, right?


And if I do add it, should I also display the level attribute on the public bookmarks at [https://github.com/CodepediaOrg/bookmarks](https://github.com/CodepediaOrg/bookmarks#readme)

What are your thoughts? Would it be useful to you, knowing the knowledge level for your bookmarks? Please answer in the comments below.
Angular 9 New Features
Tags: angular
Published: 2020-02-07 23:03:24

---
title: Angular 9 New Features
published: true
description: Angular 9 is released with new features
tags: angular
---

Angular 9 is finally released with many [new features](http://techiediaries.com/angular/angular-9-new-features-and-ivy/). 

The major feature of the release is the Ivy renderer and runtime which makes Angular bundles smaller and increases the performance of your apps.

Unlike version 8, Angular 9 uses Ivy by default and fixed many bugs.

These are the features mentioned in an official post:

- Smaller bundle sizes and augmented performance
- Faster testing
- Better debugging
- Improved CSS class and style binding
- Improved type checking
- Improved build errors
- Improved build times, enabling AOT on by default
- Improved Internationalization
- The Ivy compiler: The default use of the Ivy compiler is the most important feature of Angular 9, Ivy is what actually designed to solve the major problems of Angular i.e the performance and large file size
- Selector-less bindings support for Angular Ivy
- Support for TypeScript Diagnostics Format
- Support for more scopes in providedIn
- A New Type-Safe TestBed.inject() Method Instead of TestBed.get()


Angular 9 makes it easy to use Google Maps and YouTube in your front-end apps.


Angular 9 added support for TypeScript 3.7 and improved the IDE and language service extension which will increase the productivity of Angular developers and help them spot errors when developing apps. 

Many bugs have been fixed along with stability and performance issues.
https://www.youtube.com/watch?v=sb0UlBeOvEo
Cold Showers
Tags: goals, motivation
Published: 2020-02-08 05:19:51

---
title: Cold Showers
published: true
description: 
tags: goals, motivation
canonical_url: https://joshuawood.net/cold-showers
---

Next time you rinse off, do this:

Standing right under the showerhead, gradually increase the hot water. When you can’t handle it anymore, turn the temperature all the way to cold (and brace yourself). Wait to stop hyperventilating before turning the water off.

Do this every day. Not only is it refreshing, but it’s also a daily reminder that for many things, getting past the initial resistance is the hardest part. 🚿
Conference Talk: Technical Debt Must Die
Tags: codequality, techtalks, codemash, communication
Published: 2020-02-08 04:41:33

---
title: Conference Talk: Technical Debt Must Die
published: true
date: 2020-02-08 04:37:35 UTC
tags: codequality, techtalks, codemash, communication
cover_image: https://i1.wp.com/killalldefects.com/wp-content/uploads/2020/02/CM_Title.png

canonical_url: https://killalldefects.com/2020/02/07/technical-debt-must-die/
---

The post [Technical Debt Must Die](https://killalldefects.com/2020/02/07/technical-debt-must-die/) appeared first on [Kill All Defects](https://killalldefects.com).

---

My talk at [CodeMash 2020](https://www.CodeMash.org) is now [LIVE on Pluralsight](https://app.pluralsight.com/library/courses/codemash-session-25/table-of-contents) and will be perpetually free to view, even without a subscription and outside of free weekends.

I’ve written previously about [my process in practicing for the talk](https://killalldefects.com/2020/01/11/preparing-my-first-conference-talk/), and most of everything I wrote on [KillAllDefects.com](https://killalldefects.com/) last fall was a direct result of preparing for this talk.

Overall, it’s a dream come true and a bucket list item checked to be hosted on a platform like Pluralsight. It’s also extremely helpful for me to study my first conference talk and see what I can improve on, because there are many things left to improve and I want to do the best job I can.

[Check out the course](https://app.pluralsight.com/library/courses/codemash-session-25/table-of-contents) and I hope you enjoy it and benefit from it.
Day 81 : What A Job
Tags: hiphop, code, coding, lifelongdev
Published: 2020-02-08 04:37:17

_liner notes_:

- Professional : Whew! What a job! Today was pretty awesome! Here's a time lapse of just a PART of the day speaking with developers from all over:
{% youtube MwhXDhsHqOA %}
A lot of people are creating some really cool things. You can check out all the things I'm posting at https://dwane.in/SunshinePHP2020

- Personal : Got back to the room pretty tired. Working on getting the radio show we recorded on Sunday uploaded so that anyone that wants to hear it will be able to. So tired. haha.

![The mountains of Brecon, United Kingdom](https://dev-to-uploads.s3.amazonaws.com/i/v64bvvk5eqt570widn70.png)

Tomorrow is the last day of the Sunshine PHP 2020 conference. We pretty much gave away everything we had at the table. haha Will be talking to more people and helping host a live stream and interview some speakers.
Should be fun. Hopefully I'll get some more pics to post to the site.

Then I head home on Sunday and probably sleep all day! haha.

Have a great night and weekend!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube Mz9B7Bct_So %}
Week 5 discussion
Published: 2020-02-08 04:00:27

1. Why do you think arrays in Swift only support a ​collection of objects of the same type. This is so that the array can be read easier and things can be kept clean. For example if you'd like to create a function where you are adding two numbers from the array and the index that you are using falls on a string, the program will return an error.


2. How can you access objects within an array one at a time? you would call them based on their index for example arrayX.5


3. How might you check if an array is empty? This can be done by checking isEmpty.arrayX
Install nvidia-docker 2.0 on Ubuntu 18.04
Tags: docker, ubuntu
Published: 2020-02-08 03:28:16

I needed to install nvidia-docker 2.0 to use Runwayml's local GPU.
Here are the commands I ran.

### Runwayml
>Machine learning for creators
Bring the power of artificial intelligence to your creative projects with an intuitive and simple visual interface. Start exploring new ways of creating today.

https://runwayml.com/


```bash
$ curl -sL https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
$ curl -sL https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list
$ sudo apt update
$ sudo apt install nvidia-docker2 -y
$ sudo pkill -SIGHUP dockerd
$ sudo docker run --runtime=nvidia --rm nvidia/cuda nvidia-smi
```

Probably you will see this.
```bash
7ddbc47eeb70: Pull complete
c1bbdc448b72: Pull complete
8c3b70e39044: Pull complete
45d437916d57: Pull complete
d8f1569ddae6: Pull complete
85386706b020: Pull complete
ee9b457b77d0: Pull complete
be4f3343ecd3: Pull complete
30b4effda4fd: Pull complete
Digest: sha256:31e2a1ca7b0e1f678fb1dd0c985b4223273f7c0f3dbde60053b371e2a1aee2cd
Status: Downloaded newer image for nvidia/cuda:latest
Sat Feb  8 03:11:46 2020      
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.33.01    Driver Version: 440.33.01    CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1070    On   | 00000000:01:00.0  On |                  N/A |
| N/A   52C    P8     4W /  N/A |    349MiB /  8111MiB |      2%      Default |
+-------------------------------+----------------------+----------------------+
                                                                               
+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
+-----------------------------------------------------------------------------+

```
Best Websites To Hire an Online Tutor
Tags: hiring, career, whoishiring, productivity
Published: 2020-02-08 02:53:14

Hiring a teacher to teach you or your kid stuff is hard. There're so many choices of schools and websites.

Which one do we choose?

Fortunately, we can take care of this problem easily. Here are the top websites for hiring tutors.

1. [Tychoo](https://www.tychoo.com/)
2. [VIPKid](https://www.dreamhomebasedwork.com/go/VIPKid)
3. [Tutor.com](http://www.tutor.com/)
4. [Homework Tutoring](http://www.homeworktutoring.com/index.shtml)
5. [Aim-for-A Tutoring](http://www.aim4a.com/tutors.php)
6. [My Tutor 24](https://www.flexjobs.com/jobs/online-tutoring)
7. [Revolution Prep](https://www.revolutionprep.com/)
8. [Tutorvista.com](http://www.tutorvista.com/)
9. [SmartThinking](https://www.pearson.com/us/higher-education/products-services-institutions/smarthinking-online-tutoring/become-a-tutor.html)
10. [Brainfuse](http://brainfuse.com/login/)

These sites have lots of teachers and tutors waiting to be hired. Many of them are good and they can teach a lot. They're from all over the world so the rates they charge range from affordable to expensive.

Affordable doesn't mean bad. This is because they're from affordable regions of the world. They can live with less than the developed world.

Some tutors have different time zones that you so that's definitely a consideration. Also, they may not be available all the time. This lets you get a chance to try out different tutors and teachers and see who suits your needs.

Some sites like Tychoo have lots of tutors. Also, you can get help with other things like programming, consulting, entertainment and more.

Most other sites are more limited in scope and don't have as much people in non-teaching categories waiting to be hired.
Gridsome g-images with dynamic paths
Tags: gridsome, vue, javascript
Published: 2020-02-08 02:27:21

I've seen other people with this issue. Here's what has been working for me.

Go to `gridsome.config.js` and add an alias for your images folder inside of the `chainWebpack` function (you may need to add it):

```javascript
module.exports = {
  siteName: 'Jeremy Jackson',
  plugins: [],
  chainWebpack: config => {
    config.resolve.alias.set('@images', '@/assets/images')
  },
  templates: {}
}
```

Save the file and restart the server.

Then in your code where you want to use the image you can do:

```
<g-image :src="require(`!!assets-loader!@images/${imageUrl}`)"/>
```

And the dynamic image shows up. This works inside of v-for as well.

For reference, here's the code I'm using inside of a v-for in my site:

```
<div id="project-images">
  <div class="section-header">Screenshots</div>
  <div class="row">
    <div 
      class="col-xs-12 col-sm-3 project-image"
      v-for="(projectImage, index) in $page.project.images"
      :key="projectImage"
      @click="openLightBox(index)"
    >
      <g-image class="responsive-image" :src="require(`!!assets-loader!@images/${projectImage}`)"/>
    </div>
  </div>
</div>
```

and the result:

![project screenshots](https://i.imgur.com/IMaaBXq.png)

This has worked for me. If there's a better solution to this, let me know so I can fix my stuff ;)