teleren/devto huggingface dataset:
This Tailwind Twitter Drama Could Have Been Avoided😓
Tags: tailwindcss, webdev
Published: 2023-01-22 01:00:22

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

So this is the tweet that caused the massive Tailwind drama on twitter recently. All because @shadcn decided to breakup tailwind classes and group them into different lines. All because @shadcn didn't know about [Prettier plugin for Tailwind CSS](https://tailwindcss.com/blog/automatic-class-sorting-with-prettier)

With this plugin, Tailwind classes will be intelligently sorted with every save. Seriously I don't know why they just don't include this plugin with Tailwind by default. Here is the quick summary:

> The actual order of the different utilities is loosely based on the box model, and tries to put high impact classes that affect the layout at the beginning and decorative classes at the end, while also trying to keep related utilities together.

Tailwind is honestly magic people. If you haven't tried it, you're missing out. And if you have tried it but didn't like it, try it a little longer.
Toggling inside [array] in React
Tags: react, javascript, webdev, programming
Published: 2023-01-22 00:58:59

When we focus on much complex logic to solve, then sometimes some simple logic is fade away from our mind... (because we pressure our brain to lode over cognitive bandwidth) & in that situation, we are just stuck at that moment...

So it's helpful to identify reusable logic of code and keep a reference somewhere else, so when needed we can easily reuse that code snippet...

So, this is simple reusable **little code snippet** for data toggling inside [array]...


```jsx
const [inputIds, setInputIds] = useState([]);

const handleBtnToggling = (e) => {

    const id = e.target.id;

    setInputIds((pre) => !pre.includes(id) 
       ? [...pre, id] 
       : pre.filter((data) => data !== id)
    );

};
```
"Utils.ts" Security?
Tags: javascript, typescript, webdev
Published: 2023-01-22 00:14:31

Up until now I always put my `client side` and `server side` utils on the same file

**1st Method**
```
---rootfiles...
---utils.ts
```

**2nd Method**
but maybe this approach is better and more secure 

```
---Utils
------ClientUtils.ts
------ServerUtils.ts
------SharedUtils.ts
```
This method makes it clearer which code is intended to run on the client side and which code is designed to run on the server side, which can help you manage and comprehend your codebase more easily.

---

## QUESTION

Let's assume we are doing named imports
Is using 1st method can expose some server side utils in the client side?
jikAPI - The #1 Job Search API in Kenya.
Tags: api, software, programming, development
Published: 2023-01-22 00:10:39

Excited to announce that the development of a Job Search API -  **jikAPI** - a powerful tool for all job seekers in Kenya, is underway.

The API allows users to search for job opportunities that have been recently posted by employers in Kenya. It provides a simple and easy-to-use interface for users to find the perfect job for them.

**jikAPI** offers a variety of search parameters for users to filter their results by. Users can search for jobs by keyword, location, job category, etc.

One of the most useful features of the Job Search API is its real-time updates. As soon as a new job is posted, it is added to the API's database and becomes searchable by users. This means that users will never miss out on a new job opportunity again.

The API will also provide detailed information about each job listing, such as the job title, company, location, and a link to the job listing on the employer's website. This makes it easy for users to apply for jobs they are interested in.

Searching for a job can be a stressful and time-consuming process. That's why **jikAPI** was created to make the process as easy as possible. With the API, web applications that use it can help their users quickly and easily find job opportunities that are relevant to them, saving them time and effort.

Stay tuned for updates on its progress and release date!
Expresión regular para remover caracteres al final
Published: 2023-01-22 00:09:03

Expresión regular para remover N caracteres al final de todas la líneas de un archivo, en este ejemplo 1, usando notepad++.

## .{8}$


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

https://stackoverflow.com/questions/15454869/how-to-remove-the-last-13-or-n-characters-of-every-line-using-notepad
[PHP Guidelines series] Adapter design pattern + a dangerous workaround to implement Class Adapter
Tags: php, oop, designpatterns, tutorial
Published: 2023-01-22 00:07:10

As announced [here](https://dev.to/nikolastojilj12/announcement-detailed-php-development-practices-series-1jg5), I am working on a series of posts related to good and bad development practices.

## Adapter design pattern

The third design pattern covered by this series of articles is Adapter design pattern. The main article, its sub-articles and a solid amount of runnable examples is available at: https://github.com/constup/php-guidelines/tree/master/src/DesignPatterns/Structural/Adapter

Having the ability to use an interface or class, which might come from a third party (Composer) library, and is incompatible with interfaces that your application can use, is pretty neat.

The theory defines a couple of ways to implement the Adapter, however, only one of them is available in PHP - the so called "Object Adapter". Other ways ("Class Adapter" and "Two way adapter") can not be implemented in PHP because they require a language which supports multiple inheritance, which PHP doesn't.

I've come across a couple of resources which are describing a workaround to implement the Class Adapter in PHP (or in any language which does not support multiple inheritance) including a really simplified example. The example looks like it works and does the job, but has a terrible flaw which I have covered (with examples) in the linked repository. 

## More to come later

While the article and examples are providing a solid coverage of the Adapter design pattern, if observed as a separate concept and implemented on a controlled set of examples, there is also a need to cover it from a different perspective - usage in the real world. There is a couple of things which bothers me regarding Adapter and a couple of other design patterns which deserve separate dedicated analysis. I simply can not shake the feeling that the 24 "well known" and (numerously) repeated design patterns are a bit bloated, and that the Adapter, although useful, belongs to this bloatware. But, more on that later in a separate article.

Enjoy. Comment. Like. Subscribe.

If you liked the article,...
[![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kugdh9szk858ncio2mzi.png)](https://www.buymeacoffee.com/puEW3HvWvP)
Poem on Web Development
Tags: webdev, html, css, javascript
Published: 2023-01-22 00:03:05

**Web development** is like a **poem**,
With code as the verse,
Design as the meter,
And user experience as the rhyme.

Each line is crafted with care,
To create a website fair,
With HTML as the foundation,
CSS and JavaScript for decoration.

The browser is the stage,
For your digital page,
Responsive design, the play,
For users **on** any device to engage.

Debugging is the editing,
Ensuring the website is dediting,
Deployment the final stage,
For the world to see the page.

A website is a work of art,
A **poem** for the digital age,
Built with love and skill,
To inspire and thrill.

| Poetry every other week - Follow for updates  | <a href='https://www.instagram.com/efecollinsevb/' target="_blank"><img alt='Instagram' src='https://img.shields.io/badge/Instagram-100000?style=for-the-badge&logo=Instagram&logoColor=ffffff&labelColor=fa7e1e&color=d62976'/></a> <a href='https://twitter.com/EfeCollins7' target="_blank"><img alt='Twitter' src='https://img.shields.io/badge/Twitter-100000?style=for-the-badge&logo=Twitter&logoColor=ffffff&labelColor=00acee&color=00acee'/></a> |
|---|---|
How to get full CSS selector path?
Published: 2023-01-21 23:07:08

I need to get full CSS selector path for element like this

`html > body > div > div:eq(1) > div > div:eq(4) > div > div:eq(1) > div > div:eq(0) > p:eq(21)`

but what I get currently from Chrome for example is something like this

`#post_1 > div:nth-child(2) > div.topic-body.clearfix.highlighted > div.topic-meta-data > div.names.trigger-user-card > span > a`
Any tool to get the full path ?
Hashes with default procs
Tags: ruby, programming, tutorial, birds
Published: 2023-01-21 22:41:00

---
title: Hashes with default procs
published: true
description: Setting a default proc on a ruby hash
tags: ruby, programming, tutorial, birds
canonical_url: https://www.codeandclay.com/2023/01/21/z-hash-default-proc/ 
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j5zblvwsu6cc7ws33c6l.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-01-21 22:33 +0000
---

Our app uses a list of bird names.

```ruby
bird_names = %w(
  redbreast
  crow
  eagle
  hedge-sparrow
  sparrow
  pigeon
  owl
  penguin
)
```

One day, someone mentions that a couple of the birds – the redbreast and hedge-sparrow – are now more commonly known as the robin and dunnock. Not wanting to confuse our users, we decide we should use [the modern vernacular](https://bou.org.uk/british-list/bird-names/).

Instead of going back and changing the data we can create a new list of bird names – updating any names that have changed with their modern equivalents.

We pair the old with the new names in a hash.

```ruby
bird_names_and_modern_equivalents = {
  "redbreast" => "robin",
  "hedge-sparrow" => "dunnock"
}
```

We treat the hash as a proc.

```ruby
> bird_names.map &bird_names_and_modern_equivalents
```

The result isn't quite what we want. We have the new names for the redbreast and the dunnock but all the other birds are now `nil`.

```ruby
=> ["robin", nil, nil, "dunnock", nil, nil, nil, nil]
```

We want our list to contain the original names if there are no substitions in our hash.

Just as we can set a default hash value, we can also set a default proc.

Below, if we ask the hash for the value of a key that doesn't exist, it returns the value of the default proc instead. In this case, it returns the name of the bird we asked for unchanged.

```ruby
bird_names_and_modern_equivalents.default_proc = Proc.new { |_h, k| k }
```

```ruby
> bird_names.map &bird_names_and_modern_equivalents
=> ["robin", "crow", "eagle", "dunnock", "sparrow", "pigeon", "owl", "penguin"]
```
How to Add a Self-Referencing Security Group Rule via the AWS CDK
Tags: aws, cdk, security
Published: 2023-01-28 01:54:23

---
title: How to Add a Self-Referencing Security Group Rule via the AWS CDK
published: true
date: 2023-01-21 22:29:58 UTC
tags: AWS,CDK,security
canonical_url: https://benellis.cloud/how-to-add-a-self-referencing-security-group-rule-via-the-aws-cdk
---

![Post Cover Image](https://assets.benellis.cloud/images/selfrefsecgroup/self-ref-sec-group-cover.png)

If you look at the default VPC in your AWS account, you'll notice there's also a default Security Group. It includes an inbound rule that allows all traffic from itself, a self-referencing rule. This means that any resources with this Security Group attached would be able to communicate with each other over the allowed protocols and ports.

![Screenshot of default security group](https://assets.benellis.cloud/images/selfrefsecgroup/DefaultSecurityGroup.jpg)

It wasn't immediately obvious to me how to accomplish this via the CDK. It turns out, it's pretty simple. The first argument of the `addIngressRule()` method on the `SecurityGroup` takes an `IPeer`. `SecurityGroup` implements `IPeer`, so it is as simple as passing itself in as the first argument.

```
const selfRefSg = new SecurityGroup(this, "SelfRefSg", {
  vpc,
  allowAllOutbound: true,
})

selfRefSg.addIngressRule(
  selfRefSg,
  Port.allTraffic(),
  "allow local VPC traffic",
)

```

After running a `cdk deploy`:

![Screenshot of self-referencing rule](https://assets.benellis.cloud/images/selfrefsecgroup/SelfRefRule.png)

For a full example, check out the [GitHub repo](https://github.com/benb1n/SelfRefSecurityGroupsCDK) I put together.
Analyzing the 24 Hour Fitness QR Code format
Tags: qrcode, 24hourfitness
Published: 2023-01-21 22:29:20

24 Hour Fitness, like most gyms, lets you sign in with a QR code -- this QR code is generated in their [iOS app](https://apps.apple.com/us/app/24go-by-24-hour-fitness/id1291447822) and is only valid for a few minutes.

I wanted to see if I could create a QR code without using the application.

# QR Code format

The QR code format looks like this:

```
MBR01234567|1673568280102|4248F3FA-FDEE-478E-B23E-22C3286B2FA8
```

## Member ID

The first part is your 8-digit member ID. This ID is assigned when you sign up for a membership.

## Timestamp

The next part is a timestamp: 

Using any [epoch converter](https://www.epochconverter.com/), we can see when this QR code was generated:

![Epoch converter screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6jtaacw63eusnylxf4a4.png)

## ❔ Unknown ID  ❔ 

The next part is where things get tricky - I don't know what this field actually is. It looks like it can be either some kind of hash or ID, but for what?

### Format

This field consists of 32 hexadecimal digits, with 4 hyphens, for a total length of 36. The segment lengths are 8, 4, 4, 4, and 12.

### Variation?

I checked this field across 10 days of QR codes, and it was the same every time. So if it does change, it's on an interval of larger than 10 days (maybe every month?), or, it doesn't change.


### Hash?

Since the data portion is 32 characters long, and an MD5sum is also 32 characters long, my first idea was that it was an MD5sum of some kind. But, that begs the question, of what?

I tested the MD5sum of my membership ID and that didn't work, which makes sense, carrying both the membership ID and it's MD5sum wouldn't make much sense.

I also tried the MD5sum of my date of my birth, which didn't work.

### Device identification?

My first thought was that this field somehow identifies the current device that you're using. This would mean that if you installed the 24 hour fitness app on another device and used that to generate a QR code, the devices would have different ID fields. I unfortunately don't have a second device to test that hypothesis with.

If this field is used for device identification, it begs the question of, how is the application able to uniquely identify your device?

For iOS at least, there's a specific [UDID field](https://www.theiphonewiki.com/wiki/UDID).

However, my device UDID didn't match any part of this field, which rules out that possibility.

![My UDID from iTunes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ghvgdjwur7dqfdp9nev.png)
How to handle gRPC errors in NestJS
Tags: nestjs, node, grpc, microservices
Published: 2023-01-21 21:27:28

NestJS has a great way of creating microservices specially when it comes to gRPC! You can easily use gRPC in your NestJS applications without doing extra work.


### Error Handling: The Basic Solution

Handling errors correctly in microservices is really important. NestJS provides **RpcException** for this. Let's take a look at some code:

```ts
// user-service/src/find-user.query.ts

export class FindUserQuery implements IQuery {
    async execute(params: FindUserQueryParam): Observable<User> {
        const user = await this.repository.findOne({ id: params.id });
        
        if(!user) {
            throw new RpcException("User Not Found.");
        }

        return of(user);
    }
}
```

This example code shows how to throw exceptions that are microservice related. Although this works fine but there is a problem! If you want to send a HTTP error this will not help because you actually don't know what type of error this is.

We all know that **404** is a **Not Found** error but gRPC uses **5** for that. On the other hand since the **RpcException** Isn't only for gRPC (You can use this exception regardless of the transport method which you use), The client side wouldn't know that this is a **code 5** error.


### Efficient gRPC Error Handling

To solve the explained problem, you have to pass an object containing the gRPC error code. But let me save you!

I have published a library that provides some wrappers for the **RpcException**. It includes almost all commonly used gRPC error codes. The library provides 2 main features:

- Exception classes similar to NestJS built-in **HttpExecption**s
- Automatic conversion of gRPC error from your microservice servers to **HttpException** in the client



### How To Use The Library?

First install the library with any package manager you prefer.

```bash
npm i nestjs-grpc-exceptions
```

Then add the **GrpcServerExceptionFilter** to your gRPC server:

```ts
import { Module } from "@nestjs/common";
import { APP_FILTER } from "@nestjs/core";
import { GrpcServerExceptionFilter } from "nestjs-grpc-exceptions";

@Module({
  providers: [
    {
      provide: APP_FILTER,
      useClass: GrpcServerExceptionFilter,
    },
  ],
})
export class UserModule {}
```

Add the client interceptor to your client:

```ts
import { GrpcToHttpInterceptor } from 'nestjs-grpc-exceptions';

@Get(':id')
@UseInterceptors(GrpcToHttpInterceptor)
function findUser(@Param('id') id: number): void;
```

Now you can use the exception classes in your servers:

```ts
import {
  GrpcNotFoundException,
  GrpcInvalidArgumentException,
} from "nestjs-grpc-exceptions";

throw new GrpcNotFoundException("User Not Found.");
throw new GrpcInvalidArgumentException("input 'name' is not valid.");
```

And that is all you need.


Useful links:
- [Library On NPM](https://www.npmjs.com/package/nestjs-grpc-exceptions)
- [GitHub Repo Link](https://github.com/mohsenbostan/nestjs-grpc-exceptions)
- [My Personal Newsletter](https://bostan.dev)

Wish you bugless codes! ❤️
The ultimate package / software management system
Tags: productivity, packagemanager
Published: 2023-01-21 21:22:18

Hello Dev Community!

So, I made a post on Reddit about finding the "ultimate" package manager u could say. I realized that it might also be useful to share this post here so that others can help me. Any advice or recommendations would be appreciated. Thank you!!!

Here is the Reddit post:
{% embed https://www.reddit.com/user/Sham_Haydar/comments/10dnkd4/the_ultimate_package_software_management_system/ %}
This is a test Post
Published: 2023-01-05 19:23:12

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent enim ex, semper vitae orci at, tempor consequat tortor. Quisque ultricies nulla sapien, ac viverra elit auctor non. Mauris placerat risus feugiat lorem rutrum dignissim. Proin vel dui tristique, fringilla tellus eget, auctor sapien. Pellentesque lobortis nunc vitae pulvinar pretium. Proin rutrum arcu quis fringilla ornare. Praesent eu quam quis eros venenatis convallis eu at velit. Sed at eleifend velit, vitae volutpat lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque iaculis arcu vitae egestas tincidunt. Suspendisse rutrum ultricies metus quis sodales.

Mauris eu quam quis metus pulvinar pulvinar. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Maecenas ut urna risus. Aliquam laoreet purus eget sem rhoncus, sit amet placerat turpis malesuada. Duis eget risus tincidunt, rutrum eros eu, gravida sem. Suspendisse condimentum nisi quis massa luctus, at pulvinar ligula iaculis. Fusce sem purus, convallis in urna vitae, congue facilisis neque. Nullam gravida sapien id porta egestas.

Mauris imperdiet purus sed placerat laoreet. Vivamus blandit arcu eros, a pulvinar justo sagittis pharetra. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc maximus lacus augue, nec viverra lorem porta eu. Integer molestie mauris ex, sed mollis justo consectetur eu. Fusce vitae porta erat. Maecenas eu mi ac leo mollis mollis.

Aenean magna lorem, mollis vehicula laoreet eu, pulvinar in leo. Donec ut risus urna. Integer sed pellentesque nulla. Sed facilisis nisl sed lorem venenatis, in finibus enim pulvinar. Integer mauris elit, dictum id ligula in, hendrerit pulvinar turpis. Vivamus posuere laoreet odio nec scelerisque. Suspendisse eu ipsum a enim scelerisque viverra. Etiam sed suscipit sapien. In quis purus ut nibh vehicula euismod id ut eros. Curabitur sed lorem aliquet, vulputate diam viverra, iaculis enim. Aliquam erat volutpat. Phasellus a tellus id turpis ornare aliquam a vitae urna. Nullam tincidunt efficitur nisi eu facilisis. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam fringilla imperdiet finibus. Aliquam nec leo imperdiet, maximus nunc vitae, volutpat leo.

Vestibulum fringilla orci tellus, at mollis mi dapibus non. Sed a hendrerit felis. Nullam arcu neque, sodales vel est in, sollicitudin fringilla tortor. Nunc id egestas ex. Nullam egestas arcu vel mauris convallis, non sagittis libero ultrices. Morbi dignissim lobortis est nec tempor. Nulla sed odio nisi.
How to setup AWS Managed Microsoft Active Directory
Tags: aws
Published: 2023-01-21 20:51:01

This is my first post in series on Outsource your Authentication and Authorization to AWS IAM Identity Center. And we will be using Microsoft Active Directory as our Identity Source. 

### Prerequisites
- AWS Account

I will be using N. Virginia(us-east-1) region throughout the series. To launch AWS Managed Microsoft Active Directory follow the following steps:

1. On your AWS Console search for Directory and click on Directory Service
![Searching Directory Service](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k01sxkb2osptjzd011zt.png)

2. Then choose Set up directory
![Set up directory](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pxlhy262ggsyewto2smt.png)

3. Then choose AWS Managed Microsoft AD, and then click Next
![Select directory type](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xwrm6r1i2ncp0hkxhmk0.png)

4. Then select Standard Edition, configure Directory DNS name it does not need to be publicly resolvable and set Admin password and click next
![Enter directory information](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8o4pb9hxs81ohqocyph2.png)

5. Now select the VPC and subnets in which you want you Directories Domain Controllers to be deployed in and click Next
![Choose VPC and subnets](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zipq90uya2o47xi2eg15.png)

6. On Review & create page review everything and click Create directory and go for a Coffee break.

That's it your AWS Managed Active Directory is now deployed.

### Optional Steps
If you are following my series then you will eventually need a EC2 Instance to manage Users/Groups in your AD

7. [Follow this AWS article to launch a Windows EC2 Instance and join our recently launched AWS Managed AD.](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/launching_instance.html)

8. Once Instance is launched then connect to it using our Active Directory Admin Username and Password and [Install AD Tools using this article.](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_install_ad_tools.html)
C++ interview question
Tags: cpp
Published: 2023-01-21 20:33:37

Hi, I have a question below from one of the reputed companies. I got stuck in this question. I would appreciate any answers. TIA.


typedef unsigned int UINT;
typedef void VOID;

struct StructData
  {
      UINT  numEntries;
      VOID* pBuffer;
      UINT  minAllocatios;
      UINT  maxAllocations;
  };

  UINT*       pIntPtrArray[10];// usigned int* pINTPtrArray[10]
  StructData* pStructDataArray[10];
  
  UINT pArray[10];

  printf("%d", sizeof(pIntPtrArray));
  printf("%d", sizeof(pStructDataArray));
  printf("%d", sizeof(pArray));