teleren/devto huggingface dataset:
How I've deleted my git remote branch and kind of managed to restore it
Tags: git
Published: 2023-05-25 14:43:20

Restoring things (branches) from git that were deleted in git, git git git git.

I'm a spaz. Last night I've felt like tidying up, so I've started dropping my branches in remote and locally. Few hours later I've realised some pull requests are gone. 

So my local branch is gone, my remote branch is also gone. What do i do now?

Good solution would be to search for SHA that's printed every time you delete branch. With that you can `git checkout -b new-branch-name SHA` and you'll be fine. But not me, i've deleted 30-40 branches through a shell script (told you, i'ma spaz).
 
Next suggestion would be [git reflog](https://git-scm.com/docs/git-reflog) but that didn't do it for me either. Next is "local history" plugins in your IDE yet i had none so I'll cut straight to the chase, here's what I did:

1. you run `git fsck --lost-found` - this would print all the lost boys. Out of these i suggest you filter out ones that start with "dangling commit" (that's what i did)

2. Now you have hundreds, maybe thousands of commit hashes without a message that you can theoretically look into. Still bad? - Don't lose hope. What i did next was: i put all commits into a biiiig space-separated line. Very long line. And ran a shell script

```
#!/bin/bash

for i in [those 200 items ]do

   git show $i

done
```

3. I've re-directed output of this script into a file with > pipe, cmd+f in that huge text file and found diffs of my missing commits by names of classes and functions.

4. I've cherry-picked them by SHA into a new branch

Perhaps there's a better easier way, grep masters surely know, but here's what i did. Maybe it helps you too, you silly Milly.

Enjoy yo day boys and girls
Explorando os Library Hooks do React: Exemplos e Casos de Uso
Tags: react, reactnative, javascript, programming
Published: 2023-05-25 14:11:40

Os Library Hooks **useSyncExternalStore** e **useInsertionEffect** são dois exemplos de hooks adicionais do React que podem ser utilizados para aprimorar a funcionalidade e o desempenho das aplicações. 

Neste artigo, exploraremos esses dois hooks, seus casos de uso e será fornecido exemplos práticos de como utilizá-los.

## 1. useSyncExternalStore:
 O **useSyncExternalStore** é um hook que permite sincronizar o estado de um componente com uma fonte de dados externa, como um banco de dados ou um serviço de armazenamento em nuvem. 

Ele é útil quando se deseja manter os dados atualizados em tempo real, sem a necessidade de recarregar a página ou acionar manualmente uma atualização.

**Caso de uso:** Imagine um aplicativo de chat em tempo real, onde as mensagens são armazenadas em um servidor. O **useSyncExternalStore** pode ser utilizado para buscar e atualizar automaticamente as mensagens à medida que são enviadas e recebidas.

**Exemplo:**

```js
import React,{ useSyncExternalStore } from 'react';

const ChatComponent = () => {
  const [messages, setMessages] = useSyncExternalStore('chatMessages');

  // Renderiza as mensagens
  return (
    <div>
      {messages.map((message) => (
        <div key={message.id}>{message.text}</div>
      ))}
    </div>
  );
};

```

## 2. useInsertionEffect:

 O **useInsertionEffect** é um hook que permite executar um efeito somente quando um componente é inserido na árvore DOM pela primeira vez. Isso é útil quando se deseja executar uma ação apenas no momento inicial da renderização do componente, como configurar um evento global ou registrar um serviço.

**Caso de uso:** Suponha que você esteja construindo um aplicativo que precise inicializar um serviço de notificações push quando o componente raiz da aplicação for renderizado pela primeira vez. O **useInsertionEffect** pode ser usado para executar essa inicialização somente no momento da montagem inicial.

**Exemplo:**

```js
import React,{ useInsertionEffect } from 'react';

const App = () => {
  useInsertionEffect(() => {
    // Inicializa o serviço de notificações push
    NotificationService.initialize();
  }, []);

  return (
    <div>
      {/* Conteúdo do aplicativo */}
    </div>
  );
};

```

Esses são apenas dois exemplos dos Library Hooks disponíveis para uso no React. Esses hooks podem ser utilizados para adicionar funcionalidades específicas às aplicações, melhorando a experiência de desenvolvimento e permitindo a implementação de recursos avançados. 

Sempre verifique a documentação oficial da biblioteca que fornece o hook para obter mais detalhes sobre o seu uso e casos de uso adicionais.


### Referencias:
[React Hooks](https://legacy.reactjs.org/docs/hooks-reference.html)
[useSyncExternalStore](https://react.dev/reference/react/useSyncExternalStore)
[useInsertionEffect](https://react.dev/reference/react/useInsertionEffect)
Lesser Known Features of DEV — Embedding Call To Action (CTA) Buttons
Tags: meta, documentation, community, howtodevto
Published: 2023-05-25 14:11:06

Did you realize that on DEV you have the ability to embed a call-to-action button? For example, it looks like this:

{% cta https://dev.to/community-moderation %} Learn about Community Moderation on DEV {% endcta %}

Want to know how it's done? I got you covered! 😎

## Creating an Embedded CTA Button 

Embedding a CTA button in your posts is super simple, just use the following Markdown syntax:

`{% cta link %} description {% endcta %}`

To be clear, the example embed I created at the top of this article looks like this:

`{% cta https://dev.to/community-moderation %} Learn about Community Moderation on DEV {% endcta %}`

This isn't our only available embed... we have plenty others described in our [Editor Guide](https://dev.to/p/editor_guide#liquidtags) that behave in interesting ways. For instance, here's an embed that points to my profile:

{% embed https://dev.to/michaeltharrington %}

The syntax for that one is as such:

`{% embed https://dev.to/michaeltharrington %}`

## What Might I Use This For? 🤔

Loads of things! Maybe you wanna point folks to your personal portfolio or blog. Perhaps you'd like for folks to sign up to your newsletter. Or, maybe you recently released a book and would like for others to check it out. Go for it! These are all valid uses for a CTA button.

Just make sure that your description is accurate for whatever it is linking to. Of course, please don't mislead folks or send them to a link that automatically takes action... that won't win you any friends and could result in us unpublishing your content or taking disciplinary action against your account.

## That's a Wrap

If you have any question about this feature or others, don't hesitate to hit me up in the comments. Now, feel free to embed away and hope ya enjoy your day! 🙌
如何对Rust集合类型进行迭代
Tags: rust
Published: 2023-05-25 14:09:43

Rust 的集合类型不能直接进行循环，需要变成迭代器（这里是通过 .iter() 方法），才能用于迭代循环。在目前来看，你会觉得这一点好像挺麻烦，不急，以后就知道这么做的好处所在。
[参考](https://zhuanlan.zhihu.com/p/136482763)
It's easier to understand technology concepts with playful comparisons.
Published: 2023-05-25 14:03:02


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

I managed to better understand the technology concepts when I started to abstract and make comparisons with subjects that I have clear in my mind and the solutions that I need to implement.

For example, to understand hexagonal architecture I did the following exercise:

Let's imagine that we are building a secret club, right in the style of comic book stories. The structure of Hexagonal Architecture could be seen like this:

Club Core (Domain/Business Logic): This is where the magic happens. This is the headquarters of our superhero league, where all major decisions and strategies are made.

Club Manager (Application): This is the guy who coordinates everything. He doesn't decide the strategies, but he makes things happen. He's kind of like Alfred to Batman - he's not there to fight the villains, but without him, Batman would be lost.

Club Headquarters (Infrastructure): This is the Batcave, the Stark Industries building, the place that keeps everything running. Here you find the tools, the computers, the vehicles... everything our heroes need to get the job done.

Now, the coolest thing about this Hexagonal Architecture are the "ports" and "adapters". Let's call them "secret doors" and passports.

The Secret Doors (Ports) are like the secret entrances and exits we have in the club. They are invisible to the outside world and can only be accessed using the correct passports.

The Passports (Adapters) are like special keys that allow our superheroes (and only them!) to use the secret doors. They are the guarantee that our superhero league will not be discovered by the outside world.

So, this is how Hexagonal Architecture works - a secret superhero club that keeps evil away! (I know it's silly but didactic).

I hope this explanation has made Hexagonal Architecture a little cooler for you!
Window Functions In Mariadb (part 1)
Published: 2023-05-25 08:49:01

One of the most important features which make dealing with complex computations easy are window functions. The article goes in depth about the window functions in Mariadb (concept, syntax and use cases).

A window function in MariaDB allows users to perform calculations on a specific set of rows known as a "window." Unlike traditional aggregate functions that collapse rows into a single result, window functions maintain the individual row structure while performing calculations across a defined window frame.

## SYNTAX OF WINDOW FUNCTIONS

To use window functions in MariaDB, the OVER() clause is employed in conjunction with the desired function. The OVER() clause specifies the window frame and partitioning criteria. The syntax for window functions in MariaDB is as follows:

```
function_name() OVER (
    [PARTITION BY partition_expression]
    [ORDER BY order_expression [{ASC | DESC}]]
    [frame_clause]
)
```

## PARTITIONING AND ORDER BY IN WINDOW FUNCTIONS

Partitioning allows the data to be divided into distinct groups based on one or more columns. By using the PARTITION BY clause within the window function, users can perform calculations separately for each partition. Ordering, on the other hand, allows rows to be arranged in a specific sequence within each partition. This is accomplished using the ORDER BY clause in conjunction with the window function.

## FRAME CLAUSES 

Frame clauses define the window frame, i.e., the subset of rows used in the calculation. They specify the boundaries of the window in relation to the current row. MariaDB supports three types of frame clauses: ROWS, RANGE, and GROUPS. Each has its own significance and usage scenarios.

The article is continued in next part which discusses about currently available window functions, their use cases and performance. [link_part2](https://dev.to/umerfreak/window-functions-in-mariadb-part-2-1h6i)
Opinion required for bachelor thesis about microservices.
Published: 2023-05-25 13:53:43

Hello,
I hope this message finds you well. I am currently in the process of writing my bachelor's thesis, which focuses on microservices.  If you or someone  you know has experience with microservices, I would greatly appreciate it if you could spare some time to share your expertise.

To gather insights for my research, I have prepared a brief and straightforward survey. It will only take a few minutes of your time, and you are not required to answer all the questions. Your valuable feedback will play a crucial role in enhancing the quality of my thesis. 

If you are interested in contributing, please access the survey through the following link: [https://forms.gle/CLqcC3t6msN8yNMV9](https://forms.gle/CLqcC3t6msN8yNMV9) Should you have any questions or concerns, please do not hesitate to reach out to me at <a href="mailto:freya.de.muynck@student.howest.be">freya.de.muynck@student.howest.be</a>

 I am truly grateful for your support and your willingness to share your knowledge.
Thank you for your valuable time and contribution. I am eagerly looking forward to your insights.

Warm regards,
Freya De Muynck
RemoteHive.io Launches: The Perfect Platform for Companies to Post Remote Job Openings
Published: 2023-05-25 13:48:28

Hello there! We’re excited to announce the launch of RemoteHive, a brand new remote job board. Our mission is to connect talented developers with top-notch companies that offer remote work opportunities. We’re currently working to secure new job opportunities for our users, and we’re reaching out to companies to post their remote job openings on our platform for free.

At RemoteHive, we understand the benefits of remote work for both companies and employees. Remote work allows companies to tap into a global talent pool, while employees can work from anywhere in the world and enjoy a better work-life balance. However, finding reliable and qualified remote talent can be a challenge for companies. That’s where we come in — we help companies expand their remote workforce by providing an easy-to-use platform to connect with talented developers.

If you’re a company looking to expand your remote workforce, RemoteHive is the perfect place to post your job openings. We offer a free platform to post your remote job openings and connect with qualified developers who are passionate about their work and eager to join your team.

By posting your remote job openings on RemoteHive, you’ll have access to a pool of talented developers who are actively looking for remote work opportunities. Our platform is designed to make the job posting process as easy and streamlined as possible, so you can focus on finding the perfect candidate for your team.

We believe that remote work is the future of work, and we’re committed to helping companies and employees alike enjoy the benefits of this new way of working. So, if you’re a company looking to expand your remote workforce, look no further than RemoteHive. We’re excited to help you find the perfect candidate and grow your business.

Thank you for considering RemoteHive for your remote job posting needs. We’re excited to partner with you and help you find the best talent for your team.
CRUD: Create, Read, Update and Delete
Published: 2023-05-01 12:21:35

CRUD, or Create, Read, Update, and Delete, is an acronym. It alludes to the four fundamental procedures that are frequently carried out on the information in a database or web application.

A software programme known as a CRUD application enables users to carry out these four fundamental actions on data that is stored in a database or other type of data storage system.

1. Create: This procedure entails updating the database with fresh information. For instance, a user might create a new contact in a contact management system by entering their name, email address, and phone number into a form and sending it to the system.
2. Read: Retrieving current data from the database is what this action entails. An individual might read a post or look at a user's profile on a social media platform, for instance.
3. Update: This process entails changing the database's current data. A user might alter their order or amend their shipping address, for instance, in an e-commerce system.
4. Delete: Data is deleted during this process from the database. An administrator in a content management system, for instance, could revoke a user account or delete a blog post.

CRUD apps are frequently used in web development because they offer a straightforward and standardised method of working with data. Creating CRUD apps is supported natively by a number of web frameworks and libraries, including Ruby on Rails and Django.e
RemoteHive.io Launches: Connecting Talented Developers with Top-Notch Companies
Published: 2023-05-25 13:47:15

Hello, everyone! We’re thrilled to announce the launch of [RemoteHive.io](https://remotehive.io), a brand new remote job board. Our mission is to connect talented developers with top-notch companies that offer remote work opportunities. While we don’t have any job postings just yet, we’re actively working to secure new job opportunities for our users.

As the world continues to evolve, remote work is becoming more and more commonplace. However, finding reliable remote job openings can be a challenge. That’s where RemoteHive comes in. We’ve created a platform where talented developers can easily find remote job opportunities and connect with some of the best companies in the industry.

Our team at RemoteHive is dedicated to making the job search process as easy and streamlined as possible. We understand that looking for a job can be a stressful experience, but our goal is to make it as painless as possible. By using our platform, you can save time and energy by focussing only on the remote job openings that match your skills and interests.

At RemoteHive, we’re committed to connecting developers with the best remote job opportunities out there. We believe that everyone deserves a chance to work with top-notch companies, regardless of their location. Whether you’re a seasoned developer or just starting out in your career, RemoteHive has something for everyone.

So, if you’re on the hunt for a remote job opportunity, look no further than RemoteHive. We’re excited to help you on your journey towards a fulfilling and rewarding career. Stay tuned for updates about new job opportunities and exciting developments on our platform.

Thank you for choosing RemoteHive to help you on your job search journey. We can’t wait to see what the future holds for our community of talented developers and top-notch companies.
👀Aim+LlamaIndex: Track intermediate prompts, responses, and context chunks through Aim’s sophisticated UI.
Tags: llm, ai, opensource
Published: 2023-05-25 13:46:18

![demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5pgca1h97hf9aqzfwiyn.gif)

In this demo, you can see the capabilities of Aim for logging events while running queries within LlamaIndex. We use the AimCallback to store the outputs and showing how to explore them using Aim Text Explorer.

[aimstack.io](https://aimstack.io/) is an awesome tool for tracking metadata for your LLM app (e.g. experiments 🧪, prompts 📝, and more).

It’s the perfect tool for tracing within LlamaIndex, which manages multiple LLM calls on top of your data.

Now you can easily track intermediate prompts, responses, and context chunks through Aim’s sophisticated UI.

Full guide here: https://gpt-index.readthedocs.io/en/latest/examples/callbacks/AimCallback.html

Aim repo: https://github.com/aimhubio/aim
Llama_index repo: https://github.com/jerryjliu/llama_index
How To Render a React Component Only Once
Published: 2023-05-25 12:38:05

🐙 [GitHub](https://github.com/RodionChachura/reactkit)  |  🎮 [Demo](https://reactkit.radzion.com/show-once)

There are situations when we want to display information to the user just once. Usually, it would be for marketing or educational purposes. For example, [Increaser](https://increaser.org) shows a link to a YouTube video explaining the concepts behind the feature. We wouldn't want to keep this link constant since we prefer an uncluttered interface. For such purposes, we can use the `ShowOnce` component.

![](./example.png)

It takes two properties - children to display and a storage key. To know if the component has been rendered before we rely on the persistent storage that serves as a wrapper around local storage, you can learn more about the implementation [here](/blog/local-storage). On the ShowOnce component unmount we'll write in the storage the timestamp, and, therefore, on the next mount `wasShownAt` will be defined, and we won't render anything.

```tsx
import { ComponentWithChildrenProps } from "lib/shared/props"
import { useEffect } from "react"
import {
  PersistentStorageKey,
  usePersistentStorageValue,
} from "state/persistentStorage"

interface ShowOnceProps extends ComponentWithChildrenProps {
  storageKey: PersistentStorageKey
}

export const ShowOnce = ({ children, storageKey }: ShowOnceProps) => {
  const [wasShownAt, setShowTime] = usePersistentStorageValue<
    number | undefined
  >(storageKey, undefined)

  useEffect(() => {
    return () => {
      setShowTime(Date.now())
    }
  }, [setShowTime])

  return wasShownAt ? null : <>{children}</>
}
```
Top SQL Queries for Data Analysis
Published: 2023-05-25 11:55:59

Improving your data analysis skills is possible by mastering advanced SQL techniques, which can assist in deeper exploration of datasets leading to valuable insights. This article highlights seven advanced SQL queries that can be helpful for data analysis. Each query will be presented along with its results, syntax details and an explanation of how the database computes it.

## Top SQL Queries for Data Analysis


**1. Grouping Data by Time Period**
For the 1st Example, let us scrutinize information found in the sales table. The said data set contains a unique identifier for every product, the date when the deal has transpired, and the overall value of the transaction.

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

A very common in analysis scenario required data like specific date periods, such as month or year.

`SELECT EXTRACT(YEAR FROM date) AS year, EXTRACT(MONTH FROM date) AS month, SUM(amount) AS total_sales_amount FROM sales GROUP BY year, month ORDER BY year, month;`

**Output:**

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

Using the EXTRACT() function, we retrieve the year and month from the date field in this query. The data is then grouped based on the new year and month fields, and the total sales for each group are calculated by employing the SUM() function.

**2. Ranking Data**
Ranking information is frequently needed for complex data analysis purposes. For instance, you may want to rank your merchandise based on their sales figures to identify which items generate the majority of the earnings, or you may need to rank your outlets based on their subpar sales figures to pinpoint which locations are performing poorly.
Utilizing functions such as RANK() or DENSE_RANK() as window functions can allocate rankings to rows based on the value of a particular column. To begin, we shall examine the RANK() function:
`SELECT product_id, SUM(amount) AS total_sales_amount, RANK() OVER(ORDER BY SUM(amount) DESC) AS rank FROM sales GROUP BY id;`
**Output:**

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

Read More on [https://www.blog.tutorialwithexample.com/top-sql-queries-for-data-analysis](https://www.blog.tutorialwithexample.com/top-sql-queries-for-data-analysis)