teleren/devto huggingface dataset:
Javascript Arrays - How to Remove Duplicate Elements
Tags: webdev, javascript, typescript
Published: 2023-02-04 23:21:20

Javascript arrays can contain duplicates - which is fine most of the time, but can sometimes cause some issues. For example, if an array is supposed to only contain unique user IDs, but is taken from a data source which may contain duplicates:
```javascript
let userIds = [ '123-123', '123-123', '234-234', '345-345' ]
```

In these cases, it can seem quite difficult to get only unique values. Is the best way to check every value against every other value in an array? That seems like a lot of work which should be simple. Fortunately, there is an easy way to make a unique array, and that is to use [javascript sets](https://fjolt.com/article/javascript-sets).

A set can only contain unique values, so passing your array into a `new Set()` constructor will produce one set with unique values:
```javascript
let userIds = [ '123-123', '123-123', '234-234', '345-345' ]
let uniqueUserIds = new Set(userIds)
console.log(uniqueUserIds) // Set(3) {'123-123', '234-234', '345-345'}
```

While sets have their own methods and these are described in [my set guide here](https://fjolt.com/article/javascript-sets), sometimes arrays can be both more familiar and have more useful methods. 

To convert your set back to an array, use the `Array.from()` method:
```javascript
let userIds = [ '123-123', '123-123', '234-234', '345-345' ]
let uniqueUserIds = new Set(userIds)
let arrayUserIds = Array.from(uniqueUserIds)
console.log(arrayUserIds) // [ '123-123', '234-234', '345-345' ]
```

Now you have a perfectly unique set of array items - and you won't have to worry about processing times, or inaccuracy.
I can’t draw… but I try
Tags: art, learn
Published: 2023-02-04 23:12:56

{% embed https://open.spotify.com/track/57W5o6ojTFtydDMZ0mDDB3?si=vat5FtFQQ1iOOgApwcssZQ  %}


![Poorly draw image by me](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0vbjt1j55xuqxx0wnu7k.jpeg)
Javascript toLowerCase() - Convert Strings to Lowercase
Tags: javascript, webdev, typescript
Published: 2023-02-04 23:11:12

a `String` is a type of data in Javascript, and as with any other type of data, `String`s have prototypes and therefore inherit standard methods. One of these methods is `toLowerCase()`, which you'll often see written as `String.prototype.toLowercase()`. This method turns any string from any case to just lowercase instead. 

Here is a quick example:
```javascript
let myString = 'HELLO WORLD'
console.log(myString.toLowerCase()) // hello world
```

This will work on anything which is of string type - so trying to initiate a `new String()` and use this method also works:
```javascript
let myString = new String('HELLO!')
console.log(myString.toLowerCase()) // hello!
```
How to Check if Object is Empty in JavaScript
Tags: webdev, javascript, typescript
Published: 2023-02-04 23:07:09

Defining a new object in Javascript is pretty easy - but what if you want to find out if it's empty? For example, `{}` is an empty object, but how do we **actually** test that this is the case?
```javascript
let myObject = {}
```

The easiest (and best) way to do this, is to use `Object.keys()`. This method turns all the keys in an object to an array, which we can then test the length of:
```javascript
let myObject = {}

console.log(Object.keys(myObject).length) // Returns 0!
```

But wait... Javascript is well known for how it handles types strangely - and new constructors return an object with length 0:
```javascript
let myFunction = function() {
    console.log("hello")
}
console.log(Object.keys(new myFunction()).length)
```

Fortunately, we can check if something is an object by checking its `constructor` property:
```javascript
console.log(function myFunction() {}.constructor) // Function
console.log({}.constructor) // Object
```

Therefore, we can check if an **object** is empty if its constructor is an `Object`, and it has an `Object.keys()` value of `0`:
```javascript
let empty = {}
let isObjEmpty = (obj) => {
    return Object.keys(obj).length === 0 && obj.constructor === Object
}

console.log(isObjEmpty(empty)); // Returns true, Object is empty!
```

This will not work if some keys are non-enumerable, though. Depending on your use case, this might be fine - but let's look at how to check for non-enumerable properties next.
 
## Including Non-Enumerable keys
It is possible to define keys on an Object which are non-enumerable. That means they won't show up in `for` loops or in `Object.keys`. 

Fortunately, we can use `Object.getOwnPropertyNames` to get all non-enumerable and enumerable keys on an object. Therefore, to check if an object is empty and check for both enumerable and non-enumerable keys, we only have to change `Object.keys` to `Object.getOwnPropertyNames`:

```javascript
let empty = {}

// Example: Add a non-enumerable property to our object using defineProperty. All properties added with defineProperty are non-enumerable by default.

Object.defineProperty(obj, 'someProp', {
  value: "non-enumerable property",
  writable: true
})

let isObjEmpty = (obj) => {
    return Object.getOwnPropertyNames(obj).length === 0 && obj.constructor === Object
}

console.log(isObjEmpty(empty)); // Returns false
```

Now we have a function which can tell you if any object is empty, and accounts for both numerable and non-numerable properties.
Học... cách học
Published: 2023-02-04 23:02:14

Đây là bài blog đầu tiên và mình chọn một chủ đề không liên quan đến công nghệ :)

Sỡ dĩ mình chọn chủ đề về cách học để nói đầu tiên vì mình nghĩ đây là một kỹ năng quan trọng, đặc biệt đối với ngày nay. Ở thời điểm mà mọi thứ phát triển rất nhanh, hiếm khi có một ngành nghề nào kiến thức sẽ không thay đổi.

Điều này càng đúng đối với đặc thù của lĩnh vực công nghệ nơi mọi thứ thường thay đổi nhanh chóng. Vì vậy có lẽ kỹ năng mà chúng ta cần thành thạo nhất là kỹ năng có thể nắm bắt được kiến thức mới một cách hiệu quả (hay còn gọi là "học cách học")

Khóa học [learning how to learn](https://www.coursera.org/learn/learning-how-to-learn?) (khoá học MOOC phổ biến nhất) sẽ giúp các bạn rất nhiều trong suốt quá trình học cũng như trong công việc của các bạn. Ngoài ra, nền tảng [Coursera](https://www.coursera.org/) cũng cung cấp rất nhiều khoá học miễn phí ở hầu như tất cả các chủ đề (bao gồm cả chứng chỉ, mặc dù việc này thường kèm theo chi phí)

Điều mà mình thấy phù hợp nhất là việc nền tảng hỗ trợ rất tốt phụ đề Tiếng Việt, nên chúng ta sẽ ít gặp khó khăn trong quá trình học. 

Khóa học [learning how to learn](https://www.coursera.org/learn/learning-how-to-learn?) là hoàn toàn miễn phí, các bạn hãy thử nhé! Mình tin khoá học sẽ có ích cho các bạn :)

Have fun!!
Hello, I'm Christopher Osuji
Published: 2023-02-04 22:59:06

 My name is Christopher Osuji and I am a recent graduate with a B.Sc in Architecture. I have a huge passion for technology and innovation, I took the initiative to expand my skill set by delving into the exciting world of blockchain and coding. I have been on this journey for four months now and am thrilled to continue exploring the limitless possibilities of this field. Let's dive in together and explore the future of technology!
Centering Elements in CSS with Tailwind
Tags: tailwindcss, javascript, css, webdev
Published: 2023-02-04 22:45:51

Tailwind is an increasingly popular and widely used framework, which makes it easier in some cases to build and ship features and products. In this guide, we'll be covering how you can vertically and horizontally center an element or text with tailwind. 

In another article, I've already covered how to center an HTML element both horizontally and vertically using CSS. If you want to learn about that, [click here](https://fjolt.com/article/css-vertically-center).

## Horizontally and Vertically center an element with Tailwind
Horizontally and vertically centering something with Tailwind is easy with `flexbox`. All we have to do is three things:
- use `h-screen` to make the element the height of the screen
- use `flex` to make the element a `flexbox`
- use `items-center` to vertically center it
- use `justify-center` to center it horizontally

Our code then looks like this:
```html
<div class="h-screen flex items-center justify-center">
    Horizontally and Vertically Centered Element
</div>
```

Which produces a result like this:
{% codepen https://codepen.io/smpnjn/pen/rNrPENZ %}

## Vertically centering an element with Tailwind

The easiest way to vertically center something is to do what we did before, and use `flexbox`. This time, though, we'll remove `justify-center`. The item will then be centered only along the vertical axis.
```html
<div class="h-screen flex items-center">
    Vertically Centered Element
</div>
```

You can see an example of this in the codepen below:
{% codepen https://codepen.io/smpnjn/pen/jOpdoJL %}


## Horizontally centering an element with Tailwind

In the same way that we vertically centered the div above, we can also horizontally center using our previous approach. The code for that looks like this:
```html
<div class="flex justify-center items-center">
    Horizontally Centered Element
</div>
```

This is the same code we used for horizontally and vertically centering, just without `h-screen`. Here's the result:
{% codepen https://codepen.io/smpnjn/pen/xxJMNoM %}

## Conclusion
Centering elements with flexbox is easy in Tailwind. In this guide, we've learned how to vertically and horizontally center elements including HTML elements and text - which is infinitely useful in web development.

To learn more about [CSS](https://fjolt.com/category/css) in general, you can [find my other content here](https://fjolt.com/category/css).
Day 159: A project never ends
Published: 2023-02-04 22:42:49

"A project never ends" that's what they say means that there will always something to fix on a project even after it reaches production and starts being used by real people. But why really project never ends? why even the best team can not deliver a simple project 

Speaking from my own experience the moment you have something solid to present everyone will start feeling accomplished and that whatever they had been doing is no longer motivating or fun to do. But in reality, at that exact, that's when you need to invest more time and energy to push the working hustle because at the end of the day, delivery is the most important thing 

I have learned this through a lot of mistakes and deadlines not met but it's very important and something I will be working on to improve for my future work

signing off...
Erro!!! Mongoose Deprecation Warning the strictQuery
Tags: mongodb, react, nextjs, javascript
Published: 2023-02-04 22:42:06

##**Calma lá, é simples de resolver!**
---

_1- Não precisa usar o next.config.js, acredite, é mais simples que isso_

_2- Não precisa instalar a biblioteca DotEnv_

***

Por isso mesmo foi a solução que eu adotei… é nativa do NextJS e muito simples de aplicar.

##Passo 1
Pra ter chegado nesse erro, você já criou o aquivo .env.local e provavelmente usou o parametro MONGODB-URI=”<uri-mongodb>” como no exemplo abaixo.

```javascript
// file .env.local
MONGODB_URI='mongodb+srv://admin:<PASSWORD>@cluster0.zcxjukj.mongodb.net/?retryWrites=true&w=majority'
```

Mas aqui está o problema, o NextJS não transfere essa variável pro client, ela está somente no Server, por isso está passando como “undefined”.

Mas é simples de resolver… coloque NEXT_PUBLIC_ no nome da variável no .env.local, como no exemplo abaixo 👇

```javascript
// file .env.local
NEXT_PUBLIC_MONGODB_URI='mongodb+srv://admin:<PASSWORD>@cluster0.zcxjukj.mongodb.net/?retryWrites=true&w=majority'
```

Pronto, agora você pode chamar a variável pelo process.env.

Basta acrescentar antes da chamada esse código mongoose.set(“strictQuery”, true);

Coloquei abaixo um trecho do código.

```javascript
mongoose.set("strictQuery", true);

const connectMongo = async () => {
 try {
  const { connection } = await mongoose.connect(process.env.NEXT_PUBLIC_MONGODB_URI, {
   useNewUrlParser: true,
   useUnifiedTopology: true,
  });
  
<seu código aqui>

};
```

Lembre-se de reiniciar o servidor pra variável NEXT_INPUT ser definida e você poder consumir no seu código.
What is Java Stream and why does it exist?
Tags: java, streams
Published: 2024-02-26 12:02:53

---
title: What is Java Stream and why does it exist?
published: true
date: 2023-02-04 21:37:02 UTC
tags: java, streams
canonical_url: https://theright.dev/what-is-java-stream-and-why-does-it-exist
---

A Stream is a sequence of values. The [java.util.stream](http://java.util.stream) package defines types for streams of reference values (Stream) and some primitive values (IntStream, LongStream, and DoubleStream).

Streams are like iterators in the way they supply their elements as needed for processing.

Streams were introduced in Java 8 as a way to add manageability to existing data structures. With them, we can use some very interesting methods for our structures:

- Map

- Reduce

- Filter

- Find

- Foreach

- Among others.

For this, it is important to create a **stream pipeline**. A stream pipeline is used to manage actions on a stream. It is composed of iterators and finalizers, where iterators are methods that return stream and finalizers do not return streams and still close it. Example:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675546082622/2eac081d-4cda-48fa-bd89-4562bcd9a251.png)

To use Java streams we need to convert the data structure we are working on to a Stream, assemble and run our pipeline. Finally, we can convert the stream pipeline output back to the source structure if necessary.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675541921681/1d118121-194c-48d3-99e9-a62082e8aa7a.png)

You might be wondering: "Why weren't such methods declared directly in the data structures?"

![](https://lh3.googleusercontent.com/8-Dj522xUIgILbaL-GSXu5Vht8qG_LBEtviWFDFpScIlxTf5Dq2JmgcSwSXGOHWETY9zhvhttkPDGBwXmcLdTQeAlYHJAkBjh6YynmG4uNjv9i74ihGTQYwdgZ1EdxF1xy7XVCdOyO2lMNF5sJfJsME)

As you can see, we need to convert the structure we are working on to a stream before using the utility methods because they are not present in the Collections API but have been externalized in their own Streams API. And these are some of the reasons why Java Architects proposed this solution:

1. The Collections API is more concerned with storing the data than with the actions and work that we are going to do on the data itself;

2. Manipulation X Management of the Data Structure

3. Eager Loading X Lazy Loading

4. Even though those methods we declared in Collections API we would still need to do a conversion to work with asynchronous processing, see:

5. The risk of collision in method names increases every time we insert a new method in an API with hierarchically ordered classes.
Introduction to Fiddlehead: A Fast and Lightweight UI Library
Tags: javascript, hook, webdev, react
Published: 2023-02-04 21:20:40

[Fiddlehead](https://fiddleheadjs.com) is a fast and lightweight UI library that offers a simple, yet powerful approach to building user interfaces. Built with performance and simplicity in mind, Fiddlehead provides an intuitive API for managing state and updating the user interface in response to changes in state. This makes it an ideal choice for building single-page applications or UI libraries.

Fiddlehead is designed to be easy to use for developers of all skill levels, and is built with a functional programming style. This means that it is easy to understand, write, and debug, and it eliminates the need for complex class components. It also eliminates the need for third-party state management libraries, as it provides built-in support for managing state.

The library also comes with a suite of built-in hooks that make it easy to manage state and update the user interface in response to changes in state. For example, the [useState](https://fiddleheadjs.com/API/useState) hook can be used to manage the state of a component, while the [useEffect](https://fiddleheadjs.com/API/useEffect) hook can be used to run side-effects such as making API calls or setting up event listeners.

Additionally, the [store](https://fiddleheadjs.com/API/store) API provides a simple way to share state between components, making it easy to build complex and reusable user interfaces. The API includes a set of hooks for reading, writing, and initializing store data, and it makes it easy to manage the state of an application in a single place.

Overall, Fiddlehead offers a fast, lightweight, and intuitive approach to building user interfaces, making it an ideal choice for developers who are looking for a simple, yet powerful tool for building web applications.

[Try it now!](https://fiddleheadjs.com/#try-it-now)
React Custom Music Player
Tags: react, typescript, hoc, javascript
Published: 2023-02-04 19:49:48

**[Reaplay](https://npmjs.com/reaplay)** is React [HOC](https://reactjs.org/docs/higher-order-components.html) for create your custom music player with any styles you like.

> give me your tracks list, and i'll give you must state, functionalities you need for create a music player

### **Install**

```shell
npm install --save reaplay 
```
```shell
yarn add reaplay
```

### **Usage**

```jsx
import React from 'react'
import {Reaplay} from 'reaplay'

export default function App() {
   const songList = [
     "songSrc", // url song (https://example.com/song.mp3)
     "songSrc", // url song
     require("./songSrc"), //local song,
   ]

   return (
     //                         optional ↓
     <Reaplay tracks={songList} startIndex={2}>
        {(player) => {
          
           console.log("loading :", player.isLoading)

           return (
              // your player
           )
        }}
     </Reaplay>
   )
}
```
> "tracks" prop is required but "startIndex" is optional prop

-----------

### Example :

> * you can see a complete example [Here](https://github.com/Amir-Alipour/reaplay/tree/master/example) Or [Here](https://codesandbox.io/s/blissful-frost-yl38y)

![example of Reaplay, package for create custom music player for react](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ydmqr1urthgeqn3sgl2t.png)

------------

### some states of player (example)

`player.isLoading`
`player.duration`
`player.trackProgress`
`player.volume`
`player.isRepeat`
**and [more](https://github.com/Amir-Alipour/reaplay#props---properties) states for create your dynamically player ui**


### some functions of player (example)

`player.toNextTrack()`
`player.toPrevTrack()`
`player.setVolume(70)`
`player.setIsRepeat(true) | player.setIsRepeat((isRepeat) => !isRepeat)`
`player.playFast()`
**and [more](https://github.com/Amir-Alipour/reaplay#props---events) functionalities you can use for your own player events**

---------------

Hope it useful for your projects, if you enjoy it
for supporting me, Please click on the Star button on Github and Share this post and finally send the Repo to your friends.
Github Repo:
[https://github.com/Amir-Alipour/reaplay](https://github.com/Amir-Alipour/reaplay)
Make Creating Your flutter application splash Screen Stand Out by removing the custom white splash .
Published: 2023-02-04 20:41:53

> 

##Introduction 

Upon launching the app, the first display you see is the splash screen, which sets the tone for user experience. Flutter's white splash screen can hinder this experience. The splash displays important information such as the company logo and name, serving as a welcome screen for the app. Additionally, it informs users of loading delays caused by network issues or errors.

<img width="100%" style="width:100%" src="https://i.imgur.com/MwxUhgG.gif">

In this tutorial, we are going to learn how get rid of the ugly splash screen and display a splash screen when your  flutter  application launches .

**Prerequisites**

we will need to prepare an image that will be used as the splash image .

- PNG bitmap,
- any IDE eg visual studio code ,

**STEP 1**


Go to [Pub.dev](https://pub.dev/) to get the latest flutter_native splash_package.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/22wbzc6tazch1zdz9nuq.PNG)







**STEP 2**



in your [pubspec.yaml](https://dart.dev/tools/pub/pubspec) file, go to the dev dependecies and add 

```
dependencies:
  flutter_native_splash: ^2.2.17
```

**STEP 3**

Create a _flutter_native_splash.yaml_  file next to pubspec.yaml, i.e. in the _root directory_ of your application and paste the following code into it:

```
flutter_native_splash:
  image: assets/splash_screen/splash.png
  color: “42a5f5”
  android_disable_fullscreen: true
```

**STEP 4**

 After adding settings run the code below in your terminal and add the path to your _flutter_native _splash_.

```
flutter pub run flutter_native_splash:create --path=path/to/my/file.yaml
```

> Note: Every time you do a change to this, run pub get and splash create command.

now you can see the default white splash is removed !

<img width="100%" style="width:100%" src="https://imgur.com/eGqr25I.gif">

Alternatively , the solid background color can be changed to  a background  image .

```
flutter_native_splash:
  background_image: assets/images/backgroundimage.gif
  image: assets/images/splashimage.png
  # color: "#ffffff"
  android_disable_fullscreen: true
```
<img width="100%" style="width:100%" src="https://imgur.com/RLCQrzb.gif">

> Note: you can't use both background color and background image at the same time  you can only use either at once .

**Conclusion**
Thanks to the flutter_native_splash plugin, adding a splash screen to your app doesn't have to be difficult.
OSDC course 2023 Post #4
Tags: osdc, git, github
Published: 2023-02-04 20:20:23

This week we will start to work on our own projects.
We learned how to create a project locally on our computer, upload it to git and then add them to GitHub.
We saw how to add tests for the code.

You can find my (unfinished) project [here](https://github.com/adieg/MyProject).
My function receives a matrix and returns the sum-normalized values for the matrix.
2. Automi e linguaggi regolari
Tags: computerscience
Published: 2023-02-04 19:47:00

La teoria della computazione studia la creazione di modelli di computazione sotto diversi aspetti, ognuno dei quali ha caratteristiche diverse in base a quello che necessitiamo. Il più semplice è l'automa finito rappresentato da una quintupla {% katex inline %}(Q, \\sum, \\delta. q_0, F){% endkatex %}, dove Q rappresenta un insieme finito che contiene tutti gli stati dell'automa, mentre {% katex inline %}\sum{% endkatex %}, è l'insieme finito chiamato alfabeto, {% katex inline %} \delta {% endkatex %} rappresenta la funzione di transizione: {% katex inline %}\\delta : Q \\times \\sum \\rightarrow Q{% endkatex %} ... 

Continua nel post originale