teleren/devto huggingface dataset:
Array Methods in JS - toString()
Tags: javascript, beginners, webdev, tutorial
Published: 2022-08-18 18:06:00

Hello Guys today i will be discussing about toString() method in Javascript.

Lets get started...

toString() method gives us the string representation of array,number,strings and booleans.

## Code Example
```js
const number = 12345;
const string = "Javascript";
const boolean = true
const array = [1,2,3];
const mixedArray = [1,2,3,"HTML","CSS"]
let nestedArray = [1, 2, 3, ["Html", "JS"]];


const numberToString = number.toString()
const stringToString = string.toString()
const booleanToString = boolean.toString()
const arrayToString = array.toString()
const mixedToString = mixedArray.toString()
const nestedToString = nestedArray.toString()


console.log(typeof numberToString)
console.log(typeof stringToString)
console.log(typeof booleanToString)
console.log(typeof arrayToString)
console.log(typeof mixedToString)
console.log(typeof nestedToString)

console.log(numberToString)
console.log(stringToString)
console.log(booleanToString)
console.log(arrayToString)
console.log(mixedToString)
console.log(nestedToString)
```

## Output - 
```
string
string
string
string
string
string
12345
Javascript
true
1,2,3
1,2,3,HTML,CSS
1,2,3,Html,JS
```

* As you can see we have converted the array,number,strings and booleans to string.

## Exceptions - 
```js
const Null = null
const Undefined = undefined
const object = {name:"shubham",age:21}


const undefinedToString = Undefined.toString()
const nullToString = Null.toString()
const objectToString = object.toString()

console.log(objectToString)
```

## Output - 
```
TypeError: Cannot read properties of undefined (reading 'toString')
TypeError: Cannot read properties of null(reading 'toString')
[object Object]
```

* As you can see it can't read the undefined and null.
* For the object , it returns the [object,object] because it is the default string representation of object datatype.To solve this ,we will use another method which is JSON.stringify().

## JSON.stringify() - 
```js
const object = {name:"shubham",age:21}
const objectToString = JSON.stringify(object)
console.log(objectToString)
```

## Output - 
```
{"name":"shubham","age":21}
```

* Now it returns the string representation of our object.

## Using in comparison - 
```js
const number = 12345;
const string = "12345";

const compare = number === string;
//false due to different datatype
const compare = number.toString() === string;
//true due to same datatype
```

* You can see we can convert the number to string and then compare with strict equality operator and it returned true due to same datatype

THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo

https://dev.to/shubhamtiwari909/e-quotes-3bng

https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl
How to convert Firestore ServerTimestamp to Date in firebase v9?
Published: 2022-08-18 18:03:00


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

```
import { getFirestore,serverTimestamp} from "firebase/firestore";
//
const newTimeStamp=Timestamp.now();
```

For the format to be understandable for the user we have to do a conversion.

```
    const ConvertDate= (d) => {
        const newDate = new Date(d.seconds*1000)
        return newDate.toLocaleString();
      }
```
When we want to get the format we just call this function done with javascript

```
const normalformat=ConvertDate(newTimeStamp);
```
Result
print 17/8/2022, 10:45:33

or 

```
const newTimeStamp=Timestamp.now().toMillis();
const newDat=ConvertDate2(newTimeStamp);
    const ConvertDate2= (d) => {
        const newDate = new Date(d)
        return newDate.toLocaleString();
      }
```
CSS POSITION PROPERTY
Tags: css, webdev, html, 100daysofcode
Published: 2022-08-18 18:03:00





**What is POSITION PROPERTY in CSS ❓**

➡️ The `Position Property` in Css  is used to determine where an HTML element will appear in an HTML document.


<u>Position property has five(5) different values which are 👇</u>

> •STATIC
•RELATIVE 
•ABSOLUTE 
•FIXED
•STICKY

![values of Position property](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/prz3ag87sfiy0p028ove.png)

1️⃣ <u>POSITION STATIC</u>

👉 All HTML page elements are <u>Static</u> by nature and they are displayed just as they appeared during the normal flow of the document.

> <u>Normal</u> flow of HTML elements are displayed from LEFT ⬅️ to RIGHT ➡️ /TOP ⬆️  to DOWN ⬇️  order, in the browser window💻.


- 
Just as their name implies `"STATIC"`  This Element cannot be moved or controlled, and it is unaffected by the <u>TOP</u>, <u>BOTTOM</u>, <u>LEFT</u>, <u>RIGHT</u>, and <u>Z-INDEX</u> properties.

![Static Position](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/os4fjwcowexly6ft5zbf.png)

2️⃣ <u>POSITION RELATIVE</u>

👉 Position Relative automatically changed HTML elements from their Static, which is  the (default) state to a dynamic state.

- 
Here, using TOP, BOTTOM, RIGHT and
 Z-INDEX properties is totally acceptable.

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

> Position Relative allows any HTML element to be moved from its current state to any other portion of the page.

3️⃣ <u>POSITION ABSOLUTE</u>

👉 The Position Absolute placed  HTML elements in relation to the edges of it's first Positioned **ancestor** or the edges of the browser.

**What is ancestor in CSS**❓

An **ancestor** is just the <u>parent</u>, <u>grandparent</u>, or <u>great-grandparent</u> of an HTML tag up to the root

> 👉 NOTE: HTML elements are positioned in relation to the edges of the browser's view port **if**  position ancestor is not defined.


![Absolute Position](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uws7i9nsxcfhfydtka1i.png)

4️⃣ <u>POSITION FIXED</u>

👉 Position Fixed is used to pinned or fixed an HTML element to the edges of the browser's view port

▪︎Fixed position always maintained its state and it is not affected by scrolling.


![fixed position](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/io4kjxpwrhdb5eetzn94.png)

👉 **Hint**:  whenever Position is set to <u>Fixed</u>,two things✌ are certain


- 
The element is taking away from its normal position.


- 
The element is automatically converted from block element to inline-block.

> An **Inline-block** lost it’s 100% width by default as the width is set to auto depending on the length of the content inside of it.

5️⃣ <u>POSITION STICKY</u>

👉 Position sticky is used to position and stick an HTML element in relation to the edges of the browser view ports.

- **Position sticky** is treated as `relative` until the scroll location reaches a particular point at which it takes a `fixed position`.

![sticky position](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wprj8mv2vn4vhnoq9wy1.png)
Remove Vietnamese characters form string in JS
Tags: javascript, unicode, vietnamese
Published: 2022-08-18 16:57:37

---
title: Remove Vietnamese characters form string in JS
published: true
description: Sometime, i need get a string with only latin characters (format url, slug, seo), no difference accents/diacritics!
tags: javascript, unicode, vietnamese
---

```javascript
    function _formatString(str) {
      str = str.toLowerCase();
      str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a");
      str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e");
      str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i");
      str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o");
      str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u");
      str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y");
      str = str.replace(/đ/g, "d");
      return str;
    }
```
Working with v-model in Vue 3
Tags: vue, javascript, typescript
Published: 2022-08-18 16:45:38

In this post I will show you'll how to work with v-model in Vue 3 + Composition API using `<script setup>` on **custom components**, there's few ways to work with it, let's take a look!

First of all we always need to create an custom prop and emit  for parent component:

**1 - Creating modelValue prop and update emit (child component)**

```javascript
<script setup>
defineProps({
  modelValue: String
});

let emit = defineEmits(['update:modelValue']);
</script>
```

> **Note**: '**update:modelValue**' can't be changed on next steps, otherwise the emit event wont work.

**2 - Firing the emit event (child component)**

In this case I will use an textarea to do it, but you can use with an input too.

```javascript
<template>
  <textarea
    @keyup="emit('update:modelValue', $event.target.value)"
    v-text="modelValue" 
  />
</template>
```

**3 - Using your custom component (parent component)**

Now you can call your custom component and pass a v-model.

```javascript
<MyFancyTextArea v-model="comment" />
```

## Usage with Typescript

For use v-model w/ Typescript is very simple, look the example below:

```javascript
<script setup lang="ts">
defineProps<{
  modelValue: string,
}>()

const emit = defineEmits<{
    (event: 'update:modelValue', payload: string): void;
}>();
</script>
    
<template>
  <input
    @input="emit('update:modelValue', ($event.target as HTMLInputElement).value)"
  />
</template>
```

That's it!

If you want to read and learn more details about v-model usage, please make sure to visit the [Vue 3 official documentation about it](https://vuejs.org/guide/components/events.html#usage-with-v-model).

**See'ya!**

---

**<u>References for this post:</u>**
https://blog.q-bit.me/an-introduction-to-vue-3-typescript-component-properties-and-events/
https://vuejs.org/guide/components/events.html#usage-with-v-model
advanced enhanced-text: glossary mode
Published: 2022-08-18 16:38:29

In the previous article I wrote about how the enhanced-text element works by taking in it's light dom, using the attributes selected to then send off to the end point. It also covered progressive enhancement, loading status and fail over.

In this article let's assume that's all there but focus on a complex replacement function that has the following requirements:
- We want to define key words in bodies of text
- Our content authors don't want to write the definition every time
- Our content authors don't want to maintain or form these references

To solve this challenge we start getting into a very implementation specific solution. This illustrates that enhanced-text can be both general purpose (vide-text) as well as highly specific to a platform (HAXcms) via the attributes we leverage.

## Building the glossary
Did you know what the `dl`, `dt`, and `dd` tags do? What, you don't use them every day?! Me neither. But [these tags semantically inform the description list](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl). Think of it as HTML that's able to say "this is a series of terms and definitions related to a topic". Hiiiiiighly specific, so much so I never used it previously in 15+ years, however it's exactly what we need for building a glossary.

Here's the page leveraged to read terms off of: [EdTechJoker Example Glossary](https://oer.hax.psu.edu/bto108/sites/edtechjoker/glossary).

```html
<dl>
  <dt>Bill</dt>
  <dd>Eating Panera</dd>
  
  <dt>Coffee</dt>
  <dd>Black hot drink</dd>
  
  <dt>Milk</dt>
  <dd>Thing I am intolerant of</dd>
     
  <dt>Watchdogs</dt>
  <dd>awesome video game series</dd>
  
  <dt>Design</dt>
  <dd>A word that is constantly over defined</dd>
</dl>
```
Now obviously this is just for demonstration purposes but we are shooting to roll this out very soon as an option for courses that want to do this in context (the key will be how it's eventually visualized via requirements / discussion).

## The video 
I'll do another video once I do that as this implementation methodology is mostly proof of concept and early UX feedback suggests we'd rather have a tab that lists all the terms as opposed to replace them in context.

This video will go over:
- the general idea
- an example of how the backend and frontend work together to achieve the goal
- show how the wikipedia attribute can help mix additional context into results

{% embed https://www.youtube.com/watch?v=4yG27gBhu9I %}
Docker tipo VMware
Published: 2022-08-18 16:36:29

Boas ... não sei se estou escrevendo no lugar certo, mas vou descrever o que preciso.
como criar uma imagem docker tipo VMware ... reinicio o servidor e a imagem única com toda configuração feita de uma única vez.
cada vez que subo a imagem o BD some ... os dados somem ela volta vazia.
sem contar que não carrega automático tem logar no servidor e dar RUM -IT pra imagem subir.
simplificando, VMware continua sendo muito melhor ou se puderem me ajuda a entender, porque ate o momento não entendi nada, melhor não vi nenhum proposito real.
Criar uma imagem entrar no container instalar o que preciso (uma única vez) e ao reiniciar o servidor a sobe junto com todos os dados.
Agradeço, que puder ajudar a entender.(ao meu ver, Docker muita publicidade pra pouca eficiência).
IntelliJ-IDEA as git mergetool
Tags: todayilearned, git, java, tooling
Published: 2022-08-18 15:43:00

The [`git mergetool`](https://www.git-scm.com/docs/git-mergetool) command allows you to resolve merge conflicts from your command line. Many merge tools are available like `vimdiff`, which helps you resolve the conflicts without leaving your terminal. But of course, there are also merge tools available that open in a separate window to resolve the conflicts, like `opendiff`, `meld`, `kdiff3`, and many more. You can run [`git mergetool --tool-help`](https://www.git-scm.com/docs/git-mergetool#Documentation/git-mergetool.txt---tool-help) to see which ones are available to you.

For Java devs, IntelliJ-IDEA's 3-way merge tool provides much more comfort compared to these other merge tools. One reason is syntax highlighting, but it also seems to understand the conflicts. Often it can merge the changes automatically. Yet, I've always found it a hassle to move between my terminal and IDE.

Today, all that changed when I discovered that it's possible to [merge files from the command line](https://www.jetbrains.com/help/idea/command-line-merge-tool.html). So, after reading the git manual in some more detail, I added the following to my git config (i.e. `git config --global --edit`):

```
[merge]
	tool = idea
[mergetool "idea"]
	cmd = idea merge $LOCAL $REMOTE $BASE $MERGED
	trustExitCode = false
```

Now, when I run into conflicts, I type `git mergetool` and IntelliJ-IDEA opens a 3-way merge window. :rocket:

> **Not on macOS?**
> The config above works for macOS, on another OS you need to adjust the configuration using the OS-specifics from the [merge files from the command line](https://www.jetbrains.com/help/idea/command-line-merge-tool.html) documentation.

> **What are those `*.orig` files?**
> The merge tool creates some `*.orig` files that stay around after resolving the conflicts. These are backup files that can be safely removed after a successful merge, or used to undo your conflict resolution. You can control these backup files with [`mergetool.keepBackup`](https://www.git-scm.com/docs/git-mergetool#Documentation/git-mergetool.txt-mergetoolkeepBackup).

I don't regularly blog, and I'm not a native English speaker. But, I hope you found this post useful. Please reach out, if you have any tips on how I could improve. Of course, I'd also love to hear about it if you liked my post.

Thanks for reading :heart:
Measure latency for embedded systems with Luos
Tags: opensource, microservices, redhat, luos
Published: 2022-08-18 16:28:45

We recently wrote an article about measuring latency in embedded systems in both soft and hard use cases in opensource.com.

⏩ https://opensource.com/article/22/8/measure-latency-edge-luos?sc_cid=7016000000127ECAAY

By evaluating latency, Luos manages timelines without synchronization on multiple nodes.

Many thanks to the opensource(.)com team, Glenn and Joe from Eckert comms

Writer: Nicolas Rabault
Go snippet for creating an Ingress rule
Tags: kubernetes, go
Published: 2022-08-18 16:16:00

You probably need to migrate to apiVersion `networking.k8s.io/v1` for your Ingress rules (given that after Kubernetes 1.22, the old apiVersion `extensions/v1beta1` and `networking.k8s.io/v1beta1` will simply disappear). If you are managing your Ingress rules through Go, here is a snippet to generate a valid Ingress rule if that can help you (I struggled a little to find the correct template so I am sharing this post).

Please let me know it this snippet was useful or if you see some improvements that we can make to it.

Have a great day!

```
import (
	v1Networking "k8s.io/api/networking/v1"
    v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func MapIngress(ingressName string, hostName string) *v1Networking.Ingress {

	annotations := map[string]string{}
	annotations["kubernetes.io/ingress.provider"] = "nginx"
	annotations["kubernetes.io/ingress.class"] = "yourIngressClass"
	annotations["kubernetes.io/tls-acme"] = "true"
	// add other annotations you need

	meta := v1.ObjectMeta{
		Name:        ingressName,
		Annotations: annotations,
	}

    pathTypeImplementationSpecific := v1Networking.PathTypeImplementationSpecific

	return &v1Networking.Ingress{
		ObjectMeta: meta,
		Spec: v1Networking.IngressSpec{
			TLS: []v1Networking.IngressTLS{
		v1Networking.IngressTLS{
			Hosts:      []string{hostName},
			SecretName: "yourSecretName",
		},
			Rules: []v1Networking.IngressRule{
				v1Networking.IngressRule{
					Host: hostName,
					IngressRuleValue: v1Networking.IngressRuleValue{
						HTTP: &v1Networking.HTTPIngressRuleValue{
							Paths: []v1Networking.HTTPIngressPath{
								v1Networking.HTTPIngressPath{
									Path: "/",
									PathType: &pathTypeImplementationSpecific,
									Backend: v1Networking.IngressBackend{
									    Service: &v1Networking.IngressServiceBackend{
									        Name: "yourServiceName",
									        Port: v1Networking.ServiceBackendPort{
									            Number: 80,
									        },
									    },
									},
							    },
							},
						},
					},
				},
			},
		},
	}
}
```
Creating Websocket servers and clients in Nodejs
Tags: node, websocket, javascript, npm
Published: 2022-08-18 16:11:25

## 1. Websocket server example

```js
const WebSocketServer = require('ws');
const wss = new WebSocketServer.Server({ port: 8111 })

wss.on("connection", (ws,r) => {
  ws.on("message", data => {
    ws.send('You sent me: ' + data);
  });
  
  ws.on("close", () => { });
  ws.onerror = function () { };
});
```

- `require('ws')` - import [ws lib](https://www.npmjs.com/package/ws) to create websocket server,
- `new WebSocketServer.Server` - create and launch websocket server with params,
- `port:` - port to listen on (in our case all network interfaces are going to be listened),
- `wss.on("connection"` - what to do when someone connects to our server,
- `ws.on("message"` - what to do when we've received a message from client,
- `ws.send(` - send a message to client,
- `ws.on("close"` - what to do when client closes connection,
- `ws.onerror` - set custom error handler.

[Open original](https://onelinerhub.com/nodejs/websocket-server-example) or [edit on Github](https://github.com/Onelinerhub/onelinerhub/tree/main/nodejs/websocket-server-example.md).

## 2. Websocket client example

```js
let ws = require('websocket');
let wsc = new ws.client;

wsc.on('connect', function(connection) {
  connection.sendUTF('Hello');

  connection.on('message', function(message) {
    console.log("Received: " + message.utf8Data);
    // connection.close();
  });
});

wsc.connect('ws://echoof.me:8111/');
```

- `require('websocket')` - import [websocket lib](https://www.npmjs.com/package/websocket) to create websocket client,
- `new ws.client` - create new websocket client object,
- `wsc.on('connect'` - specify what to do when client gets connected to websocket server,
- `connection.sendUTF` - send message to server,
- `connection.on('message'` - specify what to do when client received message from server,
- `connection.close()` - close connection (and exit),
- `wsc.connect` - connect to websocket server,
- `echoof.me:8111` - public [echo websocket server](https://echoof.me/).

[Open original](https://onelinerhub.com/nodejs/websocket-client-example) or [edit on Github](https://github.com/Onelinerhub/onelinerhub/tree/main/nodejs/websocket-client-example.md).
What do you think of ASP.net core minimal apis?
Tags: dotnet, webdev, api, discuss
Published: 2022-08-18 16:04:43

I’ve been working with asp.net core since dotnet core 2.2. Wrote many different services with it.
Lately I’ve been trying out the “new” minimal apis and I’m very happy about them. What’s your opinion?

By the way:
There is a great video from Nick Chapsas about how to get started: https://m.youtube.com/watch?v=eRJFNGIsJEo
Create Linux Ubuntu 22.04 Desktop Shortcut
Tags: linux, ubuntu
Published: 2022-08-18 15:46:54

It is super simple, you just need to follow these steps.

```
In this example I was trying to add PyCharm IDE shortcut to desktop
```
<ol>

 <li>
  Create a text file
 </li>

 <li>
  <p>Add the following content</p>
  <code language="bash">
  #!/usr/bin/env xdg-open <br />
  [Desktop Entry] <br />
  Version=2022.3 <br />
  Exec=/home/user/IDES/PyCharm/bin/pycharm.sh <br />
  Icon=/home/user/IDES/PyCharm/bin/pycharm.svg <br />
  Name=PyCharm <br />
  GenericName=PyCharm <br />
  Comment=Develop JavaScript Applications <br />
  Encoding=UTF-8 <br />
  Terminal=false <br />
  Type=Application <br />
  Categories=Application;IDE; <br />
  </code>
 </li>

 <li>
  Change the extension to `.desktop`
 </li>

 <li>
  Move it to desktop
 </li>

 <li>
  If all the links `Exec` and `Icon` are correct when right 
  clicking on the file, you should be able to see `Allow 
  Launching` and by clicking on it, the shortcut is complete 
  and usable.
 </li>
</ol>
Como conectarse a (LocalDb)\MSSQLLocalDB con DBeaver
Published: 2022-08-18 15:44:41

Recientemente descubrí una gran herramienta para manejar bases de datos llamada [dbeaver](https://dbeaver.io/) pero no lograba conectarme con la instancia de SQL Server Express LocalDB que crea visual studio por defecto. Buscando un poco encontré un [issue en github](https://github.com/dbeaver/dbeaver/issues/2959) que entre tantas respuestas hubo una que me solucionó el problema así que se las comparto.

## Paso 1

Nota: Creo que DBeaver va a descargar cualquier driver necesario si es que no lo tienen, así que prueben a conectarse sin hacer esto primero.

Primero verifiquen que tienen el controlador ODBC de SQL Server instalado. Para eso van a (lo pongo en inglés porque no se como está puesto en las verisones de español del windows) Windows Control Panel >> Administrative Tools >> ODBC Data Sources (x64) >> "Drivers" Tab. Si no tenés el driver, podés descargarlo acá: https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver15
Debería aparecer algo así:

![Paso 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/icnst2e1k3pld12t4p3e.png)

## Paso 2

Una vez que tengas el controlador ODBC, vas a DBeaver y creás una nueva conexión eligiendo la opción "ODBC"

![Paso 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ac5ickolynll8cbjql6e.png) 

## Paso 3

Escribí la connection string de la siguiente manera. Asegurate de cambiar el número de versión del controlador ODBC por el que tengas instalado, y muy importante **El nombre de la base es case sensitive, yo por ejemplo tuve que poner (localdb)\MSSQLLocalDB para que me ande**:

`Driver={ODBC Driver 17 for SQL Server};Server=(localdb)\MSSQLLocalDB`

![Paso 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0uefs08p6n2oo34hq2ry.png)

Hacen clic en "Probar conexión" y vean de que funcione. 

Espero que les haya servido.

Source: [github.com/dbeaver/dbeaver/issues/2959](https://github.com/dbeaver/dbeaver/issues/2959)