teleren/devto huggingface dataset:
Why deep clone when we have stringify.
Tags: javascript, immutability, react, webdev
Published: 2021-06-06 15:34:00

Since this is my first post I just have to open it with “Don’t judge book by it’s cover”, just hear me out.

## Problem

I have to be honest, deepcloning objects can be really messy. Sure, it is easier with some packages like loadesh, but when you do that “by the hand”, it’s hard to track what you did or didn’t copy, especially when big complex objects are in play.

Oh sorry, I forgot to explain why we have to clone objects in order to update them, and I can do that in just one word: immutability. Huh, okey, that was easy :) I’m kidding. Since I don’t know my audience yet, I will try to be as clear as blue sky, so let’s get more technical.

## Immutability

Immutability is very important part of every react application. Component in react app is rendered based on props and state. When props or state changes (by this I mean when reference to the object is changed), components rerenders. It’s that simple.

When working with complex object which contain 3 or more levels of objects for e.g, and you want to change some property on third level, you need to copy that object where property lives, it’s parent, then parent’s parent. And that’s it, I think…? You see my point. Let’s say we have done that right, now we have an old unchanged object and a new copied object with just one property changed. Now, state can be updated and component rerenders! Hooray!

All that insecurity and potential bugs where your component didn’t update can be a result of badly managed immutability.

I hope I didn’t make you angry by this time but let’s get to the point.

## Solution for all your problems

```javascript
const user = {
    firstName: “Branko”,
    lastName: “Stančević”,
    location: {
        city: “Novi Sad”,
        country: “Serbia”
    }
}

const newUser = user;
```

Okay, now user and newUser have reference to the same object. If you try to do something like: `user === newUser` you will get true, as expected.

To avoid all spreading and loadash deepcloning functionalities to make new copy of the object, we can simply do this:

```javascript
const newUser = JSON.parse(JSON.stringify(user));
```

`user === newUser` is no longer true, both of the constants have their own reference to the completly same data but different object. Even children objects don’t have same reference, hence you may do with that object whatever you want without worrying about immutability.

Simply pinpoint property in child object, change it and your job is done.

```javascript
newUser.location.city = “Belgrade”;
```

Then with that updated object update your state or do whatever you want. :)

## Conclusion

This idea can be explored furthermore, test performance against familiar processes of deepcloning is just one of the  many roads that we can take together.

I’m frankly happy to hear out your thoughts on this topic good people.

Thank you for your time. I hope you have enjoyed reading this post :)
Win Cool Swags and Mac Book Pro
Published: 2021-06-06 15:06:25


Do you think #JavaScript is overrated? What's the most useful #programminglanguage 
for you? Take the new #DeveloperNation survey and let other developers 
know! You could win #SamsungGalaxy S20 Plus, #GamingLaptop, #JetBrains 
All Products License, #GitKraken Pro license, #Amazon vouchers and more!

https://developereconomics.net/?member_id=KgN1BPYe&lang=en&locale=en
Go time Sleep with cancellable with Context
Tags: go
Published: 2021-06-06 15:06:11

ฟังก์ชัน time.Sleep ใน Go เราใช้เพื่อหน่วงเวลาให้ goroutine ที่ฟังก์ชันนี้รันหยุดทำงานไปเป็นจำนวนเวลาเท่าที่เราใส่ให้ฟังก์ชันตอนเรียกใช้งาน

แต่ถ้าเกิดเราต้องการให้ time.Sleep นั้นถูกยกเลิกการ Sleep ก่อนเวลาที่เราส่งให้มัน เราต้องสร้าง Sleep ฟังก์ชันขึ้นมาเองแบบที่ยกเลิกได้ 

สิ่งที่ช่วยได้ก็คือ type Timer ซึ่งเรากำหนดค่า duration ให้กับมันแล้วมันก็จะส่ง signal ออกมาที่ channel `C` ซึ่งเป็น field นึงของ type Timer นั่นเอง

ดังนั้น ถ้าเวลาผ่านไปยังไม่ถึง duration ที่กำหนด แล้วเราไปพยายามเอาค่าออกมาจาก `C` มันก็จะหยุดเหมือน time.Sleep นั่นเอง

โค้ดแบบนี้ ทำหน้าที่เหมือน time.Sleep

```go
func mySleep(d time.Duration) {
        timer := time.NewTimer(d)
        <-timer.C
}
```

สิ่งที่ Timer มีมากกว่า Sleep คือมันมี method `Stop` ให้ยกเลิก Timer ก่อนเวลาที่กำหนดได้

ต่อไปเราจะทำให้ฟังก์ชัน SleepContext ของเรานั้นรับ context.Context เข้ามาด้วย เพื่อใช้เป็น signal ว่าเมื่อ context นั้นทำงานเสร็จ หรือยกเลิกแล้ว นั้นเราก็จะเรียก timer.Stop ด้วยนั่นเอง

โค้ดของ SleepContext ที่จะ Sleep และยกเลิกถ้า ctx นั้นถูกยกเลิกหรือ Done เรียบร้อยแล้ว

```go
func SleepContext(ctx context.Context, d time.Duration) {
        timer := time.NewTimer(d)
        select {
        case <-ctx.Done():
                timer.Stop()
        case <- timer.C:
        }
}
```

เราใช้ select statment เพื่อรอรับค่าจากทั้ง ctx.Done() หรือ timer.C อะไรมีค่ามาก่อนก็จบการทำงานของฟังก์ชัน แต่ถ้า ctx.Done() ก่อนก็ไม่ลืมที่จะยกเลิก timer ไปด้วย เพื่อไม่ให้มันยังทำงานทำให้เกิด memory leak อยู่จนกว่าจะหมดเวลา

## ขอฝาก Buy Me a Coffee
สำหรับท่านใดที่อ่านแล้วชอบโพสต์ต่างๆของผมที่นี่ ต้องการสนับสนุนค่ากาแฟเล็กๆน้อยๆ สามารถสนับสนุนผมได้ผ่านทาง Buy Me a Coffee คลิ๊กที่รูปด้านล่างนี้ได้เลยครับ

<a href="https://www.buymeacoffee.com/weerasak" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
Passing props to component in react.
Tags: react, tutorial, webdev, beginners
Published: 2021-06-06 14:32:09

In the below code, inside *MyComponent* I'm rendering *Home* component and also passing props *count* to it.

And then one can use *count* of *MyComponent* in *Home* component.
Home component is independent of *MyComponent*, any component can pass props to Home component.

```javascript
import React, { useState } from "react";
export default function MyComponent() {
  const[count, setCount] = useState(0);
 
  return (
    <div>
      <Home count = {count}/> //passing props
    </div>
  );
}
```
The below code snippet is using the passed props, one can either destructure the object or accept the single props object.

```javascript

import React from "react";
export default function Home({count}) {
  
  return (
    <div>
    {count}
    </div>
      );
}

```
**or**
```javascript

import React from "react";
export default function Home(props) {
  
  return (
    <div>
    {props.count}
    </div>
      );
}

```
The *Home* component will only display 0 on-screen since I'm not updating the value of count.
Developers do silly mistakes...
Tags: webdev, watercooler, react, javascript
Published: 2021-06-06 14:30:58

## Hello Developers 👋
Yes, We do silly mistakes, I don't know of all of you but with almost 2 years of experience in web development, I can say I make a lot of silly mistakes all the time 🤪.

### Mistakes I have done that make no sense!

I was working with **nextjs** and while writing API I forget to pass **req** and **res** parameter in the **handler** function and when I run my website it was showing **internal server error 500**, and I was going through my code, checking spellings, reading articles, and all the thing to debug but after 30 mins or more I found out req and res was missing from the parameters of the handler.

This is only one of many mistakes we(I) do all the time.
It's funny and annoying at the same time.

**What do you think about why we do these silly mistakes.**

In my defense, I say, *"Our mind continuously processes much logic and sometimes forgets about the little details."*

But hey, after all, we are humans we learn from mistakes.

and from now on whenever I get an internal error message first thing I do is (you guessed it right ) check the parameters.

and at last, I quote *"Only a fool learns from his own mistakes. The wise man learns from the mistakes of others"*
    -Otto von Bismarck

I would love to listen to your mistakes in the comments

Thanks for reading.
#EnjoyLearning.
#HappyCoding.

Closing here 👋👋👋
> This is **Shareef**.
> [GitHub](https://github.com/shareef99)
> My [Portfolio](https://portfolio.shareef.vercel.app/)
> Twitter [ShareefBhai99](https://twitter.com/shareefBhai99)
> [Linkedin](https://www.linkedin.com/in/nadeem-shareef-7a8394182/)

--------------------------------------

> Cover photo by [Jared Rice](https://unsplash.com/@jareddrice?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/funny?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
Adding Alexa script in NUXT SSR.
Tags: vue, nuxt, webdev, javascript
Published: 2021-06-06 14:23:55

Adding static scripts for various reasons in nuxt server side applications sometimes is not easy because there no html files here. So what to do then?
I had faced this problem while adding alexa certified scripts and google ad manager scripts to my project. As I didn't find any module to integrate Amazon Alexa to nuxt project. So I have found these two options.

## 1. Adding script to nuxt.config.js
In the head section of the config file you can easily add scripts. But some static scripts might cause problems for that you have add to this to head **__dangerouslyDisableSanitizers: ['script']**  so that nuxt doesn't sanitize your scripts.
```js
export default {
  // Global page headers (https://go.nuxtjs.dev/config-head)
  head: {
    __dangerouslyDisableSanitizers: ['script'],
    titleTemplate: (title) => {
      return title ? `${title} - News` : 'News'
    },
    title: '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ],
    script: [
      {
        src: 'https://securepubads.g.doubleclick.net/tag/js/gpt.js',
        async: true
      },
      {
        type: 'text/javascript',
        hid: 'alexa',
        innerHTML: `
        _atrk_opts = { atrk_acct: "hXXXXXXXXX", domain: "XXXXXXX.com", dynamic: true };
        (function() { var as = document.createElement('script'); as.type = 'text/javascript'; as.async = true; as.src = "https://certify-js.alexametrics.com/atrk.js"; var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(as, s); })();
        `
      }
   ]
 }
}
```
You can also add scripts on specific pages or components by adding scripts in this way to the head section of the vue file.

 
## 2. Adding script to app.html
In nuxt.js you can create a app.html file inside which is an actual HTML frame of nuxt document and add scripts to it. You can see detailed documentation from this link: https://nuxtjs.org/docs/2.x/concepts/views#app-template

```html
<!DOCTYPE html>
<html {{ HTML_ATTRS }}>
  <head>
    {{ HEAD }}
  </head>
  <body {{ BODY_ATTRS }}>
    {{ APP }}
  </body>
  <script type="text/javascript" src="https://securepubads.g.doubleclick.net/tag/js/gpt.js" async></script>
</html>
```
I am using the nuxt 2.14.6 version for this project.

These are the ways I have tried. If you find more efficient solution please do share here. Thank you and happy coding.
Issues are not tasks
Tags: productivity, mentalhealth
Published: 2021-06-06 14:23:09

JIRA tickets, GitHub issues, Trello cards, Excel todo lists. Our in-brain memories are not enough to plan and track all the tasks in our software projects; we (programmers, testers, product owners, project managers, ...) collectively decided that we need external tools.

And our tools became so good in collecting ideas that every team on Earth now generates more ideas than they can ever hope to complete. For many of us, we learned to accept this fact of life as an inevitable emergent property in the "machine" for producing complex software (*whether or not we hate all of those estimation and prioritization meetings from the core of our souls*).

Yet, for many people (especially for programmers motivated by the purpose of a project), ever-growing backlogs are a big source of anxiety and burnout. And the truth is, the more "open" issues there are, the harder it is to organize them. Backlog cleaning sessions and automated tools to close inactive issues are ever more popular.

However, issues are not tasks. They are a mental tool, to help with our memory and to help with our communication. If we treat them as such, we will have a somewhat easier time deciding how to organize our issue tracking tools:

* if we split "ideas" from "confirmed issues" to another tracking system, will it improve or hinder our memories?
* if we weave our "vision", "goals", "stories", "bugs", and "sub-task" into a big hierarchy of artifacts, will it help or slow down our communication?
* if we close a bunch of tickets or just lower the priority, will it make a bigger mess of duplicates or keep us better organized?
* what should be the title and metadata, what do we need to remember for search, what should pop up from search results, and do we need some reports?
* given that we [cannot document everything](https://medium.com/@peter.hozak/assumptions-treacherously-precious-2abe4b2b8f14), what to put into description or comments; what is ephemeral enough for a chat or a coffee break?

The answers will be different in every team, so we can reasonable expect that the tracking tools will be either configurable or niche.

So, if you feel weighted down by your issue tracking system, remember for your next retrospective:

> Issues are a tool for our memory and communication. How can we configure them better?

---

👋 *I am Peter, a.k.a. [Aprillion](https://github.com/Aprillion/). My strong opinions are held weakly, discussion is open here in the comments or on [Twitter](https://twitter.com/aprillion0042).*
How unit tests help you onboard existing project
Tags: react, testing
Published: 2021-06-06 14:14:50

There Is always a time when you will join a project that was built a while ago, especially if you just join a new company or new organisation.

Besides documents, training ... I would suggest starting to write unit tests is one of my favourite approaches.

Benefits to write unit tests on existing source code:
- Good understanding of the components is based on how the project is built which builds up your confidence.
- Understand state management, data flow which you need to pass correctly by mocking the store when you do unit tests for pages, screens.
- Understand and learn the coding style and from your team members
- It might be one of your KPI for first month which it is good start to help improve code quantity

Especially writing unit tests when you join a big organisation with huge code on many layers, which nowadays design systems, composition components are becoming popular, you will realise that most of the time we are over-engineering and unnecessary layers.

Gook luck :)
3D birthday card
Tags: codepen
Published: 2021-06-06 14:07:15

<p>A Little birthday card I hacked together in an afternoon for my sister's birthday. Uses 3D transforms and such, and a bit of shitty JS for opening and closing the card.</p>

<p>Forked from <a href="http://codepen.io/michd/">Michael Duerinckx</a>'s Pen <a href="http://codepen.io/michd/pen/gxFmf/">3D birthday card</a>.</p>

{% codepen https://codepen.io/enrikd13/pen/WxgQAG %}
Amazing Clear Input Using HTML & JS
Tags: html, css, webdev, javascript
Published: 2021-06-06 13:55:10

Hello

Today I created a Amazing Clear Input with HTML & JS. This is simple placeholder input I use JavaScript to clear input you can be also add a wipe animation to make more professional clear input. I hope you like this also comments about your thoughts.

For more content follow me on Instagram  [@developer_nikhil27](https://www.instagram.com/developer_nikhil27/).

Thank you!

{% codepen https://codepen.io/NikhilBobade/pen/OJpZaeW %}
JVM Testing Newsletter | May 2021
Tags: java, kotlin, testing, newsletter
Published: 2021-06-06 13:47:45

> What's new in JVM testing? Check May 2021 issue.

## Articles & blogposts

### Unit Testing Delays, Errors & Retries with Kotlin Flows
Unit testing asynchronous code is not easy – in this blogpost Mohit Sarveiya gives us tips on how to write unit tests for for Kotlin Flow delays, errors and retries.

https://codingwithmohit.com/coroutines/unit-testing-delays-errors-retries-with-kotlin-flows/

### Understanding Unit Tests for Android in 2021
Christopher Elias explains how to create unit tests for Android projects – in such way that no Android framework dependencies are used directly.

https://proandroiddev.com/understanding-unit-tests-for-android-in-2021-71984f370240

### How to mock under instrumentation test with MockK and Dexopener
Tim Rijckaert tells us story how his team managed to improve stability of instrumentation tests in Android app with MockK and Dexopener

https://proandroiddev.com/how-we-made-our-ui-tests-more-stable-with-mockk-and-dexopener-c78b02a86de

### Contract-First Development Using RestAssured and OpenAPI
Bence Eros explains how to write integration test for Spring Boot application with OpenAPI specifications and REST-assured framework

https://hazelcast.com/blog/contract-first-development-using-restassured-and-openapi/


## Libraries & releases
- [JUnit 5.7.2 released with bug fixes](https://junit.org/junit5/docs/current/release-notes/index.html#release-notes-5.7.2)
- [Kotest v4.6.0 released](https://kotest.io/docs/changelog.html#460-may-2021)
- [assertk 0.24 released](https://github.com/willowtreeapps/assertk/releases/tag/v0.24)
All about Python Dictionaries
Tags: programming, python, beginners
Published: 2021-06-06 13:28:48

#Python Program to understand dictionaries.
###1. Here I am creating a dictionary.
```
my_dict1 = {}	
```		
using {} for declaring an empty dictionary as dictionaries are declared using {}.
```
my_dict2 = dict()
```			
using dict() is also a way to declare an empty dictionary.

###2. In dictionary we use pairs of key:values.
```
my_dict1 = {'fruit' : 'apple', 'drink' : "pepsi"}
```
here we used fruit and drink as a key and apple and pepsi as their values resp.
we can't have two or more keys with same name.
```
my_dict2 = {'vegetable' : 'carrot', 'fruit' : my_dict1}	
```
here we are declaring a nested dictionary.

###3. We can add and update elements in dictionay using a no. of methods. Use [] for accesing a key or adding and updating.

```
my_dict2['fruit'] =  'orange' 
```
If we use a key which already exist then it updates the previous value.
```
my_dict2['snacks'] = 'chips', 'cookies'	
```
we are assigning a no. of values to a key and it get stored in the form of tuple(or we can cast it)
```
my_dict2.update({'snacks' : 'chips'}) 
```
here we are updating the existing key and if key doesn't exist then it will add new key.

###4. We can access a value inside dictionary using the key associated to it inside a [] and we can also use get method.
```
print(my_dict1['fruit'])
```	
If key is not present in dictionary then it will give error.
```
print(type(my_dict1.get('snacks')))
```	
the difference here is, in get(value, default='None') method will return none if key is not present in dictionary.
we can use two arguments in get(). It will return the second value if key is not present. 


###5. We can remove a key by using the del/clear/pop method.
```
del my_dict2["fruit"]	
```
here we are deleting a item from the dictionary
```
my_dict2.pop('vegetable')	
```
here we are using pop(key, default = 'None') method to remove a item from dictionary and return the value associated with key. If item not present in dictionary then it return the second argument.
```
my_dict2.popitem()	
```
this method will remove the last inserted item in the dictionary and return it as a tuple.
```
my_dict2.clear()	
```
this method will clear the dictionary.
```
del my_dict2	
```
this will delete the dictionary.

###6. Methods on Dictionaries.
```
keysl = my_dict1.keys()  
```   
it returns a list of keys.
```
values1 = my_dict1.values() 
```
it returns a list of values in dictionary.
```
items1 = my_dict1.items()   
```
it returns list of a given dictionary’s (key, value) tuple pair.
```
my_dict2=my_dict1.copy()    
```
it copies my_dict1 into my_dict2
```
my_dict3 = dict(my_dict1)   
```
this is also a way to copy a dictionary into another

below method returns a dictionary with the specified keys and the specified value(dictionary.fromkeys(keys,value))
```
my_dict2 = my_dict3.fromkeys('1', 'none') 
print(my_dict2)
```
```
dict_comb=my_dict1 | my_dict2   
```
here we are combinig two dictionary
```
dict_comb2={**my_dict1, **my_dict2} 
```
Using ** we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third.
When to use a getter vs a method in Dart
Tags: dart
Published: 2021-06-06 13:13:36

Dart provides the possibility to use [getters and setters](<https://dart.dev/guides/language/language-tour#getters-and-setters>), special methods that give **read** and **write** access to an object's properties.

You can use a getter to **hide** **write access** to a property:

```Dart
enum ProductType { normal, offer }

class Product {
  // The product id.
  final String id = "ABC1234";
  
  // This property cannot be modified directly from outside the object.
  ProductType _type;
  
  Product(this._type);
  
  // _type can be accessed read-only using this getter.
  ProductType get type => _type;
}
```

You can also use them to **calculate a certain value** that is **not****directly****stored** in your object:

```Dart
...
  
  // Get whether the type of the product is an offer.
  bool get isOffer => _type == ProductType.offer;
 }
```

You could also use a **method**, instead of a getter:

```Dart
...
  
  // Get whether the type of the product is an offer.
  bool isOffer() => _type == ProductType.offer;
 }
```

So, how do you know where to use a **getter** and where to use a **method**?

Personally, I avoid using a getter when the value **cannot be calculated in `O(1)`**. The reason is that a getter and a property look the same from the outside, from the point of view of the user of your object.

```Dart
final product = Product(ProductType.offer);

// Is this a getter or a property?
product.id;

// Is this a getter or a property?
product.isOffer;
```

So the fact that there is a calculation behind the getter might be **lost** for the **final user** of the object who might think that the getter is a property and will use it as a `O(1)` "function".
The Intersect - About the project
Tags: nextjs, go, gin, javascript
Published: 2021-06-06 12:46:49

### What is the intersect?
 From the famous series "Chuck", the Intersect is a government database of encoded information harvested from every intelligence agency in the United States. 
### How does it even work?
 The intersect is initially downloaded into chuck's brain by flashing a ton images. And then the subsequent uses of the intersect require him to flash again with the images related to that skill.
This fan wiki contains most of the knowledge you need i.e if you need it.
https://chuck-nbc.fandom.com/wiki/The_Intersect .

As I'm writing this, it sounds so weird for someone who isn't familiar with the show. I apologize (no i do not 🙃).

### So to make the intersect:
 - Scrape images from the internet 
 - Feed them into a REST API
 - Consume the REST API on the client with a... you guessed it - a JavaScript framework✨

### The stack i chose
 - [gin](https://github.com/gin-gonic/gin) (Golang) 
 - [Nextjs](https://nextjs.org/) (JavaScript)
 - REST API
 - Heroku for hosting

Alright then,
LESGOOOOO!
![drake.gif](https://media.giphy.com/media/S5yqNNTQlEZfqQ7InC/giphy.gif)