teleren/devto huggingface dataset:
The tricks of Javascript
Tags: javascript, programming, beginners, tutorial
Published: 2022-01-30 21:38:05

## Here’s a trick question:

```jsx
const arr = Array(5).fill([]);
const arr2 = arr.map((subArr, i) => subArr.push(i));
```

---

## What is the final value of `arr`? And the final value of `arr2`?

This might be something you see people asking in an interview... and before you go `console.log({ arr, arr2 })`, it’s important to know the `why` more than the answer.

An `array` is a value that will always be passed “as reference”, which means it’s pointing somewhere in memory and it simply uses that.

In contrast, a value like a `string` or a `number` is passed “by value”, meaning it’s copied to where it’s needed.

And as weird as it might seem when you say it to `fill` with `[]` you’re telling Javascript to use the same reference in all instances.

So, when you map, you’re pushing the index to the same reference, over and over.

---

## What about the second one then?

Well... that’s even more trick! Because that’s just what `push` returns!

And if you didn’t know... `push` returns the length of the array after the push.

And since it’s inside a `map`, that returns a new array... it’s easy to understand what’s going on.

---

## The result

And so it prints this:

```jsx
{
  arr: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]],
  arr2: [1, 2, 3, 4, 5]
}
```

And not gonna lie... 

This didn’t come from an interview or anything like it... but from a test I was doing that as you might have imagined, wasn’t doing what I wanted it to do.

---

## The “fix”:

```jsx
const arr = Array(5).fill().map(() => []);
const arr2 = arr.map((subArr, i) => subArr.push(i));

console.log({ arr, arr2 });
/*
  {
    arr: [ [ 0 ], [ 1 ], [ 2 ], [ 3 ], [ 4 ] ],
    arr2: [ 1, 1, 1, 1, 1 ]
  }
*/
```

Just `Array(5).map(() => [])` doesn’t work, since `Array(n)` creates an array of “empty slots” that you can access directly, but you can’t do much else, so you need the `fill()` to replace those “voids” with `undefined`.

---

## Why does this work?

This one works because `map` iterates over the array and each of the `[]` is actually a `new` object that is passed by reference since each iteration uses a new scope.

If you were to initialize a `[]` outside and pass it... then we would be back to square one. 

---

Cover Photo by [Natalia Y](https://unsplash.com/@foxfox?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
If you started over today what two things would you do?
Tags: question, programming, beginners
Published: 2022-01-30 21:26:27

If you had to forget everything you have learned and start over as a developer. What are the two things you would do first?

For me,

1. Immediately join good communities and read at least 5 things daily.
2. Learn based on what I want to get done, not what I think I need to know.

Share you're thoughts below.
Attempt to create an Elifoot style game for Football (🏈)m
Tags: football, javascript, programming, react
Published: 2022-01-30 21:24:26

I've been trying to make a game for myself for a long time, Elifoot style (https://www.footballmanager.com/)

I'm sure using Reinforcement Learning with Python might be the best option, but I'd like to be able to create my own game, making whatever changes I want to mine. 

I know the NFL has several data models, or ProFootball, but I wanted to be able to simulate football games with just dice (using something similar to RPG, in which players have points And they can use the points to build a game.

So I come here and ask you: how do I start my project?So I come here and ask you: how do I start my project?

Some references here from Brazil are Brasfoot and Elifoot, and I believe they don't use Artificial Intelligence behind

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ikvzjtstqidyqad28oox.png)
React hook Text to speech web api
Tags: typescript, react, nextjs, javascript
Published: 2022-01-30 21:12:31

Hey guys I have made a react hook to convert text to speech, using web api. 
With implementation with 
[React js](https://github.com/kumard3/react-text-to-speech)
[Next js](https://github.com/kumard3/next-js-text-to-speech)

[Hosted website link](http://react-text-to-speech-cyan.vercel.app/)

[Hook repo link ](https://github.com/kumard3/react-text-to-speech-hooks/blob/master/src/useSpeechSynthesisApi.ts)


```
import { useCallback,useState } from "react";


export const useSpeachSynthesisApi = () => {
    
  const [text, setText] = useState<string>("");
  const [isSpeaking, setIsSpeaking] = useState<boolean>(false);
  const [isPaused, setIsPaused] = useState<boolean>(false);
  const [isResumed, setIsResumed] = useState<boolean>(false);
  const [isEnded, setIsEnded] = useState<boolean>(false);

  
  const speak = useCallback(() => {
    var msg = new SpeechSynthesisUtterance();

    msg.text = <string>text;
    function speak() {
      window.speechSynthesis.speak(msg);
    }
    speak();
    setIsSpeaking(true);
    setIsEnded(false);
  }, [text]);

  const pause = useCallback(() => {
    function pause() {
      window.speechSynthesis.pause();
    }
    pause();
    setIsPaused(true);
    setIsSpeaking(false);
    setIsEnded(false);
    setIsResumed(false);
  }, []);

  const resume = useCallback(() => {
    function resume() {
      window.speechSynthesis.resume();
    }
    resume();
    setIsPaused(false);
    setIsSpeaking(false);
    setIsEnded(false);
    setIsResumed(true);
  }, []);

  const cancel = useCallback(() => {
    function cancel() {
      window.speechSynthesis.cancel();
    }
    cancel();
    setIsPaused(false);
    setIsResumed(false);

    setIsSpeaking(false);
    setIsEnded(true);
  }, []);
return {
    text,  
    setText,
    isSpeaking,
    isPaused,
    isResumed,
    isEnded,
    speak,
    pause,
    resume,
    cancel  
    
}
}
```
Totient Function Of A Prime 
Published: 2022-01-30 20:37:40




## Statement

Totient function of a prime number **p** is p-1. 

---

### Proof

Suppose {% katex inline %}
 \Phi (p) < p-1
{% endkatex %}. This means that there is a positive integer less than p which share a prime factor other than 1. However, prime numbers are divisible by only itself and 1. Hence, a contradiction. 

Q.E.D
My Journey to Become a Developer
Tags: javascript, beginners, react, node
Published: 2022-01-30 20:24:11


Hello fellow developers! I am going to document my journey as a self-taught developer from this day. These blog posts will perhaps motivate me when I feel down and hopefully, it will motivate other upcoming developers (especially self-taught because it is darn hard) too. 
Here we go. 

## My background 
A quick glance at who I am. I have got a bachelor's degree as an English major/at Payap University. I have already spent quite some time coding (roughly... 7 months). At the moment, I am learning React on Scrimba (free version) and Node.js on Patika.dev(content is all in Turkish in Patika). I also make use of a Udemy course called Node.js, Express, MongoDB & More: The Complete Bootcamp 2022 by Jonas Schmedtmann. I bought his JavaScript course too. I already built several small projects, yet I am not confident in my skills to apply for jobs.  

## Currently, What I am Doing 
I won a seat in a free coding bootcamp. Let me explain their system precisely. Kodluyoruz and Patika.dev (sibling platforms) partner up with companies and launch coding bootcamps, most of the companies hire multiple bootcamp graduates once the bootcamp is done. They select bootcamp trainees among hundreds of people through an application form, technical test and an interview. My bootcamp is launched by Patika.dev and Logo Cyber Security- full stack development (JavaScript, NodeJS). 

## My Plan
### Making Projects 
Throughout the bootcamp we will have a lot of tasks and small projects and a capstone project. For all of these, I will give my best, however, I am planning to team up with a couple of other trainees and make a side project together. So, in the end I will have a project that I developed with other trainees and capstone project. I believe this will strengthen my Github account. 

### Documenting Journey
I will document what I learn every single day. Although I have classes only on Sundays for the bootcamp, I code every day, so I learn every day. I will post about React, (and maybe Vanilla JavaScript) and NodeJS. As a self-taught developer (actually who is becoming one) I know how hard it is to understand some concepts. So, I will do my best to explain them as simply as possible.
I made changelog page for my portfolio website
Tags: webdev, nextjs, showdev, react
Published: 2022-01-30 20:04:03

A Changelog page for any website is a good way to keep your audience up to date with new and meaningful changes. 
In my previous post, I mentioned that I'll create changelog page for my portfolio website. So I got free time on the weekend and worked on it.

Page link: [ma-ahmad/changelog](https://mahmad.me/changelog)
Github repo: [https://github.com/MA-Ahmad/myPortfolio](https://github.com/MA-Ahmad/myPortfolio)

I used [Github Api](https://api.github.com) to fetch PR's of my portfolio website. You can play with Github Api according to your requirements.

### Packages:
* [remark](https://www.npmjs.com/package/remark)
* [remark-html](https://www.npmjs.com/package/remark-html)
* [react-html-parser](https://www.npmjs.com/package/react-html-parser)

**Note:** I used above mentioned packages for mdx content processing.

Here is a chunk of code where I'm processing mdx content after fetching PR's list of my portfolio website.

```ts
//Imports
import remark from 'remark'
import html from 'remark-html'

//Component code
const [prDataState, setPrDataState] = useState(null)
const processPrBody = async () => {
    await prData?.map(async (obj) => {
      if (obj.body) {
        const htmlBody = await remark().use(html).process(obj.body)
        obj['body_html'] = String(htmlBody)
      }
    })
    setPrDataState(prData)
  }
```
[Complete File code](https://github.com/MA-Ahmad/myPortfolio/blob/main/pages/changelog.tsx)

### Page Image
![page Imag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fett1s0a4uuqi8yyai49.png)

### Show your support

Give a ⭐️ on Github if you like my work!
How to make more detailed error messages with Sentry
Tags: sentry, react, errors
Published: 2022-01-30 19:05:47

---
title: How to make more detailed error messages with Sentry
published: true
date: 2022-01-30 19:00:36 UTC
tags: sentry,react,errorhandling
canonical_url: https://relatablecode.com/how-to-make-more-detailed-error-messages-with-sentry/
---

![Ladybug](https://cdn-images-1.medium.com/max/1024/1*93bxOG4-vBTd6-WtO0hO8g.jpeg)
_Photo by Ritchie Valens on Unsplash_

A while back I decided to implement [Sentry](https://sentry.io/welcome/) into my web app. This turned out to be a huge boon to the way I’m able to debug or even catch several bugs!

However, the error messages Sentry can send back can be fairly unhelpful without a complete step-by-step process on what the user did to cause the error.

Luckily enough Sentry has an option to make the steps leading up to the error a lot clearer!

To check out how to set up Sentry check out my [other article](https://relatablecode.com/how-to-quickly-add-error-tracking-with-sentry/).

DISCLAIMER: The examples are done with a React app but this can be done in any Javascript app!

First and foremost, in the area of your app where you want to have a more detailed error flow, we have to import sentry.

```
import { addBreadcrumb, Severity } from '@sentry/react';
```

addBreadCrumb is the function we are most interested in. It allows us to specify to Sentry a personalized error flow entry. It receives an object with several properties.

I won’t go into detail about every single property of the object, but there are three that are very good to keep in mind!

### The properties

![addBreadcrumb function](https://cdn-images-1.medium.com/max/1008/0*mfnBNMbTCdjRLfQQ)
_addBreadcrumb function_

The first property is category, in which we can detail how we want the breadcrumb to be categorized. This is just a simple string.

The second is incredibly important and is the message! This is where you could personalize and include parameters, data, etc in your error flow message.

Last but not least is the level which is the severity level of the error flow message.

Take into consideration these are predetermined and should be imported from the sentry library as well.

### Results

Looking over the results of the error message we can see something along these lines:

![error message](https://cdn-images-1.medium.com/max/1024/0*JXjZlLrFEK075x5i)

This is taken from a personal app of mine but it now shows up in the flow!

And that’s it! Let me know in the comments below any more tips with Sentry or bug tracking in general.

More content at [Relatable Code](https://relatablecode.com)

_Originally published at_ [_https://relatablecode.com_](https://relatablecode.com/how-to-make-more-detailed-error-messages-with-sentry/) _on January 30, 2022._
Smallest positive missing number
Tags: java, array, beginners, programming
Published: 2022-01-30 19:59:03

Find the smallest positive missing number in the given array.
Example: [0, -10, 1, 3, -20], Ans = 2
Constrains:
1<=N<=10^6
-10^6<=Ai<=10^6

This question has been asked in companies like amazon, samsung, snapdeal etc.

_To solve this question click here:_(https://practice.geeksforgeeks.org/problems/smallest-positive-missing-number-1587115621/1)

**Approach 1:**
*We can solve the problem naively by looping over all the positive integers and checking if each of them is present in the array or not. Whenever a number is not found in the array, we return it and break the algorithm. Time compexity:O(n^2)*


**Approach 2:**
_We can solve this problem in linear time by using hashing. We loop over all the positive numbers, and check if it is present in the array or not by using a lookup table or hash map in **O(1) time**. The first element not found in the array will be the answer._

**JAVA CODE:**
```
import java.util.*;
import java.util.HashSet;

public class Smallest_pos_missing_no {
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a number:");
        int n=sc.nextInt();
        int[] arr=new int[n];
        System.out.println("Enter the elements of the array:");
        for(int i=0;i<n;i++)
        {
            arr[i]=sc.nextInt();
        }
       int res= smallest_pos(arr,n);
       System.out.println(res);
    }
    public static int smallest_pos(int arr[],int n)
    {
        HashSet<Integer> hash=new HashSet<Integer>();
        for(int i=0;i<n;i++)
        {
            hash.add(arr[i]);
        }
        for(int i=1;i<=n+1;i++)
        {
            if(!hash.contains(i))
            {
                return i;
            }
        }
        return -1;
        
    }
}
```
FREE React UI Libraries for Web developers
Tags: webdev, beginners, programming, react
Published: 2022-01-30 19:53:11

15 FREE React UI Libraries for Web developers

1: NextUI
2: Mantine
3: Elastic UI
4: Theme UI
5: Chakra UI
6: Material UI
7: ReactStrap
8: BlueprintJS
9: Arco Design
10: React Admin
11: Shards React
12: React Toolbox
13: React Desktop
14: React Bootstrap
15: React Virtualized
[Me ?]
Published: 2022-01-30 19:48:24

[Comment]: # (All of this is placeholder text. Use this format or any other format of your choosing to best describe your project and experience.)

[Note]: # (If you used the GitHub Student Developer Pack on your project, add the "#githubsdp" tag above. We’d also love to know which services you used and how you used it!)

## My Final Project


## Demo Link
 

## Link to Code

[Note]: # (Our markdown editor supports pretty embeds. If you're sharing a GitHub repo, try this syntax: `{% github link_to_your_repo %}`)

## How I built it (what's the stack? did I run into issues or discover something new along the way?)


## Additional Thoughts / Feelings / Stories


[Final Note]: # (CONGRATULATIONS!!! You are amazing!)
Spring Data Transfer Objects
Tags: java, webdev, computerscience, programming
Published: 2022-01-30 19:45:29

---
canonical_url: https://www.maxdemaio.com/posts/dtos
---

Data Transfer Objects (DTOs) carry data between processes. Each call to an application is expensive so we should try to keep them to a minimum. DTOs help solve this pesky problem! DTOs need to be serializable to go across remote connections. Usually, an assembler is used on the server side to transfer data between DTOs and any domain objects.

---

## Overview

DTO design patterns are frequently used in enterprise applications. Why? This design pattern allows us to pass data with multiple attributes in one shot from client to server, avoiding multiple calls to an application. Also, we avoid exposing the implementation details of our domain objects pulled directly from the repository layer (direct object-relational mapping from our databases to Java objects).

## Examples

When writing RESTful APIs we can even analyze an incoming request and stop it in its tracks by validating its request body data against our DTOs. This saves precious I/O since you can identify validation errors before you even get past the controller layer. I've created an [example application](https://github.com/maxdemaio/demos/tree/main/dtoExample) where I demonstrate applying validation constraints to a DTO class which I will detail here.

```java
public class PersonDTO {

	@NotNull
	@Size(min=2, max=30)
	private String name;

	@NotNull
	@Min(value = 18)
	private Integer age;

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String toString() {
		return "Person(Name: " + this.name + ", Age: " + this.age + ")";
	}
}
```

You can see we've flagged this class’s attributes with a few standard validation annotations. Now, let's make an example controller to demonstrate how we can stop a request in its tracks before traveling to our service layer if there are any mistakes.

```java
@RestController
public class ExampleController {
	@PostMapping("/")
	public String checkPersonInfo(@Valid @RequestBody PersonDTO personDTO) {
		return "Valid person DTO!";
	}
}
```

In the example application's repository, I've also included two Postman API calls. If we were to make a POST request with invalid age or name data, the end user receives a 400 error. However, if all fields of the request body of the POST request are valid, we receive a nice message "Valid person DTO!". In a real application, catching these types of errors early is extremely important.

## Conclusion

We now know what DTOs are used for and why they're very helpful in enterprise applications. This design pattern is very common and allows for efficient API architecture when coupled with validation. In short: validate, validate, validate!
OPIN : membership
Tags: openinsurance, insurance, opensource
Published: 2022-01-30 19:40:56

I recently joined OPIN member. I am getting involved in working on the next version of OPIN API Data Standard.  The current version of OPIN is at : https://docs.google.com/spreadsheets/d/1Y0Gk_LpTvTNEfoDMdIxeD7juv3E8FKcbE3mHUJNV5JY/edit#gid=0

OPIN (https://openinsurance.io) is a think tank to provide thought leadership on key issues that define interoperability and compatibility. OPIN believes that designing for inter-connectedness will help insurance providers climb up the network chain towards ecosystem actualization.

OPIN informs policy debate making us the leading authority on common standards and shared access to data. Alongside regular publications from our team, we develop ideas and research activities on leading edge topics by mobilizing our network of diverse businesses.
Another wall climbed
Tags: javascript, beginners, programming
Published: 2022-01-30 19:23:41

## **Problem: Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem**

> _Complete the code for the `squareList` function using any combination of `map()`, `filter()`, and `reduce()`. The function should return a new array containing the **squares of only the positive integers** (decimal numbers are not integers) when an array of real numbers is passed to it. An example of an array of real numbers is [-3, 4.8, 5, 3, -3.2]._

Note: Your function **should not use** any kind of `for` or `while` loops or the `forEach()` function.

## **CODE:**

```
const squareList = arr => {

  // Only change code below this line
  
  return [...arr].filter(x => Number.isInteger(x) && x > 0).map(x => x**2);

  // Only change code above this line
};

const squaredIntegers = squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]);
console.log(squaredIntegers);
```

## Personal Note:
> It took me like 5 hours complete this exercise.
> This are the **3 most important lessons** for me **so far**:

- Try to not get distracted so easley
- White noise better than trapp for coding 
- Enjoy the process of strugling with the first steps
Have you tried the unpack operator in python?
Tags: python, programming
Published: 2022-01-30 19:13:23

The one thing, which I love in Python is its unpack operator (* and **). This operator can be used with any iterable(list, dictionary, tuple, etc). It makes the code very elegant, adds performance to the code and I can do a ton of things using it.

Here are some of my use cases for the unpack operator-

1\. Pass function parameters-

Often times, it happens that, the function has too much parameters with long names, and passing each value to parameter makes the code harder to read.

To tackle this problem you can use unpack operator(* if there are positional arguments or ** if there are keyword arguments)

example-
```python
def my_func1(*args, **kwargs):
  '''
  args is a tuple, so you can use indexing to get the values
  kwargs is a dict, so you can use, kwargs.get(param_name) to access the value
  '''
  print(args)
  print(kwargs)

positional_args = (1, 2, 3, 4)
keyword_args = { 'arg1': 1, 'arg2': 2, 'arg3': 3 }

my_func1(*positional_args, **keyword_args)
```

In this way you can make your code more readable, and if the values for the function are static then, you can import them from a seperate file.

2\. Update list or dictionary-

Using Unpack operator we can update a list or dict without using any inbuilt function

```python
list1 = [1, 2, 3]
dict1 = {'a': 1, 'b': 2}

# add a new element
list1 = [*list1, 10]
dict1 = {**dict1, 'c': 3}

print(list1, dict1)
```

3\. Merge a list or dictionary-

```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]

list3 = [*list1, *list2]

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'c': 4}

dict3 = {**dict1, **dict2}
```

4\. Split an iterable into multiple parts

```python
my_string = "hello devs!"

sub_str1, *sub_str2 = my_string

print(sub_str1)
print(sub_str2)
```

Thanks for reading this post
Have an awesome day!😇
I made an extremely fast, fully static rss reader
Tags: javascript, webdev, programming, vue
Published: 2022-01-30 18:55:29

So, I always wanted a rss reader, which had images for all the articles and I wanted it fast, hence came this idea, I have been using this for my personal use for a very long time now, finally making it open source.

[https://feedful.vercel.app](https://feedful.vercel.app) - do star on github if you find it good. 

> Note, this is still a work in progress.

How did I make it static?
1. A github action scrapes data and commits the data every 4 hours
2. Vercel deploys it whenever a new commit is pushed.


![Feedful - light](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/66qyjn0shnqmsrqzdgf0.png)

![Feedful - dark](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hz4honwiougm4gg171c1.png)