teleren/devto huggingface dataset:
Let's build an app for Flipper Zero
Tags: flipperzero, c, app, tutorial
Published: 2023-05-06 22:06:26

---
title: Let's build an app for Flipper Zero
published: true
description: Off the back of my experience writing apps for this cute little multi-tool device, I've put together a tutorial for first-timers...
tags: FlipperZero,C,App,Tutorial
# cover_image: https://github.com/instantiator/flipper-zero-experimental-apps/raw/main/resistors/screenshots/v1.1/banner.jpg
# published_at: 2023-05-06 21:56 +0000
---

The Flipper Zero is a digital signals multi-tool device, with some fun applications. It has an infrared module, a sub-GHz radio, RFID and NFC capability, iButton, USB, a screen, input controls, and GPIO pins. It's small enough to fit in your hand, and it can communicate with your home appliances, or help you to learn about the signals that fly around our world. It's also extremely customisable.

I recently published my first app for the Flipper on [flipc.org](https://flipc.org) - it helps you to calculate the value of a resistor based on the coloured bands printed on it:

* [**Resistance Calculator**](https://flipc.org/instantiator/flipper-zero-experimental-apps?branch=main&root=resistors)

![A Flipper Zero device running the Resistance Calculator app - showing a pixel-art resistor, it has calculated the resistance and tolerance based on the user's choice of coloured bands](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6a88duxi46z818c1z5qy.jpg)

Off the back of that experience, I've written a short tutorial for first-time app developers. I'll definitely add more to it, but for now there are two parts:

* [**Building an app for Flipper Zero, part 1: Getting started**](https://instantiator.dev/post/flipper-zero-app-tutorial-01/)
* [**Building an app for Flipper Zero, part 2: A simple user interface**](https://instantiator.dev/post/flipper-zero-app-tutorial-02/)

The first part is mainly about setting up your environment, but I also go into a bit of detail about working in C. I come from a higher level / managed code background (largely Java and C#), and I had to re-learn a lot about writing C to make progress.

There are plenty of amazing resources out there for devs now, and I hope by sharing back what I've learned I can help others. It's great to see so many folks in the community doing the same, and my content is inspired by and dependent on the work of:

* [Derek Jamison](https://github.com/jamisonderek)'s [plugin tutorials](https://github.com/jamisonderek/flipper-zero-tutorials) and [YouTube channel](https://www.youtube.com/@MrDerekJamison)
* [DroomOne](https://github.com/DroomOne)'s [plugin tutorial](https://github.com/DroomOne/Flipper-Plugin-Tutorial)
* [Chris Hranj](https://brodan.biz/) (Brodan)'s [guide to the components](https://brodan.biz/blog/a-visual-guide-to-flipper-zero-gui-components/)
* [Kuronon](https://github.com/Kuronons)'s brilliant pixel-art

I've had some great conversations with folks on the [Flipper Devices](https://discord.gg/flipper) Discord, too - and I've found it to be a supportive community.
Provisioning an Azure VM using AZURE CLI
Tags: azure, cli, cloudcomputing
Published: 2023-05-06 22:01:32


NB. Cover picture credit to Varonis
![definition](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q4jq6hvid3q98kd71rex.png)
Alright, so being a software developer, i definately prefer cli to clicking through various interfaces.
So this is how i have decided to navigate through the Azure Portal.


1. First we shall download Azure cli on ubuntu using
`curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash`

2. Next we shall log into azure using 
 `az login` .

3. To verify that we have logged we shall type 
`az account show`.

4. First we shall create a resource group by specifying the name and location of the resource group using 
   
![create resource group](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dt92mejxefh4bddn4cdq.png)
This should show

![result of resource group creation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1vuv52nymj20g8bir4qv.png)

5.Next, we shall create a VM using

![create vm](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1mjt5dti8vkoolqg7kl.png)
 

- --name - specify the name of the vm
- --resource-group - to specify the name of the resource group
- -- image - to specify the operating system to install on the vm
- --admin-username - to specify the username to use to log into the the vm
- --generate-ssh-keys - to genrate ssh keys
![create vm result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zv8nd2i8crqwlih3o31k.png)

6.To log into the vm, we shall use ssh, our ip address and the admin username.
ie ssh testadmin@public_ip_address_of_vm
![loginto vm](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0r3w6ilkjgsah4n4kdsm.png).

7.Lastly to delete the resources, we shall delete the resource group we have created.

- First use Ctrl + D to jump out of the ubuntu vm.
- Then use 
![delete resource group](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w2jeor1o5ffyv35c386c.png)

voila.
AbortController manage memory efficiently to ensure optimal performance
Tags: react, web, javascript, dom
Published: 2023-05-06 22:00:10

---
title: AbortController manage memory efficiently to ensure optimal performance
published: true
description: The AbortController is a powerful utility that can help mitigate memory leaks in these scenarios.
tags: react, web, javascript, dom
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-05-06 21:57 +0000
---

In modern React applications, it's essential to manage memory efficiently to ensure optimal performance. One common issue developers face is memory leaks that can occur during asynchronous fetch operations. 

The AbortController is a powerful utility that can help mitigate memory leaks in these scenarios.

The AbortController allows developers to cancel ongoing fetch requests, which is particularly useful when dealing with components that might unmount before the fetch request has completed. By canceling fetch requests when a component is no longer needed, developers can prevent memory leaks and enhance overall application stability.

Here's a simple example of how to implement the AbortController in a React project:

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

const FetchDataComponent = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    const controller = new AbortController();
    const signal = controller.signal;

    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data', { signal });
        const data = await response.json();

        if (!signal.aborted) {
          setData(data);
        }
      } catch (error) {
        if (error.name !== 'AbortError') {
          console.error('Fetch error:', error);
        }
      }
    };

    fetchData();

    return () => {
      controller.abort();
    };
  }, []);

  return (
    <div>
      {data ? <pre>{JSON.stringify(data, null, 2)}</pre> : 'Loading...'}
    </div>
  );
};

```

In this example, we create an instance of AbortController and use its signal property to link it to the fetch request. If the component is unmounted before the fetch request is complete, the cleanup function in the useEffect hook will be invoked, aborting the ongoing request and preventing potential memory leaks.

By incorporating the AbortController into your React project, you can efficiently manage asynchronous fetch operations, mitigate memory leaks, and ensure a smoother user experience.




learn more: https://developer.mozilla.org/en-US/docs/Web/API/AbortController
SOLID principles (Python) in my simple understanding
Tags: beginners, python, systemdesign
Published: 2023-05-06 21:36:42

Nowadays, I have been learning SOLID principle in python.


**S: Single responsibility principle** -- A class/ module must have only one role.


**O: Open/Closed principle** -- open to extension but closed to modification. This can be achieved by using an interface (a base/ mixin class that can be used polymorphically). We don't modify the base class itself, instead, we create new interfaces to full fill the requirements. 


**L: Liskov substitution principle** -- different parts of a program can be used interchangeably, as long as they behave in the same way. e.g. Each car class has different properties, like its speed and handling, but they all behave in a similar way, because they all have to move around the track and avoid crashing.


**I: Interface segregation principle** -- interfaces should be small. Small enough to only do one thing but still contains methods needed. e.g: When you create a mixing class with context manager logic, it should contain at least two methods: `__enter__` and `__exit__`. They must go together, or the outcome will not be a valid context manager at all.


**D: Dependency inversion principle** --  high-level modules should not depend on low-level modules. Rather, both should depend on abstractions. Using general ideas instead of specific details to make it easier to modify and add new features to a program.


references:
- Clean Code in Python - Second Edition by Mariano Anaya
Como criar uma packege/lib npm ?
Tags: javascript, webdev, react, typescript
Published: 2023-05-06 21:26:05

## Como criar um Packege npm ?

Hoje veremos o comando NPM na criação de pacotes npm.

### Criando sua conta no npm

Primeiro precisamos ter uma conta no site [npm](https://www.npmjs.com/)

### Adicione sua conta ao npm na sua maquina

```
$ npm adduser [nome do usuario]
```

### Criando o projeto

```
$ npx tsdx create mylib
```

### Criando o componente

Nesse exemplo usaremos `styled-components` então instale antes de continuar o tutorial

```
$npm install styled-componentes && npm install @types/styled-componets
```

Agora sim, criamos o componente

```
import React from "react";
import { ReactNode } from "react";
import ThemeProvider from "../../provider/theme-provider";
import styled from "styled-components";

interface ButtonStyleProps {
  variant: string
}

export const ButtonStyle = styled.button<ButtonStyleProps>`
  ${({theme, variant})=>{
    return {
      color: theme[variant].text,
      backgroundColor: theme[variant].background,
      padding: '10px 20px',
      cursor: 'pointer',
      fontWeight: '500',
      margin: '10px 0',
      width: '100%',
    }
  }}
`

export interface ButtonProps {
  children: ReactNode
  variant?: 'dark' | 'light';
  onclick: (e:  React.MouseEvent<HTMLButtonElement>) => void;
  type?: 'submit' | 'button' | 'reset';
  name?: string;
}

export function Button({
  children,
  onclick,
  name='formulario',
  type = 'submit',
  variant = 'light'
}: ButtonProps){
  return (
    <ThemeProvider>
      <ButtonStyle
        name={name}
        type={type}
        onClick={onclick}
        variant={variant}>
        {children}
      </ButtonStyle>
    </ThemeProvider>
  )
}
```

## Versionando a lib

Existem 3 formas de versionamento, _patch_, _minor_, _major_, cada uma com um propósito diferente. Conforme explicado abaixo.

### O comando npm version patch

O comando serve para atualizar apenas uma Correção: quando corrigir falhas mantendo compatibilidade.
EX: 0.1.0
Apos o comando 0.1.1

```
$ npm version patch
```

### O comando npm version minor

O comando serve para atualizar versão Menor: quando adicionar funcionalidades mantendo compatibilidade, e
EX: 0.1.0
Apos o comando 0.2.0

```
$ npm version minor
```

### O comando npm version major

O comando serve para atualizar versão Maior: quando fizer mudanças incompatíveis na API,
EX: 0.1.0
Apos o comando 2.0.0

```
$ npm version major
```

### O comando npm publish

O comando serve para publicar o projeto

```
$ npm publish
```

### Criando um script

Podemos criar um script para rodar na linha de comando e agilizar as coisas.
Adicione na parte de script do packege.json a linha de código ` "deploy" : "npm version patch && npm publish"` em seguida rode o comando:

```
$ npm run deploy
```

Assim enviaremos nosso projeto para o npm

### Usando nossa lib

Para usar a lib basta instalar ela via npm ou yarn

```
$ npm install [nome da lib]
```
A Server - Client JS Serialization Approach
Published: 2023-05-06 20:49:18

Given that Next.js Server Actions and TRPC are gaining traction as approaches that utilize code-splitting, javascript serialization, and fetch calls I thought I'd document a way I approached this in my library HTMX Components, as I revisit the library and ponder whether this is the best way to achieve this.

HTMX Components is a Deno server for serving HTMX compliant front-end code, handling routing, code splitting and bundling. 

We're going to be looking at and breaking down one piece of code and focusing on just the serialization part.

```ts
const { component, partial, serve, bundleImport, routes } = new HTMXComponents('@reggi/delete-row')
export const EditOne = await bundleImport('./client_code/edit_one.ts')

const DumbRow = ({ data }: { data: any }) => (
  <tr>
    <td>{data.firstName} {data.lastName}</td>
    <td>{data.email}</td>
    <td>
      <EditRow.button.get onclick={EditOne.onClickEdit(THIS_ELEMENT, EVENT)} identifier={data.id}>Edit</EditRow.button.get>
    </td>
  </tr>
)
```

I'm doing some special stuff with `bundleImport`, think of it as a custom dynamic `import`. `./client_code/edit_one.ts` is the client code file we'd like to include with this code, meaning we want to 1) bundle the code with any imported dependencies and 2) convert the code from TS to JS. We also return `EditOne` fully typed as it is in that file, there are no changes to that typing. We then call the `.onCLickEdit` function in the `onclick` handler `EditOne.onClickEdit(THIS_ELEMENT, EVENT)`. Note this is server-side JSX it's not `onClick` because we're on the server, `onclick`, like within the DOM [takes a string](https://www.w3schools.com/jsref/event_onclick.asp). So what do we need the value of `EditOne.onClickEdit(THIS_ELEMENT, EVENT)` to return? A reference to itself! Literally just that string `edit_one.onClickEdit(this,event)`!

Anyway this is one way to do serialization that I thought was interesting and wanted to document. There's examples in the repo for more info!
How Philips Hue Bridge discovery actually works
Tags: iot, philipshue, nat
Published: 2023-05-06 19:01:57

Having been bitten by a change in the Hue discovery protocol a while ago that I've only just got round to figuring out and fixing, I figured it would be useful to stick this up somewhere where Google can find it. So, here we go...

When a Hue bridge boots up, it has a brief interaction with the Hue servers at `meethue.com` and sends it the bridge ID, its IP address and port. This is stored under the IP address that the Hue servers have for you - essentially `REMOTE_HOST` in CGI terms (or 'the answer `whatismyip.com` gives you').

When an app (such as the Hue app or the Alexa skill) wants to know where your hub is, it connects to `discovery.meethue.com`, which will look at your IP, and if there's a record (or more than one if you have multiple bridges, I guess) for it, returns it/them, like so:

```
[
  {
    "id":"001788fff536899d",
    "internalipaddress":"192.168.0.14",
    "port":443
  }
]

```

The app then knows it can go find the bridge on the given internal IP, and you're all happily sorted.

Spotted the issue yet?

Yup - the wired sockets and one of the Wifi networks on my home network are from the /27 my ISP gave me two decades ago. The Hue is (obviously) on a different IP to my phone, and because there was no NAT involved, the bridge's info was stored on `meethue.com` under its *actual* routed IP. 

Result, the answer from discovery.meethue.com is:
```
[]
```
Zip. Nada. Discovery failed. 

To quote `@tweethue`:

> That could be the issue. The bridge is designed to be used with a simple home router.

Well, duh.
Creating your own ExpressJS from scratch (Part 5) - Serving static files
Tags: node, javascript, webdev, programming
Published: 2023-05-06 18:57:25

Our Web Framework so far can create a REST API, but cannot serve files yet, we need to implement it to make the framework complete.

To serve files we are going to use the Streams concept to read the files and serve to the client.

If you want to know more about NodeJS Streams take a look at it [here](https://dev.to/wesleymreng7/processing-massive-amount-of-data-on-demand-without-crashing-nodejs-main-thread-2epl)

Let's go!

---

## Reading files and folders

`src/app.js`

```js
// (1)
const { readdir } = require('fs/promises')
const { statSync, createReadStream } = require('fs')
const path = require('path')
const { pipeline } = require('stream/promises')

// (2)
async function* getAllStaticFiles(folder) {

    const files = await readdir(folder)
    for (const file of files) {
        const absolutePath = path.join(folder, file)
        if (statSync(absolutePath).isDirectory()) {
            yield* getAllStaticFiles(absolutePath)
        }
        else {
            yield absolutePath
        }
    }
}

// (3)
const static = async (folderPath) => {
    let folderRelative = folderPath.replace('./', '')
    for await (const file of getAllStaticFiles(folderPath)) {
        const pathWithoutBase = file.replace(folderRelative, '')
        get(pathWithoutBase, async (req, res) => {
            const relativePath = path.join(__dirname, '..', file)
            const fileStream = createReadStream(relativePath)
            res.setHeader('Content-Type', file.split('.').filter(Boolean).slice(1).join('.'))
            return await pipeline(fileStream, res)
        })
    }
}

// (4)
return {
    run,
    get,
    post,
    patch,
    put,
    del,
    use,
    useAll,
    useRouter,
    static
}
```

**From the code sessions above**

1 - To read files and folders and deal with Streams we need to import `fs` and `stream` libraries.

2 - Here we are reading files and folders' paths recursively using a generator pattern to make the reader be ordered.

3 - For each file path found we are going create a new GET route, read the file path as a `Stream`, and pass the `Stream` to the `response` object. If you didn't know the `response` object is a `Writable Stream`.

4 - Exporting the `static` function.


## Testing

Now we can call the `static` function passing the folder path that contains the files we want to serve.

`index.js`

```js
app.static('./files')

const start = async () => {
    app.run(3000)
}

start()
```

To test I will create a folder structure with a file like that.

`files/folder1/file.json`

```json
{
  "test": "test"
}
```

If I run the app and try to access the path `localhost:3000/folder1/file.json`, I can see the content inside it.

You can see [here](https://github.com/wesleymreng7/web-framework-scratch)how the code is looking.

See you in the next tutorial to improve our Web Framework, we are going to create a body-parser middleware.

I hope you like it!
(Streaming)#UFC 288: Sterling vs Cejudo En Vivo Online transmisión gratuita el 05.06.2023
Published: 2023-05-06 18:54:45

hace 1 minutos — UFC 288 SterlingCejudo en vivo: ver la pelea en TV y streaming
Desde el Prudential Center SterlingCejudo en vivo pelean por el título Peso Gallo en el main event UFC 288 Aquí los datos relevantes

¿Qué canal transmite Sterling vs Cejudo en vivo ahora por UFC 288?
Consulta los horarios y canales TV para ver la pelea Sterling vs Cejudo en vivo por UFC 288 Todos los detalles en esta previa

UFC 288: Día hora cartelera cómo y dónde ver por TV y streaming el evento con las peleas Sterling vs Cejudo y 
El campeón de peso gallo Aljamain Sterling defiende su título en UFC 288 ante el excampeón Henry Cejudo que regresa al octágono
Day 2, #100DaysOfCode (2/100)
Tags: webdev, programming, career, 100daysofcode
Published: 2023-05-06 18:15:42

_My second day of #100DaysOfCode: flexbox losing control and tools that I use to organize my life_

I am still working on the basic part of my portfolio, like yersterday. At this stage, my main goal is to finish the basic structure, which does not need to be perfect since I can always improve it over time. However, I want to create something that I can be happy with. Today, I am primarily working with HTML and CSS. I have finished the main skeleton of my portfolio, which currently has only four main sections: about me, projects, curriculum, and contact.

I am considering adding another section, possibly to feature my blog. It would be amazing if I could consume my Medium posts on my blog, but I do not know if there is a public API available from Medium for users to do so. Does anyone have any knowledge about this? Your help would be greatly appreciated!

I’m working on very basic things at the moment, and my biggest problem has been my flex-container going beyond the limits I set on the page because, at some point, I accidentally typed a semicolon that messed up my entire layout. So, in today’s post, I’m going to talk a little bit about the tools I’m using to organize everything about my #100DaysOfCode.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2gyd4as3ti0q4e8i43tx.jpeg)

1. Notion 

Notion is probably my favorite tool ever. I love how I can use it for almost everything in my life, including work, studies, organization, habit tracking, and now my portfolio. I use it to keep track of references that could be useful for me, my to-do plans, and any ideas that come to mind. I don’t trust my memory, so I put everything in Notion.


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

2. Clockify

I cannot function without Clockify. It’s the most amazing time tracking tool I have ever used, and I use it for everything in my life, just like Notion. I even use it to keep track of my reading time. FOR REAL! For my #100DaysOfCode challenge, I created a project with the same name and added everything I am working on. Today and yesterday were all about the structure of my portfolio, so I will know exactly how much time I spent on that.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3bxkzw0p5x6b8enbo3fe.jpeg)

3. Notebook (paper)

Good old paper is impossible to live without. I mainly use it to organize my daily tasks, put down ideas, and check off completed tasks at the end of the day. It’s one of the most satisfying things to do. I also use Google Calendar, but mainly for organizing my week, everyday tasks, appointments, and other fixed or casual things.

That’s all for today! Bye-bye.