teleren/devto huggingface dataset:
Easily manage image type with sealed classes
Tags: kotlin, android, jetpackcompose
Published: 2021-11-30 15:06:58

---
title: Easily manage image type with sealed classes
published: true
description: 
tags: kotlin, android, jetpackcompose
cover_image: https://miro.medium.com/max/1400/0*bKqULqeOaMPzWHtr
---

This post was originally posted on [medium](https://5abhisheksaxena.medium.com/easily-manage-image-type-with-sealed-classes-4e361c6f4db9).

With the introduction of sealed classes in Kotlin, it opened up a way to easily handle restricted hierarchies.
The most common use case of a sealed class is with the handling `Result<T>` of an API response.

…..but there are way more applications of the sealed classes than you can imagine. I'll discuss one of them here, which would be to handle image type in android.
The source of the image can either be **remote**, i.e, a URL or **local storage**. Since the resource can come from only these two types, it makes a perfect use case for the sealed classes.

```kotlin
sealed class UiImage {
    data class LocalImage(val imageRes: Int) : UiImage()
    data class RemoteImage(val imageUrl: String) : UiImage()
}
```

You can use the Image everywhere in the project and easily refer to either of the two.

Example:
```kotlin
data class Student(
    val name: String,
    val profileImage: UiImage
)

fun main() {
    val abhishekSaxena = Student("Abhishek Saxena", UiImage.RemoteImage("https://remoteurl.com/images/sample.png"))
    val johnDoe = Student("John Doe", UiImage.LocalImage(R.drawable.default_profile_pic))
}
```

Additionally, you can easily load images with the image loading library like Glide
```kotlin
 fun ImageView.loadImage(
    image: UiImage
) {
    Glide.with(this.context)
        .load(
            when (image) {
                is UiImage.LocalImage -> image.imageRes
                is UiImage.RemoteImage -> image.imageUrl
            }
        )
        .into(this)
}
```

You can use it with **Jetpack Compose**.

You can create a composable that consumes a UiImage, that in-app code ends up being remote, but for previews, you can supply a drawable res, so I can see the full behavior

```kotlin
// Component
@Composable
fun UserProfile(
  profileImage: UiImage,
)

// In production
UserProfile(
  profileImage = UiImage.RemoteImage(avatarURL)
)

// In preview
@Preview
@Composable
fun UserProfilePreview() {
  UserProfile(
    profileImage = UiImage.LocalImage(R.drawable.preview_profile_image)
  )
}
```

## Conclusion
Kotlin sealed classes are really powerful when you have a strict hierarchy of classes. Herewith the images, you can even extend the usage to text as it can be directly passed as a string or as a reference of the string resource.

A special thanks to [Adam McNeilly](https://twitter.com/AdamMc331) for the feedback and suggestions.

Thank you very much for reading the article. I hope you liked it. Do you have any feedback? Comment below or reach out to me on [Twitter](https://twitter.com/abhisheks031).

###### Cover photo credits: 
Photo by Pablo Arroyo on Unsplash
Fun feature update
Tags: javascript, buildinpublic, webdev, gamedev
Published: 2021-11-30 14:59:47

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

Had too much coffee this morning and added a fun animated gesture feature to [flat.social](https://flat.social) - a fun video conferencing app that utilises [spatial](https://flat.social/spatial-chatting) audio & video to create an experience where attendees can move around and speak with others around them. The GIF with demo might load for a minute or two!

This work was done quite quickly - fortunately I found [davidfig/pixi-ease](https://github.com/davidfig/pixi-ease) on Github which made it much easier. 

How does it work?

1. User selected a gesture on the keyboard (each key from 1->7 is bound to a different gesture).
2. App picks it up and sends an event via socket.io to the server. The server picks it up, figures out who sent it and informs everyone in the same room that a gesture has been emitted.
3. Gesture event with associated playerId comes back to all of the clients connected to the room.
4. Particular animation is triggered on the body of the player using pixi-ease.

Would love to know what you think! Maybe virtual gestures could be a cool addition to this new [zoom alternative](https://flat.social/zoom-alternative) :)
Introduction to Ansible
Tags: ansible, automation, beginners
Published: 2021-11-24 08:22:27

Ansible is an [Open-Source](https://en.wikipedia.org/wiki/Open-source_software) IT automation engine which allows [provisioning](https://en.wikipedia.org/wiki/Provisioning), [configuration management](https://en.wikipedia.org/wiki/Software_configuration_management) and [application deployment](https://en.wikipedia.org/wiki/Application_deployment) tool enabling [infrastructure as code](https://en.wikipedia.org/wiki/Infrastructure_as_code)(Iac).

###Why Ansible?

At the beginning of the [network computing](https://en.wikipedia.org/wiki/Computer_network), system administrators managed servers manually. But the reliability and the efficiency of such practices were an issue. Eventually, data centres grew, the hosted applications in them became more complex and cumbersome to handle. Therefore doing complex configurations in thousands of servers manually was not efficient practice. Therefore IT personnel needed a tool to do these server configuration tasks effectively and efficiently. 
The tool that they came up with is **Ansible**.

###Why is this Popular?

There are indeed other tools that do the same as Ansible. If that is true, why do professionals use Ansible? There are several factors for that. Let's dive in 🐋,
* Ansible is simple and human-readable, which allows any user level to grasp it relatively quickly.
* Since Ansible is agentless, it does not stick to a platform.
* It's capable of handling tens of thousands of nodes at a time.
* More secure since it runs on SSH(on Linux)
* For provisioning, configuration management, orchestration, and deployment, there are different tools available. But Ansible can provide all these services by itself.  

###Ansible Terms
* **Controller Machine:** There server where Ansible is installed, This is responsible for provisioning.
* **Inventory:** This contains the information of the servers that are managed.
* **Module:** This is a reusable, standalone script that Ansible runs on your behalf locally or remotely.
* **Task:** Defines a single procedure to be executed.
* **Playbook:** Is the blueprint of automation tasks. Playbooks are written in YAML format.
* **Role:** A series of actions for configuring a host to perform a certain function, such as configuring a service. 
* **Play:** Execution of a playbook.
* **Facts:** Global variables which keep data gathered about target nodes.
* **Handlers:** Are special tasks which only get executed when triggered via the notify directive.
* **Ansible Tower:** Web-based interface to manage Ansible.

###Ansible Architecture

![Ansible Architecture Diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5mwkczc1yn04vo4an9yg.jpg)

Wanna know more?👇
###Useful Resources

* [Ansible Docs](https://docs.ansible.com/)
* [Wiki] (https://en.wikipedia.org/wiki/Ansible_(software))

---
Thanks for reading.. 🙌
SQL Injection Nedir?
Tags: cybersecurity, sql, linux, database
Published: 2021-11-30 14:58:07

> SQL injection nedir demeden önce SQL Nedir buna bakalım

**SQL Nedir?**
SQL Bir sorgulama dilidir. İlişkisel veritabanları ile etkileşime girmek için geliştirilmiştir.Veritabanındaki verilerde değiştirme,silme ekleme gibi bir çok etkileşimi SQL komutları ile yapabiliriz.MSSQL , MYSQL gibi veritabanı türleri SQL sorgu dilini kullanılır.

Örnek Bir SQL Sorgusu

```
SELECT * FROM Users where Username='Berkay' and Password='123456'
```
Bu SQL sorgusu veritabanındaki Users tablosundan **kullanıcı adı** “Berkay” ve **şifresi** “123456” olan kullanıcıların tüm bilgilerini getirir.

Biz bir sisteme login olurken de buna benzer komutlar arkaplanda çalışıyordur.Login olduğumuz formda ya da URL üzerinden bu arkaplanda çalışan sorguya müdahale edebiliriz.Tabii böyle bir açık programcı tarafından kapatılmadıysa/önlenmediyse.

> Şimdi SQL injectionu anlatalım.

SQL injection saldırıları normal sql sorgularına müdahale edip kendi istediğimiz SQL kodlarını sisteme enjekte edip çalıştırmamızı sağlayan güvenlik açıklarıdır.

SQL injection güvenlik açığı sayesinde saldırganlar;

1. Web sitesindeki kullanıcı bilgileri çalınabilir
2. Veritabanındaki veriler değiştirilebilir
3. Veritabanı silinebilir
...

Normal bir senaryoda giriş yaptığımız sistemde kullanıcı adı ve parola yerimiz vardır. Buradaki inputlara girdiğimiz veriler aşağıda tırnaklar arasına verdiğimiz kısımlara gelmektedir

```
SELECT * FROM Users where Username='KULLANICIADI' and Password='PAROLA'
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hxfsdpkoiw1x27ywqcmw.png)

Görüldüğü üzere kullanıcı adı kısmına **brktrl** yazdım.Şifre kısmına da **123456789deneme** yazdım.Arkaplanda bu nasıl bir sorgu yaratıyor hemen bakalım. 

```
SELECT * FROM Users where Username='brktrl' and Password='123456789deneme'
```

Buraya kadar her şey normal.Ancak ben kullanıcı adı inputunun yerine şu kodu yazsam ve şifre input yerini de boş bıraksam ne olurdu sizce?

```
'--
```
Eğer şifre kısmına bunu yazsaydım ne olacaktı hemen bakalım.

```
SELECT * FROM Users where Username='brktrl'--' and Password='123456789deneme'

```
Çift tire kullandığımızda bu SQL’de yorum satırı anlamına gelir.Yani bizim yazdığımız tek tırnaktan sonra kalan kısım yorum satırıdır. Bu yüzden arka tarafta şu kod çalıştırılmış gibi olacaktır.

```
SELECT * FROM Users where Username='brktrl'
```

Kalan kısım yorum satırı olduğu için çalıştırılmayacaktır.Bu yüzden yazmadım. Gördüğünüz gibi arkaplanda çalışan komut sadece kullanıcı ismini yazarak bu hesaba giriş yapmamızı sağlıyor.İşte SQL Injection bu ve bunun gibi işlemlere denir.

Programcının alabileceği bazı önlemlere göre stratejimizi değiştirebiliriz.Yukarıda anlattıklarım işe yaramazsa daha farklı denemeler payloadlar kullanabilirsiniz.

Açık olduğunu düşündüğünüz sitenin linkini “sqlmap” aracına vererek de veritabanına sızabilirsiniz.
A Workflow for Sending GitHub Issues, PRs, or Discussions Updates to WeChat
Tags: actionshackathon21
Published: 2021-11-30 14:55:22

{% github https://github.com/HollowMan6/GitHub-Issues-to-Wechat %}

# Motivation
Many Chinese developers prefer to use [WeChat](https://en.wikipedia.org/wiki/WeChat) when they are at work, so they seldom check their emails. While GitHub only provides notifications for issues, PRs, or discussions by email, many Chinese developers may delay their response to those updates. As a result, setting up a Workflow for sending GitHub issues, PRs, or discussions updates to WeChat will bring great convenience for Chinese developers.

# Features
Send GitHub issues, PRs, or discussions updates to WeChat, just like those updates sent by GitHub through emails.

# Realization
This workflow is realized through several WeChat message push platforms, such as [PushPlus](https://www.pushplus.plus/) and [ServerChan](https://sct.ftqq.com/), as well as the native Enterprise version of WeChat (WeCom) message push API.

The workflow uses python requests library for coding, and Docker for packaging to be used in the GitHub Actions.

# Usage
You can choose a realization for pushing the messages to WeChat, and set the needed GitHub Actions secrets [as the instructions here](https://github.com/HollowMan6/GitHub-Issues-to-Wechat#usage).

An example use for this workflow is [here](https://github.com/HollowMan6/GitHub-Issues-to-Wechat/blob/main/.github/workflows/message.yml).

You can set at what event the notifications will be sent through Wechat by modifying [these headers](https://github.com/HollowMan6/GitHub-Issues-to-Wechat/blob/main/.github/workflows/message.yml#L2-L12) and using them in your workflow.

Then, append the following line in the steps of your workflow.

```yaml
- name: 'Send GitHub Update Message to Wechat'
  uses: HollowMan6/GitHub-Issues-to-Wechat@v1
  with:
    DELAYS: ${{ secrets.DELAYS }}
    SERVERCHANSCKEY: ${{ secrets.SERVERCHANSCKEY }}
    PPTOKEN: ${{ secrets.PPTOKEN }}
    PPTOPIC: ${{ secrets.PPTOPIC }}
    CORPID: ${{ secrets.CORPID }}
    CORPSECRET: ${{ secrets.CORPSECRET }}
    AGENTID: ${{ secrets.AGENTID }}
```

Finally, enjoy it!

![](https://raw.githubusercontent.com/HollowMan6/GitHub-Issues-to-Wechat/main/img/wecom.jpg)
OutSystems Coding Challenge
Tags: development, devrel
Published: 2021-11-30 14:45:13

Hi there!

We’re really happy to announce the first ever OutSystems Coding Challenge that will happen throughout the month of December: Neo’s Odyssey!

This will be a great challenge for you, whether you’re a seasoned OutSystems developer or just starting out.

So if you are into coding challenges, would like to try a new technology or just want to build an app to use with your friends - join us!

[https://www.outsystems.com/our-community/2021-neo-odyssey/](https://www.outsystems.com/our-community/2021-neo-odyssey/)
Fetching data from API in shortest time [React js]
Tags: react, javascript, webdev, tutorial
Published: 2021-11-30 14:44:36

Hello programmers, in this his blog I am sharing the shortest and fastest way to fetch data from API in React js. This video shows exactly what to do to achieve this in 100 seconds! Enjoy!

https://www.youtube.com/watch?v=hC-m7EX-8rY

![https://www.youtube.com/watch?v=hC-m7EX-8rY](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llmvpfcf4j5qs1x48guy.png)
¿Cómo crear una colección de NFTs?
Tags: blockchain, nfts, web3, solidity
Published: 2021-11-30 14:43:09

---
title: ¿Cómo crear una colección de NFTs?
published: true
description: 
tags: blockchain, nfts, web3, solidity
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/acgbnl5i4y8gxey96139.png
--- 

Para crear una colección de NFTs se requiere hacer un montaje de una combinación de tecnología. En este video mostramos todo lo que necesitas saber para lanzar tu propia colección con las características que han mostrado ser atractivas para los compradores.

A continuación muestro los 3 pasos que necesitas. Para los detalles de cada paso te aconsejo ver el video completo o revisar la documentación en el `Readme.md` en cada repositorio.

{% youtube nh4KnGPerXM %}

## Dependencias

Para este tutorial ocuparás [NodeJs](https://nodejs.org/es/) que recomiendo descargarlo en Linux via [NVM](https://github.com/nvm-sh/nvm#installing-and-updating) , también necesitarás un URL de RPC te recomiendo usar [INFURA](https://infura.io/), y finalmente [Metamask](https://metamask.io/) con fondos de Rinkeby Testnet que puedes conseguir desde el [Faucet](https://faucets.chain.link/rinkeby).

## 1. Crea el arte y la metadata

Cuando ya tengas tu arte separado por capas con transparencia. Descarga y ejecuta la librería que usamos para generar el arte.

```bash
npm i https://github.com/FilosofiaCodigo/nft-art-generator
npx nft-generate
```

Llena la información en base a tu proyecto. Excepto por el URL, déjalo en blanco por ahora.

## 2. Lanza la metadata API y scripts auxiliares

De la misma manera, clona el repositorio y sigue paso a paso las instrucciones en el `Readme.md` y usa el video de youtube como apoyo.

Crea un proyecto a través del siguiente template:
[https://github.com/FilosofiaCodigo/nft-collection-api.git](https://github.com/FilosofiaCodigo/nft-collection-api.git)

## 3. Lanza el contrato y el frontend

Clona el repositorio y sigue paso a paso las instrucciones en el repositorio.

Crea un proyecto a través del siguiente template:
[https://github.com/FilosofiaCodigo/NFTCollectionTemplate.git](https://github.com/FilosofiaCodigo/NFTCollectionTemplate.git)
Delete elasticsearch index without Delete Index API over the TLS while using x-pack security
Published: 2021-11-30 14:36:32

```
#!/bin/bash

DAYSAGO=$(date --date="1 day ago" +%Y%m%d)

https://localhost:9200/_cat/indices?v | grep 'filebeat'`
ALLLINES=`/usr/bin/curl -s -XGET -u 'elastic:Elastic@123' https://localhost:9200/_cat/indices?v | grep 'filebeat'`

echo
echo "This is what to be delete for ELK!!! You can not recover this one gone"
echo

echo "$ALLLINES" | while read LINE
do
#  FORMATEDLINE=`echo $LINE | awk '{ print $3 }' | awk -F'-' '{ print $4 }' | sed 's/\.//g' ` 
  FORMATEDLINE=`echo $LINE | awk '{ print $3 }' | awk -F'-' '{ print $(NF) }' | sed 's/\.//g' `
  if [[ "$FORMATEDLINE" -lt "$DAYSAGO" ]]
  then
    TODELETE=`echo $LINE | awk '{ print $3 }'`
    echo "https://localhost:9200/$TODELETE"
  fi
done

echo
echo -n "if this make sence, Y to continue N to exit [Y/N]:"
read INPUT
if [ "$INPUT" == "Y" ] || [ "$INPUT" == "y" ] || [ "$INPUT" == "yes" ] || [ "$INPUT" == "YES" ]
then
  echo "$ALLLINES" | while read LINE
  do
     FORMATEDLINE=`echo $LINE | awk '{ print $3 }' | awk -F'-' '{ print $(NF) }' | sed 's/\.//g' `
    if [[ "$FORMATEDLINE" -lt "$DAYSAGO" ]]
    then
      TODELETE=`echo $LINE | awk '{ print $3 }'`
      /usr/bin/curl -XDELETE -u 'elastic:Elastic@123' localhost:9200/$TODELETE
      sleep 1
      fi
  done
else 
  echo SCRIPT CLOSED BY USER, BYE ...
  echo
  exit
fi
```
JS Interview : EP-2 : Hosing Explained Well
Tags: javascript, webdev, beginners, programming
Published: 2021-11-30 14:31:03

Lets’s discuss about the behaviour **Hosting**..
If you have minimum knowledge of how code works in JavaScript, you can easily guess the output of below code.
`
    var channel="CodeWellTech";
    console.log(channel);
`

and result will be  
   `CodeWellTech`

But let’s move the console.log statement one step above.. i.e place it before the declaration of channel variable like below
`
    console.log(channel);
    var channel="CodeWellTech";   
`

Now, generally we expect console.log statement to print an error but its gives something else…
`undefined`
So what is happening here ?
JavaScript interpreter will see above code as
`  
    var channel;
    console.log(channel);
    channel="CodeWellTech";   
`
Basically all the global declarations of variables in JavaScript will be moved to the top of the scope before execution of code and this behaviour is called **Hoisting**
For more detailed explanation on how JavaScript works behind the scenes
**Kindly like the video** if you are happy with explanation :)

{%youtube xfH1A4IuZRk%}
JavaScript Default Function Parameters.
Tags: javascript, webdev, beginners, programming
Published: 2021-11-30 14:13:16


In JavaScript when we call a function which expects some data to be passed in if you call that without passing in that data JavaScript will use `undefined.`


Let's understand this practically ⚙️



What the following function does is that it takes a name as an input and console logs it.


```js
function printName(name) {
  console.log(name);
}
```

Now if we call the `printName` function by passing in a name as shown below: 

```js
printName("frontendenthusiast");  
```
We'll get the following output.

```js
frontendenthusiast
```

Now lets call the same function without passing anything in

```js
printName();  
```
We will get `undefined` as the output in the console.

```js
undefined
```

`undefined` isn't that useful in most situations what if we can use a fallback if no name is passed into the function. Well for that we can use the `||` operator in JavaScript as shown below:

```js
function printName(name) {
  name = name || `Anonymous`;
  console.log(name);
}
```

The **Logical OR (||)** operator returns **the very first truthy value** and undefined is a falsy value so in the `printName` function it will return **Anonymous** which is a truthy value.

Now with the above addition of `||` operator if we call the function by passing in no value as shown:

```js
printName();

```
We will get `Anonymous` as the output.

```js
Anonymous

```

In ES6 we have a more compact way of doing the above which is to set up default parameters directly using the assignment operator `=` as shown:

```js
function printName(name = `Anonymous`) {
  console.log(name);
}
```

this returns default value we set using `=` operator in case no value was passed in.

```js
function printName(name = `frontendenthusiast`) {
  console.log(name);
}

printName(undefined);
```
The output of the above function will be `frontendenthusiast`

`Happy coding! 🥰`
A sample e-commerce web app built with ReactJS, ExpressJS and MongoDB
Tags: webdev, javascript, react, tutorial
Published: 2021-11-30 14:12:04

MERN stack which stands for MongoDB, ExpressJS, ReactJS and NodeJS has become a popular choice for fullstack Javascript web developer.

As a personal project for education purpose, I developed a basic bookstore web app with MERN stack.

Through this project, beginners could have a useful resource to understand how to implement ReactJS, Redux, React Router and others related libraries in React ecosystem to build up a functional front-end solution.

In addition, the back-end developed with ExpressJS and MongoDB is also an example for building a web api with Javascript.

Further detail information is available on Homepage of the live demo at:
https://bn-bookstore.herokuapp.com/#/

The source code is available at:
https://github.com/linhtch90/bn_bookstore_public_source

Please give me a Github star :star: as a compliment if my effort is useful for you! Thanks!
DevOps with Github Actions Hands on Labs
Tags: actionshackathon21
Published: 2021-11-30 13:51:48

[Instructions]: # (To submit to the GitHub Actions x DEV Hackathon 2021, please fill out all sections.)


### DevOps with Github Actions Hands on Labs Content
1. DevOps with Github Hands on Lab Repository consists of 10 Github Actions Lab providing hands on experience on JavaScript, Java, Python , PHP , ASP.NET core, Django Framework, ExpressJS
3. Code based is tested for Appservice, Appservice for containers and AKS environments
4. Lab content Includes hands on experience to do DataOps using Github Actions
5. Content is sufficient to conduct 2 Days Deep Dive with your Partners/customers on Github Actions workflow


### Submission Category: 

DIY Deployment


### Yaml File or Link to Code

https://github.com/jethanivijay/DevopsWithGithub-Hands-on-Labs


### Additional Resources / Info

Github Actions Workflows for each Labs are placed in respective branches under ./github/workflows folder structure , for ease of navigation branch link is provided below each lab so that it is easy to navigate to code and see Github Actions built for that lab. 
Step by step instructions are placed in  in readme file at root of reposistory.
How to Create Vertical Bar Chart Using Chart Js in React
Tags: react
Published: 2021-11-30 13:44:11

There are several npm packages that allow charts to be created in React; chart.js is one of the packages which makes the creation of charts and graphs ​very easy.

The React wrapper for chart.js is react-chartjs-2; it makes things simpler in React, however, it doesn’t support all the customization features that come with Chart.js.

Both these packages need to be installed using npm before they can be used.

https://www.codecheef.org/article/how-to-create-vertical-bar-chart-using-chart-js-in-react
What is React Suspense and When to Use It in React
Tags: react
Published: 2021-11-30 13:42:46

This post is about understanding how Suspense works, what it does, and seeing how it can integrate into a real web app. We’ll look at how to integrate routing and data loading with Suspense in React. For routing, I’ll be using vanilla JavaScript, and I’ll be using my own micro-graphql-react GraphQL library for data.

https://www.codecheef.org/article/what-is-react-suspense-and-when-to-use-it-in-react
Laravel Eloquent Limit Eager Loading Data Example
Tags: laravel
Published: 2021-11-30 13:40:24

Hi All,

In my Laravel 5.0 app I have an Account model which has a hasMany relationship with an Activity model. I’d like to provide my users with a list view of Accounts along with the timestamp of the most recent Activity for each Account.

For obvious performance reasons, I’d like to eager load the appropriate Activity model for each account. I’ve tried to do this with an eager loading constraint as follows:

[Laravel Eloquent Limit Eager Loading Data Example](https://www.codecheef.org/article/laravel-eloquent-limit-eager-loading-data-example)