teleren/devto huggingface dataset:
Splitting String on Date Format Producing an Array
Tags: beginners, javascript, programming, tutorial
Published: 2022-04-01 22:43:36

I had a need to parse a string with no clear delimiter except for a particular date, so I created this function to split the string based on the date format (M/D/YY, MM/DD/YYYY) within the string so I could then add my own delimiter to then break it up into an array.

```
function getStringArrayByDateFormat(str, pattern) {

  const DELIMITER = '~';
  let m, updatedText = str;
  let uniqueMatches = [];

  while ((m = pattern.exec(str)) !== null) {
    if (m.index === pattern.lastIndex) {
      pattern.lastIndex++;
    }

    m.forEach((match, groupIndex) => {
      if (!uniqueMatches.includes(match)) {
        uniqueMatches.push(match);
      }
    });

  }

  uniqueMatches.forEach((item) => {
    const regex = new RegExp(`${item}`, 'g');
    updatedText = updatedText.replace(regex, `${DELIMITER}${item}`);
  })

  const list = updatedText.split(DELIMITER).filter((s) => s.length > 0);
  console.log(list);

}
```
To call it

```
const DATE_PATTERN = /\d{1,2}\/\d{1,2}\/\d{2,4}/g;
const textToSplit = `3/22/2022: This is a test comment 1 3/25/2022: This is a test comment 2 3/26/2022: This is a test comment 3 3/27/2022: This is a test comment 4`;

getStringArrayByDateFormat(textToSplit, DATE_PATTERN);
```

After running this script, we get the following array, which we can loop over and render on the screen.

```
[
	"3/22/2022: This is a test comment 1 ", 
	"3/25/2022: This is a test comment 2 ", 
	"3/26/2022: This is a test comment 3 ", 
	"3/27/2022: This is a test comment 4"
]
```

Here is the [fiddle](https://jsfiddle.net/bg123456/ox84vygz/) for it.
I'm building a telegram bot to remind me changing my car oil
Tags: node, tutorial, programming, productivity
Published: 2022-04-01 22:36:15

I hate to remember changing my car oil.
Too many minor things to remember in life already!

So I decided to build a simple Telegram bot that remembers changing the oil for me.

**I want to share my thought process before actually coding it.**

I want this to be as simple as possible and free as possible, practically costing $0 to maintain.

**Oilly** will be his name, with a headline that says: 

"Oilly will help you preserve your car engine by reminding you to change the oil, so you have one less thing to remember".

## Oilly will interact with the user ask them:

1. Current mileage
2. Roughly estimate the last time the oil has been changed.
3. The mileage in the last time oil changed.
4. What is the type of the last changed oil 5k, 10k, 15k?
5. How frequent they change the oil 3 mo, 6 mo?
6. Have they changed the oil filter in the last oil change?

Bot will respond with "Thanks, based on the information you gave me I'll notify you!".

## How to calculate the oil change (research)

Upper limit 10,000 KM or 6 months whichever comes first.

- every 6 months
- every 3 months
- every 5000 km or 3 months (recommended)

## User input example (my real usage):
- current mileage: 25,258
- last time changed oil: 2 months ago
- mileage last before change: 21,201
- Oil type: 5k
- Change oil frequency: every 3 months
- have you changed the oil filter: No

## Simple Process: First state the facts

- Calculate how long the user will take to reach 5k mileage:
- Ideal mileage usage 5k in 3 months.

- Current mileage - mileage last before change => 25,258 - 21,201 = 4,056 in 2 months.

- Avg mileage per day => 4056 /60 = 67.6 KM

- Mileages left in distance unit => 5000 - 4,056 = 944 KM

- Mileage left in time unit => 1 months

- Change Oil filter last time: NO, so this time change it.

### My approach:
- Easiest way to approach this is by sending notification after 1 month.

- Or Mileage left (944) / avg usage (67.6) = 14 days.

- Maybe sending the user notification after 14 days that says if you reach (25,258 + 944 = 26,202 KM) it's time to change.

If the user says no, fall back to 1 month change.

**I'm trying to get some hold over this process, I would appreciate your take on this whole thing.**
🤔 What is Database Index?
Tags: database, sql, beginners, mysql
Published: 2022-04-01 22:00:33

## 💎 What is it?
Simply put, you can search data from database sooooo much faster

Normaly SQL searches all data from 0, it is like you search some word in dictionary from page 0.

So what do you need to find quickly?

▼ something like that, you can find so much faster! Yes it's like Index
![index metafor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hegimfbzax05u21vulec.jpg)

## 💎 When you should use it?
You could search without index until around 1000 without any problem, but from around 10000 you should add index!



## 💎 How should I check it?
We need to find how SQL tries to search data which we want.
How? Just use `Explain` command

```sql
--just add "EXPLAIN" before query
EXPLAIN SELECT * FROM member WHERE Id=1;
```
![sql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j4lba63ac8megsmltzyz.png)

> ### 📕 select_type

- **SIMPLE** : simple SELECT (not use UNION or SUB QUERY)

> ### 📕 type

- **ALL** : search all records (= table scan. Scan is like copy scan, from left to right, just ALL of them)
- **Index** : use index
- **Ref** : use index, but not UNIQUE or PRIMARY KEY (🤩 We want it!!)
- **EQ_REF** : index is UNIQUE or PRIMARY KEY
 
> ### 📕 rows

**Number of records of query** 

For example there is 50,000 records now, and rows is 45780, so almost 92% records SQL searched.

## 💎 Let's create Index
▼ show index information (shouldn't show anything so far)
```sql
SHOW INDEX FROM hoge_table;
```

▼ create index
```sql
--ALTER TABLE hoge_table ADD INDEX hoge_index_name(column_name);
ALTER TABLE member ADD INDEX member_index_by_id(Id);
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w1no8881vo9a7p72pr5c.png)

▼ check same SELECT SQL
```sql
EXPLAIN SELECT * FROM member WHERE Id=1;
```
▼ Now rows is only 1! (SQL searched only one record/column)
![sql1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0quqbg0yxg14gqavu6n9.png)

> ### 📕 index_type

- **Btree**: 
It is **Balanced tree**, one of the searching algorithms. It is similar to **Binary tree**
 

## 💎 Primary key, Unique key
### - primary key
Actually setting primary key is the same as setting index, and faster than normal Index, so you should check it at first

### - unique key (ex. email)
it is also setting unique keys means using index

### ▼ Priority is like this
Primary key > Unique key > index

## 💎 Disadvantage

**1.** Something which changes record list because it needs to create new index file.

**2.**If you set index which starts **LIKE** or **%**, SQL would
search all records
AlmaLinux Web Team Call for Ideas and Contributors
Tags: opensource, linux, contributorswanted, webdev
Published: 2022-04-01 21:33:28

Hello Community! We're currently in the midst of rethinking our web presence and associated entities. Our site is our face to the world and is the primary source of information and resources for tens of thousands of visitors each month. As we continue to grow we want to make sure the site gets even better and more useful, informative, localized and accessible.

To that end, we would like to put out a call for ideas, improvements and also contributors. Our current stack is django and python and lives [here on github](https://github.com/almalinux/almalinux.org
). We're not necessarily against moving to a different stack if anyone has a good idea and thinks they can pull it off.

Please let us know how we can help make the site more useful for you. If you're a web dev and would like to rock it with us on a site which reaches million of people a year then please reach out to us on The [AlmaLinux Community Chat](https://chat.almalinux.org/
), the [AlmaLinux subreddit](https://reddit.com/r/almalinux
) or [@almalinux on Twitter](https://twitter.com/almalinux
).
Javascript topics i will cover
Tags: javascript, discuss
Published: 2022-04-01 21:20:19

Here is a list of Javascript content that i will write blogs on and try to explain in the future
- continue oop posts
- scopes and the scope chain
- callstack and execution contexts
- closures
- hoisting
- data structures and algorithms
- high order functions
- typescript

And btw next oop post is tomorrow :)
Top 3 Casts of the Week #4
Tags: typescript, javascript, tutorial, python
Published: 2022-04-01 20:38:48

It's that time of the week again where we give our love to our top 3 Casts of the week on [CodeCast](codecast.io)! This week, we have some great videos in store for you, so let's get right into it.

## [Building A Recipe App](https://www.codecast.io/casts/6bXQ4XWoQkY4-build-a-recipe-app-with-spoonacular-api-part-four?_ga=2.7767410.1100315142.1648570642-2146326382.1646946127) by [@kauress](https://www.codecast.io/users/shahzaibkamal?_ga=2.7767410.1100315142.1648570642-2146326382.1646946127)

![Fetch Cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2owtovrbj5f5q5e88ig6.png)

Using the Spooonacular API, Jannat builds out a recipe app! In this Cast, she works with the fetch API to grab data from Spoonacular. It's a great way to practice fetch requests and working with APIs.

## [Path Traversal in Python](https://www.codecast.io/casts/KrEQeqdxQXMJ-web-security-with-python-path-traversal-with-python?_ga=2.212691284.1100315142.1648570642-2146326382.1646946127) by [@jesusvilla](https://www.codecast.io/users/kauress?_ga=2.212691284.1100315142.1648570642-2146326382.1646946127)

![Path Traversal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9vc0ghszhud8reyg7d33.png)

Jesus is passionate about cybersecurity and in this Cast, he goes over easy it is for someone to introduce a vulnerability in a simple flask application. Of course, he then shows you how to fix it! He has lots more videos on web security coming so be sure to follow him if that's a topic you'd love to know more about.

## [OOP TypeScript: Working With Classes](https://www.codecast.io/casts/PbwpyNxXQG0l-oop-with-typescript-basics-of-classes?_ga=2.36097504.1100315142.1648570642-2146326382.1646946127) by [@shahzaibkamal](https://www.codecast.io/users/shahzaibkamal)

![Classes cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n5cppja28rgxl198auh8.png)

Shahzaib has created [an entire Series](https://www.codecast.io/series/83-object-oriented-programming-with-typescript?_ga=2.237349184.1100315142.1648570642-2146326382.1646946127) on learning object-oriented programming basics with TypeScript. In this video, he goes over all the basics of working with classes in TypeScript.

Be sure to follow us here and [everywhere](https://linktr.ee/codecastapp) to stay up to date with our latest features!
Web Application Development Process of a Full Stack Developer
Tags: webdev, programming
Published: 2022-04-01 20:10:35

What an amazing time we are living in? Inexpensive access to technology and the rise of JavaScript has created a new breed of developers i.e., Full Stack Developers can work equally well on the front-end and back-end technologies, thanks to JavaScript.

Building a SAAS product was never simple. Now you can partner up with a Full Stack Developer to bring your idea to life. There is no need to hire multiple developers & designers to make it happen. A single full stack developer can do wonders now. Web application development process with a Full Stack Developer be like:

## Wireframes 
Picture worth a thousand words. Wireframes serve this purpose. If you have brilliant idea in mind and nothing on paper, you will face difficulty visualizing the solution be it web app or mobile app. Wireframing will bring the developer and product owner to same page regarding the expectations of the final solution.

## UI/UX Design
Once the wireframes are finalized and overall flow has been established, it's time for UI/UX design of the solution (web or mobile app). User Experience (UX) provides the maximum user satisfaction when they interact with the application. User Interface (UI) provides the best presentation and interactivity of the web or mobile app. 

## Frontend Development
JavaScript provides multiple libraries and frameworks for frontend development of mobile or web app. Based on the specific use-case and requirements full stack developer choose to work in ReactJS, React Native, Angular, Vue, NextJS etc. Frontend helps in finalizing the response required from backend to update frontend.

## Backend Development
JavaScript provides Node.js for backend development of mobile or web app. Based on the specific use-case and requirements full stack developer choose to work in ExpressJS, NextJS etc. REST API or GraphQL can be used to serve the data required at frontend.

## Testing
Unit tests and integration testing can be performed with Jest and Cypress. Each library has its own pros and cons depending upon the type of application being developed. Sometimes this can be delayed and rather release for initial set of users who can provide feedback for improvements and report the bugs if found.

## Deployment
Heroku, AWS amplify, Netlify can be used as they provide free tiers for evaluation and charge you as you go. In case of mobile apps, these can be submitted to Google Play Store and Apple App Store.
Muti-PHP Docker Environment
Tags: php, webdev, devops, showdev
Published: 2022-04-01 20:03:10

I've been working on a small utility to handle multiple PHP versions for all of my projects.

https://github.com/phpdocdev/docdev

Features

- CLI utility (docdev)
- Pre-built PHP images (5.4, 5.6, 7.2, 7.4, 8.1)
- Automatic SSL certificates (http and https)
  - `docdev certs`
- Automatic host mapping (project1.loc)
  - `docdev hosts`
- Shell into a container
  - `docdev exec`
- One command to switch between PHP versions
  - `docdev php --start 74`
- Testing utility
  - `docdev test`
- DNS server: mapping folders to hostnames
- MailHog
- Self updating

![Test](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxojwhnvyythkudqd2ix.jpeg)

![Help](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2urfzcfhp2gorkelg63l.png)
 
Tested only on Mac, sorry everyone else :(
Looking for developers to chat with!
Tags: webdev, discuss, beginners
Published: 2022-04-01 19:50:03

Hey! This is my first post on DEV. I have started learning web development late 2021. I've been learning from home on my free time with the hopes of gaining enough skills to start applying for positions by 2023. 

Learning to code has been an amazing experience so far and I'm very excited I've found something I enjoy doing. 

With that being said, I've been feeling a bit lonely not knowing any developers and having no one to chat with. So this post is reaching out to the community in hopes of connecting with some developers. 

I'd love to connect with other developers on their learning path and I would also love to connect with a developer who is currently employed! I would be stoked to learn about what it's like working as a developer and the daily tasks involved! 

Thanks for reading this post and I hope I can connect with a few people :).
Yubikey meets an EC2 instance
Tags: aws, yubikey, opengpg, ec2
Published: 2022-04-01 19:27:31

---
title: Yubikey meets an EC2 instance
published: true
description: Use your yubikey to ssh into an ec2 instance
tags:  aws, yubikey, opengpg, ec2
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezvx7gx04g668ef72gow.png

---

I recently got a Yubikey to lock some of my most critical accounts. In the process, I discovered that the yubikey also supports OpenPGP with the capabilities of Sign, Encrypt and Authenticate!. 

This is a game-changer in terms of security since I no longer need to have my private RSA keys in my computer (hot environment because it touches the internet).

The process of how to generate the OpenPGP keys and burn them in the yubikey is well explained here: 

https://youtube.com/playlist?list=PLmoQ11MXEmahVl_uJVH0-a3XJtMV59PBu


### The EC2 way

When we launch a new EC2 instance we have to choose a pem file (private key) to SSH. 

```bash
ssh -i keypair.pem ubuntu@ec2-*********.com
```

What I used to do is to load the pem key into my ssh-agent to ssh to the instance without providing the key as a parameter.

```bash
ssh-add keypair.pem
ssh ubuntu@ec2-*********.com
```


### EC2 + Yubikey 

Assuming that your private key is already in the yubikey all you have to do is to plug the device into your computer and update the `ssh-agent` socket to communicate with pgp agent socket. 

After doing that your `ssh-agent` will use OpenPGP.

```bash
SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket)
```

Now Copy your public pgp key to the EC2 instance.

```bash
ssh-add 
ssh-copy-id ubuntu@ec2-*********.com
```
Now everything is in place to SSH into your ec2 instance with your yubikey.

```bash
ssh ubuntu@ec2-*********.com

**waits for confirmation in the yubikey**

ubuntu@ec2-local:/home/ubuntu 
```

### Summary 

And you are connected!.
Using this method removes the need to use the pem file provided by AWS. You can also use the same method for other servers Just copy your public key and you yubikey is your Authenticator.
Async gotcha: returning Task.FromResult or Task.CompletedTask
Tags: csharp, dotnet
Published: 2022-04-01 19:23:53

So you're implementing this async handler or interface method that doesn't have anything to await, and you write something like

```csharp
async Task<bool> HandleAsync()
{
     DoSomethingSynchronous();
     return true;
}
```
But now the C# compiler emits a stern warning: "CS1998: you're using `async`, so you should be awaiting stuff! find something to await!"* Well, you have nothing to await, but you must still return Task. You remove `async` and return `Task.FromResult(true)` instead, as [top-rated](https://stackoverflow.com/a/29923484) answers by [high-reputation members](https://stackoverflow.com/a/16526019) on Stackoverflow recommend. Job done.

```csharp
Task<bool> HandleAsync()
{
    DoSomethingSynchronous();
    return Task.FromResult(true);
}
```

Or is it?

As long as `HandleAsync` is always called and awaited immediately, all is fine.

```csharp
var success = await HandleAsync(); // This is fine.
```

But a dark threat lurks in the shadows.  Sometimes a try-catch fails to catch an exception.

```csharp
var task0 = a.HandleAsync();
var task1 = b.HandleAsync();

try
{
     await Task.WhenAll(new[] { task0, task1 });
}
catch (Exception ex)
{
    // this handler does nothing and the exception escapes! What gives??
}
```

Because `HandleAsync` is actually synchronous, any exception propagates as soon as it's called, not when it's awaited. **This is surprising to most C# programmers.** A *synchronous method that returns a Task* is not what you expect, especially when it's called SomethingAsync. Surprising, unexpected behavior leads to bugs. Bugs lead to unhappy customers and developers alike.

So what should we do instead?

One option would be to disable warning CS1998, but it may point out cases where a method just shouldn't return a Task in the first place. Probably the best thing would be to mark the function as async and await `Task.FromResult`:

```csharp
async Task<bool> HandleAsync()
{
    DoSomethingNotAsync();
    return await Task.FromResult(true);
}
```

Or if it's a plain `Task`, awaiting `Task.CompletedTask`.
```csharp
async Task HandlerAsync()
{
    DoSomethingNotAsync();
    await Task.CompletedTask;
}
```

Is this slower? Not much - awaiting a completed task does almost nothing, and the runtime might be able to recognize this common pattern and elide all the overhead - but choosing the async-looking-but-actually-synchronous behavior for hypothetical performance reasons firmly falls in the category "[evil premature optimization](https://wiki.c2.com/?PrematureOptimization)", in my opinion.

*Actually, it says
> warning CS1998: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run(…)’ to do CPU-bound work on a background thread.
OpenCL on Blender with Intel Integrated GPUs
Tags: blender, opencl, intel
Published: 2022-04-01 19:13:27

So far **only AMD**'s OpenCL is officially supported but if you like to take some risks you can force enable OpenCL on Intel setting two environment variables:
- **CYCLES_OPENCL_SPLIT_KERNEL_TEST=1**: That's the one referenced in any post about it
- **CYCLES_OPENCL_TEST=all**: that variable is not so mentioned 

A detail that you might forget is that you need to install the OpenCL drivers for your GPU before doing this. My 7th gen i5 still uses the legacy driver. The still maintained driver is for 8th gen and above. The driver link is broken but Wayback Machine covers this case fortunately.

Here is a full command for quick testing:

```bash
CYCLES_OPENCL_TEST=all CYCLES_OPENCL_SPLIT_KERNEL_TEST=1 blender --python-expr "import bpy; [[print(d.type, d) for d in ds] for ds in bpy.context.preferences.addons['cycles'].preferences.get_devices()]" --verbose 69 -E CYCLES -b
```

And that's the output that appears on my machine:

```
Blender 2.93.5
Read prefs: /home/lucasew/.config/blender/2.93/config/userpref.blend
[ALSOFT] (EE) Failed to set real-time priority for thread: Operation not permitted (1)
[ALSOFT] (EE) Failed to set real-time priority for thread: Operation not permitted (1)
I0401 16:07:26.994379 438579 blender_python.cpp:195] Debug flags initialized to:
CPU flags:
  AVX2       : True
  AVX        : True
  SSE4.1     : True
  SSE3       : True
  SSE2       : True
  BVH layout : EMBREE
  Split      : False
CUDA flags:
  Adaptive Compile : False
OptiX flags:
  CUDA streams : 1
OpenCL flags:
  Device type    : ALL
  Debug          : False
  Memory limit   : 0
I0401 16:07:28.091580 438579 device_cuda.cpp:56] CUEW initialization failed: Error opening the library
I0401 16:07:28.091853 438579 device_opencl.cpp:48] CLEW initialization succeeded.
I0401 16:07:28.093667 438579 opencl_util.cpp:957] Enumerating devices for platform Intel(R) OpenCL.
I0401 16:07:28.093719 438579 opencl_util.cpp:777] OpenCL driver version 1.2
I0401 16:07:28.093741 438579 opencl_util.cpp:993] Using more readable device name: Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz (OpenCL)
I0401 16:07:28.093761 438579 opencl_util.cpp:995] Adding new device Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz (OpenCL).
CPU <bpy_struct, CyclesDeviceSettings("Intel Core i5-7200U CPU @ 2.50GHz") at 0x7f812be0b608>
OPENCL <bpy_struct, CyclesDeviceSettings("Intel Core i5-7200U CPU @ 2.50GHz (OpenCL)") at 0x7f812be0b688>
CPU <bpy_struct, CyclesDeviceSettings("Intel Core i5-7200U CPU @ 2.50GHz") at 0x7f812be0b608>

Blender quit

```

With this a OpenCL GPU will appear on preferences.
![OpenCL device appearing on blender settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0e74dkp0oeq00nbjk6g.png)

But beware, in my case when I started rendering the CPU only got 100% but without slowdown the computer and Blender just stop reacting to any input so working is a too strong word.

Tested with Blender 2.93. Both nixpkgs and blender-bin 2.93 definitions works basically the same way.
Weekend Plans?
Tags: discuss
Published: 2022-04-01 19:06:47

---
title: Weekend Plans?
published: True
description: 
tags: #discuss
//cover_image: https://direct_url_to_image.jpg
---
I always enjoy popping open the FreeCodeCamp newsletters from Quincy. Every once in a while there is something that catches my eye more than normal. This is one of those days...

My plans for this weekend are to go through this tutorial recommended in the newsletter.

[https://www.freecodecamp.org/news/learn-go-by-building-11-projects/](Learn Go Programming by Building 11 Projects)

What's your plans for this weekend?