teleren/devto huggingface dataset:
Kotlin Flatten List – Problem & Solution
Tags: kotlin, flatten, list
Published: 2021-04-14 15:33:59

Kotlin Flatten List – Problem & Solution

https://grokonez.com/kotlin/kotlin-flatten-list-problem-solution

In the tutorial, <a href="https://grokonez.com">JavaSampleApproach</a> will introduce Kotlin <code>flatten()</code> and the limit of the method. So we will provide a <strong>new Flatten Solution</strong> for Kotlin List.

<!--more-->
<h2>I. Kotlin List flatten()</h2>
<h3>1. flatten() method</h3>
Kotlin provides a method to flatten a List:

<pre><code class="language-java">
public fun <T> Iterable<Iterable<T>>.flatten(): List<T>
</code></pre>

-> Returns a single list of all elements from all collections in the given collection.

<strong>Practice</strong>:

<pre><code class="language-java">
data class Customer(
	val name: String,
	val age: Int
)

fun main(args : Array<String>){
	val list = listOf(
			listOf(1, 2, 3),
			listOf("one", "two", "three"),
			listOf(Customer("Jack", 25), Customer("Peter", 31), Customer("Mary", 18))
	)
	
	var flattenList = list.flatten()
	
	println(list)
	/*
		[[1, 2, 3], [one, two, three], [Customer(name=Jack, age=25), Customer(name=Peter, age=31), Customer(name=Mary, age=18)]]
 	*/
	println(flattenList)
	/*
		[1, 2, 3, one, two, three, Customer(name=Jack, age=25), Customer(name=Peter, age=31), Customer(name=Mary, age=18)]
 	*/
}</code></pre>
<h3>2. Problem</h3>

More at:

https://grokonez.com/kotlin/kotlin-flatten-list-problem-solution
AWS EC2 Resilience Engineering the easy way
Tags: aws, security, devops, architecture
Published: 2021-04-14 15:29:44

Most of you are probably familiar with Resilience and Chaos engineering. No, those are not synonyms, but stubborn as I am, I treat them as the same thing. My apologies if that is like cursing in the church to you. The term 'Chaos' has a bit of a negative connotation, that's mostly why I prefer to talk about resilience engineering instead. 

In case you wonder:
> The goal of resilience engineering is to design systems to adapt in the event of failure.

> Chaos engineering helps test the resiliency of the system by proactively throwing common failures at the system.

The bottom line, chaos helps to test a system for resilience. But I digress :smile:

## Chaos Tools
Back in the early days, we only had [Netflix's Chaos Monkey](https://netflix.github.io/chaosmonkey/) to bring down EC2 instances every now and then. Nowadays, there's quite a bunch of tools to pick from and recently AWS released its own [AWS Fault Injection Simulator](https://aws.amazon.com/fis/) with the same purpose. However, there's another AWS property that can offer chaos but is often overlooked... `MaxInstanceLifetime`.

## MaxInstanceLifetime
In late 2019 [AWS released the Maximum Instance Lifetime property for Auto Scaling Groups (ASG)](https://aws.amazon.com/about-aws/whats-new/2019/11/amazon-ec2-auto-scaling-supports-max-instance-lifetime/). **The Maximum Instance Lifetime property helps you ensure that instances are recycled before reaching the specified lifetime.** No, it's not a replacement for Chaos Monkey or AWS Fault Injector but **this property is effortless to set and it doesn't cost a penny**. Nevertheless, it offers nice protection against `Configuration Drift` and it's very helpful to enforce `Immutable Infrastructure`.

Before you ask, the property's design is well thought thru:  
> Note that instances are not guaranteed to be replaced only at the end of their maximum duration. In some situations, Amazon EC2 Auto Scaling might need to start replacing instances immediately after you configure the maximum instance lifetime parameter. The intention of this more aggressive behavior is to avoid replacing all instances at the same time.

From: [Replacing Auto Scaling instances based on maximum instance lifetime](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-max-instance-lifetime.html)

In CloudFormation you set it as follow:

```YAML
  SomeAutoScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      MaxInstanceLifetime: 1209600 # 14 day
```

**It's a pity to see this property is little known. I add it to all my Autoscaling Groups by default.**

Enjoy and until next time!
¿ Cómo empezar aprendiendo Vim ?
Tags: discuss, spanish, vim, help
Published: 2021-04-14 15:28:08

Para empezar con tenemos que saber la base de los comandos ahora te voy a recomendar varios cursos y recursos en Español y En inglés:

# Cursos introductorios a Vim

1. Este curso es del compañero Nicolas Schurmann es completamente gratis [Link del curso aquí](https://www.udemy.com/course/vim-aumenta-tu-velocidad-de-desarrollo/)

2. Este es una pequeña wiki con los comandos básicos de Vim lo escribí yo todas las anotaciones se encuentran en **Anotaciones.txt** [Link de la wiki aquí](https://github.com/TeoDev1611/curso-neovim)

3. Este es el inicio de un minicurso de Vim gracias a *EDTeam* [Link del curso aquí](https://www.youtube.com/watch?v=iWo1cDGlNDI)

4. Otro gran curso que me sirvió mucho es este gracias a *Astro* [Link del curso aquí](https://www.youtube.com/watch?v=nC6I4XbvK3g)

5. Por último te comparto esta gran web que te ayudará a mejorar tus movimientos como Vimmer [Link a Vim Adventures](https://vim-adventures.com/)

# Experiencias sobre Vim y Neovim

Mucha gente al ver que uso vim me dice por que lo usas x editor es mejor etc por eso te quiero compartir algunas experiencias del por que uso Vim:

1. Este video de aquí es del Canal de YouTube HolaMundo [Link del Video Aquí](https://www.youtube.com/watch?v=EYaPvgXjFXo)

2. Este video es del Canal de YouTube BettaTech [Link del Video Aquí](https://www.youtube.com/watch?v=EYaPvgXjFXo)

#### Y si sigues sin convencerte de aprender Vim te enseño algunos de los mejores canales de NeoVim en inglés 

1. Este canal es de ThePrimeagen un YouTuber que va cerca de 8 años con Vim enseña trucos nuevos plugins etc [Link al Canal](https://www.youtube.com/channel/UC8ENHE5xdFSwx71u3fDH5Xw)

2. Este canal es de ChrisAtMachine tiene un blog y un canal de YouTube con una configuración genial que es muy famosa en GitHub [Link a el Canal](https://www.youtube.com/channel/UCS97tchJDq17Qms3cux8wcA)

--- 

Espero haberte convencido de que Vim es una opción que deberías probar pero como una frase famosa lo dijo a gustos colores te leo en el siguiente artículo **Spoiler:**  ¿ Cómo encontrarías plugins para Vim?
Kotlin SQLite example - CRUD operations with ListView | Android
Tags: kotlin, sqlite, crud, android
Published: 2021-04-14 15:19:54

Kotlin SQLite example - CRUD operations with ListView | Android

https://grokonez.com/android/kotlin-sqlite-example-crud-operations-with-listview-android

<strong>SQLite</strong> is an Open Source database that supports standard relational database features like SQL syntax, transactions and prepared statements. Each column in an SQLite database is assigned one of data types: <code>NULL</code>, <code>INTEGER</code>, <code>REAL</code>, <code>TEXT</code>, <code>BLOB</code>. In this tutorial, we're gonna look at how to make SQLite <em><strong>CRUD operations</strong></em> when interacting with <code>ListView</code>.

Related Posts:
- <a href="https://grokonez.com/android/kotlin-listview-example-android">Kotlin ListView example | Android</a>
- <a href="https://grokonez.com/android/kotlin-gridview-example-show-list-of-items-on-grid-android">Kotlin GridView example: Show List of Items on Grid | Android</a>

More Practice: <a href="https://grokonez.com/android/kotlin-sqlite-example-search-with-listview-android">Kotlin SQLite example – Search with Listview | Android</a>

<!--more-->
<h2>I. Technologies</h2>
- Android Studio 3
- Kotlin 1.1.51
<h2>II. Overview</h2>
<h3>1. Goal</h3>
We will build an Android App that supports showing, inserting, editing, deleting Notes from/to SQLite Database with <code>ListView</code>:

<img src="https://grokonez.com/wp-content/uploads/2017/12/kotlin-sqlite-goal.png" alt="kotlin-sqlite-goal" width="700" height="385" class="alignnone size-full wp-image-9793" />
<h3>2. SQLite</h3>
<h4>2.1 SQLiteDatabase</h4>
<code>SQLiteDatabase</code> is the base class for working with a SQLite Database in Android. It provides:
- <code>insert()</code>, <code>update()</code>, <code>delete()</code> method
- <code>execSQL()</code> to execute an SQL statement directly

To work with SQLite Database, we create a subclass of <code>SQLiteOpenHelper</code> class:
- constructor: call <code>super()</code> method to specify database_name, version and context
- override <code>onCreate()</code> to execute CREATE TABLE command
- override <code>onUpgrade()</code> to handle database version increment
- indicate read/write mode by using <code>getReadableDatabase()</code> or <code>getWritableDatabase()</code> method

More at:

https://grokonez.com/android/kotlin-sqlite-example-crud-operations-with-listview-android
Generate TypeScript definitions from PostgreSQL
Tags: javascript, typescript, postgres, database
Published: 2021-04-14 15:12:55

I've been enjoying using [Knex.js](https://knexjs.org/) database client for quite some time when implementing GraphQL API backends. One thing that it currently lucks though, is the ability to generate strongly typed (TypeScript) models from the actual database schema.

Luckily, there is a [solution](https://github.com/kriasoft/knex-types#readme)! Assuming you have a database table that looks like this (Knex migration):

```js
await db.raw(`
  CREATE DOMAIN short_id
    AS text CHECK(VALUE ~ '^[0-9a-z]{6}$')`);
await db.raw(`
  CREATE TYPE user_role
    AS ENUM ('consumer', 'provider')`);

await db.schema.createTable("user", (table) => {
  table.specificType("id", "short_id").notNullable().primary();
  table.specificType("email", "citext").unique();
  table.text("name").notNullable();
  table.jsonb("credentials").notNullable().defaultTo("{}");
  table.specificType("role", "user_role").notNullable();
  table.timestamps(false, true);
});
```

Having `User` (class) and `UserRole` (enum) data models in place, you would take full advantage of using Knex.js with TypeScript:

```ts
import db, { User, UserRole } from "./db";

const [user] = await db
  .table<User>("user")
  .insert({ id: "1", name: "John", role: UserRole.Provider })
  .onConflict()
  .merge()
  .returning("*");
```

TypeScript definitions for this particular database schema would look like this:

```ts
export enum UserRole {
  Consumer = "consumer",
  Provider = "provider",
}

export type User = {
  id: string;
  email: string | null;
  name: string;
  credentials: Record<string, unknown>;
  role: UserRole;
  created_at: Date;
  updated_at: Date;
}
```

Now, the interesting part, how to generate these types automatically. Here is the script that will do the trick:

```js
const { knex } = require("knex");
const { updateTypes } = require("knex-types");
const db = knex(require("./knexfile"));

updateTypes(db, { output: "./types.ts" }).catch(err => {
  console.error(err);
  process.exit(1);
});
```

You would execute it as part of database migration workflow, e.g. by adding it to `yarn db:migrate` script in `package.json`:

```json
{
  "dependencies": {
    "knex": "^0.95.4",
    "pg": "^8.6.0"
  },
  "devDependencies": {
    "knex-types": "^0.1.3"
  },
  "scripts": {
    "db:migrate": "knex migrate:latest && node ./update-types"
  }
}
```

Check out [kriasoft/node-starter-kit](https://github.com/kriasoft/node-starter-kit) containing a complete usage example.

Happy coding!
AzureFunBytes Reminder - Microsoft Identity with @ChristosMatskas - 4/15/2021
Tags: azure, activedirectory, iam, beginners
Published: 2021-04-14 15:09:25

AzureFunBytes is a weekly opportunity to learn more about the fundamentals and foundations that make up Azure. It's a chance for me to understand more about what people across the Azure organization do and how they do it. Every week we get together at 11 AM Pacific / 2 PM Eastern on [Microsoft LearnTV](https://cda.ms/226) and learn more about Azure.

![AzureFunBytes animation](https://res.cloudinary.com/practicaldev/image/fetch/s--Z7BxBMz1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j2xzw2g664tj31jij13t.gif)

This week I welcome [Christos Matskas](https://twitter.com/ChristosMatskas), Program Manager at Microsoft, to the show.  We have discussed Identity before, but we'll get a great look into [authentication, authorization](https://cda.ms/24G), and [Azure AD](https://cda.ms/24F).  Christos will help us understand how we can bridge the gap between our on-prem and Azure solutions for access management to ensure a great experience for developers.  We will chat about the importance of [multi-factor authentication](https://cda.ms/24K) and conditional access.  We will discuss implementation in [JavaScript](https://cda.ms/24H) and [.NET](https://cda.ms/24J) apps to ensure all you developers get the most out of this session.  Come join Christos and me so we can learn more about Microsoft Identity!

When: Thursday April 15, 2021 11 AM PT / 2 PM ET
Where: [Microsoft LearnTV](https://cda.ms/24Q)

Our Agenda:  
* What is Microsoft Identity?
* Why should devs not manage their own user databases!
* How to get started with Microsoft Identity.
* Types of Identity you can manage with Microsoft Identity
Demos.


{% youtube XzNrZgB4ynA %}

---

Join us at 11 AM Pacific / 2 PM Eastern for the latest episode! We'll get you the information you need to start building your global scale apps. We can be found every week on [Microsoft LearnTV](https://cda.ms/24Q)! Ask questions, take part in the conversation, and don't miss out!

Learn about Azure fundamentals with me! You can also find the recordings here as well:

[AzureFunBytes on Twitch](https://twitch.tv/azurefunbytes)
[AzureFunBytes on YouTube](https://aka.ms/jaygordononyoutube)
[Azure DevOps YouTube Channel](https://www.youtube.com/channel/UC-ikyViYMM69joIAv7dlMsA)
[Follow AzureFunBytes on Twitter](https://twitter.com/azurefunbytes)

Useful docs:

[Microsoft Learn: Introduction to Azure Fundamentals](https://cda.ms/22w) 
[Create a Free Azure Account!](https://cda.ms/233)
[Identity and access management (IAM)](https://cda.ms/24G) 
[Azure Active Directory](https://cda.ms/24F)
[How it works: Azure AD Multi-Factor Authentication](https://cda.ms/24K) 
[Azure AD Conditional Access documentation](https://cda.ms/24L) 
[Plan a Conditional Access deployment](https://cda.ms/24M) 
[Microsoft Learn: Azure Fundamentals](https://cda.ms/24N) 
[Microsoft Learn: Manage identity and access in Azure Active Directory](https://cda.ms/24P)
Kotlin ListView example | Android
Tags: kotlin, listview, android
Published: 2021-04-14 15:07:30

Kotlin ListView example | Android

https://grokonez.com/android/kotlin-listview-example-android

In this Kotlin tutorial, we're gonna look at way to show list of items with Android <code>ListView</code>.

Related Post: <a href="https://grokonez.com/android/kotlin-gridview-example-show-list-of-items-on-grid-android">Kotlin GridView example: Show List of Items on Grid | Android</a>

More Practice: <a href="https://grokonez.com/android/kotlin-sqlite-example-crud-operations-with-listview-android">Kotlin SQLite example – CRUD operations with ListView | Android</a>

<!--more-->
<h2>I. Technologies</h2>
- Android Studio 3
- Kotlin 1.1.51
<h2>II. Overview</h2>
<h3>1. Goal</h3>
We will build an Android App that uses <code>ListView</code> to show list of items:

<img src="https://grokonez.com/wp-content/uploads/2017/12/kotlin-listview-goal.png" alt="kotlin-listview-goal" width="285" height="526" class="alignnone size-full wp-image-9745" />
<h3>2. Android ListView</h3>
<h4>2.1 Input Types</h4>
Input (items) of a list can be arbitrary Kotlin object. We use an <code>adapter</code> to extract data from this Kotlin object, then assign object fields'value to the views in each row of <code>ListView</code>.

For example:
<pre><code class="language-java">
class Note {

    var id: Int? = null
    var title: String? = null
    var content: String? = null

    constructor(id: Int, title: String, content: String) {
        this.id = id
        this.title = title
        this.content = content
    }
}</code></pre>
Class for Kotlin object is called <strong>data model</strong>.

Kotlin ListView example | Android

https://grokonez.com/android/kotlin-listview-example-android
How to use angular library locally with Hot Module Reload
Tags: angular, typescript
Published: 2021-04-14 15:04:52

We can create angular library for reusability and there are many different ways to use it in your angular application.

One of them is is to use **"npm link"** command to link your library and application. However there are some drawbacks in that approach.

The biggest one is if you make any changes in your library you need to build your library again and again we is very not a very productive way. In this article I will explain how to use --watch command with ng build to overcome that drawback.

### Steps to create angular library

* Use below Angular CLI commands to generate Angular library project.
```
ng new ngx-shared-lib --create-application=false
cd my-workspace
ng generate library ngx-shared-lib
```

* Navigate to library workspace and use below commands to build library project.

```
ng build --watch
```

We are building the library project in "watch" mode so that any code changes will reflect in target application instantly.

* Use below Angular CLI commands to generate Angular Application.
```
ng new ngx-sample-app
```

* Navigate to angular application created above and install the library using below commands.
```
npm install file://C://angular-local-lib-example//ngx-shared-lib//dist//ngx-shared-lib"
```

Replace library path with physical path of your local system where library is created.

* Run below commands to serve your application.
```
ng serve
```

That's all...

Now **make any code changes in your library and save it.**
It will automatically reflect in your target application as we have run the library in "watch" mode.

You can find the sample code base in this github repository.
{% github https://github.com/patelvimal/angular-local-library-example no-readme %}
Development process
Tags: beginners, devjournal, womenintech
Published: 2021-04-14 14:59:12

Last week we had a number of different discussions about the development process.

One of the discussions was about the work-slots feature.
The work-slots feature allows businesses to alert workers with specific availabilities about the upcoming shifts. As we only have eight weeks left that need to include QA and user feedback, we decided to reduce our App's MVP. We decided to remove the worker slots feature because implementing this feature is far more complex for the time we have.

Another topic we discussed was styling. We will be using SASS and bootstrap. I am very excited to take advantage of SASS to keep the code readable. 

During our discussion, I discovered that there will be a collaboration between Arit and Chris Oliver for testing the App. They promised to put together a guide on using the MiniTest library. I can't wait to see the results.

Once again, we promised to keep our PRs small. Everybody likes small PRs, and it's more efficient and easier to review.

A note about devise gem: as we went further working on different features of the App, we realized (with a help of senior developers) that the devise is too complex to modify to the needs of our App. 

I think these moments are best for learning. You understand how quickly things get complex in a considerably small application. Discussing and researching is a big part of development.

Hooray! I kept it short this time! Thanks for reading! 


Photo by <a href="https://unsplash.com/@johnschno?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">John Schnobrich</a> on <a href="https://unsplash.com/s/photos/learning?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
JavaScript Interview Question #32: 0.1 + 0.1 + 0.1 === 0.3
Tags: beginners, javascript, webdev, codenewbie
Published: 2021-04-14 14:47:43

![js-test-32](https://learn.coderslang.com/js-test-32.png)

What will be logged to the console?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

At a first glance, the answer is `true` as `0.1 + 0.1 + 0.1` is obviously equal to `0.3` .

But that’s only before we get into the details of how the numbers are represented in JavaScript.

If you try to execute the statement `console.log(0.1 + 0.2)` in JS, you’ll get a number `0.30000000000000004`.

This happens because in JavaScript and quite a few other programming languages some decimal numbers can't be represented exactly as they are.

For example `0.1` in binary will result in an endless fraction, the same way as `1/3` becomes `0.333(3)` in the decimal number system.

---

**ANSWER**: `false` will be logged to the console.

[Learn Full-Stack JavaScript](https://js.coderslang.com/sign-in)
Quick VS Code tip: Automatically add image width and height to images
Tags: vscode, images, performance
Published: 2021-04-14 14:32:50

---
title: Quick VS Code tip: Automatically add image width and height to images
published: true
description: 
tags: vscode, images, performance
canonical_url: https://christianheilmann.com/2021/04/14/quick-vs-code-tip-automatically-add-image-width-and-height-to-images/
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u2h2ydslq0sck47jfzqh.png
---

One thing that keeps amazing me about [Visual Studio Code](https://code.visualstudio.com) is how much it helps you automate annoying tasks when you write code. For example, if you add an img tag to the document you need to know the src and find out the width and height to avoid reflow issues when the image was loaded. You also need to add an alt attribute either to provide an alternative text or to prevent assistive technology to read out the src attribute instead.

You can do this by following these steps: 

* Start the img tag 
* As soon as you write `src="` VS Code gives you an autocomplete for local images. 
* Close the `img` tag (this is important)
* Use the Command Palette (`CMD + Shift + P` on `Mac or Ctrl + Shift + P` on Linux / Windows) and type "size" to trigger the [Emmet](https://www.emmet.io/) size script that automatically adds width and height. 

You can see it in this screencast:

![emmet-image-size](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/anchuap6bmr6ygq4wq9b.gif)

My setup also warns me when I have images without any alt attribute. It puts a wavy line under any element with a problem like the img tag and shows the error right next to it. I am using two extensions for this: [webhint for VS Code](https://aka.ms/webhint4code) and [Error Lens](https://marketplace.visualstudio.com/items?itemName=PhilHindle.errorlens).