teleren/devto huggingface dataset:
CometChat Offline Support in React Native
Tags: reactnative, cometchat, cache, offline
Published: 2022-06-25 14:37:00

When you building mobile chat app you definitely want keep your app usable while phone offline or with poor internet connection. [Offline Chat Support](https://feedback.cometchat.com/sdks-apis/p/offline-chat-support) is actually top voted feature request for CometChat Sdks. Unfortunately it's not there yet, but luckily there is undocumented functionality which allow you to implement it yourself. 

Basically what we need is to store CometChat.BaseMessage as JSON string and restore message from this string back.

There is `getRawMessage` which return the raw JSON of the message. So to store array of the messages per group to some local storage we will do following
```typescript
const setMessages = (groupId: string, messages: CometChat.BaseMessage[]) => {
    const rawMessages = messages.map(msg => msg.getRawMessage());
    const serialised = JSON.stringify(rawMessages);
    storage.set(groupId, serialised);
}

```

And to restore message back we can use `CometChatHelper` and it's method `processMessage` which takes rawMessage data and return instance of `TextMessage | MediaMessage | CustomMessage | BaseMessage`. So to get array of messages from storage back we have to do something like this 
```typescript
const getMessages = (groupId: string) => {
    const serialisedMessages = storage.getString(groupId);
    if (serialisedMessages) {
      const rawMessages = JSON.parse(serialisedMessages) as string[];
      return Promise.all(
        rawMessages.map(rawMsg =>
          CometChat.CometChatHelper.processMessage(rawMsg),
        ),
      );
    }
},
```

Here is my implementation of `MessagesStorage` with [react-native-mmkv](https://github.com/mrousavy/react-native-mmkv). 

```typescript
import {MMKV} from 'react-native-mmkv';
import {CometChat} from '@cometchat-pro/react-native-chat';

const storage = new MMKV({
  id: 'mmkv-messages-storage',
});

export const MessagesStorage = {
  setMessages: (groupId: string, messages: CometChat.BaseMessage[]) => {
    const rawMessages = messages.map(msg => msg.getRawMessage());
    const serialised = JSON.stringify(rawMessages);
    storage.set(groupId, serialised);
  },

  getMessages: (groupId: string) => {
    const serialisedMessages = storage.getString(groupId);
    if (serialisedMessages) {
      const rawMessages = JSON.parse(serialisedMessages) as string[];
      return Promise.all(
        rawMessages.map(rawMsg =>
          CometChat.CometChatHelper.processMessage(rawMsg),
        ),
      );
    }
  },
};
```

Now you can enjoy of opening your chat screen with immediate list of messages cached from previous chat open.
Identify Where you are Uncomfortable and Lean into it
Tags: discuss, beginners, programming, webdev
Published: 2022-06-25 13:52:56

It took me two months to open a JSON file. I didn’t know anything about them and every time they came up at work I would avoid being involved in the conversation. I had a mental block that came up every time I heard someone say “check the JSON” file. It wasn’t until I accidentally opened one that I realized how simple they were. I can’t believe it took me that long to even try to learn what they were *facepalm*.

The real lesson here is that avoiding a topic because it makes you uncomfortable can hinder your progression. The sooner you lean into what makes you uncomfortable, the faster you will grow as a software engineer. As they say at Replit: “seek pain”.

Anyone else have a similar experience? 

### Join the community

Looking for a study partner? Hackpack is the most active community of engineers studying for programming interviews. We hold each other accountable, provide support, and fight burnout to study more efficiently and get the job faster.

Apply [Here](https://www.hackpack.io/) 

[Events](https://discord.gg/VQkMr234zk?event=970275330294153257) | [Youtube](https://www.youtube.com/channel/UCfotE5RL1pfhIZ0fv2kAN9Q) | [Twitter](https://twitter.com/hackpack_) | [LinkedIn](https://www.linkedin.com/company/hackpack-io/?viewAsMember=true) | [Newsletter](https://fangprep.substack.com/)
My tech stack
Tags: trafik, webdev, devops
Published: 2022-06-25 13:51:23

## What is a Tech stack?
Tech stack is essentially a curated list of technologies used to build, run and manage applications.

I am very comfortable to use:
- Java/Spring Boot
- Node.js/Express.js
- Vue.js
- Flutter
- Docker
- PostgreSQL
- MySQL
- Python, with google of course, take the internet away, I'm not a python developer :stuck_out_tongue_closed_eyes:  
- Bash scripting
- GitHub/GitLab

### Servers/Routing/Hosting
I prefer [digital ocean](https://www.digitalocean.com) , as of writing this I am currently using the 2GB droplet.

I have docker setup on the droplet,  this allows me to run my applications as docker containers. 

To manage all the traffic and routing, I use [traefik](https://traefik.io). A very easy to setup reverse proxy. I hope to write a post on how to set it up.

Upon signing up on digital ocean, you get a public IP address to your server, something like `216.58.223.142`, That is so hard to remember, now to link that up with my [domain](https://mmontshengmaoto.dev). I bought the domain through Google domains and transferred it to Cloudflare and manange it from there. This allows me to create create a DNS entry for the IP I got from Digital Ocean.

I love CI/CD, so GitLab was my go to, I use their CI/CD tools, basically create a file, `.gitlab-ci.yml` with a list of jobs/steps amongst other things. In a nutshell, CI/CD involves automated testing and release/deploying of source code to users. 
I will write more about this.


That's about it my tech stack.
Selectors Family in Recoil for Statement Management — Nextjs
Tags: nextjs, recoil, statemanagement
Published: 2022-06-25 13:46:39

Welcome friends. This blog post will teach you how to use the recoil selectors family for state management.

Video for those who understand **Hindi:**
{% embed https://youtu.be/GJUq2PkGJWs %}
[How to use atoms in Recoil](https://medium.com/@nextdevelopment1111/recoil-state-management-in-nextjs-4d1cb371470a)
[How to use Selectors in Recoil](https://medium.com/@nextdevelopment1111/how-to-use-recoil-selectors-in-nextjs-81727c54b401)

### 🤯Selectors vs SelectorFamily

When you use selectors, you **cannot **pass any parameters for doing some logical work. But when you use selectors Family, you can pass a param and can have a logic.

Example 👇

### 🤔Situation

Suppose, you have a to-do list website.

Example of the website:

![](https://cdn-images-1.medium.com/max/3840/1*MqIDulLmwB5nwO4ZC5zJIQ.jpeg)

**In simple words, **you enter the id of a todo that you want to edit. Then using the recoil selector family, we can get the data of **specific **todo by passing id as a param.

Then you have made the **atoms **for it 👇.
{% gist https://gist.github.com/studywithdesign/8d96a64ab756b84dc9b530f8a3ecd88a.js %}
Index.tsx file 👇
{% gist https://gist.github.com/studywithdesign/36918d9fd144e2ba17539093184dec92.js %}
This is your **selectors **file.
{% gist https://gist.github.com/studywithdesign/f7491373d8224a5b973bf116bd589b28.js %}
Now, let’s go to box.tsx file 👇
{% gist https://gist.github.com/studywithdesign/c27bedd459d2391dbdb0682b61b166d2.js %}
Still any doubt 🤔. You can join our discord channel👇
[**Join the Next Dev Discord Server!**](https://discord.gg/hN4Wc5VR4M)
Generando Video Sintesis, "Software Defined Video" con ShotCut HTML
Tags: video, html, css, javascript
Published: 2022-06-25 13:43:15

Video definido por software. 

La base para la video sintesis definida por software es conectar html css y javascript en forma de filtro a un editor de video, existia ya eso en ShotCut pero la capacidad fue removida, no quiero pensar mal, pero asi fue. la función suprimida era "shotcut html overlay filter", la última vez que se vio funcionando es en la version 20.07.11 bajo el nombre de "Text:HTML", después de esa version fue suprimida por una alerta de seguridad.

Ahora bien, se que la capacidad existe en OBS, el famoso streamer open source y por supuesto su hermano gemelo ya mas avanzado el OBS Mediastreamer, el problema es que ahi estamos restringidos en resolución por que nos limitaría nuestro hardware, la maxima resolucion de nuestra pantalla y el poder de nuestro CPU y para video arte desde el sur, eso no nos funciona.

La gran ventaja de la sintesis de video definida por software es que con el hardware mas anticuado podemos generar renderear animaciones con mucha resolución y muchos cuadros por segundo, es viable, si ya se que tiene uno que esperar mucho tiempo de rendereado, pero aca estamos hablando de videos cortos.

Aqui en la siguiente link, hay un ejemplo de muestra, se usa camvas para recortar un video en forma circular, esta en mltframework con webvfx, me queda duda si esto todavia funciona en las versiones actuales de shotcut. 

https://www.mltframework.org/doxygen/webvfx/examples_2filter-demo_8html-example.html

SI TE URGE AGREGAR EFECTOS CREADOS CON WEB HTML CSS JAVSCRITP, DESCARGA LA VERSION VIEJA DE SHOTCUT  20.07.11 USA EL FILTRO TEXT:HTML (DEPRECATED)... Y SIGUE LOS PASOS AQUI: 


https://forum.shotcut.org/t/where-is-the-overlay-filter/546

---

## Experimentos futuros:


Se me ocurre hacer un software que genere XML MTL que sean compatibles con shotcut para procesar video automaticamente

https://shotcut.org/notes/mltxml-annotations/

En el tema de recrear un filtro overlay html, Aqui hay un ejemplo de un html para generar un filtro webvfx:

https://www.mltframework.org/doxygen/webvfx/examples_2filter-demo_8html-example.html

y aqui un par de pens para animaciones en video en codepen
https://codepen.io/augs0/pen/RXNgEB
https://codepen.io/yemon/pen/pWoROm

Tambien planeo hacer estos experimentos para convertir animación css3 a elusien de forma automática.

https://nmihaylov.medium.com/an-easy-way-to-use-css3-animations-in-shotcut-44594f8be114


---
## Links relacionados.

https://www.mltframework.org/

https://www.mltframework.org/doxygen/webvfx/examples_2transition-demo_8html-example.html

https://blog.wang-lu.com/2019/10/chromevfx-prototype.html?m=1

https://webvfx.rectalogic.com/effects_authoring.html
AWS profile chooser
Published: 2022-06-25 13:37:17

Super short AWS hint.

Having different AWS profiles, I do not want to pick default one just because I forgot `--profile` command line option.

Just looking for a way of forcing me having to choose an AWS profile before issuing any command.

My solution was (for bash only):

1. Removing default profile in ~/.aws/credentials
No command will work from now on without a `--profile` or an AWS_PROFILE environment variable

2. Creating a one-liner alias for choosing the desired profile and setting $AWS_PROFILE environment variable.  
An alias let me reuse the same shell I'm in.

```sh
alias aws-profile-chooser='x() { select prof in $( aws configure list-profiles ) ; do  export AWS_PROFILE="$prof"; break; done }; x'
```

(you can see the [gist here](https://gist.github.com/andreav/b5188a8640a9e612d39bc52743abab99))

This command will show me available profiles, and after choosing the right one, it will set AWS_PROFILE environment variable.

```sh
$ aws-profile-choose 
1) default
2) amplify-udemy
3) aws-lambda-deploy
4) test-aws
#?
```

From now on if I forget to choose a profile, any command will break.

Choosing and setting an AWS profile...is now a breeze! ;)
JavaScript Clipboard API
Tags: javascript, webdev, programming, tutorial
Published: 2022-06-21 12:51:26

Hello everyone! In today's article i will talk about the Clipboard API in JavaScript.

So, what does this Clipboard API do?

As the name suggests, it responds to clipboard commands, such as cut, copy, paste!

Let me show you an example, then i will explain it to you!

Check the example below:

```javascript
navigator.clipboard.writeText("Hello").then(res => {
  alert("Copied to clipboard!");
}, rej => {
  alert("Could not copy to clipboard");
});

navigator.clipboard.readText().then(text => {
  console.log(text);
})
```

The code below copies the string "Hello" to the clipboard, then it logs the text in the clipboard to the console. We can use this API to write and read from the Clipboard, which makes the whole "Copied to clipboard!" buttons incredibly easy.

Obviously that is not the only thing we can do. Clipboards can be used to do a lot of stuff, even copy images.

But on some browsers that functionality is not that great, so i suggest you check the compatibility table as always: [Clipboard API Browser Compatibility](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API#browser_compatibility)

We can use the Clipboard API to get data other than strings, as i said before, and this is done like the example below:

```javascript
const copyImageToClipboard = async () => {
  const response = await fetch("path/to/the/image");
  const blob = await response.blob();
  await navigator.clipboard.write([
    new ClipboardItem({"image/png": blob})
  ]);
};
```

In the example above we fetched the image from the path of wherever the image is, then we made it into a blob, and we wrote it to the clipboard as a new ClipboardItem instance.

And obviously then we can read those items by writing the code below:

```javascript
const readClipboard = async () => {
  const items = await navigator.clipboard.read();

  return items;
}
```

But like i said, the browser support for this API can still be a problem. So always check MDN for the browser compatibility issues!

That's it for today's article, if there are any problems and issues in my post, please don't forget to tell me about them in the comments!

Have a great day everyone!
[ECS] Service launch Error - "the role being passed has the proper trust relationship and permissions"?
Tags: terraform, ecs, aws
Published: 2022-06-25 13:17:48

# Error

I got the following error when applied terraform.

```
service xxxxx failed to launch a task with (error ECS was unable to assume the role 'xxxxx' that was provided for this task. Please verify that the role being passed has the proper trust relationship and permissions and that your IAM user has permissions to pass this role.).
```

# How to fix

Added the `assign_public_ip` in terraform

```hcl
resource "aws_ecs_service" "ecs" {
  name = var.ecs_service_name
  cluster = var.ecs_cluster_name
  launch_type = "FARGATE"
  desired_count = "1"
  task_definition = xxxxx

  network_configuration {
    subnets         = [xxxxx]
    security_groups = [xxxxx]

    # NEW
    assign_public_ip = true
  }
}
```
Script tag integrity attribute
Tags: html, javascript, security
Published: 2022-06-25 12:55:36

We know that when a website is opened it loads the javascript file in the browser. Most of them are served from CDN servers. 

### Issue

Suppose one of the CDN server for that website is hacked and the hacker has added some malicious code in one of the JS file, then the client will be at risk of exposing sensitive information to the hacker.

So how to prevent this from happening ?
How browser will know that this JS file is a malicious or tampered one ? 

### Solution

To address this problem, most of the browsers have started supporting a new attribute in script tag called `integrity` attribute.

Example:

```html
<script src="main.js" type="text/javascript" integrity="sha265-XU3HpWw3sNnYKqNWosvZyNN7HMyCOJGOrf1t5CLuuBc=" ></>
```

There are two parts to the `integrity` attribute, first part is the algorithm (`sha256` or `sha384` etc.) and second part is the `hash` generated by the algorithm

`integrity="{algorithm}-{hash}"`

### How to generate this hash ?

Basically this `hash` is not any random string, it is generated against the JS file. This hash is different for different JS files. The `hash` for the JS file can be generated by using the command below.

Command:
`shasum -b -a 265 main.js | awk '{ print $1 }' | xxd -r -p | base64`

The output of this command is appended to the integrity attribute in the script tag. It will generate a new `hash` every time the JS file is updated.

In real time development we do not have to generate the `hash` manually. Most of the modern bundlers like `webpack` or `rollup`, now a days are supporting generation of `hash` for JS files and append it to the related script tag.

### How does the browser validate ?

When browser is done with downloading the JS file, it uses the same algorithm (`sha256` or `sha384`) to generate the `hash` for the same file.
Now browser will compare between the `hash` generated by it and the `hash` present in the integrity attribute.
If the comparison fails, then browser will not allow that JS file to execute.

![Script integrity attribute](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2rwgcx5aecdd9gm5xqgt.png)

This concept can be applied to any rest api, when we want to keep the integrity of the data between server and client.
[Discussion] Named routes vs file-based routes on frontend frameworks
Published: 2022-06-25 12:39:40

Hi guys, I wanted to know the community's thoughts on named routes on the frontend frameworks instead of the file system routing (like on NextJS or Nuxt). 

For those who are unaware, named routes is a common feature on backend frameworks (eg. Laravel, express), where you statically declare the routes, assign a name & have a specific handler for it. File based routing generates the app's route based on the files present in a designated folder (ie `/pages`)

-----

Personally, I think named routes is a much better development experience than file-based routing. My thoughts: 

- Consistent route generation tooling through named patterns. Eg.
  - declare the route: `route('/', 'home:index')`
  - Then, when generating the URL, you can: `route('home:index')`

- You don't manage URL strings directly, control is abstracted for query or parameter replacement.

- Clear view of the routes available to the app

- Extensible to other route-based logic inside the app (middleware & layout generation, etc)

-----

Not sure if this has been discussed, but would like to know your thoughts whether you agree to the same reasoning or have different opinion about this. Cheers
The stupidest mistake I have made.
Published: 2022-06-25 12:02:43

The stupidest mistake I have made. 



I work as a #software #engineer, and Version Control System(#VCS as we call it) is a basic part of my work life. 

One day there was a feature break due to some code that I had pushed(Thankfully it was on stage environment only).

My Tech lead asked me to revert the PR and deploy the older version via #CI/CD(#jenkins basically). 

It was the first time I was facing such an issue, I didn't know how to fix it, didn't even know how to revert the change on Git. 

So, I googled it(why? because, "Parampara, Pratishtha, Anushasan" - DEV thing) and also asked my senior what to do by explaining the situation I was into, and I found something about REVERT in GIT. Now that was something I have never used in life. 

So I created a PR to revert the changes which were causing the issue and I went on to check if everything works fine. 

and for some reason it was working fine, I was like, well done Jayesh, You did it(*I pat myself on the back if that matters*), and, yeah, the world was again safe for the human race to exist.



And I notify the team about the same, "Hey, guys don't worry, everything is under control."



I was not so stupid, right? 

but but but but... this was not the stupid part...(Hope your mind is not blown)

Somebody reported the same issue again... and I was like "How is this possible?", I have reverted the change.



Then my senior pointed out that we have to MERGE the revert PR to remove the change. Which I clearly hadn't merged yet, I had 

created PR and checked on stages if the issue still exists, and since I couldn't reproduce the issue, I thought it was resolved, I thought it was because of the REVERT PR that I just had created. (Yes, yes, there you go... all laughing... hahaha).


So, that was the stupidest mistake I made during the first few months of my career. 


and... THE END. The show is over, you can scroll yourself down to the next post.

.

.

.

.

.

.

**Credit scene rolling**

Oh, Yeah shared it, because, why not? 

If people can share about their achievements they also should share their mistakes, Right? 

Now these days we open LinkedIn, Instagram, or any other social media apps, People share (or brag) about their achievements(that's completely okay), but they also should share the incidences where they have made mistakes, they might have failed, fallen. So the person who's going through the same does not lose hope, does not feel like he/she is not enough, and that he/she is the one who makes mistakes/failed.
Slices in Go
Tags: beginners, slices, go, programming
Published: 2022-06-25 11:32:50

A slice is a data type in Go that represents a sequence of elements of the same type. But the more significant difference with arrays is that the size of a slice is dynamic, not fixed.

A slice has only three components:

- Pointer to the first reachable element of the underlying array. This element isn't necessarily the array's first element, array[0].
- Length of the slice. The number of elements in the slice.    
- Capacity of the slice. The number of elements between the start of the slice and the end of the underlying array.

![Go](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gi54300xdk0npk1h4gy3.png)

## Declare and initialize a slice

```
package main

import "fmt"

func main() {
    months := []string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
    fmt.Println(months)
    fmt.Println("Length:", len(months))
    fmt.Println("Capacity:", cap(months))
}
```

## Output

```

[January February March April May June July August September October November December]
Length: 12
Capacity: 12
```

Slice items

Go has support for the slice operator s[i:p], where:

**s** represents the array.
**i** represents the pointer to the first element of the underlying array (or another slice) to add to the new slice. The variable i corresponds to the element at index location i in the array, array[i]. Remember this element isn't necessarily the underlying array's first element, array[0].
**p** represents the number of elements in the underlying array to use when creating the new slice. The variable p corresponds to the last element in the underlying array that can be used in the new slice. The element at position p in the underlying array is found at the location **array[i+1]**. Notice that this element isn't necessarily the underlying array's last element, **array[len(array)-1].**

![Go](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xgcnno8cebea47g1jjfj.png)




```
package main

import "fmt"

func main() {
    months := []string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
    quarter1 := months[0:3]
    quarter2 := months[3:6]
    quarter3 := months[6:9]
    quarter4 := months[9:12]
    fmt.Println(quarter1, len(quarter1), cap(quarter1))
    fmt.Println(quarter2, len(quarter2), cap(quarter2))
    fmt.Println(quarter3, len(quarter3), cap(quarter3))
    fmt.Println(quarter4, len(quarter4), cap(quarter4))
} 
```

## Output
```
[January February March] 3 12
[April May June] 3 9
[July August September] 3 6
[October November December] 3 3
```