teleren/devto huggingface dataset:
What I've learned today - 3 - Elixir add color to console
Tags: elixir, programming
Published: 2021-05-05 03:04:52

## Coloring your console prints

Since Elixir 1.4.0 we have ANSI color printing option.

Ir supports also background colors. 

For more information, see: [https://hexdocs.pm/elixir/IO.ANSI.html](https://hexdocs.pm/elixir/IO.ANSI.html)

## Examples
 
```elixir
import IO.ANSI
IO.puts red <> "red" <> green <> " green" <> yellow <> " yellow" <> reset <> " normal"
IO.puts Enum.join [red, "red", green, " green", yellow, " yellow", reset, " normal"]
IO.puts IO.ANSI.format([:blue_background, "Example"])
IO.puts IO.ANSI.format([:green_background, "Example"])
```

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

I appreciate everyone who has read through here, if you guys have anything to add, please leave a comment.
Handling multiple checkboxes in react
Tags: react
Published: 2021-05-05 08:47:29

Let's say we want to have input for our favorite foods and we want to show it on the page.

First, we should prepare two variables, one for the food list, and another for a list of the selected food which is empty by default.

```js
this.state = {
  foods: [
    {
      id: 1,
      name: '🍕'
    },
    {
      id: 2,
      name: '🍙'
    },
    {
      id: 3,
      name: '🍰'
    },
  ],
  selected: [],
}
```

Now we make the form and show the `selected` state.

```html
<form>
  <p>
    { JSON.stringify(this.state.selected) }
  </p>
  <p>Foods</p>
  {
    this.state.foods.map(item => {
      return (
        <label key={ item.id }>
          <input type="checkbox"></input>
          <span>{ item.name }</span>
        </label>
      )
    })
  }
</form>
```

For checkbox input, we need to add `selected` and the usual `onChange` attributes.

```html
<input type="checkbox"
  onChange={ () => this.onChange(item.id) }
  selected={ this.state.selected.includes(item.id) }
  ></input>
```
The `selected` attribute accepts a boolean value that specifies if the input should be 'pre-selected' (checked) or not. And the `onChange` attribute will be triggered each time the input is checked and unchecked.

So because of this behavior, we have to put a function on the `onChange` attribute. 

```js
onChange(id) {
  let selected = this.state.selected
  let find = selected.indexOf(id)

  if(find > -1) {
    selected.splice(find, 1)
  } else {
    selected.push(id)
  }

  this.setState({ selected })
}
```

`find` is a variable that checks whether the checked item is in the `selected` array or not. find > -1 means that the item exists in the selected variable and it is checked so we want to remove it from the selected list while find == -1 means the opposite. The item doesn't exist in the selected array so we want to add it to the array.

Now it should look like this

![React Checkboxes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4vjy5izbj634upoqk94v.gif)

## Beyond IDs

If you want to keep the whole object (not only the id), we can change the way we find the index and push the item to the selected array

```js
onChange(id) {
  let selected = this.state.selected
  // instead of using indexOf, we can use findIndex to look through array of objects
  let find = selected.findIndex(item => item.id === id)

  if(find > -1) {
    selected.splice(find, 1)
  } else {
    // We can use find to get the item based on its id
    selected.push(this.state.foods.find(item => item.id === id))
  }

  this.setState({ selected })
}
```

Now it should look like this

![React Checkboxes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ssyxl3rr7htuvw9m574c.gif)

## Sorting

And finally, basically the selected array has no specific order so if you want to keep the order you can add some sorting method before we use the `setState`.

```js
// sort by id in ascending order
selected.sort((a, b) => a.id - b.id)
```
Unique SVG Shape Generators You Should Know About
Tags: webdev, productivity, beginners, css
Published: 2021-05-05 09:20:58

Here I list a few CSS shape generators, which can be included in your project, these generators produce svg codes, which can be copy-pasted into your project directly.

###[Blob Maker](https://www.blobmaker.app/)
![Blob Maker](https://exceed-team.com/images/1783/unique-svg-shape-generators-you-should-know-about.webp)

###[Squircley](https://squircley.app/)
![Squircley](https://exceed-team.com/images/1784/squircley.webp)

###[Blobs](https://blobs.app/?e=6&gw=6&se=21224&c=d1d8e0&o=0)
![Blobs](https://exceed-team.com/images/1785/blobs.webp)

###[Chartgen](https://chartgen.frederickallen.co/)
![Chartgen](https://exceed-team.com/images/1786/chartgen.webp)

###[Wavelry](https://wavelry.vercel.app/)
![Wavelry](https://exceed-team.com/images/1787/wavelry.webp)

Thank you for reading! I hope this [SVG Shape Generators](https://exceed-team.com/tech/unique-SVG-shape-generators-you-should-know-about?s=de&a=a) were useful for you, good luck and have a nice day)
Fix keyboard is freezed by Xfce4 screensaver and LightDM light-locker
Tags: xfce, screensaver, lightdm, lightlocker
Published: 2021-05-05 14:56:18

## Background

I use [Artix Linux](https://artixlinux.org/) as my workstation. It is based on [Arch Linux](https://archlinux.org/) and adopts [Systemd](https://www.freedesktop.org/wiki/Software/systemd/)-free approach.
I chose [Xfce4](https://www.xfce.org/) as lightweight desktop environment with [LightDM](https://wiki.archlinux.org/title/LightDM) as login manager and [OpenRC](https://wiki.gentoo.org/wiki/OpenRC) as init system.
I like it🙂

## Problem

Well, I had had a small but inconvenient problem.
Keyboard didn't work after the session was locked due to a certain time passed without any operation.

![lock screen was light-locker's](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zffenn11z6na114qds2e.jpg)

I logged in again then to restore the session. Then I hit some keys in application which had been the primary before locked. Nothing worked.

I had to activate another application once. So I could use the primary application as I had.
It was actually some sort of solution but inconvenient, unpleasant and uncomfortable.

## Cause and reason

I found it was because __both__ [Xfce4 screensaver](https://git.xfce.org/apps/xfce4-screensaver/about/) ( [`xfce4-screensaver`](https://git.xfce.org/apps/xfce4-screensaver) ) and [Light Locker](https://wiki.archlinux.org/title/LightDM#Lock_the_screen_using_light-locker) ( [`light-locker`](https://github.com/the-cavalry/light-locker) ) locked the session.

## Solution

### Summary

To disable either `xfce4-screensaver` or `light-locker`.

### Case 1: Use `light-locker` (= disable `xfce4-screensaver`)

Uninstall `xfce4-screensaver` if you don't use it:

```console
# pacman -Rs xfce4-screensaver
```

It was my option.

As another option, you may disable it with Xfce4 "Settings" menus. Go to "Settings" > "Session and Startup", select "Application Autostart" and uncheck "Screensaver". Make only "Screen Locker" checked:

![settings menus case 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xcgrql2i0xds71mkfn9y.png)

Then log out and log in again.
You will see Light Locker screen when the session is locked:

![light-locker lock screen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zffenn11z6na114qds2e.jpg)

### Case 2: Use `xfce4-screensaver` (= disable `light-locker`)

Go to "Settings" > "Session and Startup", select "Application Autostart" and uncheck "Screen Locker". Make only "Screensaver" checked:

![settings menus case 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2dnn0p2kg0arw2kzyn8i.png)

Then log out and log in again.
You will see Xfce4 Screensaver lock screen when the session is locked:

![xfce screensaver lock screen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24kfuzsp2e4mhu8gvehb.jpg)
CGN4 - Cloud Gaming Notes Episode 4 - Cross-platform social Sudoku with Azure PlayFab
Tags: architecture, gamedev, gaming, azure
Published: 2021-05-05 18:23:12

![CGN4 - Cloud Gaming Notes Episode 4 - Cross-platform social Sudoku with Azure PlayFab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/soaxu1gwa5udxvbicfy5.jpg)

Ever thought about what it takes to host a game in the Cloud? Well, this is the series for you! On the first Wednesday of every month, we explore Cloud Concepts that impact your journey to a connected multiplayer gaming experience! In this session, Chris is joined by Dominic who has recently been through the process of building his own game, Sudoku Social! Take the classic puzzle game and adding a cross-platform social twist with the cloud. Sudoku Social has been a passion project to learn game development and bring players together to answer the ultimate question. Who is the fastest Sudoku player?

{% youtube GfOlIrflFq0 %}
SwiftUI: a new way to build views
Tags: mobile, swift, ux, ios
Published: 2021-05-19 13:03:04

One of the best announcement in 2019 was [SwiftUI](https://developer.apple.com/xcode/swiftui/) a complete different way to build visual interfaces more declarative and intuitive. Following Android with [Jetpack Compose](https://developer.android.com/jetpack/compose?hl=es-419) (both inspired by React Native ) Apple launched into the task of changing the old way that him have for make views.

##A Little history
Formerly for make apps in Apple environment we have to familiarizing with Storyboard this is a little difficult if you are a front-end developer used to web programming, concepts like a constraints, xibs and the way to connect the components with the view was something tedious, archaic and unintuitive. Also StoryBoards were difficult to merge, they almost always gave merge conflicts if 2 developers were working on the same StoryBoard even if they had not touched the same view, and they were difficult to undock. 

![storyboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dlbrfgq2x486blckikxr.jpg) 

##SwiftUI and iOS 13
SwiftUI work with iOS13+ and this is for a simple reason and it have to do binary stability of the OS. Before iOS13 each app loaded in the SO have the specific resources library for the specific version of the code. Now iOS13 bring the resource library preloaded and can be understood with any app from iOS13, fir this reason the apps building for iOS13+ will weight less.

##How work SwiftUI
Those who have worked with React Native will found it very similar in the way to work, basically we have a view that return a body in where we have all the container at first level, just we can have one, and in that we can put anything you want, for example we can put a toolbar, like a first level, and nested containers inside. 
What about the data?, we can pass data between different views that we use, use data enumerations within the structure itself, or create synchronous data sources that provide us with objects as dynamic data. Even asynchronous data that once retrieved causes events in the interface to be displayed. We can also give status to a property and each time it changes(DataBinding), the view on the screen will be redrawn. In the next example we have a NavigationView like a first container, so in the inside, we have a List with nested element like stacks and labels.

![Screen Shot 2021-05-05 at 17.03.00](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lzgrdkk8zjsq7cujsvfq.png)

##Conclusion
SwiftUI is a new tools than allow create views that a way more intuitive, simple and declarative. After having working with React Native i realized of the archaic that Storyboard was. For that i loveled it SwiftUI. What do you think?
Curtidos Menacho
Tags: cuero
Published: 2021-05-06 17:23:25

En Curtidos Menacho, queremos como mayorista de piel, que obtengas cueros de gran calidad. Somos expertos en el curtido de trozos de piel y tenemos una gran experiencia en todo lo relacionado, con la piel y el curtido artesanal. 
<a href="https://curtidosmenacho.com/es/">Curtidos Menacho</a>
Performance🚀 hype🤓
Tags: performance, webdev, jamstack
Published: 2021-05-07 10:09:49

Ever since big G announced [Page Experience](https://developers.google.com/search/docs/guides/page-experience) metrics will become a part of its ranking algorithm, every now and then, I do performance reviews of the cool and pretty websites. Sometimes just for the kicks, sometimes for our **account-based marketing** efforts, and sometimes provoked by clients when we talk about the benefits of better website performance.

While I can and do use Bejamas original case studies when talking with clients (like the last one, how we helped [Backlinko move to headless WordPress and Next.js](https://bejamas.io/blog/backlinko-case-study/) for better website performance), sometimes you do need to make a point on websites that are known to the clients.

Recently I came across Sumo’s [The Best Homepages Online](https://sumo.com/stories/best-homepages) post and wanted to check the performance and CWV of those together with some of the tools and their homepages I use in everyday work. So, this is just for kicks.😎
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6uamu83pbuwu8zw2byo8.jpg)
I’ve used the same approach measuring these previously explained in this post [here](https://dev.to/cookieduster_n/are-gatsby-websites-fast-47jn). 
## Takeaway
Time and time again, we see brands fail when it comes to performance. That is if you stick to the numbers.

No doubt performance is hyped these days thanks to big G. While it is true that website speed/performance influences user experience, conversions, and, will soon, organic search ranking, it is also true you have to put your website performance in the context that matters.

That means in the context of the tech stacks you use, functionalities your website just has to have, the industry your business is in, audience expectations, and personal preferences, as I tried to explain in [the performance vs. functionalities](https://bejamas.io/blog/performance-vs-functionality/) post.

To give you an example, say you run a website in an industry (and keywords you’ll try to rank for) for which it is expected to have video or animation on a page. Most certainly, your performance won’t be that great. But it is also doubtful your text, and images-only page with excellent performance scores would rank well for industry-related keywords. On top of that, the page probably won’t convert the targeted audience well either because it did not deliver what is expected.

Performance, vital as it is, is just one piece of the puzzle that influences your potential buyers’ journey. It’s balancing all of them what matters and what brings the best business results.
DISCUSS: The blurred line between front-end and fullstack
Tags: discuss, watercooler, webdev
Published: 2021-05-07 14:05:12

The meaning of a "front-end webdeveloper" has really shifted over the years as more technologies started becoming the norm. Here are two of my favourite articles that talk about this: 
- [**CSS Tricks**: ooooops I guess we’re* full-stack developers now](https://css-tricks.com/ooooops-i-guess-were-full-stack-developers-now/)
- [**Brad Frost**: front-of-the-front-end and back-of-the-front-end web development](https://bradfrost.com/blog/post/front-of-the-front-end-and-back-of-the-front-end-web-development/).

# Front-ends without frontiers

I've started off as a front-end webdeveloper myself. As I started learning more back-end technologies it was hard for me to tell when I could start considering myself a fullstack. Even today, I'm not actually sure where the front-end ends and where the back-end begins.

The front-end has become such a blurred subject that it made job hunting exceedingly slower. Now you have to carefully read every job description just to determine what kind of "front-end webdeveloper" they're talking about.

I've even seen job descriptions that use front-end and fullstack interchangeably. Yes. Not even sure if that's intentional or they're a little confused themselves. 😶

# ✍ Comment below answering the following questions

1. Do you consider yourself a fullstack webdeveloper? Why?
2. If you could make a clear definition of "front-end" and "fullstack", what would it be?

---

![Thalita logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sa0hfs0886uf0g7c0b7e.png)

[Twitter](https://twitter.com/thalitadev) | [Website](https://thalita.dev)
A Complete Beginners Guide of Predis Package
Tags: predis
Published: 2021-05-07 17:45:20

Predis does not require any additional C extension by default, but it can be optionally paired with phpiredis to lower the overhead of the serialization and parsing of the Redis RESP Protocol.

More details about this project can be found on the frequently asked questions.

#Main features

    Support for Redis from 2.0 to 6.0.
    Support for clustering using client-side sharding and pluggable keyspace distributors.
    Support for redis-cluster (Redis >= 3.0).
    Support for master-slave replication setups and redis-sentinel.
    Transparent key prefixing of keys using a customizable prefix strategy.
    Command pipelining on both single nodes and clusters (client-side sharding only).
    Abstraction for Redis transactions (Redis >= 2.0) and CAS operations (Redis >= 2.2).
    Abstraction for Lua scripting (Redis >= 2.6) and automatic switching between EVALSHA or EVAL.
    Abstraction for SCAN, SSCAN, ZSCAN and HSCAN (Redis >= 2.8) based on PHP iterators.
    Connections are established lazily by the client upon the first command and can be persisted.
    Connections can be established via TCP/IP (also TLS/SSL-encrypted) or UNIX domain sockets.
    Support for Webdis (requires both ext-curl and ext-phpiredis).
    Support for custom connection classes for providing different network or protocol backends.
    Flexible system for defining custom commands and override the default ones.

#How to install and use Predis

This library can be found on Packagist for an easier management of projects dependencies using Composer. Compressed archives of each release are available on GitHub.

#Loading the library

Predis relies on the autoloading features of PHP to load its files when needed and complies with the PSR-4 standard. Autoloading is handled automatically when dependencies are managed through Composer, but it is also possible to leverage its own autoloader in projects or scripts lacking any autoload facility:
[A Complete Beginners Guide of Predis Package](https://www.codecheef.org/article/a-complete-beginners-guide-of-predis-package)
[Laravel 8.x Cursor Based Pagination Example](https://www.codecheef.org/article/laravel-8-cursor-based-pagination-example)
My [Automated] Trello Movie Organizer
Tags: trello, aws, lambda, fsharp
Published: 2021-10-20 17:44:02

I use Trello for [everything](https://dev.to/fischgeek/why-i-moved-my-notes-to-trello-po9). It only made sense (back when I did this) to put and track my movie collection into Trello.

It all started as an Excel file that I used to keep track of what movies I owned, where they were, who had them and what-not. As my development skills grew, the more I played with the movie list.

I always felt like I was in between technologies and didn't possess the necessary skills to pull off what I wanted to achieve. I used [AutoHotkey](https://autohotkey.com), C# with WinForms, WPF, I even went the painful route of vanilla HTML. Ultimately, these projects all failed. 

I finally got an ASP.NET project working running on a Virtual Server on my home computer. You can see the issues with this setup, right? And, running a Windows server on Azure or AWS is only free for a limited time. This was not going to make me money so those options were out.

Recently, I learned about AWS Lambda. No, I haven't been living under a rock. I just simply didn't know about it, not to mention how to hold it.

At any rate, I finally figured it out and I gotta say I'm very happy with it!

In a nutshell, here's what I did...
1. Created an FSharp Lambda project in Visual Studio
1. Wrote the logic for handling the events I was interested in
1. Hooked up the Lambda with an AWS API Gateway
1. Registered a Webhook event in Trello's API

The result:
* A new movie (Card) is added
* Trello fires a Webhook event to my Lambda function's URL
* The Lambda function 
  * grabs the name of the new Card
  * asks The Internet Movie Database (not IMDB) for a match
  * selects the best match
  * updates the Card Title with the proper movie title
  * updates the Card Description with the movie's synopsis
  * updates the Card's Cover with the movie's poster

See it in action:
{% youtube -q42-L8C1N8 %}
How to uppercase the first letter of a string in JavaScript
Tags: javascript, beginners, string
Published: 2021-05-07 22:50:24

JavaScript offers many ways to capitalize a string to make the first character uppercase. Learn the various ways, and also find out which one you should use, using plain JavaScript.

## 1. chartAt + slice
The first way to do this is through a combination of `cartAt()` and `slice()`. With  `chartAt()` uppercases the first letter, and with `slice()` slices the string and returns it starting from the second character:

```javascript
const name = 'codax';
const nameCapitalized = name.charAt(0).toUpperCase() + name.slice(1);
// expected output: "Codax" 
``` 
You can create a function to do that:
```javascript
const capitalize = (s) => {
  return s.charAt(0).toUpperCase() + s.slice(1)
}

capitalize('codax'); // "Codax"
```

## 2. Replace function
My favorite is with `replace()` because I love regex (even if I'm not an expert) and regex is more customizable in general.

```javascript
const name = 'codax';
const nameCapitalized = name.replace(/^\w/, (c) => c.toUpperCase()));
// expected output: "Codax"
```
You can also make it a function:
```javascript
const capitalize = (s) =>
  return s.replace(/^\w/, (c) => c.toUpperCase()));
}

capitalize('codax'); // "Codax"
```

### Conclusion
For readability, I recommend the first option (`chartAt` + `slice`), and for speed, I recommend the second option (`replace`).
If you know other/better ways please leave below in the comments, or how to improve on the ones mentioned here.
Thanks.
5 Easy LeetCode questions to start competitive-coding
Published: 2021-05-08 16:46:17

_These are 5 LeetCode questions which boost my confidence to start competitive programming and there can be many easy ones out, but I started with these. I provided my Python solutions to the problems, these solutions can be optimized too, just sharing my approach :)_

## 1. [FizzBuzz](https://leetcode.com/problems/fizz-buzz/)

```python
class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        l=[]
        for i in range(1,n+1):
            if i%3==0 and i%5==0:
                l.append("FizzBuzz")
            elif i%3==0:
                l.append("Fizz")
            elif i%5==0:
                l.append("Buzz")
            else:
                l.append(str(i))
        return l
```

## 2. [Single Number](https://leetcode.com/problems/single-number/)

```python
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return 2*sum(set(nums))-sum(nums)
```

## 3. [Intersection of two arrays](https://leetcode.com/problems/intersection-of-two-arrays/)

```python
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return set(nums1).intersection(set(nums2))
```

## 4. [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/)

```python
class Solution:
    def fib(self, n: int) -> int:
        m=0
        if n==0:
            return 0
        elif n==1:
            return 1
        else:
            m=self.fib(n-1)+self.fib(n-2)
            return m
```

## 5. [Array Partition-I](https://leetcode.com/problems/array-partition-i/)

```python
class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        nums.sort()
        return sum(nums[::2])
```

_Just make sure to start your journey no matter if you're a beginner or pro. I just started off and I can definitely feel the difference, be it in my problem-solving ways or maintaining consistency. Hope this article helps!!_