teleren/devto huggingface dataset:
TypeScript - Como pegar uma string no seu Literal Types
Tags: typescript, howto, braziliandevs, tutorial
Published: 2023-07-24 20:11:30

Salve, salve devs seniors.

Não vou enrolar nada. Basicamente é só você utilizar o _Utility Type_ `Extract` do próprio **TypeScript** e boa! _**Por exemplo:**_

```ts
type CatNames = 'Garfield' | 'Yoru' | 'Yuki' | 'Fluffy' | 'Lady' | 'Lucky'

type MyCatNames = Extract<CatNames, 'Yoru' | 'Yuki'>
                                    // |-> Extract these two `literal types` from CatNames `literal type`

type Cat = {
  age: number
  name: CatNames
}

function getMyCat(age: number, name: MyCatNames): Cat {
                               // |--> only show 'Yoru' and 
                               //                'Yuki'
  return {
    age,
    name,
  } as Cat
}

const myCat1 = getMyCat(1, 'Yoru')
const myCat2 = getMyCat(1, 'Yuki')

const otherCat: Cat = {
    age: 3,
    name: 'Garfield'
}
const otherCatWithMyCatName: Cat = {
    age: 5,
    name: 'Yoru'
}

// tmj!
```

> link do [TS Playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAwghsAcnAthAzlAvFA5AcTgCcAzASwgBsATXKAHzwE0B7IgVzsdyfYGsyXPADFK7EiRBDcAGTjUpDPDPYBjPlIBQm0JCgBZEPCSoM2KAFEAHsCJxVwADzHkadABpmbTkp79BAHyaUCGhYeERkVEA9NEMALQBljZ2DlDAABYY0MAA7ixQAAaUZMAQdpTp4BiFUCRELCiwCK5mxaXlcJW6EIXaPc3A5gDewVBwAOYQAFxQAHbsKABG5e5jc6azLqbomgC+2iTscw5kLHNQU8CGxgAUkzPziytEnhtoszctOwCUWwhQUZRYEgsKxBKJKDnSggKDoDIsXJeDh0OBzahQMag7ERcE4kJ+AS4MZECDAdhEC5A0IPNZhd4QOlQPbjTDGfbaVTndBDFBGBAARnMVy+wFuAs8PG8uB+mi5cx5UD5xgATMKyaLxZLeETZXLuUMWJlysZ-kMcNSQg9ZgBmJkhBmzAjEchUWgc+WKo1ZIjGADqpQyotaZpGWPGU1mAFZ7fNNsjOPsgA)

espero que ajude alguém! 

(OBS: esse post foi escrito em no máximo 10 minutos)

meus links: https://thayto.com/linktree

_Originalmente postado em [https://thayto.com](https://thayto.com/blog/ts-como-pegar-string-no-seu-literal-types) dia 24 de Julho de 2023._

_Photo by <a href="https://unsplash.com/@_k_arinn?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Karina Vorozheeva</a> on <a href="https://unsplash.com/photos/white-butterfly-resting-on-cats-nose-rW-I87aPY5Y?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a>_
Unleashing PostgreSQL's Potential: Easy C Extension Development for Beginners! Part-2
Tags: apacheage, database, c
Published: 2023-07-24 20:04:04

In the previous part we learned how to develop a simple C extension for our postgreSQL database. But now the question arises, why even bother making extensions especially when postgres has certain built-in functions or operators that can do the same task as we did. 

Well, one reason why you might think of doing this would be for performance reasons. Allow me to elaborate.

In part 1 we created a subtraction function that took in two arguments are subtracted the second arg from the first arg. Simple enough!

But we could have done this in two other ways. One simply using the basic SQL - operator and the other making a PLpgSQL function inside our database that does the work for us. Let us look at the two approaches. 


## PLpgSQL function
Inside our postgreSQL database we can run this code

```
CREATE FUNCTION submepl(a integer, b integer)
 RETURNS integer
as $$ 
BEGIN
  return a-b;
END;
$$ LANGUAGE plpgsql;
```
This will create a function that does exactly the same thing that our C function did i.e subtract two numbers. 

## SQL operator 

This is self-explanatory we simply subtract numbers using the - operator. For example 
`SELECT 10 - 5;`

## Benchmark
Now let us consider our function vs the SQL operator and the PL function call way. In order to track the time we will use the time function in linux and run each methodology **1 million times**!

Needless to say, the results are as follows: 


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

The operator and the C function took almost the same time in execution. The PL function on the other hand, took way more time: 


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

And this was just for a simple basic function that subtract. This would only increase as more complex functions are formed.

In short, if performance is your demand then extensions are your friend!
Conhecendo os diferentes sistemas de cores
Tags: color, ryb, rgb, cmyk
Published: 2023-07-24 20:00:00

No post anterior vimos que as cores tem significados e como montar uma paleta equilibrada e coerente com cada tipo de projeto, porém precisamos representá-las e assim como tudo em nossa vida, as cores também podem ser mostradas de diversas formas.

**- RYB**
RYB é um sistema de cores subtrativo que se baseia nas cores primárias (vermelho, amarelo e azul), ou seja, ele descreve a forma como as cores absorvem a luz e partindo delas obtemos as cores secundárias e terciárias. Ele é muito usado na teoria de cores e nas aulas de educação artística quando aprendemos a misturar as cores.

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

**- RGB**
RGB sem dúvidas é o sistema de cores mais conhecido. Ele é um sistema de cor aditivo, ou seja, diferentes cores são combinadas para criar uma nova cor por meio da adição de luz. Cada cor é representada por um valor numérico que vai de 0 à 255, onde 0 representa a ausência e 255 sua máxima intensidade. Esse sistema é muito utilizado em monitores e TVs.

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

**- CMYK**
CMYK é um acrônimo para a junção de cores utilizada nesse sistema de representação. Temos o C de ciano, M de magenta, Y de amarelo e K de preto. Esse modelo é muito utilizado em impressões e reprodução de cores em meios físicos por ser mais preciso. Com a combinação dessas cores podemos criar uma ampla gama de tons e para representá-las utilizamos o valor em % para cada cor, onde 0% significa ausência dessa cor e 100% a máxima intensidade.

![CMYK](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e80mevv72qdtbr48xz8c.png)
Svelte: set a default radio button with bind
Tags: svelte, html, javascript, learning
Published: 2023-07-24 19:45:50

I've just started using Svelte, and it's been really fun to work with!

Today, I did, however, run into a little quirk with radio buttons. If you use the `bind` directive, there is no way to have a radio button checked by default.

## bind directive

In Svelte, you can use element directives, and particularly helpful for radio buttons is the [bind directive](https://svelte.dev/docs/element-directives#bind-group).

Basically, you can group a number of radio inputs together. Here is the example from Svelte's docs:

```svelte
<script>
  let tortilla = 'Plain';

  /** @type {Array<string>} */
  let fillings = [];
</script>

<!-- grouped radio inputs are mutually exclusive -->
<input type="radio" bind:group={tortilla} value="Plain" />
<input type="radio" bind:group={tortilla} value="Whole wheat" />
<input type="radio" bind:group={tortilla} value="Spinach" />
```

It's pretty straightforward — all these inputs are bound together as part of the group `"Plain"`. 

_Note: if the variable were named `group` instead of `tortilla`, you can just write `bind:group`, which is nice._

If you were to create a [Svelte repl](https://svelte.dev/repl) you would notice that when the code compiles, no radio buttons are checked.

That may be ok in some situations, but I wanted to ensure that at least one is checked.

The solution is a lifecycle hook.

## onMount hook

Like most component libraries, Svelte allows you to hook into the components lifecycle.

For this issue, the [onMount](https://svelte.dev/tutorial/onmount) hook is needed.

Now, when the component is mounted, I can can check if there are any checked inputs. If not, then I check the first:

```js
onMount(() => {
  const inputs = document.querySelectorAll("input");
  const hasChecked = Array.from(inputs).some((input) => input.checked);
  if (!hasChecked) {
    inputs[0].checked = true;
  }
});
```

That's it!

Here is a full example and a link to a [repl](https://svelte.dev/repl/93857e5d460044279e7db22350fbea65?version=4.1.1).

```svelte
<script>
  import { onMount } from "svelte";
  let group = "philosophers"
  const options = ["Søren Kierkegaard", "Jean-Paul Satre", "Simone de Beauvoir", "Albert Camus"];

  onMount(() => {
    const inputs = document.querySelectorAll("input");
    const hasChecked = Array.from(inputs).some((input) => input.checked);
    if (!hasChecked) {
      inputs[0].checked = true;
    }
});
	
</script>

<div class="question">
  <legend>Who is your favorite existentialist philosopher?</legend>
  {#each options as option}
    <div class="option">
      <input type="radio" id={option} bind:group value={option}>
      <label for={option}>{option}</label>
    </div>
  {/each}
</div>

<style>
  div.question {
    display: flex;
    flex-direction: column;
  }
</style>
```
Hopefully, this helps anyone else who encounters this issue.
Photos Crop For Social Media
Tags: imagecropp, javascript, programming, socialmedia
Published: 2023-07-24 19:28:04

In today’s visually-driven social media landscape, the right image can make all the difference in capturing your audience’s attention. Whether you’re an influencer, a marketer, or simply someone who loves sharing moments on social platforms, having the perfect image size is crucial for maximum impact. To help you achieve just that, we’ve compiled a list of the top 10 best free image croppers that will make cropping photos for social media a breeze. 

Let’s dive in:

1. Mozjpeg (https://www.mozjpeg.com/)

A powerful tool to edit resize, crop and compress jpeg and png images.
Using mozjpeg makes your website faster and save bandwidth. it optimizes your images 50–80% without any quality loss,

🖼️ Upgrade your design game with our All-in-One Image Toolkit! 🎨 Easily crop, colorize, and resize images to create stunning visuals. No more boring pictures — make your content shine!

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




2. Fotor (https://www.fotor.com/)

Fotor’s image cropping tool is packed with features to enhance your photos and adjust them to the ideal size for your favorite social media platforms. Its user-friendly interface makes it an excellent choice for beginners.

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



3. Canva (https://www.canva.com/)

Canva needs no introduction; it’s a popular graphic design platform that also offers an easy-to-use image cropper. With pre-defined social media templates and intuitive tools, you can crop your photos to fit perfectly on various platforms.

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



4. Pixlr (https://pixlr.com/)

Pixlr offers a robust online photo editor with an efficient cropping tool. It allows you to crop, resize, and edit your images to create stunning visuals for your social media posts.

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



5. Croppola (https://croppola.com/)

Croppola is designed to automatically crop your photos based on the composition, ensuring your subject remains the focal point. You can specify the aspect ratio and let Croppola do the rest.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zroeqcpadf8759xnp3xb.png)
Episode 03 - Find the number of 1s and 0s from the array
Tags: javascript, javascriptcode, interview, coding
Published: 2023-07-24 19:20:16

You have been given an array of integers that consists only 1s and 0s. Your task is to find the total number 1s and 0s in the array.

**Example Input:**
[1, 0, 1, 0, 0, 1, 1, 0]

**Expected Output:**
Total 1s are 4.
Total 0s are 4.

Sounds easy, right? 

But wait, there is one condition that you should not use any conditional operators like **if** or **ternary operator**. Interesting right?

The easiest way to find the solution is sum all the numbers in the array and subtract it from the array length. Since we only have 0s and 1s, the sum of the array is equal to the number of 1s and the difference from array length is equal to the number of 0s. Sounds easy, right? lets code it now.

```
const findOnesAndTwos = (array) => {
  const sum = array.reduce((acc, num) => acc + num, 0);
  console.log(`Total 1s are: ${sum}`);
  console.log(`Total 0s are: ${array.length - sum}`);
};

findOnesAndTwos([1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0])
// Total 1s are: 7
// Total 0s are: 6

```
Check it in our YouTube

{% embed https://youtu.be/1DhJFqA8DVU %}
Custom Chip - Beer CSS Tips #2
Tags: css, tutorial, html, javascript
Published: 2023-07-24 19:04:35

Hello,

I want to share a serie of posts containing some tips of Beer CSS. Beer CSS is a new framework around, based on (not restricted to) Material Design 3. Material Design 3 is a design system created by Google. In this post, we will learn about custom chips. The logic of chips is very simple.

If you don't known the concept of **settings**, **elements** and **helpers** used by Beer CSS, you can [read this page](https://github.com/beercss/beercss/blob/main/docs/INDEX.md).

1) First, you need to create a chip **element**.

```html
<a class="chip">Chip</a>
```

2) You can use a form **helper** like `border` or `round`.

```html
<a class="chip border">Chip</a>
<a class="chip round">Chip</a>
<a class="chip border round">Chip</a>
```

3) You can add a media **element** like `i`, `img`, `svg` or `video` inside a `chip`.

```html
<a class="chip">
  <i>search</i>
  <span>Chip</span>
</a>
```

4) With a position **helper** like `front` or `back`, you can determine if the media **element** is clickable or not. Optionally you can use the `wave` or `no-wave` **helper** too:

```html
<a class="chip">
  <i class="front wave">search</i>
  <span>Chip</span>
</a>
```

5) You can use another **elements** inside a `chip` like `badge`, `tooltip`, `menu`, `progress`, etc...

```html
<a class="chip">
  <i class="front wave">search</i>
  <span>Chip</span>
  <span class="tooltip">Tooltip</span>
</a>

<button class="chip">
  <i class="front wave">search</i>
  <span>Chip</span>
  <menu>
    <a>Item 1<a>
    <a>Item 2<a>
    <a>Item 3<a>
  </menu>
</button>
```

The **helpers** of Beer CSS can be used in any **element**. This makes the framework very customizable. It has the same logic and names in all ways. This makes the Beer CSS very easy to understand and reuse. I made a codepen to see how far Beer CSS can go and I achieve +100 different use-cases of chips [here](https://codepen.io/leo-bnu/pen/BaGOLvJ). 

Hope you enjoy this article. Thanks for read!

Beer CSS:
https://www.beercss.com

Material Design 3:
https://m3.material.io/

Codepen:
https://codepen.io/leo-bnu/pen/BaGOLvJ

About settings, elements and helpers used by Beer CSS:
https://github.com/beercss/beercss/blob/main/docs/INDEX.md
react-konva useRef type error
Tags: react, errors, reactkonva
Published: 2023-07-24 18:58:54

## Error Solution Note

I didn't know how to define the type of the `ref` prop of the `Image` component. `InstanceType`, `ClassAttributes` and the other ways I found didn't work. When I used `Image` as a type, I could use the `ref` but the other type error occurred. I just decided to get the type of the ref from the component using ComponentProps and it worked. the `ref` Object is defined as `React.LegacyRef` though, it seems working well.

---

## Error Message
> 'Image' refers to a value, but is being used as a type here. Did you mean 'typeof Image'?ts(2749)

---

## Solution

```typescript
const imageRef: ComponentProps<typeof Image>["ref"] = useRef(null);
```

---

## Sample Code

```typescript
import { ComponentProps, useEffect, useRef, useState } from "react";
import { Stage, Layer, Image } from "react-konva";
import MapTileset from "./assets/map/map-tileset.png";

const App = () => {
  const [image, setImage] = useState<HTMLImageElement>();
  const imageRef: ComponentProps<typeof Image>["ref"] = useRef(null);

  useEffect(() => {
    const mapImage = new window.Image();
    mapImage.src = MapTileset;

    mapImage.onload = () => {
      imageRef.current.crop({ x: 0, y: 0, width: 30, height: 30 });
      imageRef.current.width(30);
      imageRef.current.height(30);

      setImage(mapImage);
    };
  }, []);

  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <Image image={image} ref={imageRef} />
      </Layer>
    </Stage>
  );
};

export default App;
```
making a better pixel editor with godot 4.1 ✨
Tags: godot
Published: 2023-07-24 18:54:16

there are many pixel editors out there, but they are mostly closed source or lacking many features. we're trying to make a pixel editor that values being updated regularly, having commits almost every day 👀. 

you may be worried about my profile picture (the cover), but dont worry. i am perfectly **s a n e**. jajajajaja. 

to help support us on our journey, consider contributing on our [github](https://github.com/theMostBest/the-most-best-pixel-editor)

many thanks
ExpiringLRUCache and The CLOCK Algorithm: A Fun Dive into Python Caching
Tags: python, caching
Published: 2023-07-24 18:36:41

## Introduction

Caching is a common technique that programs use to speed up access to slow data sources by keeping a copy of the data in fast access memory. In Python, we can implement this concept in many ways, but let's talk about an exciting one: The ExpiringLRUCache!

## What is ExpiringLRUCache?

ExpiringLRUCache is a cache implementation that combines two powerful concepts: The Least Recently Used (LRU) cache eviction policy and an expiration time for cache entries. In simple terms, it remembers the most recently used items up to a specified limit and for a particular duration. After the duration expires or when the cache is full, it starts removing items, making room for the new ones. Sounds cool, right?

## The CLOCK Algorithm

But, how does ExpiringLRUCache decide which item to remove first? Here comes the CLOCK algorithm! It's a smart approximation of the LRU policy. Imagine a clock hand moving over each cache item. If the item is recently used, it gets a "second chance," and the hand moves on. If not, it's time to say goodbye to that item!

## How Can We Use ExpiringLRUCache?

Now, let's get our hands dirty with a fun example:

```python
from expiringlrucache import ExpiringLRUCache

# Create a cache of size 3 with items expiring after 60 seconds
cache = ExpiringLRUCache(3, 60)

# Put some items in the cache
cache.put("apple", "delicious")
cache.put("banana", "yummy")
cache.put("cherry", "tasty")

# Get an item from the cache
print(cache.get("banana"))  # Output: "yummy"

# After 60 seconds...
print(cache.get("apple"))  # Output: None (as it's expired)
```

With just a few lines of code, we've implemented a speedy cache! 🚀

## How to Improve It?

Though ExpiringLRUCache is quite efficient, there are a few ways to boost its performance:

1. **Eviction Policy**: For more precise LRU behavior, consider implementing a true LRU cache.
2. **Parallelism**: If you have a high degree of parallelism, consider partitioning the cache into multiple segments each with its own lock.
3. **Cache Size Tuning**: Adjust the cache size based on its observed hit rate.
4. **Dynamic Expiration Strategy**: Assign longer expiration times to entries that are accessed more frequently.

Remember, it's all about finding the right balance based on your specific needs!

## Conclusion

Caching is a powerful tool, and with Python's flexibility, we can customize it to our heart's content. ExpiringLRUCache and the CLOCK algorithm offer an efficient approach to caching, making our applications faster and more efficient. So, next time you find your program waiting for data, consider using an ExpiringLRUCache. It might just save your day!

Happy caching! 🎉
Deep Dive into Apache AGE
Published: 2023-07-24 18:34:14

Let's delve deeper into Apache AGE features and see how it  can enhance your data management capabilities.

###1. OpenCypher Compatibility

Apache AGE uses the openCypher Query Language, the most widely adopted, fully-specified, and open query language for graph databases. This means that if you're already familiar with SQL, you'll find the transition to openCypher relatively smooth. Here's an example of a more complex openCypher query:

```sql
SELECT * FROM cypher('my_graph', $$ 
  MATCH (a:Person)-[:Friendship]->(b:Person) 
  WHERE a.name = 'John' 
  RETURN b.name 
$$) AS (name text);
```

This query finds the names of all people who are friends with 'John'.

###2. Interoperability with SQL

One of the key strengths of Apache AGE is its seamless interoperability with SQL. Since AGE is an extension of PostgreSQL, you can use SQL and openCypher queries side by side. This allows you to leverage the full power of SQL for data manipulation and aggregation, while using openCypher for complex graph queries.

###3. Scalability and Performance

Apache AGE leverages the performance and scalability of PostgreSQL. This means that as your data grows, you can rely on PostgreSQL's proven mechanisms for handling large datasets. Furthermore, AGE's graph model is stored in tables, allowing PostgreSQL's query optimizer to improve the performance of graph queries.



##Conclusion

By extending PostgreSQL with Apache AGE, we can manage complex data relationships more intuitively and efficiently. Whether you're dealing with social networks, recommendation systems, or any other domain where relationships between entities are key, PostgreSQL and Apache AGE provide a powerful, scalable, and efficient solution.

Stay tuned for more posts on advanced topics in PostgreSQL and Apache AGE. Happy coding!

#postgresql #apacheage