teleren/devto huggingface dataset:
Destructuring in JavaScript
Tags: webdev, javascript, beginners, tutorial
Published: 2022-06-08 16:16:54

This is probably going to be a shorter article on a very important and useful concept. In this article, I'll be going over some basic uses of the destructuring assignment in JavaScript! 

The destructuring assignment is a special syntax that allows us to extract properties from an object or array. From there, we are able to bind them to variables.

Destructuring is super useful to know once you understand the basics of it's usage. This concept allows you to take data from arrays, objects, and  maps and attach them into new and unique variables. We can even extract multiple properties or elements from an array at a time.  

Let's look at an example to understand how this concept works:

Instead of writing this:

```JavaScript
const inviteList = ["John", "Anna", "Paulina", "Chris"];

const guestOfHonor = inviteList[0];
const guestOne = inviteList[1];
const guestTwo = inviteList[2];
const guestThree = inviteList[3];

```

We can use destructuring to unpack our values from arrays or objects attach them to variables. 

```JavaScript

const inviteList = ["John", "Anna", "Paulina", "Chris"];

const [honoredGuest, firstGuest, secondGuest, thirdGuest] = inviteList;


```
By destructuring, we are able to assign to the honoredGuest (John), firstGuest (Anna), secondGuest (Paulina), and thirdGuest(Chris).


---


Let's look at an example when working with objects!

```JavaScript
const cat = {
name: 'Cleo',
age: 3,
breed: 'Calico'
}

const { name, age, breed } = cat

console.log(name) //Cleo
console.log(age) // 3
console.log(breed) // Calico

```

Above, we assign separate variables to the name, age, and breed of a cat. 

---

Now let's see how we can change the names of the variables. 

```JavaScript
const cat = {
name: 'Cleo',
age: 3,
breed: 'Calico'
}

const { name: catName, age: catAge, breed: catBreed } = cat

console.log(catName) //Cleo
console.log(catAge) // 3
console.log(catBreed) // Calico

```

---

Let's look a nested example of a destructuring assignment for an array: 

```JavaScript

const nestedArr = [1, [2,4], [5,7,9]]

const [first, [second, third], fourth] = nestedArr

console.log(first) //1
console.log(second) //2
console.log(third) //4
console.log(fourth) // [5,7,9]

```

---

Finally, let's look at destructuring assignment with objects:

```JavaScript

let employee = {
id: 1001,
name: {
   firstName: 'John',
   lastName: 'Doe'
   }
};

const {
   name: {
    firstName,
    lastName
    },
 name
} = employee;

console.log(firstName); // John
console.log(lastName); // Doe
console.log(name); //{firstName: 'John', lastName:'Doe'}


```
This is just the tip of the iceberg as to what destructuring can do!
JNoSQL CriteriaQuery API preview
Tags: jakartaee, nosql, mongodb, java
Published: 2022-06-09 09:46:08

Have you ever heard of [Jakarta NoSQL](https://jakarta.ee/specifications/nosql/) ?

Since JavaEE adoption and rebranding by [Eclipse Foundation](https://www.eclipse.org/), I consider it the most exciting feature for the upcoming Jakarta EE 10.

By splitting the NoSQL databases in four different abstractions (**Column**, **Key-Value**, **Graph** and **Document**), it allows agnostic coding with such technologies. So, for example, you could access both MongoDB and ElasticSearch with the same codebase, for they are both categorized and exposed as **Document** databases.  

Cool, isn't it ?

Personally, I already adopted it even if both specification and default implementation, [JNoSQL](http://www.jnosql.org/), are in preview state and may lack some functionalities.

For example, I found myself struggling with the absence of a proper Criteria API, allowing us to build up a criteria query object programmatically, where we could apply different kinds of filtration rules and logical conditions.

Also, following the JPA example, I would expect such Criteria API to be used in combination with an automatically generated Metamodel attributes.

Typos and backend don't get on well, do they ?

So I decided to contribute myself and, with the support of [Otavio Santana](https://otaviojava.com/), JNoSql Lead, this functionality has been delivered in the brand-new 1.0.0-b4 version.

Looking for a concrete example ?
Here you are :

```
CriteriaQuery<Person> personQuery = template.createQuery(Person.class);

EntityQueryResult<Person> executeQuery = template.executeQuery(
        personQuery.select().where(
                personQuery.from().get(
                        Person_.name
                ).equal(
                        "Poliana"
                ).or(
                        personQuery.from().get(
                                Person_.age
                        ).greaterThanOrEqualTo(17)
                )
        )
);

Stream<Person> stream = executeQuery.getEntities();
```

For the moment, it has been published as a [MongoDB extension](https://github.com/eclipse/jnosql-mapping-extension/tree/master/mongodb-extension) but, with the community approval and once it's stable enough, it will brought to the main API and will work with every other **Document** NoSQL databases.

There are still many features to add and possibilities to explore.
For example, I strongly believe that Criteria API should also support update and delete operations too.
Also, wouldn't it be nice to have this working with other NoSQL abstractions (**Column**) ?

What do you think ?
Take a Break!!!
Tags: productivity, mentalhealth, tutorial, webdev
Published: 2022-06-09 09:41:22


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/50rzo8gn712w9n7sjy77.jpg)
Hello there 👋! It has been a minute. How you doing? Sometimes as a person that's all you need, someone to ask how you doing.

Today we going to talk about taking a break, YES I know, you probably don't have time for taking a break. We do so much work that there isn't any time for taking a break, as there is ALWAYS something to do. Although sometimes, just, sometimes doing what you supposed to do and what you need to do, do not go hand in hand.

You probably already know that you should be taking a break. Although we often can get carried away and simply forget to step away and take a breather. If you are one of them, like me, here is something you should know about taking breaks to take them more seriously.

Taking a break is not only for taking a break from your work, YOU NEED A BREAK FROM FAMILY TOO. Have you noticed that sometimes family can be a bit much. They can be very demanding, parenthood is another story altogether.


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

Taking a break is as much important as doing the work you do on daily basis. Probably that is why ME TIME came about. At the end of the day you only have 1 life to live, with so many people to take care of, directly or indirectly. You need to take better care of yourself.



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

What can you do to relax?

- Listen to music. It's a great way to boost creativity.

- Do some journaling. Express your thoughts and unwind.

- Meditation, can assist in relaxing your mind. Take 15 minutes or less to just be

- Play a game or solve a puzzle

- Take a walk, go outside and see the beauty that is mother nature

There could be a number of things to do to help you relax, seriously TAKE A BREAK! I could give you a number of statistics on how taking a break is beneficial not only for you but for everything around you. Everything being your family, friends and your work. Taking care of you is as much important as taking care of other people or work.

Now, we talked about taking a break, the things you could probably do to relax. Basically if you want to be more productive, take as many breaks as possible. Relax, take a breather, it's not only good for you it is also beneficial for you. It is time for my break NOW. But before I do, remember that you are also IMPORTANT, you are awesome and you deserve a BREAK.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7by28xgezesiuklacjjg.jpg)

Enjoy your "ME TIME"
How to Work with Celery in Django using TLS RabbitMQ configuration
Tags: celery, django, rabbitmq, tls
Published: 2022-06-09 09:35:59

I want to know if celery supports TLS enabled RabbitMQ configuration?

and if yes then how we can make it work or any workaround possible

I have tried by using below source in my celery.py file of my Django application

```
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
import ssl

os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<app_name>.settings')
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

app = Celery('<app_name>')

app.conf.broker_use_ssl = {
  'keyfile': '<path>/client_key.pem',
  'certfile': '<path>/client_certificate.pem',
  'ca_certs': '<path>/ca_certificate.pem',
  'cert_reqs': ssl.CERT_REQUIRED
}
app.conf.broker_url = 'amqps://rabbitmq.example.com:5671/vhostname'

app.conf.broker_login_method = 'EXTERNAL'
app.autodiscover_tasks()
```

through the above code I am able to connect to the rabbitMQ server
but background tasks are not processing

I highly appreciate your help onto this
Minimum Absolute Difference
Tags: leetcode, dsa, theabbie
Published: 2022-06-09 09:30:40

Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.

Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows

*   `a, b` are from `arr`
*   `a < b`
*   `b - a` equals to the minimum absolute difference of any two elements in `arr`

**Example 1:**

**Input:** arr = \[4,2,1,3\]
**Output:** \[\[1,2\],\[2,3\],\[3,4\]\]
**Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.

**Example 2:**

**Input:** arr = \[1,3,6,10,15\]
**Output:** \[\[1,3\]\]

**Example 3:**

**Input:** arr = \[3,8,-10,23,19,-4,-14,27\]
**Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\]

**Constraints:**

*   `2 <= arr.length <= 105`
*   `-106 <= arr[i] <= 106`

**SOLUTION:**

    class Solution:
        def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
            n = len(arr)
            mindiff = float('inf')
            mindiffindexes = []
            arr.sort()
            for i in range(n - 1):
                currdiff = arr[i + 1] - arr[i]
                if currdiff < mindiff:
                    mindiff = currdiff
                    mindiffindexes = []
                if currdiff == mindiff:
                    mindiffindexes.append(i)
            return [[arr[i], arr[i + 1]] for i in mindiffindexes]
GitHub Skills 🦄🛠️
Tags: github, beginners, tutorial, news
Published: 2022-06-09 09:12:34

This month, GitHub announced GitHub skills! A new way to learn Github basics or improve your knowledge!🎉

I'm turning into a massive fan of GitHub, first I only used it to display my work, but now, I go there every day to check the news, the community, and I really want to start to get more involved!

![GitHub Skills](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1kuoa0roncuusw5a6txb.png) 

So, I'm super thrilled with this announcement and for my first impression what I can say is:


- If you are a beginner at GitHub there is a perfect course for you! I recommend you to check [Introduction to Github](https://github.com/skills/introduction-to-github)

- If you are already familiar with GitHub and you want to improve your knowledge, I found this one very interesting [Hello GitHub Actions](https://github.com/skills/hello-github-actions) where you will learn how to create and trigger workflow files as well as how to find them

- If you have an idea for an Open Source project, or you would like to have a portfolio page then the [GitHub Pages](https://github.com/skills/github-pages) will be perfect for you!

It's also available a free [open-source](https://github.com/skills/template-template) template if you want to build your own course


Have you already tried any of the courses? Share your ideas ❤️
"Crossing the Rubycon" at Code Your Future
Tags: career, codenewbie
Published: 2022-06-09 09:06:41

Back in late April, I hosted a bookclub at Code Your Future, an international charity where I [volunteer](https://codeyourfuture.io/blog/volunteer-stories/volunteer-stories-nadia/) as a personal development trainer.

The event was dedicated to "Crossing the Rubycon: How to Learn to Code and Build a Programming Career", a [book](https://beetlehope.gumroad.com/l/fhIFH) I wrote and published in 2020 to help people from non-STEM backgrounds learn to program and build a career in tech.

This is a belated vlog from that day:

{% embed https://youtu.be/yHqnwyrl-hI %}

🛒 Check out the book:
https://beetlehope.gumroad.com/l/fhIFH
https://www.amazon.co.uk/Crossing-Rubycon-Learn-Programming-Career-ebook/dp/B08Q7FS36K
How to style a checkbox using CSS
Tags: css, html, webdev, jetthoughts
Published: 2022-06-09 09:02:15

In this post I’l show you exactly how to make awesome checkboxes with just CSS.
```html
<div>
  <input id="first_name" type="checkbox" checked="checked">
  <label for="first_name">First Name</label>
</div>
```
Let’s take a few simple steps:

- Hide the browser’s default checkbox.
- Create a custom checkbox. We will use a pseudo-element `:before` for the substrate.
- On mouse-over, add a darkly on 10% background color.
- Style the checkmark/indicator, by pseudo-element `:after`
- Show or hide the checkmark when checked.

## Hide the browser’s default checkbox
```css
input {
  position: absolute;
  opacity: 0;
  height: 0;
  width: 0;
}
```

## Create a custom checkbox
```css
label {
  position: relative;
  display: block;
  padding-left: 30px;
  cursor: pointer;
}
label:before {
  content: '';
  position: absolute;
  top: 50%;
  margin-top: -10px;
  left: 0;
  display: block;
  height: 20px;
  width: 20px;
  background-color: #50CDBE;
  border-radius: 3px;
}
```

## On mouse-over, add a darkly on 10% background color
```css
label:hover:before {
  background-color: #1AE6E6;
}
```

## Style the checkmark/indicator
```css
label:after {
  content: '';
  position: absolute;
  left: 7px;
  top: 1px;
  width: 5px;
  height: 10px;
  border: solid #333;
  border-width: 0 3px 3px 0;
  transform: rotate(45deg);
  opacity: 0;
}
```

## Show or hide the checkmark when checked
```css
input:checked + label:after {
  opacity: 1;
}
```
String Compression
Tags: leetcode, dsa, theabbie
Published: 2022-06-09 09:00:43

Given an array of characters `chars`, compress it using the following algorithm:

Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:

*   If the group's length is `1`, append the character to `s`.
*   Otherwise, append the character followed by the group's length.

The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`.

After you are done **modifying the input array,** return _the new length of the array_.

You must write an algorithm that uses only constant extra space.

**Example 1:**

**Input:** chars = \["a","a","b","b","c","c","c"\]
**Output:** Return 6, and the first 6 characters of the input array should be: \["a","2","b","2","c","3"\]
**Explanation:** The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".

**Example 2:**

**Input:** chars = \["a"\]
**Output:** Return 1, and the first character of the input array should be: \["a"\]
**Explanation:** The only group is "a", which remains uncompressed since it's a single character.

**Example 3:**

**Input:** chars = \["a","b","b","b","b","b","b","b","b","b","b","b","b"\]
**Output:** Return 4, and the first 4 characters of the input array should be: \["a","b","1","2"\].
**Explanation:** The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".

**Constraints:**

*   `1 <= chars.length <= 2000`
*   `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.

**SOLUTION:**

    class Solution:
        def compress(self, chars: List[str]) -> int:
            n = len(chars)
            i = 0
            while i < n:
                ctr = 1
                while i < n - 1 and chars[i] == chars[i + 1]:
                    i += 1
                    ctr += 1
                i += 1
                if ctr == 1:
                    chars.extend([chars[i - 1]])
                else:
                    chars.extend([chars[i - 1]] + list(str(ctr)))
            for i in range(n):
                chars.pop(0)
            return len(chars)
Cmocka Quick Start
Tags: c, testing
Published: 2022-06-07 20:39:35

Today I have occasion to learn a C unit test framework again. This comes about in my career every 3 years or so, so each time, I do a quick re-survey of what's available and pick something that looks good. This time, I've picked [cmocka](https://cmocka.org/).

The main page links to the API documentation and a slideshow. Neither of these, in my quick perusal, actually give you an example of building a project with Cmocka. I really appreciate it when there's some kind of quickstart skeleton project you can just roll with, so I've taken their [first example from the API](https://api.cmocka.org/) and done just that.

The first thing you'll want to do to follow along here is download cmocka. I grabbed the [source release of 1.1.5](https://git.cryptomilk.org/projects/cmocka.git/).

Untar the archive:

```bash
tar -xzvf cmocka-1.1.5.tar.gz
```

build the cmocka library. For my project, I want the cmocka library to be statically compiled, so I configure cmocka with cmake accordingly:

```bash
cd cmocka-1.1.5
mkdir build
cd build
cmake -DWITH_STATIC_LIB=ON ..
make
```

cmocka will have built the `libcmocka-static.a` library to the `build/src` directory. This is what you'll need to link your tests against to get them to build. Using the static cmocka library means that the library will be copied into the binary that's created. This makes it so that the C interpreter doesn't have to find libcmocka at runtime. This is handy if you don't want to install the libcmocka library on your system, or if you're going to be running your tests in an environment other than you development environment. Be aware though that this does make your binary larger and has other portability concerns attached to it, so in lots of (production) cases, static libraries are _not_ the way to go.

Next, make yourself a `test.c` file with the following contents:

```C
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) {
    (void) state; /* unused */
}
int main(void) {
    const struct CMUnitTest tests[] = {
        cmocka_unit_test(null_test_success),
    };
    return cmocka_run_group_tests(tests, NULL, NULL);
}
```

and build your test file:

```bash
gcc -I cmocka-1.1.5/include/ -L cmocka-1.1.5/build/src/ test.c -l:libcmocka-static.a
```

This will have produced a `a.out` binary. Run it!

```bash
$ ./a.out 
[==========] Running 1 test(s).
[ RUN      ] null_test_success
[       OK ] null_test_success
[==========] 1 test(s) run.
[  PASSED  ] 1 test(s).
```

And there you go. If you want to write unit tests for real C code, the only difference is you need to `#include` your headers for the source you're testing, and compile the source files you're testing along with the tests.
I Created A Simple SMS Site Using MERN Stack
Tags: react, showdev, devjournal, javascript
Published: 2022-06-09 08:52:49

## Introduction

Hello! 😀

I created a simple social media site using the MERN stack, so I just wanted to show you guys it.
I'm a newbie when it comes to React so it's not something fancy but it's the first thing I created using React. 😆

---

## Implementing Signup

![Signup Image](https://i.ibb.co/5vPKg94/signin.png)

I made the Signup form simple. All it requires is a Name, Email and Password.
Next I'm thinking of adding a confirm password field to prevent password confusion, I would also like to make it so that the user has to use a strong password with a mix of numbers and symbols. 👀

Once the user is registered they are taken to the signin page.

---

## Implementing Signin

![Signin Image](https://i.ibb.co/6YqNF9w/signup.png)

The signin form is pretty standard you log in via email/password. Once the user has signed in the session is managed via a unique JWT token.

Here I would eventually like to implement OAuth. 

---

## Implementing Newsfeed

![Newsfeed](https://i.ibb.co/ZzV9yjd/newsfeed.png)

The Newsfeed page is shown once the user has signed in, it only displays posts from people the user is following. 

To the right is people the user hasn't followed yet and gives the user quick access to their profile and/or to follow them. 

Posting allows both text and photo. I would also like to implement video support and possibly access to the camera so the user can upload their camera image.

Once a post is submitted the poster can delete the post if needed, other users are able to like the post and comment.

---

## Implementing Profile

![Profile](https://i.ibb.co/jgDhG3n/profile.png)

The profile page shows the user's profile, the user can edit their profile and can also delete it.

At the bottom the user can view the posts they have made, who they are following and their followers.

![Followers](https://i.ibb.co/Dks1qPg/followers.png)

The ui was made with the help of Material Design. 😎

---

## Conclusion 

Here I have shown a simple SMS site I built using the MERN stack. 

I'm pretty new when it comes to frontend stuff, but I had a lot of fun building it. 😆
Though I did spend quite a bit of time trying to translate the errors that React somethings throws. 🥴

Once I get better at React I would like to have a go using Tailwind instead of Material Design.
I hope you enjoyed my simple SMS site.

The source code can be found via Github:
https://github.com/ethand91/sample-sms

I also used the following book as a reference to help me build it:
https://amzn.to/3tpN9eY

Although package versions etc, have changed quite a bit. 😅
Next I'm thinking of trying to build an online learning platform. 👀

---

Like me work? I post about a variety of topics, if you would like to see more please like and follow me.
Also I love coffee. 

[![“Buy Me A Coffee”](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/ethand9999)
Shuffle the Array
Tags: leetcode, dsa, theabbie
Published: 2022-06-09 08:30:38

Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.

_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.

**Example 1:**

**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\] 
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].

**Example 2:**

**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]

**Example 3:**

**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]

**Constraints:**

*   `1 <= n <= 500`
*   `nums.length == 2n`
*   `1 <= nums[i] <= 10^3`

**SOLUTION:**

    class Solution:
        def shuffle(self, nums: List[int], n: int) -> List[int]:
            return [nums[(i >> 1) + n * (i & 1)] for i in range(2 * n)]