teleren/devto huggingface dataset:
Unit Testing Higher Order Components with Enzyme and Jest
Tags: jest, enzyme, unit, hoc
Published: 2019-06-11 22:17:20

Not all the components you write for your React application can be divided into Stateful and Stateless (dumb) categories. There is a 3rd advanced type of component in React called a higher-order component. A higher-order component is a function that takes a component as an argument and returns another component. Check out my other article to see how higher-order components are used in the real world.

## Creating a HOC with Tests

We’ll be using Enzyme and Jest, but these concepts apply to any testing library.

One of the common HOCs I write for every project of mine is called `withConditional`. Its purpose is to render a component if and only if the condition passes, otherwise just return null.

```jsx
import React from "react";
const withConditional = Component =>
  function withConditionalComponent({ condition, ...props }) {
    if (condition) {
      return <Component {...props} />;
    }
    return null;
  };
export default withConditional;

```

As you can see, when the condition passed to the HOC evaluates to true, it returns the component, otherwise, it returns `null`.

So how can you unit test the HOC? There are surprisingly minimal articles talking about unit testing these components, and I had a hard time figuring out the proper way. Recently the solution clicked!

## Solution

To properly test these badass components, you just need to know that they are simple functions and that’s all!

`withConditional` is used in the following manner:

```jsx
const ConditionalComponent = withConditional(MyComponent);
class HelloWorld extends React.Component {
  render() {
    return <ConditionalComponent condition={3 > 4} />;
  }
}
```

So, we should use the exact same concept to unit test them as well.

The important thing to take into account here is to test the component for all states. For instance, if our HOC can handle two different states, depending on the condition passed to it, then we MUST account for both states in the tests.

## When the condition passes:

```js
it("should render the component only when the condition passes", () => {
  const ConditionalComponent = withConditional(Component);
  const wrapper = shallow(<ConditionalComponent condition={true} />);
  expect(wrapper.html()).not.toBe(null);
});
```

## When the condition fails:

```jsx
it("should return null when the condition fails", () => {
  const ConditionalComponent = withConditional(Component);
  const wrapper = shallow(<ConditionalComponent condition={false} />);
  expect(wrapper.html()).toBe(null);
});
```

---

Have fun and test it up!
3 Ways to clone objects in Javascript
Tags: javascript, objects, clone
Published: 2019-06-11 22:12:04

Cloning an object is somewhat a task that is almost always used in any project from a simple one to the most complicated ones. As it may seem simple for not seasoned Javascript developers, it actually has some pitfalls that would hurt you in the bones if you didn’t know the proper way to do it.

## Talk is cheap, show me the code

The first way that could cross a developer’s mind is to deeply iterate through the source object’s properties and copy them one by one on the target object. As it may seem good at the beginning, it is not a performance friendly solution and a potential bottleneck when it comes to large and deep objects.

### 1: Shallow copy using iteration

``` js
function iterationCopy(src) {
  let target = {};
  for (let prop in src) {
    if (src.hasOwnProperty(prop)) {
      target[prop] = src[prop];
    }
  }
  return target;
}
const source = { a: 1, b: 2, c: 3 };
const target = iterationCopy(source);
console.log(target); // {a:1, b:2, c:3}
// Check if clones it and not changing it
source.a = "a";
console.log(source.a); // 'a'
console.log(target.a); // 1
```

So as you see, it’s working!

Now let’s cut the chase to the second solution which is indeed more elegant but, more limited to use.

### 2: Converting to JSON and back

```js
function jsonCopy(src) {
  return JSON.parse(JSON.stringify(src));
}
const source = { a: 1, b: 2, c: 3 };
const target = jsonCopy(source);
console.log(target); // {a:1, b:2, c:3}
// Check if clones it and not changing it
source.a = "a";
console.log(source.a); // 'a'
console.log(target.a); // 1
```

>Note: Be careful about using this method as your source object MUST be JSON safe. So it may need some sort of exception handling to keep it safe in cases in which the source object is not convertible to JSON.

### 3: Using `Object.assign`

>Update: This method has a flaw that it only does a shallow copy. It means that nested properties are still going to be copied by reference. Be careful about it.

This way is the best and the safest way I personally consume in my projects. It’s leveraging a built-in static method on the Object object and is handled and provided by the language. So use this one!

```js
function bestCopyEver(src) {
  return Object.assign({}, src);
}
const source = { a: 1, b: 2, c: 3 };
const target = bestCopyEver(source);
console.log(target); // {a:1, b:2, c:3}
// Check if clones it and not changing it
source.a = "a";
console.log(source.a); // 'a'
console.log(target.a); // 1
```


## Conclusion

You must know that every framework and including libraries such as Lodash and Underscore has a way to support cloning objects. Almost all of them used a more complex version of iterationCopy before ES6 was introduced. On ES6+ environments, there is language support for `Object.assign`, so try to use the most out of it. As a rule of thumb, always try to use the 3rd solution and avoid the JSON solution.

Keep calm and clone objects without any hesitation 😊
Decision making in PHP.(module 3)
Published: 2019-06-11 21:45:15

Like most programming languages, PHP is built with conditional statements for making decision based on different conditions.
   The if statements execute code if one condition is true. the syntax is 
if(condition){
code to be executed;
}
The if statement is suitable when there is only one condition to be tested.

 The if else if statements execute code if a condition is true and if false another code is executed. the syntax is 
if(condition){
code to be executed
} else{
    code to be executed;
}
It is suitable when there are only two conditions to be tested.
 The nested if is used when the condition to be tested is more than two. the syntax is
if (condition) {
    code to be executed if this condition is true;
} elseif (condition) {
    code to be executed if the first condition is false and this condition is true;
} else{
    code to be executed if all conditions are false;
}
The switch case conditional statement is used to perform different actions based on different conditions. The switch statement selects one of many blocks of code to be executed. the syntax is 
switch (a) {
    case label1:
        code to be executed if a=label1;
        break;
    case label2:
        code to be executed if a=label2;
        break;
    case label3:
        code to be executed if a=label3;
        break;
    default:
        code to be executed if a is different from all labels;
}
The first single expression (a) which is often a variable is evaluated once. then the value of the expression is then compared with the values for each case in the structure. If the value of the expression matches any one of the cases, the block of code associated with the code is executed. the break statement is used to prevent the code from running into the next case automatically. the code in the default statement is executed if there no match found.
 The jump statements are keywords which are used in moderating the conditional statements wether to break, continue or exit the running of code. The break statement is usually used in loop or switch statement. The code will stop working if the condition is true.
The continue statement skip the program execution and go to the next program. and the exit statement terminates the program's current execution flow.
Strategies for Contract/Studio Developers?
Tags: discuss, webdev, management
Published: 2019-06-11 20:56:22

At the time of this writing, I'm currently responsible for 15 client websites and web applications, 18+ internal sites and apps, and 8 OSS apps and libraries. I guess you would refer to my business as a development studio? Contract developer? As a part-time solo developer the management is getting tough.

One thing I'm specifically struggling with is how to handle technical debt and maintenance for client projects.

For the most part, these projects are complete and delivered. The client has paid me and I am providing the hosting service. Most of these are for small businesses, who paid me the price I charged and now have a website up and running. The problem is that I never addressed who covers the cost when a website needs maintenance. For example, I am spending this spring and summer upgrading every project from PHP 5 to 7. Enabling SSL by default, updating 3rd party plugins, etc. 

It occurs to me that I never told my customers that this type of maintenance would be inevitable. I've corrected this by offering all new/recent clients a support contract for a small monthly fee, or informing them that if they don't want a support contract I will bill them for maintenance as it happens to be necessary. So new projects going forward are not the problem. However most of my older clients are not technically savvy, they are small local businesses, and it's hard for them to understand that a website built 5+ years ago won't just work forever. I'm planning to do it for free this year, and inform them that this won't be the case going forward.

I have an internal wiki where I record details of each project, and a checklist of info and things to be done for each project.

I'm wondering if any of my fellow Dev.to readers have strategies or suggestions for managing a large portfolio of distinct and different projects. Do you deliver a project then wash your hands of it? Do you share my feeling of responsibility for keeping your clients' sites up and running? Other tips?

I'm starting to see the allure of managing just one big SAAS project!
Unity and bad (outdated) advice.
Tags: beginners, unity3d, discuss
Published: 2019-06-11 20:52:09

Just started taking programming serious. Thought I would make a game since it's something fun that I will enjoy and can see the outcome of my efforts. It's been a rough 3 months but I have a game. It's on the Android store and my friends and I enjoy playing it and comparing high scroes. Being new to programming and game development I spend a lot of time googling thing. From how to do something to how to fix something I broke. The problem I have is how many places you have to check to get the answer you want. And trying to figure out what is right and what is wrong. Take Unity monetization for example. Most content you find is for Advertisement. Which is a old way and not recommended anymore. I also noticed a lack of info on things like Google Play Games Services. Which is what I am stuck on now. One of the last things I want bubble danger to have is a leaderboard. What do you all do to figure out good from bad information and even a lack of information.
Mary Meeker's 2019 Internet Trends discussion thread
Tags: news, discuss
Published: 2019-06-11 20:35:36

---
title: Mary Meeker's 2019 Internet Trends discussion thread
published: true
description: Discussing Mary Meeker's 2019 Internet Trends report
tags: news, discuss
---
You can view the full report here: https://www.bondcap.com/report/itr19

This is one of the most highly-anticipated industry reports released each year.  This is a discussion thread where people can drop key takeaways and comments.
The Journey From Java to Python
Tags: java, python, career, beginners
Published: 2019-06-11 19:44:28

---
title: The Journey From Java to Python
published: true
description: The slow but very rewarding transition from Java to Python.
tags: #java #python #career #beginners
---

### Introduction

I'm definitely not one of these wizard kids that started programming at 13 and were a genius by the time they completed 20. I started programming at 18 years old and I started with Java. I was terrible at it, the first time I saw a `for loop` I thought it was magic.
I'm 25 now and have been programming since then, 3 years professionally and two of them coding in Java.

### Background and Java

I went to college get the title of BSC in Software Engineering, I thought all my colleagues were at the same level - level 0 - but boy was I wrong. Almost everyone there could program, I did not. That made me the underdog, and as such I had to learn and study harder than most people.
From 2011 to 2016 I've been studying Java, it's patterns, code styles, best practices and idiosyncrasies. I'm sure I barely scratched the surface of the language, but after some time I started to feel productive. That's when I landed my first job as a Software Engineer Jr, back in January 2017.
Fast forward to September of the same year. At that time I was into Machine Learning and had already developed a few ML algorithms in Java by hand, then I experimented developing a few of them in Python.

### Python with Love

At this point I already knew how to code and collaborate. Picking up a new language was not going to be as hard as it was the first time, but Python was so friendly and the community so active that I barely had any problems.
It took me another year to get a job as a full time Python developer, but today I'm way more productive in Python than I have ever been in Java. It feels fresh, clean and powerful.
It used to take me a day to go from a Factory to a full REST endpoint with Java, now it takes me a couple hours to model a basic CRUD application with Python and Flask.

### What I miss the most about Java

Python also has its weaknesses, after I transitioned what I miss the most is the static checked type system. That saved me a lot of trouble and ensured my code would work wherever I needed to use it. In python to remedy this, I use the type hints and doc strings. It is still not checked and still gives me run-time errors, but when your software is growing, it can save you a lot of time that you would spend reading and refactoring your old code.

### How could you transition to another language?

I started reading and experimenting, published a few articles on Medium in Portuguese (my native language), started tweeting about it and got some contacts. I suggest you follow the same path, study, write about it, tell people about your experiences and teach. 
I started programming fairly late considering my peers, If I did it, you can do it too.

---
Did you change paths in your career? Tell me in the comments!
MAD Game DevLog #1
Tags: gamedev, unity3d, csharp
Published: 2019-06-11 19:24:00

---
title: MAD Game DevLog #1
published: true
tags: gamedev, unity, csharp
cover_image: https://thepracticaldev.s3.amazonaws.com/i/73kzpoaw6a32oevx2sge.png
series: MAD Game DevLog
---

Hello Everyone!

In this devlog I'll try to keep you updated with the latest state of our game. Since we all have full-time jobs, we've been working on this game only on our free time.

I've been implementing the world generation code and since I hadn't any Sprites for the walls available, I've made my own ones in Aseprite.

![](https://thepracticaldev.s3.amazonaws.com/i/x9to3149mg2foghf89sn.png)

Using the Sprite from above I've created two prefabs in Unity and I've changed the colour of one prefab to brown, the generated world looks like this: 

![](https://thepracticaldev.s3.amazonaws.com/i/f9xknt4gbwcrr7qp83th.png)

The player sprite is also my doing.

A few days later I've received the wall sprites from Max and I imported them in Unity.

![](https://thepracticaldev.s3.amazonaws.com/i/gxp0vxnpdc63m1k4145o.png)

The reason the sprites look so small is that Max designed them so they can overlap but we're not exactly sure how we're going to do that, since this game is based on a matrix grid adding overlapping sprites to it might make it a bit confusing.

![](https://thepracticaldev.s3.amazonaws.com/i/ofa11ul3irl4nygzshbe.png)

Here are some pictures on how the game would look like with overlapping.

![](https://thepracticaldev.s3.amazonaws.com/i/jxohuosgcd2jb9sfhjm7.png)

![](https://thepracticaldev.s3.amazonaws.com/i/lj23ruge3z3eyrcdd2jj.png)


Andrei took the heaviest task to get the bombs working. He was struggling with Raycasting, Coroutines and the 2D Physics system from Unity. After some time he managed to get it working. The bombs are placed and explosions are spawned, it still needs a bit of polish.

![](https://thepracticaldev.s3.amazonaws.com/i/bfzq62uy8gqhppqc0nph.png)

Thanks for reading and have a nice day!

![](https://thepracticaldev.s3.amazonaws.com/i/4t30ab747l8bp7kwzi3q.gif)
Spring boot and Kafka a great combination
Tags: java, springboot, kafka, devlive
Published: 2019-06-11 19:23:02

I am happy to share that a talk I had the opportunity to give a few weeks ago at the [SpringIO Barcelona 2019](https://2019.springio.net/)  was published today. 

If you're interested in microservices development with java, Spring boot and Kafka this might be interesting for you.

**Real Time Investment Alerts using Apache Kafka & Spring Kafka at ING Bank** 

> [Tim van Baarsen](https://twitter.com/TimvanBaarsen) and [Marcos Maia](https://twitter.com/thegroo)

[Slides are available](https://www.slideshare.net/TimvanBaarsen/springio-barcelona-may-2019-real-time-investment-alerts-ing-using-apache-kafka-spring-kafka-149207956) 

and also the full [video on Youtube](https://www.youtube.com/watch?v=RZ0l30GJZqA)

In this talk, we present how we deal with the massive stream of price updates on stocks and how we leverage many features of Apache Kafka to improve and simplify our solutions. From simple producer/consumer up to advanced usage of streams we strongly rely on Kafka to solve our functional and non-functional requirements delivering high quality, real-time stream processing software that is reliable, precise and extremely valuable to our customers.

One of the main challenges of this project was to deal with a massive continuous stream of stock price updates and matching them against thousands of alerts created by our customers and still keep up with sending real-time alerts to them.

If you are on the business side you will be able to understand how we use Kafka to fulfill legal regulations while delivering extra value to our customers.

If you are a Developer you will have a chance to understand how we use many of the Kafka features to deliver simple, quality and reliable software that fulfills the business and regulations requirements while learning and having fun doing it.

What will the audience learn from this talk?
If you are a developer you will have a chance to understand how we are relying on Spring Boot and Spring Kafka to leverage many of the Kafka features to deliver simple, quality and reliable software that fulfills the business and regulations requirements while learning and having fun doing it!

If you are on the business side you will be able to understand how we use Kafka to fulfill legal regulations while delivering extra value to our customers.

Does it feature code examples and/or live coding?
We show a lot of code and do a live demo but we don’t code on stage.

Honest and constructive feedback is always welcome. I hope you enjoy it. I will be back writing here soon, to sharing on Spring boot and Kafka development.
CodePen JavaScript Console Template
Tags: codepen
Published: 2019-06-11 18:48:41

<p>This pen allows you to use all your favourite console functions right in CodePen: <code>console.log</code>, <code>console.info</code>, <code>console.warn</code>, <code>console.error</code>, and <code>console.clear</code> are supported.</p>

<p>To scroll the console to the bottom as messages are printed use the <code>console.follow</code> function.</p>

<p>Fork this pen to quickly create a new pen which is pre-configured for JavaScript console output.</p>

<p>If you want to learn how this works then take a look at <a href="http://codepen.io/nullobject/pen/cngzI">this pen</a>.</p>

{% codepen https://codepen.io/nullobject/pen/rAbio %}
Overflow in integer arithmetic with C
Tags: overflow, c
Published: 2019-06-11 18:47:48

---
title: Overflow in integer arithmetic with C
published: true
description: How to overcome overflow in integer arithmetic in C
tags: overflow, c
---

##Overflow

Sometimes, the results of working with integers may go outside the range that can be represented, that is, when the result of operating on two k-bit numbers is a (k+1)-bit result. Static analysis tools such as Polyspace or Sonar may also trigger a warning on an operation or in the worst case, you come upon an error in run time.

Typically, addition and multiplication are the sources of overflow, but it can appear with subtraction and the abs function.

##How to overcome the problem

###Up-casting to a larger size.

The first proposal requires to know the maximum (or minimum) value of the types you are working with. If so, it is possible to do something like this:

```c
#include <stdint.h>

int16_t add_without_overflow(int16_t x, int16_t y)
{
  int32_t z = (int32_t) x + y;
    
  if (z > INT16_MAX)
  {
        z = INT16_MAX;
  }
  else if (z < INT16_MIN)
  {
        z = INT16_MIN;
  }
  return (int16_t) z;
}
```

This piece of code upcast the addition to larger type size, from int16 to int32, from two k-bit numbers to (k+1)-bit number. Afterward, check for overflow. That is, if your result fits in the k-bit number, you got it.

###To compare with a well-known domain value

Maybe is not so easy to know the maximum or minimum or a certain type in the target platform. In that case, an easy way to overcome is to check the operands with a maximum or minimum of your specific domain. Suppose that we are operating on two variables which stand for the weight of two loads in grams. But we are guaranteed (by system requirements) that no load can be heavier than 5.000 grams.

It can be just put:

```c
int16_t add_without_overflow(int16_t x, int16_t y)
{
  int16_t total = 0;
  
  if (x <= MAX_LOAD_WEIGHT &amp;&amp; y <= MAX_LOAD_WEIGHT)
  {
        z = x+y;
  }
   
  return total;
}
```

Furthermore, that way the correctness of the data is checked.

Nevertheless, this approach have a drawback in my opinion. You need you be very careful with the domain ranges. Imagine that the maximum of the load could be 40,000. An addition of two the heaviest loads (40,000+40,000) results in an overflow.

In my opinion, that would be a valid solution when your domain values are far away from the limits of you type size.

##References

Here can be found more precise and detailed explanations

[Understanding and Preventing Overflow](hhttp://embeddedrelated.com/showarticle/532.ph)
[Catching overflows in C](https://www.fefe.de/intof.html)
[Understanding integer overflow in C/C++](http://www.cs.utah.edu/~regehr/papers/overflow12.pdf)


[Original post in myram](https://myram.xyz/overflow-in-integer-arithmetic-with-c/)
What's the quickest path into game development for a curious webdev?
Tags: discuss, webdev, gamedev
Published: 2019-06-11 18:27:11

Personally, I've always been into game development. I'm pretty happy with where I am now, but have some "grass is greener on the other side" sort of thoughts. Is web development similar enough where transitioning would be easy? What's the industry like in terms of hiring someone with a web development background?