teleren/devto huggingface dataset:
Unit testing with react-testing-library
Tags: react, unittesting, reacttestinglibrary, testing
Published: 2021-04-13 11:57:30

<h4>This is a simple example but it will explain how the testing library works.</h4>
<br>

You can install react-testing-library by running
```
 npm i @testing-library/react
``` or you can just run
```
npx create-react-app
``` to create a new React project, and you will have the library already installed.

This is our Button component:
```
import React, { useState } from "react";

export default function Button(){
    const [clicked,isClicked]= useState(false);

    return(
        <>
        <button style={{background: clicked ? 'red' : 'green'}} onClick={e => isClicked(true)} data-testid="btn">
         {clicked ? 'Clicked' : 'Click'}
        </button>
        </>
    )
}
```
<p>Give the button a data-testid="btn", so we can access it later from the test file.</p>

<h5>Now the test file:</h5>
First we have to import render and fireEvent.
<p><strong>render</strong> -  to render into a container which is appended to document.body.</p>
<p><strong>fireEvent</strong>- fire a DOM event.</p>
<br>
<p>Then we import the component we want to render.</p>
```
import { render, fireEvent } from "@testing-library/react";
import Button from "./Button.js";
```

We use the beforeEach method to render components, elements, methods  or something else before each test. 

First we render the Button component, then we get the btn element by data-test-id.
```
let btn;
beforeEach(()=>{  //execute before each test
    const component = render(<Button />); // render Button component
    btn = component.queryByTestId('btn'); // get the btn element from Button 
});
```

<h4>Each test has two arguments, a description of the test and a function.</h4>

<strong>1.Test</strong><br> We are checking if the element btn exists.
```
test('Check if btn is rendering correctly',()=>{
   expect(btn).toBeTruthy(); //check if btn exists in the component
});
```
<strong>2.Test</strong><br> We are checking if the button is changing it's background color on click. First we check if button has 'background: green' on render, then we fire a click event , and expect the button to have 'background: red'; 
```
test("Check if btn is changing it's color from green to red on click",()=>{
    expect(btn).toHaveStyle('background: green'); // btn has the style of 'background:green'
    fireEvent.click(btn); // btn is clicked
    expect(btn).toHaveStyle('background: red'); //btn has the style of 'background:red'
 })
 
```

<strong>3. Test</strong>
We are checking if the text in button is changing on click. 
First we check if the button's text-content is 'Click', then we fire a click event, and we expect the text-content to be 'Clicked'.

```
test("Check if btn says Clicked after it's clicked",()=>{
    expect(btn.textContent).toBe('Click'); 
    fireEvent.click(btn); 
    expect(btn.textContent).toBe('Clicked'); 
 })
```

Then we run 
```
npm test
```
And if everything works fine, and all the test pass, we will see this:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hemv7hsmv3qdzlpulhko.png)
Top 4 online education trends, or will AI become the future of eLearning?
Tags: ai, onlinelearning, education
Published: 2021-04-13 11:56:23

Pushed by COVID-19, education has switched to the online mode. But it looks like online education is likely to stay with us even after the pandemic is over. More colleges and universities are switching to fully online degrees and iMBA’s as they are cheaper and more accessible.

And techs, and specifically AI, can take online learning a step further. For example, artificial intelligence solutions can be used for curriculum personalization or automated test grading. AI can make distance learning less stressful and more engaging. 

Learn more about benefits of artificial intelligence in online learning in this article https://itrexgroup.com/blog/online-education-trends-will-ai-become-future-of-elearning/
Add Custom Fonts in React Native 0.63 >= for android and iOS
Tags: reactnative, javascript, tutorial, mobile
Published: 2021-04-13 11:41:17

Adding Custom Fonts to React Native App is quite easy and only needs a few steps. I am writing down the steps I did to add custom fonts to my app.

**Download Google Font**
First, you need to download your desired fonts from [Google Fonts](https://fonts.google.com/).

**Add fonts to app folder**
Then create a fonts folder in your root App/assets folder and paste downloaded fonts files in it.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/895dra001ni051xdcs4q.png)

**Export fonts**
Now create a file named `react-native.config.js` at the root of your app and add the path of fonts folder like this

```
module.exports = {
  project: {
    ios: {},
    android: {},
  },
  assets: ['./App/assets/fonts'],
};
```

**Link assets to project**
After adding this, Now run “react-native link”. This will copy the font to the app. For android it will be copied to “android > app > src > main > assets > fonts” folder. For iOS the font name will be added to info.plist file in ios > your_app_name > Info.plist
```
npx react-native link
```

**Add resources to target**
Now at this point, your custom fonts will start working for the android app but you need to do one last step to make it work for iOS.

Go to the desired target of your app in Xcode, select the `Build Phases` tab, and add font files in the "Copy Bundle Resources" tab as shown below.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5o8wm8q8i85ne3rp1jit.png)

Xcode step is done for us at the linking step. Just have to remember to rebuild the app after.

Hope you were able to add custom fonts to your app.
Share state between React components using custom hooks and observables
Tags: webdev, react, tutorial, javascript
Published: 2021-04-13 11:34:35

React [custom hooks](https://reactjs.org/docs/hooks-custom.html) are a powerful feature that provide a handy way to organize and reuse logic in a simple functional manner. And mixing them with [observables](https://en.wikipedia.org/wiki/Observer_pattern) allows us to solve one of the most common problems in a Single Page Apps - state management.

Firstly we need to create some basic observable implementation:

```javascript
function makeObservable(target) {
  let listeners = []; // initial listeners can be passed an an argument aswell
  let value = target;

  function get() {
    return value;
  }

  function set(newValue) {
    if (value === newValue) return;
    value = newValue;
    listeners.forEach((l) => l(value));
  }

  function subscribe(listenerFunc) {
    listeners.push(listenerFunc);
    return () => unsubscribe(listenerFunc); // will be used inside React.useEffect
  }

  function unsubscribe(listenerFunc) {
    listeners = listeners.filter((l) => l !== listenerFunc);
  }

  return {
    get,
    set,
    subscribe,
  };
}
```

And then create a store and hook it to React by using subscribe in useEffect:

```javascript
const userStore = makeObservable({ name: "user", count: 0 });

const useUser = () => {
  const [user, setUser] = React.useState(userStore.get());

  React.useEffect(() => {
    return userStore.subscribe(setUser);
  }, []);

  const actions = React.useMemo(() => {
    return {
      setName: (name) => userStore.set({ ...user, name }),
      incrementCount: () => userStore.set({ ...user, count: user.count + 1 }),
      decrementCount: () => userStore.set({ ...user, count: user.count - 1 }),
    }
  }, [user])

  return {
    state: user,
    actions
  }
}
```

And that is it! You can now use `useUser` hook in any of your components, trigger related actions and be sure that `state` is always up to date. No need for `React.Context`, lifting state up or using external state management tool.

Let me know what you think and thanks for reading.
Django Translation tutorial with an example
Tags: django, python, tutorial
Published: 2021-04-13 11:26:19

We noticed there are some unanswered questions on Django internationalization (i18n) topic. So we created a working example with Django Translation usage.

## Example explains
- Django Translation setup
- i18n inside python code
- i18n inside Django templates
- i18n inside Javascript code
- How to easily manage translations

## Github repo 
https://github.com/localizely/django_i18n_example

## Full article on Django internationalization
https://localizely.com/blog/django-i18n-tutorial/
Turning AWS Log Insights into metrics
Tags: aws, devops, metrics, python
Published: 2021-04-13 11:25:24

---
title: Turning AWS Log Insights into metrics
published: true
description: How one of POP's developers turned Log Insight queries into time-based metrics using Lambdas
tags: aws, devops, metrics, python
---

[Leo Giordani](https://www.thedigitalcatonline.com/pages/about.html) one of POP's developers has written up a [detailed blog](https://www.thedigitalcatonline.com/blog/2021/03/22/aws-log-insights-as-cloudwatch-metrics-with-python-and-terraform/) on his recent work creating a Cloudwatch metrics dashboard. The dashboard helps visualise our application's use of [Celery](https://docs.celeryproject.org/en/stable/index.html) tasks and to provide alerts where problems in the system occur such as tasks backing up as demand spikes.

Leo's post pretty much steps through the entire process involved including setting up a DynamoDB table in [Terraform](https://www.terraform.io/) and creating the Python Lambda to does the work of converting the queries into time-series metrics.

This is a new technique for us and we're looking at how we might use this idea of polling, transforming and writing CloudWatch information more in the future.
Angular 11.2^ + Tailwind + NX - Build slow and freezing when purge enabled
Published: 2021-04-13 11:22:56

---
title: Angular 11.2^ + Tailwind + NX - Build slow and freezing when purge enabled
published: true
description: 
tags: 
//cover_image: https://direct_url_to_image.jpg
---

If you have multiple applications in an NX Workspace and you are using TaiwindCSS you might have slow builds or build will be stuck when purge is enabled.

Since Angular 11.2, Tailwindcss now work out of the box. but purging is still not smooth at-list for me, maybe this might be NX Workspace problem. It took me hours to fix this.

Here is a possible fix.

I will start with `tailwind.config.js`

    // tailwind.config.js
    module.exports = {
      purge: [],
      darkMode: false, // or 'media' or 'class'
      theme: {
        extend: {},
      },
      variants: {},
      plugins: [],
    }

Now to purge you need to enable it and tell tailwind where to purge. 

    module.exports = {
      purge: {
        enabled: process.env.NODE_ENV === 'production',
        content: [
          `./apps/${process.env.APP_NAME}/src/**/*.html`,
          './libs/**/*.html',
        ],
      },
      mode: 'aot',
      darkMode: false, // or 'media' or 'class'
      theme: {
            extend: {},
          },
          variants: {},
          plugins: [],
      },
    };

The magic is those two environment variables `NODE_ENV` and `APP_NAME`.
`APP_NAME` is to make sure your build only purge the project you currently building and `NODE_ENV` will enable purge.

And now to finish everything, you need to add those variables in your `package.json` build script. In my workspace I have an Admin app and Store app.

    // package.json
    {
      "name": "myawesome-app",
      "version": "0.2.25",
      "license": "MIT",
      "main": "dist/apps/functions/main.js",
      "scripts": {
        "ng": "nx",
        "nx": "nx",
        "start": "ng serve --project store",
        "start:admin": "ng serve --project admin",
        "build:store": "NODE_ENV=production APP_NAME=store ng build --prod --project store",
        "build:admin": "NODE_ENV=production APP_NAME=admin ng build --prod --project admin",
      }
    ...

That's how I managed to purge Tailwind in my project, I am not sure if this is the correct way, but It's working and builds are very fast.
Kotlin Map collection with flatMap(), flatMapTo() methods
Tags: kotlin, map, flatmap, flatmapto
Published: 2021-04-13 11:17:21

Kotlin Map collection with flatMap(), flatMapTo() methods

https://grokonez.com/kotlin/kotlin-map-collection-flatmap-flatmapto-methods

In the tutorial, <a href="https://grokonez.com">JavaSampleApproach</a> will show you how to work with Kotlin Map <code>flatMap()</code> and <code>flatMapTo()</code> methods.

<!--more-->
<h2>I. Kotlin Map collection with flatMap(), flatMapTo()</h2>
<h3>1. with flatMap() method</h3>
We use <code>flatMap()</code> to create a single list of all entries from results of [<strong>transform</strong>] function being invoked on each entry of original map.

Method signature:

<pre><code class="language-java">
public inline fun <K, V, R> Map<out K, V>.flatMap(transform: (Map.Entry<K, V>) -> Iterable<R>): List<R>
</code></pre>

Practice:

<pre><code class="language-java">
val customerMap = mapOf(Pair(Customer("Jack", 25), Address("NANTERRE CT", "77471")),
						Pair(Customer("Mary", 37), Address("W NORMA ST", "77009")),
						Pair(Customer("Peter", 18), Address("S NUGENT AVE", "77571")),
						Pair(Customer("Amos", 23), Address("E NAVAHO TRL", "77449")),
						Pair(Customer("Craig", 45), Address("AVE N", "77587")))

val customerList = customerMap.flatMap { (customer, _) -> listOf(customer) }
customerList.forEach{ println(it) }
/*
	Customer(name=Jack, age=25)
	Customer(name=Mary, age=37)
	Customer(name=Peter, age=18)
	Customer(name=Amos, age=23)
	Customer(name=Craig, age=45)
*/

val addressList = customerMap.flatMap { (_, address) -> listOf(address) }
addressList.forEach{ println(it) }
/*
	Address(street=NANTERRE CT, postcode=77471)
	Address(street=W NORMA ST, postcode=77009)
	Address(street=S NUGENT AVE, postcode=77571)
	Address(street=E NAVAHO TRL, postcode=77449)
	Address(street=AVE N, postcode=77587)
*/

val customerInfos = customerMap.flatMap { (customer, address) -> listOf("${customer.name} lives at ${address.street}") }
customerInfos.forEach{ println(it) }
/*
	Jack lives at NANTERRE CT
	Mary lives at W NORMA ST
	Peter lives at S NUGENT AVE
	Amos lives at E NAVAHO TRL
	Craig lives at AVE N
*/</code></pre>

More at:

Kotlin Map collection with flatMap(), flatMapTo() methods

https://grokonez.com/kotlin/kotlin-map-collection-flatmap-flatmapto-methods
Kotlin - How to convert Object to/from JSON by Gson with Kotlin language
Tags: kotlin, json, gson
Published: 2021-04-13 11:00:43

Kotlin - How to convert Object to/from JSON by Gson with Kotlin language

https://grokonez.com/kotlin/kotlin-convert-object-tofrom-json-gson-kotlin-language

This tutorial shows you how to use Gson to convert Kotlin object to/from JSON.

<!--more-->
<h2>I. Technology</h2>
- Java 1.8
- Kotlin 1.1.2
- Maven 3.5.1
<h2>II. Overview</h2>
<h3>1. Goal</h3>
- Convert <strong>JSON string</strong>/<strong>JSON file</strong> to <code>Person(name:String,age:Int,messages:List)</code> Kotlin <strong>Object</strong>/<strong>List</strong>/<strong>Map</strong>
- Convert <code>Person</code> <strong>Object</strong>/<strong>List</strong>/<strong>Map</strong> to <strong>JSON string</strong>.
<h3>2. Steps to do</h3>
- add Dependency:
<pre><code class="language-html">&lt;dependency&gt;
	&lt;groupId&gt;org.jetbrains.kotlin&lt;/groupId&gt;
	&lt;artifactId&gt;kotlin-stdlib&lt;/artifactId&gt;
	&lt;version&gt;1.1.2&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
	&lt;groupId&gt;com.google.code.gson&lt;/groupId&gt;
	&lt;artifactId&gt;gson&lt;/artifactId&gt;
	&lt;version&gt;2.8.0&lt;/version&gt;
&lt;/dependency&gt;</code></pre>
- import:
<pre><code class="language-java">
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
</code></pre>

More at:

https://grokonez.com/kotlin/kotlin-convert-object-tofrom-json-gson-kotlin-language
Kotlin + SpringBoot JPA + MySQL- Save/retrieve Files/Images with @Lob annotation

Tags: kotlin, springboot, springjpa, mysql
Published: 2021-04-13 10:16:34

https://grokonez.com/spring-framework/spring-boot/kotlin-spring-boot/kotlin-springboot-jpa-mysql-saveretrieve-filesimages-lob-annotation

Kotlin + SpringBoot JPA + MySQL- Save/retrieve Files/Images with @Lob annotation

In the tutorial, <a href="http"//grokonez.com">JavaSampleApproach</a> will show you how to create a SpringBoot Kotlin project that uses SpringJPA with <code>@Lob</code> annotation to save Files/Images to MySQL database.

<!--more-->
<h2>I. Technologies</h2>
– Kotlin 1.2.20
– Apache Maven 3.5.2
– Spring Tool Suite – Version 3.9.0.RELEASE
- MySQL 
– Spring Boot – 1.5.10.RELEASE
<h2>II. Goal</h2>
– We create a SpringBoot project to save files/images to MySQL database as below structure:

<img src="https://grokonez.com/wp-content/uploads/2018/02/Kotlin-Spring-JPA-save-Files-Images-to-MySQL-pre.png" alt="Kotlin Spring JPA save Files Images to MySQL - pre" width="436" height="328" class="alignnone size-full wp-image-10585" />

Create MySQL table:

<img src="https://grokonez.com/wp-content/uploads/2018/02/Kotlin-Spring-JPA-save-Files-Images-to-MySQL-create-mysql-table.png" alt="Kotlin Spring JPA save Files Images to MySQL - create mysql table" width="226" height="300" class="alignnone size-full wp-image-10586" />

-> Run and check results:

<img src="https://grokonez.com/wp-content/uploads/2018/02/Kotlin-Spring-JPA-save-Files-Images-to-MySQL-result.png" alt="Kotlin Spring JPA save Files Images to MySQL - result" width="566" height="226" class="alignnone size-full wp-image-10587" />

<img src="https://grokonez.com/wp-content/uploads/2018/02/Kotlin-Spring-JPA-save-Files-Images-to-MySQL-goal.png" alt="Kotlin Spring JPA save Files Images to MySQL - goal" width="412" height="364" class="alignnone size-full wp-image-10588" />
<h2>III. Practice</h2>
<strong>Step to do</strong>:
– Create SpringBoot Kotlin project
– Create data model
– Create JPA Repository
– Implement Client to save/retrieve files/images
– Configure JPA connection & MySQL script
<h3>1. Create SpringBoot Kotlin project</h3>
Using SpringToolSuite to create a SpringBoot project with dependencies:

More at:

https://grokonez.com/spring-framework/spring-boot/kotlin-spring-boot/kotlin-springboot-jpa-mysql-saveretrieve-filesimages-lob-annotation
Combining Backend with Frontend
Published: 2021-04-13 10:57:38

## Connecting Frontend with Backend

{% youtube U9JsoasSUAE %}

[GitHub Repo Tag](https://github.com/softwaredevacademy/spring-web-app-demo/releases/tag/frontend)

## CORS

{% youtube fGRFpCLadRo %}

#### Links
[Cross-Origin Resource Sharing (CORS) - MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)

<hr>
<p style="align: center;"> <span> <a href="https://dev.to/softwaredevacademy/application-structure-4c18">Previous article</a> | </span>
<span>Next article</span>
Java without semicolons
Tags: code, development, leadership, programming
Published: 2021-04-13 12:43:25

---
title: Java without semicolons
published: true
date: 2021-04-13 10:56:00 UTC
tags: code,development,leadership,programming
canonical_url: https://craignicol.wordpress.com/2021/04/13/java-without-semicolons/
cover_image: https://craignicol.files.wordpress.com/2021/04/wp-1617831687080.png?w=1024
series: mentor
---

When I was a tutor at university I remember one student who I only saw towards the end of the year. I think computer science was their additional course. They came in after apparently spending the best part of a year learning Java, and sat down to complete their assignment.

It didn’t take long before I was called over to help. Their code wouldn’t compile. A fairly standard console application, with some output. And no semicolons.

I was incredulous, and as a young eejit, I’m not sure how well I hid that. I couldn’t believe someone could have completed the lectures, read the books, and completed the previous 29 assignments without using semicolons.

How could they spend a year on a Java course and not learn anything?

Regrettably, I refused to help them and pointed them towards the obvious and clear error messages that they’d obviously been looking at before they called me over.

I wasn’t going to build it for them. I couldn’t teach them 1 year’s coding in 15 minutes.

And yet, they turned up. They asked for help instead of struggling on. Exactly the things I’d wish for in my new starts when I started leading teams and onboarding staff.

They knew the shape of the solution and they knew where their talents were. If I’d been a little more patient, I could have nudged them gently on. But I don’t know if that would have been enough.

If you are mentoring or leading developers, are you stepping in early enough? Are you praising effort and being vulnerable enough to ask for help? Can you see their strengths and weaknesses? Are you giving yourself enough time with them?

_Are you being the senior that you wish you’d had when you were a junior?_
How to give your dog a good basic health
Published: 2021-04-13 10:55:00

Provide excellent quality food

Why do veterinarians and nutritionists recommend the dog to eat a high quality diet? This is because good nutrition will help your dog live healthier and longer. A healthy diet helps protect against diseases like cancer, diabetes, obesity and many others.

Some people keep dogs on their own. Use information from your veterinarian in raw material selection It might take a little extra time. But it is worth the dog's health. Dogs will be fed a combination of real meat, fruit and vegetables with regular dog pellets. Will Make The Nutrients Full Cheap <a href="https://www.all4pets.in/products/pet-food/for-dogs/">dog food</a> often contains a number of supplements. Additionally, the ingredients have little nutritional value. And only make the dog feel full. You should read the labels before you buy and avoid poor quality food if possible.

Daily exercise

Even the lazy dog ​​lying on a chair all day needs exercise to stay in shape. And a daily walk is a must for all dogs. Active breeds like the Weierstrass require more exercise each day. Without adequate exercise your pet may be anxious, repressed and unhappy. The older the dog, the more it is recommended to walk the dog because it will be beneficial for both physical and mental health. Additionally, exercise can help fight the symptoms of arthritis. Canine dementia And many other serious diseases.

All you have: can dogs eat goldfish

Find fun and exotic activities to do together.

Like humans, dogs always need an intellectual challenge to perfect their brain. They can play a simple ball or a discus throw, but practice new tricks. Introduce them to dogs or others for a new brain training game like ringing a bell. Or steal things Or run and play in some new ways, the body will be perfect, both body and brain. Not only will it get happy. You will have fun with it.

Health check

Treat your dog like a family member. Find a good vet. And make sure your dog is getting the medication or vaccine on time. Make sure to get important vaccines such as the heart worm vaccine. You can also consult your veterinarian about using medicinal or natural ways to prevent fleas and ticks. Ask how to brush your teeth Brush and bathe following the advice of your veterinarian for the right instructions for your dog.

Be prepared at your expense

When you look into the eyes of your little furry friend you may have accidentally dreamed of one day running with him on the grass. But the fact that taking care of a pet can surprise many owners. And it is expected that the first year of adopting them will cost about 800 - 1000 USD (about 25000 to 30000 baht) Cost is one of the important factors for adopting puppies. Lost by Together only during the first year So ask yourself if you can afford them.