teleren/devto huggingface dataset:
How to get a React element as an HTML string
Tags: javascript, react
Published: 2021-05-09 14:20:21

---
title: How to get a React element as an HTML string
description: For use cases, you may want to have the generated HTML string from your React component instead of a mounted component rendered on the page. The simplest way is to use the renderToString function provided by the react-dom package.
published: true
date: 2021-05-02 00:00:00 UTC
tags:
  - javascript
  - react
canonical_url: https://www.emmanuelgautier.com/blog/react-element-render-to-string
---

For use cases, you may want to have the generated HTML string from your React component instead of a mounted component rendered on the page.

The simplest way is to use the `renderToString` function provided by the `react-dom` package :
```jsx
import { renderToString } from 'react-dom/server'

renderToString(<YourAwesomeComponent props1="value1" props2={{ value: "2" }} />)
```

The function `renderToString` can be used on both the server-side and client-side.

If you want to render all page server-side for SEO or UX purposes for example, you can use the function `renderToNodeStream` to improve your load time. 

More informations on the React [documentation](https://reactjs.org/docs/react-dom-server.html).
What to do with the error for /etc/securetty on Ubuntu
Tags: ubuntu, tutorial
Published: 2021-05-01 23:00:04

## Steps

```
sudo vi /etc/securetty
```

Paste what the file has which is mentioned at [this page](https://askubuntu.com/questions/1239503/ubuntu-20-04-and-20-10-etc-securetty-no-such-file-or-directory).

## References

- [Ubuntu 20.04 and 20.10, /etc/securetty: No such file or directory](https://askubuntu.com/questions/1239503/ubuntu-20-04-and-20-10-etc-securetty-no-such-file-or-directory)
CSS roadmap - CSS Concepts you will use everyday.
Tags: css, tutorial, codenewbie
Published: 2021-05-01 22:55:34

Hello Everyone!!
These are the CSS concepts I think everyone should know to be comfortable using and designing anything with CSS.

I will also leave links to some resources below.

## Let's start with the basics (IMHO)

### Formatting text

- changing text colors
- changing text size
- style a text (italic, bold, ...etc)
- spacing letters or words *(`letter-spacing` & `word-spacing`)*
- changing capitalization (uppercase, lowercase, small-caps...etc)

### Changing lists

- removing bullet points
- changing the default bullet points
- using roman numbers in lists

### Colors

- color specificity *(very important to know)*
- background and foreground color
- opacity

### Backgrounds

- background images
- gradients
- clipping the background

> You can also learn about **Pseudo-Element/Class** after background, or you can wait after the box model.


## Now to the Advance Basics

### Box Model

- padding, margin and border
- box shadows
- display types *(`inline`, `inline-block`, `block`,...etc)*
- block-level and inline elements

### Positioning
Sites with only colors and good fonts, are great. But without positioning, they are terrible to the eyes.

- positions (`absolute`, `relative`, `sticky`, & `fixed`)
- floats
- normal flow of elements

> Always try to use position no matter how small. `floats` are hardly used these days, they are dying if not already.)


## Now to Intermediate

### Flexbox
Learn how flex affects the container and children, when and how to use them efficiently.

- `display: flex`
- center text/elements with `justify-content` or `align-items`
- `flex-direction`

### CSS Grid or Grid
Much harder to learn than Flexbox, but they can do what Flexbox does and more. Use both for their correct use.

- `display: grid`
- `grid-gap`
- `grid-template-areas`
- `grid-template-columns`
- `repeat()`, `minmax()` and grid units - fractions *(fr)*

### Responsive Web Design (RWD)

- media queries
- choosing good break points

### Transitions and Animations *(the fun CSS)*

- transform
- transitions
- translate
- skew
- keyframe animation

### Conclusion

Everything else that comes after these are features to boost productivity and adds more cool features to your skills and designs. Like:
 - imports, replacing images, feature detection,...etc

Feel free to add anything I might have missed, and please leave your comments below.

#### Resources

- [CSS Tricks](https://css-tricks.com/)
- [FreeCodeCamp CSS](https://www.freecodecamp.org/learn/responsive-web-design/basic-css/)
- [W3School](https://www.w3schools.com/Css/)
- [Learn to code with me](https://learntocodewith.me/getting-started/topics/css/)
- [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
How to make Vue's (v2) v-model or syncable props optional?
Tags: vue
Published: 2021-05-01 22:45:39

## Long story short

Use computed with `get`ter and `set`ter that conditionally use either passed property or internal data.

Component definition:

```vue
<!-- FooModal.vue -->
<template>
  <div v-show="syncShow">
    Lorem ipsum dolor sit, amet consectetur adipisicing elit.    
    <button @click="syncShow = false">
      Close self
    </button>
  </div>
</template>

<script>
export default {
  props: {
    // property that controls the visibility of the modal (if used)
    show: {
      type: Boolean,
      required: false,
      default: null
    }
  },

  data: () => ({
    // internal state for cases where prop is not defined
    intShow: true
  }),

  computed: {
    // proxy computed that uses either internal state
    // or passed property (if present).
    syncShow: {
      get () {
        return this.show === null
          ? this.intShow
          : this.show;
      },

      set (val) {
        if (this.show === null) {
          this.intShow = val;
        } else {
          this.$emit('update:show', val);
        }
      }
    }
  }
}
</script>
```

And then, it's usage:

```vue
<!-- App.vue -->
<template>
  <div id="app">
    <!--
      You can control the visibility from the parent scope.
    -->
    <FooModal :show.sync="showFoo" />

    <!--
      Or you can let the component handle it.
    -->
    <FooModal />
  </div>
</template>

<script>
import FooModal from './components/FooModal.vue'

export default {
  components: {
    FooModal
  },
  data: () => ({
    showFoo: true
  })
}
</script>
```

Let me know if you use any other way to achieve the same.

Dan
Trucos en Angular que mejorarán el performance de tus aplicaciones.
Tags: angular, webdev, codenewbie, discuss
Published: 2021-05-01 22:42:58

Angular es un framework bastante popular en el mundo empresarial. A pesar de que tiene la curva de aprendizaje más elevada que el resto, mucha gente se anima a aprenderlo. Personalmente, a mi me gusta bastante y es por eso que acá te dejaré unos trucos que tal vez no conocías 😎

##Lazy Loading##

Está característica es bastante popular ya que nos permite configurar nuestra aplicación para que cargue los archivos únicamente cuando son necesarios. Por ejemplo, tenemos dos vistas donde la primera sería la presentación y la segunda el blog. Todos los recursos que se necesiten para cargar el blog, no serán 'llamados/ejecutados' hasta que el usuario no vaya a esa sección.

##Destruyendo Observables##

Si bien los observables son de RxJs, cuando trabajemos con Angular, los vamos a usar bastante ya sea para los servicios o estar escuchando ciertos cambios de nuestra aplicación. Sin embargo, los observables tienen la particular característica que no se destruyen por si solos sino que debemos forzar a que suceda. Esto es necesario ya que sino, nuestros observables seguirán consumiendo espacio de memoria en background y podría hacer nuestra aplicación más lenta. Formas para destruir observables hay muchas, pero una que me gusta bastante es a través del operador *takeUntil*, el cual podemos anteponer a nuestra suscripción con el operador *pipe*, también de Rxjs. Al mismo tiempo nos apoyamos de un subject de tipo void que su única función sera hacer un *next()* y *complete()* en el OnDestroy del componente. Lo mejor es que de esta manera, podemos reutilizar nuestro subject en todas las subscripciones que tengamos en nuestro componente.

##Pre fetching##

Está funcionalidad es sin duda demasiado buena, parecido a lo que viene por default en otras tecnologías como *Gatsby*, podemos hacer que algunos archivos vayan pre cargando antes que el usuario entre a esa página. Por ejemplo, si vamos a entrar a una galería al colocar el mouse sobre el botón que nos llevará, nuestra aplicación irá cargando en background las imágenes respectivas para que de esta manera la experiencia del usuario sea mucho mejor.

Si te han gustado estos trucos puedes verlos en mis diferentes proyectos de github(https://github.com/QuispeRosasGabriel) 😎 y tú tienes algún truco que te gustaría compartir?
Ethereum Diamonds Solve These Problems
Tags: ethereum, blockchain, smartcontracts
Published: 2021-05-01 22:38:43

Diamonds solve these problems:
1. The maximum size a smart contract can be on Ethereum is 24kb.  But sometimes larger smart contracts are needed or desired. Diamonds solve that problem.
2. Provides a structure to systematically and logically organize and extend larger smart contract systems so they don't turn into a spaghetti code mess.
3. Provides fine-grained upgrades. Other upgrade approaches require replacing functionality in bulk. With a diamond you can add, replace, or remove just the functionality that needs to be added, replaced or removed without affecting or touching other smart contract functionality.
4. Provides a single address for a lot of smart contract functionality. This makes integration with smart contracts and user interfaces and other software easier.

If you plan to build a system that can grow or change over time then a diamond is a good choice because it enables a system to grow in a systematic, organized way.

The standard for diamonds is here: https://eips.ethereum.org/EIPS/eip-2535

Resources: https://eips.ethereum.org/EIPS/eip-2535#learning--references
Murphy’s setup guide for a new Phoenix (1.5) project
Tags: uncategorized
Published: 2021-05-26 17:43:29

---
title: Murphy’s setup guide for a new Phoenix (1.5) project
published: true
date: 2021-05-01 22:16:54 UTC
tags: Uncategorized
canonical_url: https://mrmurphy.dev/murphys-setup-guide-for-a-new-phoenix-1-5-project/
---

What follows is an extremely concise list of steps I'm keeping around for reference when setting up a new Elixir / Phoenix project with Tailwind, Alpine, and user auth.

NOTE: Pretending the name of the app is "love\_notes"

## Generate it

`mix phx.new love\_notes --live`

## Use UUIDs

in **config/config.exs**

```
config :love_notes, :generators,
  migration: true,
  binary_id: true,
  sample_binary_id: "11111111-1111-1111-1111-111111111111"
```

## Setup Tailwind

from [https://pragmaticstudio.com/tutorials/adding-tailwind-css-to-phoenix](https://pragmaticstudio.com/tutorials/adding-tailwind-css-to-phoenix)

### Install

```
cd assets
npm install tailwindcss @tailwindcss/forms postcss autoprefixer postcss-loader@4.2 --save-dev
```

### Postcss

In `assets/postcss.config.js`

```
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}
```

### Webpack

In your config:

```
use: [
  MiniCssExtractPlugin.loader,
  'css-loader',
  'postcss-loader',// <-- add this
  'sass-loader'
]
```

### Tailwind Config

```
cd assets
npx tailwindcss init
```

Modify the config to add purge directories, set up the jit, enable dark mode, and add the tailwind UI plugin:

```
module.exports = {
  purge: [
    '../lib/**/*.ex',
    '../lib/**/*.leex',
    '../lib/**/*.eex',
    './js/**/*.js'
  ],
  mode: 'jit',
  darkMode: 'media',
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [
    require('@tailwindcss/forms')
  ],
}
```

### Modify script in package.json

```
"deploy": "NODE_ENV=production webpack --mode production"
```

### Include the CSS in the main file

in **assets/css/app.scss**

```
@tailwind base;
@tailwind components;
@tailwind utilities;
```

### If you want to use component classes

You can do it like this.

```
@layer components {
  .btn-indigo {
    @apply bg-indigo-700 text-white font-bold py-2 px-4 rounded;
  }
}
```

## Adding Alpine JS

```
npm i alpinejs
```

In **app.js** :

```
import 'alpinejs'

// other stuff

let liveSocket = new LiveSocket("/live", Socket, {
  dom: { // <- Add this 'dom' section
    onBeforeElUpdated(from, to){
      if(from.__x){ window.Alpine.clone(from.__x, to) }
    }
  },
  params: {_csrf_token: csrfToken}
})
```

## Adding Auth

Inside of **mix.exs**

```
      {:jason, "~> 1.0"},
      {:plug_cowboy, "~> 2.0"},
      # Add the following line 👇🏻
      {:phx_gen_auth, "~> 0.6", only: [:dev], runtime: false}
    ]
```

Get deps and run the generator:

```
mix deps.get
mix phx.gen.auth Accounts User users
mix deps.get # Do this again so that the deps added by the generator get fetched.
```
How to set environment variable for Lambda using CDK
Tags: aws, cdk, python
Published: 2021-05-01 21:46:02

In the [previous post](https://dev.to/upupkenchoong/how-to-provision-lambda-and-lambda-layer-with-cdk-2ff4), I show how to make a Lambda function using CDK. In this post, I will show we can set the environment variable, so we can use it inside the Lambda function. 

**When to use environment variable?**
You want to access different value of a variable depending on production or development environment, but this value is very important, you need to keep it secret, not comfortable to keep it in version control(eg. github). 

Some example use case:
- Access different database depending on production environment
- Access different Stripe credential depending on environment. 

**Steps:**
In this example, we access different database URL depending on environment.

Use back the previos Lambda function 
```python
my_first_lambda_function=PythonFunction(
    self, 'MyFirstLambda',
    entry='lambda/MyFirstLambdaFunction',
    index='app.py',
    runtime=lambda_.Runtime.PYTHON_3_8,
    layers=[boto3_lambda_layer],
    environment={ # ADD THIS, FILL IT FOR ACTUAL VALUE 
        "production_db_url": "YOUR_ACTUAL_PROD_DB_URL",
        "development_db_url": "YOUR_ACTUAL_DEV_DB_URL"
    },
    handler='MyFirstLambdaHandler',
    timeout=core.Duration.seconds(10)
)
```

Now, we already define the environment variable, now we need to access this inside our Lambda function. 

```python
import boto3
import os

def MyFirstLambdaHandler(event, context):
    client = boto3.client('dynamodb')
    
    # You get the value back like this
    prod = os.environ['production_db_url']
    dev = os.environ['development_db_url']

    # later you other stuff using the above value
```

Ok, for now you know how to define the environment variable and use it inside the Lambda function. You can put in any value inside `environment`, in key value depending on you need.

May be you not sure why you need to set `environment variable` for now, but is ok, next part of the series, you will connecting the dots.

**In next part of the series:**
We will talk about `version`, `alias` for the Lambda function, APIgateway with `stageVariables`, and use different environment value depending on the Lambda `alias` 

**Before you go,** if you like this series or find this useful consider to buy me a coffee 😊🤞 for 5 USD or more. 
I will prepare a GitHub repo for this whole tutorial series and arrange into separate commit for each part. 
This will only available for my supporter cause I spent a lot of time to prepare this. Anyway, I appreciate you here. Have a good day.

<a href="https://www.buymeacoffee.com/kenchoong" target="_blank">
![bmaco](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ap0mog1ue623vr1zbo36.jpg)
</a>

Shout out to me on Twitter: [@upupkenchoong](https://twitter.com/upupkenchoong)
LeetCode 516. Longest Palindromic Subsequence
(javascript solution)
Tags: algorithms, javascript
Published: 2021-05-01 21:45:34

###Description:
Given a string s, find the longest palindromic subsequence's length in s.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

###Solution:
Time Complexity : O(n^2)
Space Complexity: O(n^2)

```javascript
var longestPalindromeSubseq = function(s) {
    const dp = [...Array(s.length)].map(() => Array(s.length).fill(0))
    
    // Base case 
    for(let i = 0; i < s.length; i++) {
        dp[i][i] = 1
    }
    
    for(let i = 1; i < s.length; i++) {
        for(let j = 0; j < s.length; j++){
            if(j+i < s.length){
                // If the end letter and start letter are the same add 2 to the value in the bottom left diagonal. This value is a potential palindrome. If the letters are not equal set the current value to the previous highest palindrome subsequence
                dp[j][j+i] = s[j] === s[j + i] 
                    ? dp[j+1][j+i-1] + 2
                    : Math.max(dp[j][j+i-1], dp[j+1][i+j])
            }
        }
    }

    return dp[0][s.length-1]
};
```
Running a dockerized React Native application
Tags: docker, reactnative, devops, container
Published: 2021-05-01 21:37:55

## Why do we run a React Native application in a docker container?

At times setting up React Native dev environment could be a prick in the spine, hence docker solves all those issues and let's us build a React Native application in a container facilitating testing the application as well.

In this tutorial, we'll orchestrate a docker container with a bare minimum React Native application with Expo managed workflow.

We'll use [https://github.com/taher07/dockerized-react-native](https://github.com/taher07/dockerized-react-native) to complete our task

## pre-requisites
- docker
- docker-compose (which usually comes along with docker but if it's not the case then yeah)

## steps
- clone the repository using `git clone https://github.com/taher07/dockerized-react-native.git my-app`
- Navigate to the repository and run `rm -rf .git/`
- Run `docker-compose up`, you gotta give it some time
- Your React Native application would have probably been running by now, go to [http://0.0.0.0:19002]() from your browser and it would render dev tools in your browser
- Under the `connection` section click on `Tunnel` and you can now run your expo managed app from the Expo Go app on Android or iOS devices (It has been shown below)

![Metro](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ligrzpmh7pzj2quamvvd.png)
 
- Now let's get into bash specific to docker container as
  - Run `docker ps` and copy the container id
  - Run `docker exec -it <container_id> bash`
- You're all set to start developing your dockerized React Native application

#### Any further discussion on this thread are welcome below!
What is the best way to learn HTML/CSS/JS and other frameworks?
Published: 2021-05-01 21:10:15

Recently, I started a Web Dev Bootcamp, and it was crazy. I successfully made a simple website using Bootstrap; however, I had to google basically everything. And this scared me:

For the current developer, do you have to remember everything or we are allowed to look up in documentation.

I'm afraid that I will not get better if I don't figure out what the right way to learn :(

Thanks guys.

https://19216881.org/ https://1921681001.link/ https://19216801.digital/
GitHub Profile README Generator
Tags: github, programming, portfolio, python
Published: 2021-05-01 20:26:49

https://github.com/rahulbanerjee26/githubProfileReadmeGenerator

**A few inputs + ~15 mins = Your Github Profile reaches a new level 🔥**

## Usage 🔧

Fill in the text boxes. Leave the ones you do not wish to fill blank.
By default the generated ReadMe has GitHub stats and Wakatime stats, feel free to remove them.
If you want to build on top of the Readme, refer to the article I mentioned above for resources and tips
If you used this app to build your README, consider adding yourself to the "Users who used this app to generate a README" section. You can showcase your README and others will be able to view it and star it. You are guranteed a star from me ⭐

## Features 💿

- Gifs
- Social Icons
- Skill Icons
- Visitors Badge
- Github Stats
- Chose GitHub Stats Card Type
- WakaTime Stats
- .yml file to display Blog Posts from your feed
- Ability to add image banners at beginning of README
- Random Jokes Card
- Clicking on Skills shows your GitHub Repos filtered on that skill
- Cool Image in the About Me section
Using AWS QuickSight to create dashboards from your DynamoDB data (CDK)
Tags: aws, cdk, devops
Published: 2021-05-01 20:11:12

I'm sure you've come up against the same problem that many of us have. You've got a bunch of data in DynamoDB and you just want to easily query it, create some dashboards and maybe share that around.

AWS Athena have made some really exciting changes in the past few months which enable us to query DynamoDB using federated queries. This basically means, deploy a Lambda function that uses JDBC and query the DynamoDB, return the results to Athena. Now, Athena gives us some really cool ad-hoc querying capability so you can drill into your data but no dashboards.

AWS QuickSight is AWS's managed BI tool, kinda like Power BI, Tableau etc except it's much cheaper. AWS QuickSight have released support to use Athena Federated Queries which means you can use that JDBC connector to query your DynamoDB database from within QuickSight!

If you're still following along I've mentioned a bunch of different terms here and it be getting confusing. I've put together a demo which includes using AppSync to provide access to the same powerful connector.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u45bfowx1jdpm7k3bgxh.gif)

I've created the demo using CDK which will deploy the whole stack as pictured above. It won't deploy the QuickSight part as there isn't much support for QuickSight in CloudFormation or CDK.

There is a bit to talk about for this design, I've done a bigger write up on my blog if you wanna check it out:

https://www.talkncloud.com/athena-dynamodb-quicksight-cdk/

If you just want to hit the open source repo for the CDK stack, you can grab it off github:

https://github.com/talkncloud/aws/tree/main/athena-appsync

Hopefully you found this useful, I had a great time working through this one and found it extremely easy to create nice dashboards in QuickSight once the connectors were in place.

Let me know how you go!
Inheritance in Java
Published: 2021-05-01 19:29:25

Inheritance is a mechanism or process where one class inherit the properties and functionalities from another class. Just like a child inherit characteristics from his parents. The class that inherit the properties and functionalities of another class is known as child class/subclass. On the other hand, the class whose properties are inherited is known as parent class/superclass.

Why do we need Inheritance?
There are several reasons why we need inheritance.

Reusability:  With inheritance, we can use the fields and methods again and again, or we can reuse the whole class wherever we need. As a result, we don't have to write the same code which saves us a lot of time. For example, in the collection framework of java -
Sorted Set inherit Set, Navigable set inherit Sorted set, Tree set inherits Navigable set. Here if we use the Tree set we can use all the functionalities of Set, Sorted set and Navigable set, we don't have to write code for each of them again. That's the privilege we get from inheritance.

Maintenance:  As we reuse the code, for safety the reusable code is tested more often, which means the program will have fewer errors means a better program.

Overriding: When we declare the same method in child class which is already present in the parent class with different implementation then this is called method overriding. When we use child class it inherits some functionalities from the parent class, if we need to change a certain functionality because of the requirement we can do it by overriding in the child class and it will execute the method of the child class, not the parent class.