teleren/devto huggingface dataset:
Typescript override typing for `Object.keys`
Tags: typescript
Published: 2022-09-23 07:52:12

If you guys work with `Object` in Typescript long enough, we all are aware of that one of the most used methods are `Object.keys` always returning a `string[]` which should return a list of union types of keys.

Here's how the `Object.keys` is defined within Typescript's built-in types, you can find it in `lib.es5.d.ts`:

```ts
interface ObjectConstructor {
    // other stuff

    /**
     * Returns the names of the enumerable string properties and methods of an object.
     * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
     */
    keys(o: object): string[];
}

```

This is definitely an annoying issue which should be fixed probably later on. So util then, there's a solution for it :)

- First of all, we define a proper type which returns a list of keys of a generic object:

```ts
// some util types
type IsAny<T> = 0 extends 1 & T ? true : T;
type KnownKeys<T> = {
    [K in keyof T as string extends K ? never : number extends K ? never : symbol extends K ? never : K]: T[K];
}
type IsEmptyObject<T extends Record<PropertyKey, unknown>> = [keyof T] extends [never]
    ? true
    : false;

type ObjectKeys<T> = IsAny<T> extends true
    ? string[]
    : T extends object
    ? IsEmptyObject<KnownKeys<T>> extends true
        ? string[]
        : (keyof KnownKeys<T>)[]
    : T extends number
    ? []
    : T extends Array<any> | string
    ? string[]
    : never;

interface ObjectConstructor {
    keys<T>(o: T): ObjectKeys<T>;
}

// testing
type Test1 = ObjectKeys<{foo: string, bar: string }> // Array<"foo" | "bar">
type Test2 = ObjectKeys<['']> // string[]
type Test3 = ObjectKeys<"foo">  // string[]
type Test4 = ObjectKeys<Record<PropertyKey, any>> // string[]
```

- Override the built-in `ObjectConstructor` interface. Let's define `object.d.ts` in your repo, normally I place the extra typing files under at `typings` dir. So in my case it's going to be here `typings/object.d.ts`: 

```ts
// typings/object.d.ts
type IsAny<T> = 0 extends 1 & T ? true : T;
type KnownKeys<T> = {
    [K in keyof T as string extends K ? never : number extends K ? never : symbol extends K ? never : K]: T[K];
}
type IsEmptyObject<T extends Record<PropertyKey, unknown>> = [keyof T] extends [never]
    ? true
    : false;

type ObjectKeys<T> = IsAny<T> extends true
    ? string[]
    : T extends object
    ? IsEmptyObject<KnownKeys<T>> extends true
        ? string[]
        : (keyof KnownKeys<T>)[]
    : T extends number
    ? []
    : T extends Array<any> | string
    ? string[]
    : never;

// interface can be merged together
interface ObjectConstructor {
  keys<T>(o: T): ObjectKeys<T>;
}

```
- Finally, include all defined typing files under `typings` to the configuration `tsconfig.json`:

```ts
// tsconfig.json
{
  // ...
  include: [..., "typings"]
}
```
Tiny Tips : Naming your Unit Tests
Tags: testing
Published: 2022-09-23 07:43:10


Let's assume I have a `Customer` class that can `addProduct` to basket. I have a bunch of test that test various cases. I'm not talking about any particular test framework here, they all work the same way.
For years, I used to name my test more or less like that:

```
TEST(CustomerTest, addProduct)
{
}

TEST(CustomerTest, addProductEmptyBasket)
{
}

TEST(CustomerTest, addNoProduct)
{
}
```

Meh...

I had the chance to work with Sandro Mancuso a few years ago, which gave me the following naming convention:

```
TEST(CustomerShould, addProduct)
{
}

TEST(CustomerShould, addProductInEmptyBasket)
{
}

TEST(CustomerShould, doNothingWhenAddNonExistingProduct)
{
}
```

Thanks to this, the intent of each test and the expected behavior is much clearer. It also fit very well with TDD. You can list what scenario should be tested even before writing test bodies.
DAY 3: Palindrom number
Tags: java, codereview
Published: 2022-09-23 07:42:15

Hey! It's day 3 of I4G 10 days coding challenge. Today's task was to write a code that checks if an integer is a palindrome number. A palindrome number is number that gives the same result when reversed.

**Strategy: **

- **Definition of problem:** I need to understand what the problem is before diving into the solution. To achieve I made research on google of what a palindrome number is.
- **Algorithm:** Having understood the problem I wrote an algorithm to help me narrow down the problem into solution. The Algorithm is as shown below:

**Algorithm:**

- Declare three integer variables: remainder, original and reverse
- Initialize reverse to 0 and set original to the given integer
- Set a while loop with condition: x(given integer) != 0
- while the condition is true set remainder = x % 10, reverse = reverse * 10 + remainder and x = x / 10
- Return true if reverse is same original else return false

Check out the complete code here:  Palindrome Number - LeetCode https://leetcode.com/problems/palindrome-number/submissions/
Password Security:Dynamic Salt
Tags: password, database, hash, security
Published: 2022-09-23 07:41:33

It is good to salt (static) your password.

It is good to hash your salted password.

But it is not so difficult for attackers to breach these methods.

To add an extra layer of security, the principle of DYNAMIC SALTING emerged.

Dynamic salting is the act of using different salt for different users. These salts are generated newly each time a password has to be saved, whether through a password reset or new signup.

How can you implement DYNAMIC SALT/SALTING as a developer?

Here are 5 simple steps to achieve strong password security via dynamic salting:

A. For new signup 

1. get the user's password (e.g. _myP@$swaRd_)
2. generate a new salt (e.g. _8jdn*nY4rg^s@1_)
3. salt the password to give _8jdn*nY4rg^s@1myP@$swaRd_, you can put the password first, the order does not matter.
4. then hash the password, to give something like _c150eb6c1b776f390be60a0a5933a2a2f8c0a0ce766ed92fea5bfd9313c8f_
5. save the hash to the db, also save the salt to the db in the record on this user.

B. to authenticate (confirm) a user 

1. get the email and password a user is trying to login with
2. use the email to retrieve the salt from the DB
3. use the retrieved salt to salt the inputted password.
4. using the same formula you used when creating the password as a new user, hash the result of step 3
5. compare the result of step 4 with  the password you retrieved in step 1


Voila!!

Follow and tweet @[wahabind](twitter.com/wahabind)
Avoid nesting by handling errors first
Tags: coding
Published: 2022-09-23 07:14:43

---
title: Avoid nesting by handling errors first
published: true
description: In this blog, we are going to learn one of the coding best practices which is how avoiding nesting by handling errors first increases the readability.
tags: coding
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d1vhgklgn52vw43n9iw2.png
canonical_url: https://amitshekhar.me/blog/avoid-nesting-by-handling-errors-first
---

I am [**Amit Shekhar**](https://amitshekhar.me), a mentor helping developers in getting high-paying tech jobs.

In this blog, we are going to learn one of the coding best practices which is how avoiding nesting by handling errors first increases the readability.

**This article was originally published at [amitshekhar.me](https://amitshekhar.me/blog/avoid-nesting-by-handling-errors-first).**

The best way to learn this is by taking an example.

First, let's see the nesting in which we do not handle the errors first which is not a good practice in coding.

```kotlin
fun getComments(postId: Long, pageNumber: Int, limit: Int) : List<Comment> {

    if (postId != null) {

         if (pageNumber >= 0 && limit <= 100) {

        	val comments = // fetch comments from database

            if (comments == null) {
        		// handle error and return
    		} else {
                return comments
        	}

         } else {
             // handle error and return
         }
    } else {
        // handle error and return
    }

 }
```

You can see that as we have not handled the errors first, it has led to the nesting and ultimately less readable.

Now, let's rewrite the above code by handling errors first to avoid nesting which is a good practice in coding.

```kotlin
fun getComments(postId: Long, pageNumber: Int, limit: Int) : List<Comment> {

    if (postId == null) {
        // handle error and return
    }

    if (pageNumber < 0) {
        // handle error and return
    }

    if (limit > 100) {
        // handle error and return
    }

    val comments = // fetch comments from database

    if (comments == null) {
        // handle error and return
    }

    return comments
}
```

If we compare both codes, we can clearly see that the latter one is more readable.

This is how avoiding nesting by handling errors first increases the readability.

That's it for now.

Thanks

[**Amit Shekhar**](https://amitshekhar.me)

You can connect with me on:

- [Twitter](https://twitter.com/amitiitbhu)
- [LinkedIn](https://www.linkedin.com/in/amit-shekhar-iitbhu)
- [GitHub](https://github.com/amitshekhariitbhu)
- [Facebook](https://www.facebook.com/amit.shekhar.iitbhu)
Github Study
Published: 2022-09-23 07:10:53


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


differences beetween oring and upstream

upstream = my current open-source project

origin = my forked repo from the open-source project

just a small tip for me, because it was confusing at the beginning now im starting to get the hang of it!
HTML da jadvallar bilan ishlash
Published: 2022-09-23 07:09:56

Jadval kodi quyidagicha 
```html
<table>
    <thead>
    <tr>
   <th>Name</th>
   <th>Surname</th>
   <th>Phone Number</th>
    </tr>
    </thead>

    <tbody>
    <tr>
        <td>Alex</td>
        <td>Iwobi</td>
        <td>123451</td>
    </tr>
    <tr>
        <td> Neymar</td>
        <td>Junior</td>
        <td>28212345</td>
  *  `table` - bu htmlda jadvallar shu tag orqali yasaladi  </tr>
    </tbody>
</table>
```

*  `table` - bu htmlda jadvallar shu tag orqali yasaladi 
*   `thead` - bu jadvalning asosiy qismi bu qismdi jadvalga o'zgaruvchilar beriladi 
*   `tbody` - bu jadvalning qiymatlar beriladigan qismi hisoblanadi. Bu qismda siz jadvallarga qiymat berishingiz mumkin 
*   `th va tr` - bu
Supabase, Self-hosting with Podman Instead of Docker!
Tags: supabase, firebase, docker, podman
Published: 2022-09-23 07:03:14

### Supabase, Self-hosting with Podman!

Supabase is an open source Firebase alternative providing all the backend features you need to build a product. You can use it completely, or just the features you need. Start a project with the [hosted](https://supabase.com/) platform or learn how to host Supabase yourself with podman 👇.

### Install requirements
You need to install `podman`, `podman-docker` and `docker-compose`

*i'm using linux pop_os*

```bash
sudo apt-get -y install podman podman-docker docker-compose
```

> in your ~./bashrc file add docker as a podman alias (alias docker=podman)

Now. You have to clone the supabase repo:
```bash
git clone --depth 1 https://github.com/supabase/supabase
```

Then:
```bash
# Go to the docker folder
cd supabase/docker

# Copy the fake env vars
cp .env.example .env
```

Now. You have to configure docker hub mirror in */etc/containers/registries.conf* :

```bash
sudo nano /etc/containers/registries.conf
```

Add these lines to the end of the file:
```toml
unqualified-search-registries = ['docker.io']

[[registry]]
prefix = "docker.io"
location = "docker.io"

[[registry.mirror]]
prefix = "docker.io"
location = "docker.mirrors.ustc.edu.cn"
```
Save it! Now. You are ready to install supabase studio:
```bash
sudo docker-compose up
```

Finally. visit http://localhost:3000 to start using Supabase Studio.


![local supabase dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4lq7eds8gs320730lhzn.png)



In case you face this error:

> ERROR: for db  error preparing container 22e6838a1fd10267d63f69ef400000a84a1a857a5e46718003f8a5f63388bb0f for attach: cannot listen on the TCP port: listen tcp4 :5432: bind: address already in use

Just change the `POSTGRES_PORT` in `.env` file.

😊 Enjoy!
🐦 [My Twitter](https://twitter.com/zaki_chahboun)
Python debug function
Tags: python, tutorial
Published: 2022-09-23 06:53:18

In Rust you find the [dbg!](https://doc.rust-lang.org/std/macro.dbg.html) macro that prints to what a given expression evaluates to. This on its own wouldn't be as helpful. Thus,  additionally the macro returns the value of the evaluated expression.

It is possible to mimic this functionality in Python. You may find the original implementation on [Raphael's blog](https://rtpg.co/2020/12/11/dbg-in-python.html). The one I use, is roughly:

```python
import inspect
import sys
import typing

_ExpType = typing.TypeVar('_ExpType')


def dbg(exp: _ExpType) -> _ExpType:
    for frame in inspect.stack():
        line = frame.code_context[0]
        
        if 'dbg' in line:
            start = line.find('(') + 1
            end = end if (end := line.rfind(')')) >= 0 else len(line) 
            
            print(f'[{frame.filename}:{frame.lineno}] {line[start:end]} = {exp!r}', 
                  file=sys.stderr)
            break
    
    return exp
```
Whether in it's a `*.py` file or in a notebook, it works great. Exemplary output:
```
>>> a, b = 1, 2
... dbg(a + b)
[(...):2] a + b = 3
3
```
Pure CSS Card Flip Animation
Tags: webdev, css, html, beginners
Published: 2022-09-23 06:22:04

Today we will share with you a simple but beautiful snippet about 3D flip card animation. This animation can be accomplished via an on-click event or hover. We have decided to do this animation on hover. The flip card effect animation is when we hover over a card, its back part rotates and comes in front of us. The card will come back to its previous state when we lift the hover. This animation is more common in websites nowadays, especially e-commerce websites. **[DOWNLOAD CODE](https://www.divinectorweb.com/2022/09/pure-css-card-flip-animation.html)**
HTML
Published: 2022-09-23 06:11:57

`title` - orqali veb sayt nomi kiritadi.
`p` - orqali veb saytda matn yoki textlarni yozish mumkin.
`a` - **atribute** tegi yordamiga veb saytga link berish mumkin. Bunda link quyidagich beriladi 
```html
<a href="https://www.spot.uz/oz/2021/03/11
/programming/" targe="_blanc" >dasturlash</a>
```
`target` keywordi orqali siz o'sha linkni ochiladi lekin boshqa sahifada ochiladi.
`strong` tegi orqali texni to'qroq qilib berishimiz mumkin .
*    `<!--   -->` - bu  **html**da comment deyiladi. Buni ichiga istalgan narsa jumladan kodga ta'rif yozish mumkin. 
Buni dastur o'qimaydi
Creating custom services in medusa
Tags: javascript, webdev, beginners
Published: 2022-09-23 06:03:36

Now that we know how to use an existing service in our routes. Let's take it to. The next level and see how we can create our service even.

A service is something that you can use throughout your application.

Let's say we want to add a translation service, for instance.
We'll have to open up our medusa server project and create a new file inside the `src/services`.

If our service is the `translateService`, we should name the file `translate.js` (filename without the Service part).

## Creating a service in medusa

The most basic service file would look like this.

```js
import { TransactionBaseService } from '@medusajs/medusa';

class TranslateService extends TransactionBaseService {
  func() {
    return '';
  }
}

export default TranslateService;
```

As you can see, the service extends the `‌TransactionBaseService`, which gives us access to all the existing and other services.

Let's create a mock demo function so that we can give it a try.
With translations, we would need some mapping table, but let's mock it out for now.

```js
const messages = {
  en: {
    title: 'Hello world',
  },
  nl: {
    title: 'Hallo wereld',
  },
};

class TranslateService extends TransactionBaseService {
  translate(msg, locale) {
    return messages[locale][msg] ?? msg;
  }
}
```

This translate function will be able to translate specific messages into provided locales. If there is no match, the original message will be returned.

## Using the custom service

Let's go ahead and see how we can use this custom service.
I'll use it in our [custom routes](https://daily-dev-tips.com/posts/using-services-in-custom-medusa-routes/) as we already had a good intro.

Let's add a new route that will get our title.

```js
router.get('/store/title', (req, res) => {
  const translateService = req.scope.resolve('translateService');
  const title = translateService.translate('title', 'en');
  res.json({ title });
});
```

The first thing we do is retrieve our translate service, then we define a new variable for the title and request the title in a specific locale.
And eventually, return that.

Spool up your server and test out the route.

![Medusa custom translate service](https://cdn.hashnode.com/res/hashnode/image/upload/v1663048097960/q6MZ3RbmE.png)

Now let's change the locale to `nl` and try it again.

```js
const title = translateService.translate('title', 'nl');
```

![Medusa custom translate service](https://cdn.hashnode.com/res/hashnode/image/upload/v1663048034194/mrqzXHBH4.png)

And you can even try to request a message that doesn't have any translations.

```js
const title = translateService.translate('Products', 'en');
```

![Custom translate service fallback](https://cdn.hashnode.com/res/hashnode/image/upload/v1663048180024/6TFmKsw7A.png)

And that's it. We now have a fully functional custom service in medusa.

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
Youtube Content ID
Tags: agregatormusik, musicxstudio, laravel
Published: 2022-09-23 05:43:05


![Youtube Content ID MusicX Studio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kx9ltlk9y57nz1yri4ij.png)

Sebelum kita bahas lebih jauh tentang Youtube Content ID.Kamu harus tahu terlebih dahulu apa sih Youtube Content ID.

### Apa itu Youtube Content ID?
Youtube Content ID adalah sistem dari Youtube berupa pemberian sidik jari ke dalam audio atau bahasa kerennya Audio FingerPrint agar memungkinkan kita sebagai pemilik hak cipta dapat mengidentifikasi dimana musik kita digunakan di Youtube.Ini adalah cara Youtube mengenali pemilik musik di dalam konten-konten video di youtube.

### Fungsi dari Youtube Content ID
Dengan audio musik kamu didaftarkan ke Youtube Content ID,setiap ada yang memakai audio musik kamu di videonya,maka youtube akan mengklaim pendapatan dari video itu ke penghasilan kamu melalui agregator musik seperti MusicX Studio.Kamu juga bisa melakukan takedown video youtube tersebut jika kamu tidak berkenan audio musikmu dipakai.

Dengan audio musik kamu didaftarkan ke Youtube Content ID, maka youtube akan membandingkan dan mencocokan apakah video yang diupload orang lain melanggar Hak Cipta atau tidak. Apabila ada kecocokan maka pemilik konten yang sah akan diberi pilihan untuk mengambil kebijakan terhadap pelanggaran tersebut sepert :

1. Melakukan pemblokiran terhadap keseluruhan video
2. Menghapus atau menghilangkan audio dalam video
3. Melacak statistik penayangan video yang diupload
4. Ini yang paling penting mendapatkan penghasilan dari setiap klaim terhadap video yang menggunakan audio musik kamu,penghasilan itu nantinya kamu terima dari agregator musik sepert MusicX Studio tempat kamu mendaftarkan Youtube Content ID.

Penghasilan sendiri bisa didapatkan jika kamu tidak memblokir atau membisukan audio didalam video yang diklaim.
Apa Itu Agregator Musik
Tags: laravel, music, agregatormusik
Published: 2022-09-23 05:40:06


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

Agregator musik muncul dengan berkembangnya dunia digital. Kamu masih asing dengan istilah satu ini? Yuk, simak penjelasan lengkapnya di bawah ini.

Kini, menikmati musik menjadi sangat mudah dan bisa kita lakukan kapan pun di mana pun. Hanya dengan memutar musik di aplikasi streaming musik favorit dan pilih lagu yang ingin kita dengar.

Tanpa harus tahu perkembangan kemajuan teknologi tersebut, kamu bisa tinggal menikmati musik yang disukai dan bisa bebas pilih.

Namun, apakah kamu tahu bahwa setiap musik yang kita dengar di layanan streaming merupakan peran dari agregator musik?

Jika masih asing dengan istilah agregator musik, tentu kamu belum banyak mengetahui hal tersebut.

Full Artikel Hanya di [MusicX Studio](https://musx.studio/blog/apa-itu-agregator-musik/)
What’s in my bag when I go to the office (September 2022 Edition)
Tags: productivity, programming, tooling
Published: 2022-09-23 05:02:16

Basically, I work remotely in the last 5 years right now.
And I love it. I think I should have some problems to do a step back to a “normal” office daily life.
By the way, since I joined SoftwareONE, I have to go in the office once a month (at least).
It’s ok to break the routine and spend a lot of hours with my team and the other colleagues.
But what I bring with me when I go to the office?

I don’t have a fixed setup and I change the content of my bag two or three times during the year.

Right now, I have the following setup:

- **Microsoft Laptop 4**: it's not my primary device because at home I use my gaming pc for working. But I use the laptop a few hours each week when I want to work in another room at home.
- **iPad**: it's useful during the travel (I take the train for 45 minutes) and during the day for watching tutorials or listening Spotify (and preserve battery life on the laptop)
- **Logitech M705 Marathon**: I have this dedicated mouse for the laptop. It's very similar to the mouse that I use every day, the Logitech MX Master. I love the Logitech mouse series.
- **USB-C Docking**: in the office all seats have the dedicated docking station, but who doesn't know if you have to do a presentation in a conference room or you have to work in a meeting room and you need more connections for displays or additional USB ports.
- **a Presenter**: same as the point above. It's small and it's not heavy to bring in the bag. So, why not?
- **a portable USB-C display**: it's an additional display 15.6 inch that you can easily use as a second monitor. You can use the USB-C to provide power to the display and it's useful if you are in a meeting room and you need a second display during a meeting or during a presentation. You can share this screen in the call, and you can use the main display of the laptop as the main display.
- **USB Hard disk**: we are living in the cloud era, I know. But it can happen that you need to share big amounts of data with your colleagues or an ISO image or whatever. (I have additional 2-3 usb keys in the bag)
- **Sennheiser HD BT450**: I reviewed this headphone here on my blog a few months ago. They are good to have some isolation during the day. We have an open space and everyone are in the calls during the day. 🙂
- **Cables, Cables, Cables**: I have multiple cables in a small bag for everything: HDMI, usb, usb-c and much more. You never know.
- **Powerbank**: I have a backup powerbank (it's not in the photo). It can recharge my phone and/or my laptop if needed.

What do you think? Is it enough? Is it too much?

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