teleren/devto huggingface dataset:
2021 week 36, mathematically incorrect JS. Plus numbers about the Malaysian Flag.
Tags: javascript, floatingpoint
Published: 2021-09-12 15:45:27

It’s 2021 week 36, I recently had a bit of fun with JavaScript number data type and Malaysia Day is around the corner (16th September) - that’s how I arrive at this week’s topics. Here are some interesting facts about numbers in JavaScript and numbers related to the Malaysian flag.

- **JavaScript number**: the primitive data type `number` is based on the IEEE 754 standard, which means floating-point arithmetic applies. The classic example is `0.1 + 0.2` returns `0.30000000000000004`, the result also shows the decimal precision limit of 17.

- **JavaScript bigint**: the `bigint` primitive type was introduced in ES2020, it can safely represent integers bigger than `Number.MAX_SAFE_INTEGER`, e.g. `9007199254740992 === 9007199254740993` returns `true` which is wrong but with BigInt, `9007199254740992n === 9007199254740993n` returns `false` as expected. Note that as of current, the `Math` object doesn't work with `bigint`.

- **The Malaysian flag**: before the formation of Malaysia in year 1963, the flag for Federation of Malaya had 11 stripes and the star had 11 points as opposed to 14 for both now. The original submission of the design had a five-pointed star.

This is my 9th weekly post, thank you for reading and if you have got any feedback, do let me know!

### Related Links

- [JavaScript data types and data structures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type) by MDN contributors.
- [Math - Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math#static_properties) by MDN contributors.
- [The History and Design Chronology of JALUR GEMILANG](https://www.malaysiadesignarchive.org/documents/The%20History%20of%20Malaysian%20Flag%20Design.pdf) by Muhamad Razif Nasruddin and Zarul Nazli bin Zulkhurnain.
How to create horizontal scroll with mouse wheel using JavaScript
Tags: html, javascript, webdev, tutorial
Published: 2021-09-12 15:44:38

Native horizontal scroll with mouse wheel is not so trivial for the user. However, this behavior can be changed using an **event listener**.

In fact, there are some events involving scrolling and mouse wheel such as *mousewheel* and *DOMMouseScroll*. But here I will be using the [wheel event](https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event).

So, to accomplish this behavior, the JavaScript code will look like this:

```js
element.addEventListener('wheel', (event) => {
  event.preventDefault();

  element.scrollBy({
    left: event.deltaY < 0 ? -30 : 30,
  });
});
```

Where `element` is the HTML element that the user will scroll by.

But you can ask why `left` has static values. That's because different browsers will provide different values for `event.deltaY`. So it's better to put just one value, only varying when the element is being scrolled to one side or the other.

Result:

{% codepen https://codepen.io/juanbelieni/pen/NWggWMV %}
Improving NgClass expression
Published: 2021-09-12 15:30:40

---
title: Improving NgClass expression
published: true
description: Directive to use class expression like in Vue in Angular applications
tags: 
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tz7v2cx7hj34j34l7erc.jpg
---

Sometimes happens that when you are working with a framework, you miss some features of the other. For me, this is something common because I work in Angular, Vue and (P)React (maybe others) almost every day and, when I work in Angular, I miss Vue, when I work in Vue I miss React and bla bla bla.

Today, let's talk about one difference between Vue and Angular in the class expression possibilities. Maybe, you should have some experience with Vue and Angular to get the point of this article.

For example, in Angular, you can use the following `[ngClass]` expressions:

> Note: Let's omit `[ngClass]="stringExp|arrayExp|objExp"`
```html
<!-- example of ngClass in Angular -->
<some-element [ngClass]="'first second'">...</some-element>

<some-element [ngClass]="['first', 'second']">...</some-element>

<some-element
  [ngClass]="{'first': true, 'second': true, 'third': false}"
>...</some-element>

<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
```
As you can see, the options is to use any expression as Array, Object or String where the first result, at the first level (first child) should return a string but, if you want to mix both or use a deeper child item, maybe you will have an error.

```html
<!-- with ngClass of Angular -->
<some-element [ngClass]="[{'classA': true}, 'classB']">
  ...
</some-element>
<!-- ERROR Error: NgClass can only toggle CSS classes expressed as strings, got [object Object] -->
```
As you can see, the example above, is a mix: An Array with an Object and String as item values.

If you have been working in Vue, you know that you can use more flexible expressions, so, the the example in Angular, we can do in Vue as in the following example:

```html
<!-- with :class of Vue -->
<some-element :class="[{'classA': true}, 'classB']">
  ...
</some-element>
```

For that, in my last applications, I made a directive to solve it and, the example is something like this:

```html
<!-- with ngVClass of Angular -->
<some-element [ngVClass]="[{'classA': true}, 'classB']">
  ...
</some-element>
```

The example above works. This is a directive that allows you to work with classes in Angular as in Vue.

Then I decided to share to the community publishing in a npm package [https://ng-v-class.dimaslz.dev](https://ng-v-class.dimaslz.dev).

As always, I hope could be helpful, at least as learning. Feedback are welcome, support the library clicking in the star in the repo, always helps.

Thanks for reading.
Just passed 1MIllion views on Dev.to
Tags: dev, stats, sm0ke
Published: 2021-09-12 15:14:31

---
title: Just passed 1MIllion views on Dev.to
published: true
description: 1million view (all time) views - Ty Dev
tags: dev, stats, sm0ke
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/csu5e7humqcq0p4pnvp6.jpg
---
Hello guys!

This week it was quite nice to see that my dashboard shows **1MIllion+ (all-time) views** for all articles published here on Dev. I will mention TOP-5 articles that helped me to reach this unexpected milestone: 

---

- [React Dashboards - Open-Source and Free](https://dev.to/sm0ke/react-dashboards-open-source-apps-1c7j): 144k views, 535💖
- [Admin Dashboards - Open-Source and Free](https://dev.to/sm0ke/admin-dashboards-open-source-and-free-4aep): 71k views, 569💖
- [Flask Dashboard - Open-Source Boilerplates](https://dev.to/sm0ke/flask-dashboard-open-source-boilerplates-dkg): 67k Views, 103💖
- [Vue Dashboard - Open-Source and Free](https://dev.to/sm0ke/vue-dashboard-open-source-apps-1gd1): 42k views, 379💖
- [How I’ve built 100+ free apps with automation tools](https://dev.to/sm0ke/100-open-source-apps-built-with-automation-tools-3jmj): 29k views, 463💖

--- 

A few things that I've learned during the process: 

- **Don't SPAM**, play fair & help others 
- **Be consistent** and constantly publish new content 
- **Research** the topic before writing about it
- **SEO** is important 
  - [React Dashboards - Open-Source and Free](https://dev.to/sm0ke/react-dashboards-open-source-apps-1c7j) ranks position #1 for "React Dashboard" keyword
- **Visual part** of the content is important 
- Allocate time and **respond to (all) comments** 

--- 

> **Thank you!** Feel free to AMA in the comments section.

--- 

P.S. Here is my [Twitter account](https://twitter.com/Sm0keDev) where I publish 99% `open-source` related content.
Laços de Repetição: Exemplos com do while (Parte 3)
Tags: javascript, dowhile, loops
Published: 2021-09-12 15:00:19

Vamos alguns exemplos com `do while`.

## Exemplo 1

### Ler uma determinada quantidade de números inteiros e somá-los.

Vou criar duas variáveis: uma para o número inteiro que será digitado e outra para a soma, cujo valor inicial é 0.

```javascript
let valor = Number(prompt("Digite um número inteiro ou 0 para sair"));
let soma = 0;
```

Agora vem a parte legal! Vou repetir a variável do número dentro do laço, que vai executar o seguinte: vou colocar quantos números quiser dentro dele para realizar a soma, ***desde que o valor seja diferente de 0***. Se eu digitar 0, o laço se interrompe.

```javascript
do {
	valor = Number(prompt("Digite um número inteiro ou 0 para sair"));
    soma += valor;
} while (valor !== 0);

console.log(soma);
```

## Exemplo 2

Ler uma determinada quantidade de números inteiros, somá-los e mostrar o maior valor digitado.
Vou criar três variáveis: uma para o número inteiro que será digitado, outra para a soma e outra variável para mostrar o maior número digitado. O valor inicial das últimas variáveis será 0.

```javascript
let valor = Number(prompt("Digite um número inteiro ou 0 para sair"));
let soma = 0;
let maior = 0;
```

Vou fazer a mesma coisa do exemplo anterior. Vou repetir a variável do número dentro do laço, que vai executar o seguinte: vou colocar quantos números quiser dentro dele para realizar a soma, ***desde que o valor seja diferente de 0***. Se eu digitar 0, o laço se interrompe. E ainda vou incluir uma condição para verificar qual foi o maior valor digitado.

```javascript
do{
	valor = Number(prompt("Digite um número inteiro ou 0 para sair"));
  if (valor > maior) {
  	maior = valor;
  }
  soma += valor;
}while(valor !== 0);

console.log(soma);
console.log(maior);
```

E aí? Gostaram! Até a próxima anotação! 😊
How to use a line break in JSON?
Tags: javascript, programming, webdev, css
Published: 2021-09-12 14:37:00

When using JSON data from the backend to display text in HTML of your web application, we often encounter a problem where we need to change the paragraph or add a bullet point. To achieve the same, we sometimes settle by creating different object properties in the JSON for different paragraphs and bullets points. We display the same by using `<br/>` tag separated spans or paragraphs. This increases the complexity of the code and we end up with a messy code.

```
<!DOCTYPE html>
<html>
<body>

<h2>JSON without line break</h2>

<span id="para1"></span><br/>
<span id="para2"></span>

<script>
const withoutLineBreak = {
      paragraph1: "Lorsem Ipsum", 
      paragraph2: "Lorsem Ipsum" 
     }  
document.getElementById("para1").innerHTML = 
withoutLineBreak.paragraph1;
document.getElementById("para2").innerHTML = 
withoutLineBreak.paragraph2;
</script>

</body>
</html>
```

As we can’t add `<br/>` tag in JSON, we need to use `\n` (newline) before the start of the next paragraph or bullet point to break the line in JSON. You can now use a single object property for multiple paragraphs and bullet points. This significantly reduces the line of code in the HTML file.

```
<!DOCTYPE html>
<html>
<body>

<h2>JSON with line break</h2>
  
<span id="para" style="white-space:pre"></span>

<script>
const withLineBreak = {paragraph: "Lorsem Ipsum\nLorsem Ipsum"}
document.getElementById("para").innerHTML = withLineBreak.paragraph;
</script>

</body>
</html>
```


Even after adding `\n` to the string, you still see that the JSON is not breaking into separate paragraphs. This is because the CSS property white-space is set to normal by default.
In order to break the line, one needs to add the following style to paragraph or span.
###`white-space: pre;`

pre stands for **preformatted text**. It will preserve the white space and text will only wrap on line breaks.
**Use case:** When developing a FAQ page for your web application and the data is coming in form of JSON from the backend.

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

Follow us on [Instagram ](https://www.instagram.com/commitandpush/)
If you have this three things, you can be a programmer too.
Tags: beginners, motivation, career, learning
Published: 2021-09-12 14:36:36

2021-09-13 is Programmers' day, but before you run in terror, please know that my goal is not to make you a programmer. 

Not yet...

You see, I have a bachelor in business, and while I never actually used, the *mindset* did stick with me and helped me along the way. So it doesn't matter where you're coming from, I do believe the *Programmers' mindset* can help you too. 

And with that, I can safely say: you don't need to be a programmer and that's okay. 

Seriously... run while you can...

Jokes aside, if you have this three things you can be a programmer. But not because you would be hacking your way into the matrix or anything of the like, but because you're gonna be solving problems.

Programmers solve problems and code is but one of the ways of doing that.

---

## 1. Have a problem to solve

If programmers are problem solvers, then it stands to reason that, first and foremost, you need a problem to be solved.

When you have a problem defined, you can start dissecting it, splitting it in smaller, more manageable problems and solve each one of them... and in time even the biggest problems are solved.

## 2. Laziness

Don't get me wrong here.

You really REALLY need NOT to want to do something, but not in the procrastinating kind of way.

You need the programmers laziness way of thinking: *"There should be a better way of doing this..."*

## 3. ANGER!

Again, not to be confused with frustration and Hulk Smash type of anger.

To do things *the way they have always been done* is easy. To change is hard.

To overcome the inertia, to focus on study, to overcome every and all errors that arise you need energy... you need ANGER to "say": *"I will do it in a better way!"*

---

And that's it. A big problem is something daunting, sometimes impossible to wrap your head around, but if you take it one step at a time you can do it.

And should you start to learn how to program, that's what you would be doing:

- Split a (coding) problem in smaller (coding) problems
- Solve each part (with code)
- Merge everything (with code)
- ??? (solving errors, bugs... with code)
- Problem solved! (with code!)

---

[![https://buymeacoffee.com/noriller](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uzlp2p7mt2izsjpnx517.png)](https://buymeacoffee.com/noriller)

Cover Photo by [Lagos Techie](https://unsplash.com/@heylagostechie?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/%23programmer?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
How to Install Powerline on Windows 10
Published: 2021-09-12 14:12:00

Powerline uses glyphs in order to style the prompt. If your font does not include Powerline glyphs, you may see several Unicode replacement characters ‘▯’ throughout your prompt. Though Cascadia Mono does not include Powerline glyphs, you can install Cascadia Code PL or Cascadia Mono PL, which have the Powerline glyphs included. These fonts can be installed from the Cascadia Code GitHub releases page.

http://blog.ntechdevelopers.com/how-to-install-powerline-on-windows-10/
How to Install Cmder on Windows 10
Published: 2021-09-12 14:11:04

Cmder is a software package created out of pure frustration over the absence of nice console emulators on Windows. It is based on amazing software, and spiced up with the Monokai color scheme and a custom prompt layout, looking sexy from the start.

http://blog.ntechdevelopers.com/how-to-install-cmder-on-windows-10/
Career change at 40 — best careers for women after 40
Tags: career, it, woman
Published: 2021-09-12 13:56:40

Career change in most cases is not given simply and no matter what kind of return and gender.
But if we take it specifically for women and of the specified age, then from my experience I would suggest switching to the IT sector, since there are a sufficient number of specialties that can be learned quite simply after completing a course of 3-4 months and getting the first offer in IT.

What is good about IT and why is it worth looking in this direction?
1. Good wages and benefits
2. Interesting work is not associated with hard work
3. Excellent career opportunities
4. Confidence in your future

How can the state help you change your profession?
Program name: WIA / ETPL
Resource: Bureau for Private Postsecondary Education https://www.bppe.ca.gov/

If you look closely at this resource, choose a location that interests your specialty and you can find a course to your liking.

After you have decided on a profession and a school, you need to call the selected school and ask to connect you with a person who is involved in the ETPL program at the school. After that, this person will give you the most complete information about the grant, etc.

Basic rules for the provision of grants:
• Be on welfare
• For those who have lost their jobs (unemployment), for example, Santa Clara county provides funds to pay for technical courses. You can also request additional information in the department where you are located on unemployment

Also, on the example of the state of Florida and the WIA / ETPL program
Resource: Florida Department Economic Opportunity
Link: https://floridajobs.org/office-directory/division-of-workforce-services/workforce-programs/workforce-investment-act

For more information, see Eligible Training Provider List (ETPL)
https://floridajobs.org/office-directory/division-of-workforce-services/workforce-programs/eligible-training-provider-list

There is a list of places who fall into this program and can conduct training under the ETPL program.

You can also write ETPL AZ in the search, etc.

What to choose from specialties?
The simplest of the IT specialties is QA (Quality Assurance), starting offer from $ 40USD per hour
How to flatten a tuple type in TypeScript?
Tags: typescript, javascript, tutorial
Published: 2021-09-12 13:53:17

Every time when I need to deal with type conversion/mapping, I'm asking my self: How would I do it in pure functional language wich supports `match`. I mean `match` like in `F#`, `ReasonML` or `Haskell`.

Please keep in mind, that you are allowed to use only destruction and recursion. There is no `filter`, `fold`, `map` and other fancy methods in type system.

Wait, why am I even writing about functional languages? TypeScript is not strictly functional but, I believe, that type system is, or at least has a lot in common. For instance, you are unable to mutate type itself, you can only override it.

The function I'd like to describe is written in a little bit weird style as for typescript/javascript eco system but this is not the case.

Consider this example:
```typescript
const Reducer = <T,>(
  Arr: ReadonlyArray<T>,
  Result: ReadonlyArray<T> = []
)
  : ReadonlyArray<T> => {

  if (Arr.length === 0) {
    return Result
  }
  const [Head, ...Tail] = Arr;

  if (Array.isArray(Head)) {
    return Reducer([...Head, ...Tail], Result)
  }

  return Reducer(Tail, [...Result, Head])
}
```

This is function works in a way we expect. It accepts `[[[[[1]]]]]` and returns `[1]`.

Above function should not be hard to understand. Since we already now how to flat the tuple, let's try to make it in type system.

It works only with TS nightly
```typescript
type Reducer<
  Arr extends ReadonlyArray<unknown>,
  Result extends ReadonlyArray<unknown> = []
  > =
  // if Arr is empty -> return Result
  (Arr extends readonly []
    ? Result
    // if Arr is not empty - destruct it 
    : (Arr extends readonly [infer Head, ...infer Tail]
      // check if Head is an Array
      ? (Head extends ReadonlyArray<any>
        // if it is -> call Reducer with flat Head and Tail
        ? Reducer<readonly [...Head, ...Tail], Result>
        // otherwise call Reducer with Head without flattening
        : Reducer<Tail, readonly [...Result, Head]>
      ) : never
    )
  )
```
As you might have noticed, I have used same algorithm as we used previously.

I just wanted to say, that if you want to write non trivial types, you need to change they way you are thinking.

I mean, if you learn some basics of `F#`, `OCaml` or any other functional language you will become better TypeScript programmer.

Let's go back to our utility type. You might want to ask me why I have used ReadonlyArray instead of regular Arrays?

This is because with ReadonlyArray it is easier to infer deep nested tuple.

See this example:
```typescript
const flatten = <
  Elem,
  T extends ReadonlyArray<T | Elem>
>(arr: readonly [...T]): Reducer<T> =>
  arr.reduce((acc, elem) =>
    Array.isArray(elem)
      ? flatten(elem) as Reducer<T>
      : [...acc, elem] as Reducer<T>,
    [] as Reducer<T>
  )

// readonly [1, 2, 3]
const result = flatten([[[[[[1]]], 2], 3]] as const)
```
Please see my answer on stackoverflow {% stackoverflow 69127304 %}
The end.
Map, Filter and Reduce explained.
Tags: javascript, beginners, functional
Published: 2021-09-12 13:37:20

You probably have heard of .map(), .reduce() and .filter(). 
Map, reduce, and filter are all array methods in JavaScript.In this article, you will learn why and how to use each one. 
I will try and explain with examples of how each of these functions works.

###map()

**map()** is used to transform an array. It creates a new array populated with the results of the calling function on every element in the calling array.
```
const array=[1,2,3,4,5];

const output=array.map(element=>
 {
  return element*2;
})

console.log(output);  // [2,4,6,8,10]
```
In the above code,
array ===calling array
element=>{...} ===calling function

The array elements are being traversed one by one and in each iteration the current element is multiplied by 2. The new value is pushed into a new array and after the traversal is complete we get a new array of elements in the output.

###filter()

Filter is used to filter the array. **filter()** method creates a new array with all the elements that pass the test implemented by the provided function.
If the test condition returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.


```
const array=[10,23,55,40,111];

const output=array.filter(element=>
                      {
  return element%2;
})

console.log(output);
```
In the example above it is filtering out all the odd elements from the array based on the test implemented in the function and pushing them into a new array and then returning the new array.

###reduce()

The **reduce()** method executes a reducer function on each element of the array, resulting in a single output value.
The reducer function takes two-parameter (accumulator, current).

accumulator= the returned value of the previous iteration
current=the current item in the array
```
const array=[1,2,3,4,5,6,7,8,9];

const output=array.reduce((acc,curr)=>
{
acc=acc+curr
 return acc
  
},0)

console.log(output);
```
The above code calculates the sum of the elements of the array.
The initial value of acc is set to 0 as mentioned in the code. On each iteration, the current element is added to acc, and hence at last the total sum is returned.

###Conclusion
I really hope that you enjoyed reading this article and learned something from it. If you have any doubt or you think i missed something let me know in the comments. Feel free to like and share the post. 
You can connect with me on:
Twitter:[Namit Malasi](https://twitter.com/namitmalasi)
LinkedIn:[Namit Malasi](https://www.linkedin.com/in/namit-malasi-a4b56310a/)
Github: [Namit Malasi](https://github.com/namitmalasi)