teleren/devto huggingface dataset:
Invalid Tweets | LeetCode | MSSQL
Tags: leetcode, programming, codenewbie, mssql
Published: 2023-07-05 17:06:00

## The Problem

Table: Tweets

| Column Name | Type    |
|-------------|---------|
| tweet_id    | int     |
| content     | varchar |

The `tweet_id` is the primary key for this table, which contains all the tweets in a social media app.

The task is to write an SQL query to find the IDs of the invalid tweets. A tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15.

Here's an example to better illustrate the problem:

### Input

Tweets table:

| tweet_id | content                          |
|----------|----------------------------------|
| 1        | Vote for Biden                   |
| 2        | Let us make America great again! |

### Output

| tweet_id |
|----------|
| 2        |

### Explanation

Tweet 1 has a length of 14. It's a valid tweet.
Tweet 2 has a length of 32. It's an invalid tweet.

## The Solution

In this post, we'll delve into two MSSQL solutions. Both effectively solve the problem but using different functions — highlighting their unique strengths, weaknesses, and performance metrics.

### Source Code 1

The first solution uses the `LEN` function to calculate the length of the tweet content:

```sql
SELECT tweet_id
FROM Tweets
WHERE LEN(content) > 15
```

This code's runtime is 1953ms, beating 19.62% of other submissions. Here's the performance snapshot:
![s1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hgqrewydmocu042n9pm5.png)

### Source Code 2

The second solution differs from the first by using the `DATALENGTH` function instead of `LEN`:

```sql
SELECT tweet_id
FROM Tweets
WHERE DATALENGTH(content) > 15
```

This solution's runtime is 1522ms, beating 66.57% of other submissions. Here's the performance snapshot:
![s2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ldq5khkfrc3kep9ibqn4.png)

## Conclusion

These two solutions effectively determine the invalid tweets based on the content length, with the second solution performing significantly better on LeetCode. However, performance may vary in real-world RDMS due to different factors, such as data volume, system hardware, SQL server configurations, etc.

Here's a ranking of these solutions based on LeetCode performance:

1. Source Code 2
2. Source Code 1

You can find the original problem at [LeetCode](https://leetcode.com/problems/invalid-tweets/description/).

For more insightful solutions and tech-related content, feel free to connect with me on my [Beacons page](https://beacons.ai/ranggakd).

{% embed https://beacons.ai/ranggakd %}
CSS's :root Variables. Use it!
Tags: css, variables, styling, webdev
Published: 2023-07-05 16:57:29

CSS's :root selector lets you define global variables that can be used in your stylesheets. These variables, also known as custom CSS properties, provide a convenient way of storing and reusing values, making your stylesheets more modular and easier to maintain.

## 1. Defining :root variables
To define a :root variable, use the :root selector followed by the variable name and value, surrounded by double dashes (--). 
Here is an example:

```css
:root {
  --primary-color: #fff;
  --font-size: 14px;
}
```
## 2. Using :root Variables
To use a :root variable, you can refer to it using the var() function and the variable name, as following:

```css
body {
  color: var(--primary-color);
  font-size: var(--font-size);
}
```
## 3. Overriding :root Variables
You can override :root variables at any point in your stylesheets by redefining them. This flexibility allows you to update the variable value globally, affecting all the styles that rely on it.

## 4. Benefits of :root Variables

- Reusability: Use variables throughout your stylesheets, reducing code duplication.
- Consistency: Maintain a consistent look and feel by centralizing values in variables.
- Dynamic Updates: Change variable values dynamically, resulting in global style changes.

Conclusion:
Using :root variables in CSS is a powerful way of defining and reusing values in your style sheets. By centralizing your values and making them easily modifiable, you can improve code maintenance, achieve consistent styling and create more flexible designs.

Remember to update your stylesheets to take advantage of :root variables and enjoy the benefits they provide in your CSS development process.
Javascript fetchWithAutoRetry
Tags: javascript, programming, webdev, react
Published: 2023-07-05 16:41:12

For a web application, fetching API data is a common task.

But the API calls might fail because of Network problems. Usually we could show a screen for Network Error and ask users to retry.

One approach to handle this is auto retry when network error occurs.

You are asked to create a fetchWithAutoRetry(fetcher, count), which automatically fetch again when error happens, until the maximum count is met.

For the problem here, there is no need to detect network error, you can just retry on all promise rejections.

**fetchWithAutoRetry**

```
function fetchWithAutoRetry(fetcher, count) {
  return new Promise((resolve, reject) => {
    const attempt = () => {
      fetcher()
        .then(resolve) 
        .catch(() => {
          if (count === 0) {
            reject();
          } else {
            count--;
            attempt();
          }
        });
    };   
    attempt();
  });
}
```

- It takes a fetcher function which returns a promise, and a count of maximum retries
- It returns a new promise
- On promise resolve, it passes the result to the returned promise
- On promise reject, it checks:
- If count is 0, rejects the returned promise
- Otherwise decrements count and calls attempt() again to retry the fetcher

**fetchWithAutoRetry using async-await**


```
function fetchWithAutoRetry(fetcher, count, interval = 1000) {
  return new Promise(async (resolve, reject) => {
    const attempt = async () => {
      try {
        const data = await fetcher();
        resolve(data);
      } catch (err) {
        if (count === 0) {
          reject(err);    
        } else {
          count--;
          setTimeout(attempt, interval);
        }
      }  
    }
    attempt();    
  });
}
```

- Use async/await for cleaner syntax

**Adding a delay between retries can help if the API failure was due to a temporary issue**
AWS IAM Identity Center
Tags: aws, cloudcomputing, cloudskills, iam
Published: 2023-07-05 16:28:44

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

[17/30] #30DaysOfAWS Today, AWS IAM Identity Center.

**AWS IAM Identity Center** (successor to AWS Single Sign-On) is a cloud-based identity and access management (IAM) service that helps you centrally manage and control access to your AWS resources.

## IAM Identity Center provides the following benefits

- **Single sign-on (SSO) to AWS accounts and applications** - IAM Identity Center allows your workforce users to sign in to all their AWS accounts and applications with a single set of credentials. It reduces risk of password fatigue and increases productivity.

- **Centralized user management** - IAM Identity Center allows you to create, manage, and delete users and groups centrally. This makes it easier to keep track of your users and their permissions.

- **Role-based access control (RBAC)** - IAM Identity Center supports RBAC, which allows you to grant users permissions to specific AWS resources. This helps you to secure your AWS environment and prevent unauthorized access.

- **Fine-grained access control** - IAM Identity Center allows you to define fine-grained access control policies for your AWS resources. This helps you to ensure that users only have access to the resources that they need.

- **Auditing and reporting** - IAM Identity Center provides auditing and reporting capabilities that help you to track user activity and identify potential security risks.

IAM Identity Center can be used by organizations of all sizes. It is a scalable and cost-effective solution that can help you to improve the security and efficiency of your AWS environment.

## Here are some of the ways that IAM Identity Center can be used

1. To provide SSO to AWS accounts and applications
2. To centralize user management
3. To implement RBAC
4. To define fine-grained access control policies
5. To track user activity and identify potential security risks

If you are looking for a secure and efficient way to manage user access to AWS, then IAM Identity Center is a good option to consider.

AWS IAM Identity Center step-by-step workshop [URL](https://catalog.workshops.aws/iam-identity-center/en-US).

Thanks for reading the Article.

[LinkedIn](https://www.linkedin.com/in/lasanthasilva)

[Twitter](https://twitter.com/LasanthaSilva96)
Installing Wear OS APK on Real Watch with Companion App Having the Same Package Name
Published: 2023-07-05 16:26:48

How can I install a Wear OS APK on a real watch when I have a companion app with the same package name? I'm developing a Wear OS app and want to test it on an actual device. I have created a companion Android app with the same package name as the Wear OS app. Could someone provide me with the necessary steps, code, or any other solution to download and install the APK file in development mode on my Wear OS device? I would greatly appreciate any guidance or suggestions. Thank you!
Controle de Exibição de Elementos no React usando Show e Hide
Tags: react, webcomponents, javascript, typescript
Published: 2023-07-05 16:17:26

Muitas vezes, durante o desenvolvimento de aplicações React, nos deparamos com a necessidade de exibir ou ocultar elementos com base em determinadas condições. Para tornar esse processo mais simples e legível, podemos criar componentes reutilizáveis chamados `Show` e `Hide`, que nos permitirão controlar a exibição de elementos de forma mais intuitiva.

```tsx
import React, { Fragment } from 'react';

type Visibility = {
  when: boolean;
  children: JSX.Element;
};

const Show: React.FC<Visibility> = ({ when, children }) =>
  when ? children : <Fragment />;

const Hide: React.FC<Visibility> = ({ when, children }) =>
  when ? <Fragment /> : children;
```
Vamos analisar a estrutura do código:

1. Começamos definindo uma interface chamada `Visibility`. Essa interface tem duas propriedades:

  - `when`: Um valor booleano que indicará se o elemento deve ser exibido (`true`) ou ocultado (`false`).
  - `children`: Uma propriedade do tipo `JSX.Element`, que representa o conteúdo que será exibido caso a condição seja atendida.

2. Em seguida, criamos o componente `Show`. Esse componente é uma função que recebe as propriedades da interface `Visibility` desestruturadas. Ele verifica a condição `when` e retorna o conteúdo `children` se a condição for verdadeira (`true`). Caso contrário, retorna um fragmento vazio (`<Fragment />`) para ocultar o elemento.

3. Depois, temos o componente `Hide`, que funciona de forma inversa ao `Show`. Ele também recebe as propriedades `when` e `children`, mas desta vez inverte a condição. Se when for verdadeiro, retorna um fragmento vazio, ocultando o elemento. Caso contrário, retorna o conteúdo `children`.

Agora que temos esses componentes definidos, podemos utilizá-los em qualquer lugar do nosso projeto React. Vamos dar um exemplo de uso para ilustrar como eles podem simplificar o controle de exibição de elementos:

```tsx
import React, { useState } from 'react';

const ExampleComponent: React.FC = () => {
  const [isVisible, setIsVisible] = useState(true);

  const toggleVisibility = () => {
    setIsVisible((prevValue) => !prevValue);
  };

  return (
    <div>
      <button onClick={toggleVisibility}>Toggle Visibility</button>

      {/* Usando o componente Show */}
      <Show when={isVisible}>
        <p>Este é o conteúdo exibido quando isVisible é true.</p>
      </Show>

      {/* Usando o componente Hide */}
      <Hide when={isVisible}>
        <p>Este é o conteúdo ocultado quando isVisible é false.</p>
      </Hide>
    </div>
  );
};
```

Neste exemplo, criamos um componente chamado `ExampleComponent`, que possui um botão para alternar a visibilidade do conteúdo. Quando o botão é clicado, o estado `isVisible` é alternado entre `true` e `false`, controlando assim a exibição ou ocultação dos elementos filhos dos componentes `Show` e `Hide`.

Essa abordagem torna o código mais legível, reutilizável e fácil de entender, especialmente quando temos lógica mais complexa
Advice for newbie devs that are Working From Home? 💻
Tags: discuss, productivity, career, beginners
Published: 2023-07-05 15:54:24

Hi all! ☀️

I'll be starting my first full-time software developer co-op in the fall and I will be working entirely remotely. I'd love to hear your tips/advice on how to be productive and consistent when working in an entirely remote setup!?

I also want to secure a return offer with this company, so any guidance on how to excel during my WFH co-op would also be fantastic :) 🐳
Understanding JWTs: A Simple Guide for Beginners
Tags: programming, webdev, beginners, security
Published: 2023-07-05 15:40:59

## What is a JWT?
JWT, short for JSON Web Tokens, is a compact, URL-safe way of representing claims (information) to be transferred between two parties, the client and server. Think of it like a secret message in the form of a cryptographically signed note, which can only be understood by the intended recipient.

## Structure of a JWT
A JWT has three distinct parts, each separated by a dot (.):

- **Header:** It contains metadata about the token and the cryptographic algorithm used, usually HMAC SHA256 or RSA.

- **Payload:** The actual data that the token carries is stored here. It's also known as the 'claims' and can include data like user details and additional metadata.

- **Signature:** The signature is a cryptographically secured proof that verifies the sender and ensures the message wasn't altered during transit.

![Structure of a JWT](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/94cai6lqmj2hoxnewc2o.png)

## How Does a JWT Work?
Here's the play-by-play of JWT in action:

1. A client logs in using their credentials, sending a request to the server.
2. The server verifies these credentials. If they're valid, the server generates a JWT and sends it back to the client.
3. The client stores the JWT, usually in local storage, and includes it in every subsequent HTTP request's header.
4. The server, upon receiving these requests, verifies the JWT. If it's valid, the client is authenticated and authorized.


## Why Use JWT?
JWTs are universal - any programming language can generate a JWT because they're essentially JSON. Also, they facilitate maintaining session state on the client, reducing server load, which is more scalable.

## Security Considerations
While JWTs are handy, they do come with some vulnerabilities:

- **Token Theft:** JWTs are stored on the client-side, and hence can be stolen. Always ensure your transmission is secure, preferably via HTTPS.

- **No In-built Invalidity Mechanism:** JWTs can't be invalidated individually or in a group from a user, due to their stateless nature.

- **Token Size:** Storing too much data in a JWT can make it heavy, affecting network performance.

- **Algorithm Vulnerabilities:** Some algorithms in the JWT header are vulnerable to attacks. Always use secure and updated algorithms, and treat your signing keys like secrets.

---

In conclusion, JWTs are a potent tool in web development, providing stateless, secure, and scalable communication. Remember, how effectively you wield JWTs in your application depends on your specific needs and the level of security you require.

I hope this gives you a better understanding of JWTs! Feel free to share your thoughts 😄
Debugging in Console
Tags: javascript, beginners, codenewbie, tutorial
Published: 2023-07-05 15:11:44

Something programmers use all the time is debugging. The best thing about this process is that we don't have to wait until an error is thrown to use this tool. There are many different ways that can end this tool to refine our check. We are going to talk about a few of them here today. 

`console.log()`  

It is the most basic and best tool in JavaScript for debugging.

While writing our code we can add in `console.log()` with the parameter or message that we are checking. This is called, Tracing!
This will provide feedback about 'what the machine is thinking', and showing us what is being passed. From here we know if we need to go back and see why we aren't getting the response in console, or if there's some reshaping to the code that is required.

```
console.log('Is this our info?')
```

Here are some that are not as popular as the `console.log`. 

`console.error()`

```
const pets = {smallCat: 'Flurry', bigCat: 'Keebs'}
console.error(pets)
```
This is for printing out an error to the console. This form allows it to take on multiple arguments. 


`console.warn()`

```
const pets = {smallCat: 'Flurry', bigCat: 'Keebs'}
console.warn(pets)
```
This form is a middle step between the usual .log() and the more dire .error() messages.


The final one that we are going to talk about today is:

`console.table()`.

This is going to print out a table of all the entries. Just like the last two examples, they are not as common. Primarily `console.log()` is going to be a new best friend! 

It is good practice to always `console.log()` any message, variable, and even finish functions with that to be sure that everything is still working so far. When passing or receiving elements to the DOM it's so crucial to be checking that those elements; Be sure we are moving what we want, where we want. 

There are many many uses to this debugging. It allows us to pick apart our code to see what is causing the issues and where they are. Error codes will show what folder, code line and line space that broke the code. The most common error types are Syntax, Type, Range, and Scope errors. 

Here are some great links that are helpful to understanding these tools more in depth. 
[MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Console/log)
[GeeksforGeeks](https://www.geeksforgeeks.org/javascript-console-log-method/)
[FreeCodeCamp](https://www.freecodecamp.org/news/javascript-console-log-example-how-to-print-to-the-console-in-js/)

Thanks for reading! Have a great day!
Safely use `JSON.parse()` in TypeScript
Tags: javascript, typescript, frontend, node
Published: 2023-07-05 15:00:00

Let's talk about something that most of us can relate to: `JSON.parse()`. We all know that thing we use to turn a JSON string into an object.

```typescript
const jsonString = '{ "title": "Title" }'

const jsonValue = JSON.parse(jsonString)
// { title: 'Title' } ✅
```

## Problems
Now, here's the thing... 

Have you ever wondered what happens when you mess around with the value of `jsonString`? Let's say you change `'{ "title": "Title" }'` to `''`. Well, guess what? The expected turns into... ERROR! 🤯

```typescript
const jsonString = ''

const jsonValue = JSON.parse(jsonString)
// Error: Unexpected end of JSON input ❌ 💣
```

It may seems like a small issue, but guess what? Lots of developers forget to handle it properly!

Now, here's the interesting part...

In TypeScript, `JSON.parse()` doesn't have any specific type arguments. It just returns `any`. This means, it comes at the cost of losing the benefits of static typing and type safety.

```typescript
const jsonString = "";

const jsonValue = JSON.parse(jsonString)
// const jsonValue: any ❌
```

When developers treat potentially unsafe data as completely safe, it can cause some really frustrating errors to deal with. 😫

## Solutions

But don't worry, I've got a couple of solutions! 💡

### 1. Create "safeJsonParse" function
```typescript
const safeJsonParse = <T>(str: string) => {
  try {
    const jsonValue: T = JSON.parse(str);

    return jsonValue;
  } catch {
    return undefined;
  }
};
// const safeJsonParse: <T>(str: string) => T | undefined ✅
```

This function is responsible for handling parsing errors. If an error occurs during parsing, it will return `undefined`. Otherwise, it will return the parsed JSON value along with its corresponding data type.

### 2. Add fallback


```typescript
interface JsonValue {
  title: string
}

const jsonString = '{ "title": "Title" }'

const jsonValue = safeJsonParse<JsonValue>(jsonString) || { "title": "" }
// const jsonValue: JsonValue ✅
```

Just in case the value is `undefined`, we can add a fallback mechanism. This ensures that the value will always be provided, regardless of what happens.

## Conclusion
So, if we keep these things in mind, we'll avoid headaches and make our code super solid. I hope you find these tips useful for your projects! You got this! ✨
The day I met my new AI assistant
Published: 2023-07-05 14:58:50

I was sitting at my desk, staring at a blank page. I had been trying to write a blog post for hours, but I was completely stuck. I couldn't think of a single idea.

Just when I was about to give up, I remembered that I had recently signed up for the Notion AI beta. I decided to give it a try.

I opened up Notion and typed in "write a blog post about AI." In a matter of seconds, Notion AI had generated a list of possible blog post titles, outlines, and even paragraphs of text.

I was amazed. I had never seen anything like it. Notion AI was like having a personal AI assistant who could write my blog posts for me.

I spent the next few hours working with Notion AI to refine my blog post. I added my own ideas and insights, and I made sure that the tone and style were consistent with my other blog posts.

When I was finished, I was really happy with the results. My blog post was well-written, informative, and engaging. I couldn't believe that I had been able to write it so quickly and easily.

I'm so glad that I signed up for the Notion AI beta. It's an amazing tool that can help anyone write better, faster, and more easily.

**Here are some of the benefits of using Notion AI:**

- It can help you brainstorm ideas, write rough drafts, and summarize existing content.
- It can correct your spelling and grammar.
- It can translate your content into other languages.
- It can help you plan and manage projects.
- It can help you create knowledge bases and databases.

**Notion AI is perfect for:**

- Students
- Writers
- Business professionals
- Anyone who wants to be more productive

**If you're looking for a powerful AI tool that can help you with your work or studies, then you need to try Notion AI.**

**Sign up for the beta today and see for yourself how Notion AI can help you work smarter, not harder.**

[Start Here](https://affiliate.notion.so/3q4vhf6k54yg-4y5a7)