teleren/devto huggingface dataset:
TIL Unity has Aim Constraints
Tags: todayilearned, unity3d, gamedev
Published: 2021-01-26 04:50:23

2021-01-25

So I had a meaningful conversation with an executive coach today and it was very useful; I learned a lot and I'll briefly summarize it as: find your essence and then, do the smallest but biggest thing you can do today!

Switching gears from personal development to game development, I discovered Unity has Aim Constraints. If you've used Maya, these function the same way. 
![Screen capture of list of constraint components](https://dev-to-uploads.s3.amazonaws.com/i/vii6ckoyr3jgrtrrowyr.png)
In fact, judging by the list, I daresay that the Unity Constraints were built to mirror Maya's Constraints so that you could import complex rigs and control these properties in Unity. 

Ignoring this speculation, I find these are very useful for setting up complex transform relationships between your game objects. For example: you can quickly setup security cameras with Aim Constraints to follow your character with rotation on a specific axis. Thanks to weighting, it's possible to allow constraints between multiple objects so you can build even more complex relationships!
Yet Another Covid Tracker
Tags: vue, covid, javascript, tracker
Published: 2021-01-26 03:43:26

There is no shortage of data about the covid pandemic. In the last 14 months, many sites have provided trackers to visually represent this data. However, there were many shortcomings. Either they provided too much or too little information, not intuitive, slow or overall did not provide a good user experience.

That's why I decided to build a tracker that overcome these issues and also test my Vue/API skills. 

After contemplating a few designs I was able to finalize the project. Here it is:
{% codepen https://codepen.io/khr2003/pen/WNGqWox %}

Please let me know if there are any areas need improving.
Maintainable JavaScript — JavaScript/HTML Coupling
Tags: webdev, programming, javascript, codequality
Published: 2021-01-26 03:01:17

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**


Creating maintainable JavaScript code is important if want to keep using the code.

In this article, we’ll look at the basics of creating maintainable JavaScript code by looking at loose coupling between JavaScript and HTML.

### Keep JavaScript Out of HTML

We should keep JavaScript out of our HTML code.

It’s hard to debug JavaScript code that’s in our HTML files.

For instance, if we have:

```
<button onclick="doSomething()">click me</button>
```

then we call our `doSomething` function when we click on the button.

`doSomething` maybe in an external file or in a script tag.

We may run into issues when we click the button before the function is available, which causes a JavaScript error.

The resulting error may pop up and cause the button to appear to do nothing.

It’s also harder to maintain since changing the name would mean we’ve to also look for the name in the HTML file.

We may also want to change the code in the `onclick` attribu

Embedding JavaScript code in HTML makes changing the code easier.

Most of our JavaScript code should be in external files and included on the page with a script tag.

The `on` attributes shouldn't ve used for attaching event handlers to HTML.

Instead, we should attach the event listeners to the element by getting the element with JavaScript and attaching the listener:

```
function onClick() {
  // ...
}

const btn = document.querySelector("button");
btn.addEventListener("click", onClick, false);
```

We set the `onClick` function as the click handler for the button.

The benefit of that is that `onClick` is defined in the same files as the code that attaches the event handler.

If the function needs to change, then we need to change the JavaScript file.

If the button should do something else when it’s clicked, then we just need to change the code in the file.

IE8 and earlier don’t have the `addEventListener` method.

Instead, we have to use the `attachEvent` method.

With jQuery, we can write:

```
$("button").on("click", onClick);
```

We can also embed JavaScript in HTML with a script element that has inline code.

But this isn’t good since it keeps the JavaScript code in the HTML and makes the code longer.

For instance, we shouldn’t write code like:

```
<script>
  doSomething();

</script>
```

It’s best to keep all JavaScript in external files and keep inline JavaScript out of our HTML.

This helps us debug the code easier.

When a script error occurs, we know the error is in a JavaScript file.

If the JavaScript code is in our HTML file, then we have to search through both kinds of files.

### Conclusion

We should keep our JavaScript code out of our HTML code so that we can debug them easier.
More JavaScript Habits we can Follow
Tags: javascript, webdev, programming, beginners
Published: 2021-01-26 03:00:28

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**

To make code easy to read and maintain, we should follow some best practices.

In this article, we’ll look at some best practices we should follow to make everyone’s lives easier.

# No Reassigning Exceptions in catch clauses

We shouldn't reassign the error object in the `catch` clause.

Instead, we should assign it to a new variable to ensure that we don't lose any information.

For instance, instead of writing:

```
try {
  // ..
} catch (e) {
  e = 10;
}
```

We write:

```
try {
  // ...
} catch (e) {
  const foo = 10;
}
```

# No Unnecessary Boolean Casts

If we already have a boolean variable, then e don't need to cast it again.

For instance, instead of writing:
```
var foo = !!!bar;

var foo = !!bar ? baz : bat;

var foo = Boolean(!!bar);

var foo = new Boolean(!!bar);
```

We write:

```
var foo = !bar;

var foo = bar ? baz : bat;

var foo = Boolean(bar);

var foo = new Boolean(bar);
```

`Boolean` and `!!` already does the casting so we don't have to do it again.

# No Innecessary Parentheses 

We shouldn't have extra parentheses in our code.

For instance, instead of writing:
```
a = (b * c);

(a * b) + c;
```

We write:

```
a = b * c;

a * b + c;
```

We skip them to save some typing and make them easier to read.

# No Unnecessary Semicolons

We shouldn't have more semicolons than it's necessary.

For example, instead of writing:

```
var x = 10;;

function foo() {
  // code
};
```

We write:

```
var x = 10;

function foo() {
    // code
}
```

# No Reassigning Function Declarations 

We shouldn't reassign function declarations.

Instead, we assign whatever we want to assign to a new variable.

For instance instead of writing:

```
function foo() {}
foo = bar;
```

We write:

```
var foo = function () {}
foo = bar;
```

If we create a function, then keep it a function.

# No Assignment to Imported Bindings

If we have imported bindings, then we should use it directly or `as` to rename it.

Otherwise, we assign what we have to a new variable and then work with it.

For instance, we write:

```
import mod from "./mod"

mod.prop = 1;
```

And not:

```
import mod from "./mod"

mod = 1;
```

# No Variable or Function Declarations in Nested Blocks

We shouldn't have function declarations in nested blocks.

It's invalid syntax even though it's accepted.

For instance, instead of writing:

```
if (test) {
    function doWork () { }
}
```

We write:

```
function doWork () { }
```

We can also write nested declarations:

```
function doSomething() {
  function doAnotherThing() {}
}
```

# Conclusion

We shouldn't use invalid syntax.

Also, redundant code is bad.

Extra parentheses should be removed to save us typing and space.
Coding Interview Problem: checking if two things are equal
Tags: programming, career, javascript, discuss
Published: 2021-01-26 02:54:59

It is pretty straightforward to check if two values are equal right? Just compare them!
```
value1 === value2
```
But what if `value1` and `value2` are two objects? What if they have nested properties? What if these properties are arrays? Well, then you must use recursion right?

I once got asked this problem in a Coding Interview Problem and wanted to share my solution.

{% youtube bvsSOdUYMXU %}
All About Javascript Bind
Published: 2021-01-26 02:42:38

The ``bind()`` method creates a new function, which when called, assigns its operator this the delivered value, with a sequence of arguments given preceding any given when the function is called.

The value of this is ignored when the function is called with the new operator.

#Syntax
```
fun.bind(thisArg[, arg1[, arg2[, ...]]])
```

#Parameters
``thisArg``
It is a value that will be sent to the target function when the binding function is called. This value will be ignored if the binding function is constructed using the new operator.
arg1, arg2, ...

They are the arguments that will be sent in addition to those provided to the binding function when the target function is invoked.

The [javascript bind](https://ricardogeek.com/bind-call-y-apply-en-javascript/) function creates a new function (bound function) with the same body (internal call property in ECMAScript 5 terms) as the function to be called (the target function of the bound function) with the this reference associated to the first argument de bind (), which cannot be overwritten. bind () also accepts default parameters that will precede the rest of the specific parameters when the objective function is called. A bound function can also be constructed using the new operator: by doing so, it will act as if the objective function had been constructed instead.

In the latter case, the corresponding parameter for this will be ignored, although the default parameters that will precede the rest will be provided for the emulated function.

The simplest use of bind () is to make a function that, no matter how it is called, always points to the same object with the this reference. A common mistake for newer JavaScript programmers is that they get a reference to a method of an object, then they execute that method from the external reference and expect the reference to this to still point to the original object from which the method was obtained (e.g. when use that method in a callback). Without due care, the original item is commonly lost. Creating a bound function from the function using the original object neatly solves this problem:

```
this.x = 9;
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, porque en este caso, "this" apunta al objeto global

// Crear una nueva función con 'this' asociado al objeto original 'module'
var boundGetX = getX.bind(module);
boundGetX(); // 81
```
¿Por qué es importante que el cliente se involucre en la elaboración del producto?
Tags: agile, productivity, leadership
Published: 2021-01-26 02:31:56

Se ha repetido hasta el cansancio la importancia del cliente en el desarrollo de un producto, lo vemos en el manifiesto ágil tanto en los valores como en los principios del mismo, sin embargo, todavía nos encontramos en algunos casos con la resistencia por parte del cliente o la tendencia a subestimarlo al momento de desarrollar el producto. Por esto a continuación veremos las tres razones importantes del porque es necesario que el cliente sea la parte central del desarrollo del producto.

**El producto es tuyo.**

Creo que todos hemos escuchado la frase “Le salió el tiro por la culata”. Sabemos lo difícil que puede llegar ser el estar al tanto de un proyecto si tu foco está en el negocio y por lo general buscas el apoyo de expertos que transformen tus ideas en un producto tangible, pero nada más lejos de la verdad porque a pesar de que tienes a un equipo o empresa que respalde el desarrollo del producto el producto es tuyo, tú y nada más que tu sabe que es lo que requieres lograr, a donde quieres llegar o que ventaja competitiva te otorgará si es ejecutado de manera correcta por eso es necesario que te apropies de él y lo lleves a buen puerto si no quieres terminar con una escopeta que dispara por la culata.

**Conoce los tiempos y las tempestades.**

Saber cuándo tenemos el viento en popa y advertir la borrasca son cualidades que requerimos al momento de tener la intención de realizar un producto y esto se logra únicamente estando al tanto del proyecto, para conocer los tiempos y advertir los riesgos tanto para prevenirlos como para solucionarlos es una de las habilidades primordiales que solo suceden siendo parte activa del proyecto así que conviértete en el capitán que estas destinado a ser.

**Cuida los centavos.**

En cualquier proyecto un despliegue de recursos sin sentido no es lo más acertado aun cuando se tenga la solvencia suficiente para eso y más, ya que nos podrá repercutir en el mediano o largo plazo, como dice la frase “Un centavo ahorrado es un centavo ganado” y en base a esto es ideal estar al tanto de los recursos del proyecto para enfocarlos en lo que realmente nos dará un retorno de inversión en el tiempo adecuado.

En conclusión, sabemos lo complicado que puede llegar a ser el implicar a las partes interesadas en un proyecto, pero como líder ágil es tu responsabilidad encontrar la sinergia que derive en un ganar ganar para todas las partes interesadas en la elaboración de un producto o en un proyecto. Así que dale la importancia que merece el cliente e invítalo a desarrollar su visión que a fin de cuentas él y solo él sabe el valor que conlleva.

IG:[@agile.rockstar](https://www.instagram.com/agile.rockstar/)
FB:[@AgileRockstar](https://www.facebook.com/AgileRockstar/)
TW:[@ocazares](https://twitter.com/ocazares
Como saber se um número é par ou ímpar em JavaScript?
Tags: javascript
Published: 2021-01-26 02:23:34

As vezes é necessário saber, via programação, se um número é par ou ímpar. Mas como fazer isso em JavaScript?

## Método 1
```js
const isOddOrEven = (number) => {
  return number % 2 ? 'Is Odd!' : 'Is Even!';
}

console.log(isOddOrEven(3)); // Is Odd!
```
Nesse método, testamos a divisão por 2 do número passado, usando o operador `%`, que em vez de retornar o resultado de uma divisão, ele retorna o `resto`.

Qual a sacada? Todos os números pares são divisíveis por 2, ou seja, o resto da divisão de um número par por 2 é sempre 0.

Então caso essa operação retorne algum valor acima de 0, o número passado é ímpar.

## Método 2
```js
const isOddOrEven = (number) => {
  return value & 1 ? 'Is Odd!' : 'Is Even!';
}

console.log(isOddOrEven(3)); // Is Odd!
```
Nesse método, utilizando do operador `&`, que é um operador JavaScript da categoria _bitwise_ ou "bit a bit".

Essa categoria trabalha com os valores no formato de base 2, ou seja, binários. Aquelas representações em 1s e 0s. _(Ex: valor 5 em decimal é igual a 101 em binário)_

Para operação to tipo bit a bit, o JavaScript converte por padrão todos os operandos para inteiros de 32 bits _(Ex: 10100000000000000110000000000001)_

> Detalhe: caso o número convertido seja maior que 32 bits, os bits mais significativos são descartados, então não é recomendável usar operações bit a bit no JavaScript caso necessite usar números muito grandes, como cálculos com números primos.

Agora voltando a lógica do método...

O operador `&` retorna 1 para cada posição de bit em que ambos os operandos tinham um bit 1.

Qual a sacada? Estamos comparando ali os números com o número 1, que em binário seria `00000000000000000000000000000001`, ou seja, apenas os números ímpares possuem o primeiro bit com valor 1, que é o único bit do número 1_(decimal)_ que também tem valor 1.

## É isso!

São apenas dois métodos simples, mas o que eu queria passar aqui é a lógica de como resolver o problema de saber se um número é par ou ímpar.

Você também vai querer adicionar outras validações e muitos outros dilemas para deixar seu método super completo e a prova de quebra.

Mas o legal é entender como foram pensadas as lógicas para resolver problemas em programação, que podem ajudar na hora de resolver aquele seu problema de código que não é tão simples ou é muito específico ao contexto em que só você mexe.

Boa sorte!

------

Outros links:

- [Bitwise Operators](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators)
- [Foto por Nathan Fertig](https://unsplash.com/photos/y0HerwKQLMk)
Unable to install sharp npm packge on ubuntu
Tags: npm, ubuntu, sharp
Published: 2021-01-26 01:45:04

OS : Ubuntu 20.04
node v12.19.0
npm module :sharp(module to convert large images in common formats to smaller, web-friendly JPEG, PNG, WebP and AVIF images of varying dimensions).
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/y6kx4mlz7siebbnytpsj.png)
The image shows error while running the node app after installation of sharp npm module.To resolve the issue follow the steps below:

Step 1 : Complete the installation of sharp using the following command:
`npm install sharp`
output:
```
npm WARN task-manager@1.0.0 No description
npm WARN task-manager@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.1 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

audited 297 packages in 2.041s

22 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
```

Step 2 : <b>Delete "node_modules" folder completely</b>(Dont hesitate,you are not going to lose packages, they are stored in package.json file which you should not edit or delete).

Step 3 : Run the following command:
 `npm cache clean --force`
this command will clean the npm cache memory.
output:
```
npm WARN using --force I sure hope you know what you are doing.
```

Step 4 : Install npm packages using ignore script flag as shown below:
`npm install --ignore-scripts=false`

```
> sharp@0.26.3 install /home/manoj/Documents/task-manager/node_modules/sharp
> (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)

info sharp Downloading https://github.com/lovell/sharp-libvips/releases/download/v8.10.0/libvips-8.10.0-linux-x64.tar.br

> nodemon@2.0.7 postinstall /home/manoj/Documents/task-manager/node_modules/nodemon
> node bin/postinstall || exit 0

Love nodemon? You can now support the project via the open collective:
 > https://opencollective.com/nodemon/donate

npm WARN task-manager@1.0.0 No description
npm WARN task-manager@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.1 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

added 297 packages from 356 contributors and audited 298 packages in 76.916s

22 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
 ```

After following this steps, now you should be able to run sharp on your node app. if you are still not able to run sharp, please let me know in comments.
Editing Without An Editor
Published: 2021-01-26 01:04:31

##Writing
```bash
echo "blablabla
into
different
lines" > file.txt
```

##Reading
```bash
cat file.txt
```

##Editing
like vim
```
:%s/stirring/string/g
```

you can use sed
```bash
sed -i "s/stirring/string/g" file.txt"
```

##Deleting
```bash
sed -i "/string/d" file.txt
```
CURL to Test REST API
Published: 2021-01-26 01:01:05

```bash
curl -X GET -v http://localhost:8000/home
```
`-X` to specify a HTTP method and `-v` to display headers (verbose)

```bash
curl -X POST \
     -H "Content-Type: application/json" \
     -d '{"username":"xyz","password":"xyz"}' \
     -v http://localhost:8000/home/create
```

`-H` for headers, `-d` for data (e.g. JSON or XML)
Five Classic Reads in Software Development
Tags: bestofdev, codequality, history, books
Published: 2021-01-26 00:56:03

I was looking back on some discussions I've started in the past on DEV, and felt like sharing some top comments from [this #discuss post](https://dev.to/ben/what-are-some-classic-reads-in-programming-12c). Enjoy!

{% devcomment 11m9g %}

{% devcomment 11ma6 %}

{% devcomment 11mag %}

{% devcomment 11mm7 %}

{% devcomment 11me2 %}
Functional composition and lodash
Tags: lodash
Published: 2021-01-26 00:10:07

In functional programming, functional composition is snapping together a series of functions.
for example:

```js
// code to trim a string
let trim = str => str.trim();
// code to convert string into lowercase
let lowerCase = str => str.toLowerCase();
//code tp wrap a string inside a div
let wrapper = str => <div>${str}</div>;
console.log(wrapper(lowerCase(trim(" HELLO WORLD! "))))
```

Here, i have a string **“ HELLO WORLD! ”** , i want to to
a. trim the string (removing spaces on both the sides)

b. convert the string into lowercase

c. wrap the string inside a div
in the above example, I have called a function and passing the output of a function as a parameter to another.
Here, as the functions increase, the complexity to read the code increases, debugging will be difficult as well.

To solve this problem, we can use lodash

Steps to use lodash in your project:

a. Install lodash package

```js
npm install lodash
```

b. include lodash reference

```js
include {compose, pipe } from "lodash/fp"
let trim = str => str.trim();
let lowerCase = str => str.toLowerCase();
let wrapper = str => `<div>${str}</div>`;
const newString = pipe(trim, lowerCase, wrapper);
console.log(newString("HEllo WORLD"))
```

In the above example, i have used pipe, where we can give a sequence of functions that needs to be executed on a given input. (executed from left to right)

c. If you wish to give the sequence of functions from right to left, we can use compose

```js
include {compose, pipe } from "lodash/fp"
let trim = str => str.trim();
let lowerCase = str => str.toLowerCase();
let wrapper = str => `<div>${str}</div>`;
const newString = compose(wrapper, lowercase, trim);
console.log(newString("HEllo WORLD"))
```
How to check whether the user has turned on the option to reduce data usage using JavaScript?
Tags: javascript
Published: 2021-01-26 00:00:00

---
  title: How to check whether the user has turned on the option to reduce data usage using JavaScript?
  published: true
  tags: JavaScript
  date: Tue Jan 26 2021 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/check-whether-user-turned-on-save-data-mode-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-4009a8c8222244815a3989ad85c3bf9c.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/check-whether-user-turned-on-save-data-mode-javascript)
  
## This is an experimental technology still in Draft, so it may not work in all browsers.

To check whether the user has turned on the option to reduce data usage on the user's device, you can use the `saveData` property in the `navigator.connection` object in JavaScript.

```js
// Check whether user turned on the option
// to reduce data usage
const isDataSaverTurnedOn = navigator.connection.saveData;

console.log(isDataSaveTurnedOn); // false
```

- **The `saveData` property returns a boolean `false` if it is turned off and `true` if it is turned on.**

- **This API can be used to switch to use the low-quality content thus saving the user's data usage**.

For better usability, it's better to check whether the Network API is available in the appropriate browsers by first checking for the appropriate `connection` object in the `navigator` object.

```js
// check if connection object present
const connection =
  navigator.connection || navigator.mozConnection || navigator.webkitConnection;

// then check whether the user turned on the option
// to reduce data usage
console.log(connection.saveData);
```

See this example in [JSBin](https://jsbin.com/navemovaya/2/edit?js,console).

### Feel free to share if you found this useful 😃.

---