teleren/devto huggingface dataset:
TIL: Audio Buffers, Remix, CSS
Tags: todayilearned
Published: 2023-01-17 14:33:28

- I've been working on a little tool for work involving recording audio in the browser and sending it to a 
server for processing with Deepgram. It took me a long time to figure out the difference between a blob, file,
buffer, and arrayBuffer. TL;DR:
  - A `File` is a type of `Blob` in JavaScript.
  - You can go from a `Blob` to and `ArrayBuffer` by calling `blob.arrayBuffer()`.
  - To create a `Buffer`, call `Buffer.from(arrayBuffer, encoding)`. For `wav` files, the encoding should be `base64`.
  - Deepgram expects a `Buffer` along with a mimetype (in this case `audio/wav`).

  I plan on making a more detailed post about this soon.
- Since this tool was just for testing, I wanted a simple CSS solution so that I didn't have to focus on styling.
I went with [MVP.css](https://andybrewer.github.io/mvp/) and [Tailwind](https://tailwindcss.com/) for small tweaks.
It worked really well, but in the future, I'd like to take a look at [Pico.css](https://picocss.com/docs/), which I
just learned about from [this Fireship video](https://youtu.be/lHZwlzOUOZ4).
- I used [Remix](https://remix.run/) to build this application, and there were a few gotchas that I had to navigate around.
To be honest, I don't even know if my approach is correct.
  - I've heard many people talk about how TypeScript saves them time, but right now, it only slows me down. I plan to
  keep at it and hopefully get over that hump.
  - I kind of forgot that Remix is a SSG app. This means, there is code that is run on the server and on the client in the same file.
  Code that can only run on the server needs to be handled one way, and code that can only run on the client (relying on web APIs),
  needs the same attention. I rn into the problem in both directions. There are many React libraries that won't work with Remix out of the box.
  Server side code is an easier fix by moving all imports to a `*.server.ts` file.
  - Remix has a one way data flow model that spans accross the server and the client. I'm not sure how this cycle is supposed to interact with local state.
  I needed to maintain some local state to determine the visibility of a component. When receiving a response back from the server,
  I wanted to change that local state value, but I'm not sure how to do that. I ended up using `useTransition` to observe that response from the server,
  but it doesn't quite feel right.
  
  It's been a long time since I've done development in React. I think I did okay, but my code could definitely use some refactoring...
iOS Debugging Tips
Published: 2023-01-17 14:25:37

Collection of some iOS Debugging tips.

### 1. Changing variable values

Add a breakpoint where you want to change the variable value. Then use the following command (lldb) to update the variable's value.
In this example, I am updating the value of `address` variable.

```
expression address = "New address"
```

You can use `expr` or `ex` (short forms) instead of `expression`.

### 2. Printing variable value

When the execution stops at a breakpoint, you can use one of the following to print the value of a variable to the console:

1. `p` (a.k.a `expr --`) - This prints the value of the given variable.
Usage - `p address` 

1. `po` (a.k.a `expr -O --`) - This also works as `p`, but if the passed variable is an object, it prints the output of the `description` for that object.
Usage - `po address`

### 3. Printing values of non-computed variables

Use `v` instead of `p` or `po` to print the value of non-computed variables (e.g. IndexPath).

### 4. Skipping lines of code to execute (Moving the instruction pointer)

While debugging, you can move the instruction pointer to the desired location to start execution from that line.

Or, you can use this lldb command to jump by n number of lines:

```
thread jump --by 1
```

### 5. Printing view tree (recursive descriptor)

Using this lldb command to print the view hierarchy for a particular view:

```
expression -l objc -O -- [view recursiveDescription]
```

### 6. Adding aliases

To create an alias for an lldb command that you use often, you can create an alias like this:

`command alias poc expression -l objc -O --`

Now, instead of typing `expression -l objc -O -- [view recursiveDescription]`, you can simply use `poc [view recursiveDescription]`.

### 7. Printing object description using a memory address

Use this lldb command to print the description of a memory address.

```
expression -l objc -O -- 0x7fc2b240e3a0
```

Or using the alias we created earlier:

```
poc 0x7fc2b240e3a0
```

### 8. Returning early from a function

Use the following lldb command to return early:

```
thread return
```

### 9. Changing UIView properties on the fly

To change the property of a UIView, use this:

```
po unsafeBitCast(0x7fc2b240e3a0, to: UILabel.self).text = "New text"
```

Followed by:

```
expression CATransaction.flush()
```

### 10. Adding a fancy description for your own classes

To print a different output to the console when an instance of your classes is printed, you can use `CustomDebugStringConvertable`.

Usage:

```swift
extension YourClass: CustomDebugStringConvertable {
  var debugDescription: String {
    "Your custom description"
  }
}
```
Moonly weekly progress update #32
Tags: nft, blockchain, crypto, saas
Published: 2023-01-17 14:23:21


![](https://cdn-images-1.medium.com/max/3200/1*8CpUONniq18OyUgEEUwcyg.png)

As you all know we are currently in the testing phase. Buckle up and be patient just a little longer, because soon enough you will have the chance to test it yourself!

**Weekly devs progress:**

* Added loading parameters to next/dynamic imports

* Fixed hovering issue on NFT cards

* Modified cron job to check rules

* Modified DB schema for holder verification on Bot DB

* Handled newly added verification rule

* Fixed NFT page viewpoint bug and implemented new functionality and logic

* Finished upcoming page changes (descriptions)

* Improved wallet checker

* Started working on metadata scraping during token creation

* Excluded markdown in NFT description and fixed the fonts

* Fixed ‘Internal server issue’ on holder-verification

* Made DB schema changes and implemented holder notification feature

**Staking (Locking):**

* Solved asset image not loading issue

* Fetch the data of the token from the collection and show it on the NFT card

* Fixed Staking related issue

* Improved data fetching on the staking page

* Created “Claim Reward” function and UI

* Show claimable reward in NFT-Card

* Rewrite staking-apps state management with recoil

* Improved “Error Showing” to the user

* Added Extra Claim Reward Button (Now the user will be able to claim the reward while staking and also when withdrawing (automatically))

* Added functionality for handling server-side error

* Testing Staking and Token Creation

* Implemented “Collecting Metadata” for the new token and tested

**Portfolio Tracker:**

* Improved performance of TX logs upload

* Made backup of transaction table from BigDB

* Updated structure, compressed the whole table

* Made a new type of backup for the BigDB

* Stashed backups on the main disk

* Fixed issues with PT stats

* Database structure cleanup on PT

* Running utility to link transactions

Check out our latest blog post: 7 Ways to Make Money in Crypto and Web 3.0

[https://moon.ly/blog/ways-to-make-money-in-crypto-and-web-3-0/](https://moon.ly/blog/ways-to-make-money-in-crypto-and-web-3-0/)

Upcoming NFT projects to mint:

[https://moon.ly/nft/custodios](https://moon.ly/nft/custodios)

[https://moon.ly/nft/moonapes-planet](https://moon.ly/nft/moonapes-planet)

[https://moon.ly/nft/pool-party](https://moon.ly/nft/pool-party)

[https://moon.ly/nft/bullyz-crew](https://moon.ly/nft/bullyz-crew)

[https://moon.ly/nft/awkward-cats](https://moon.ly/nft/awkward-cats)

Minted projects worth mentioning:

[https://moon.ly/nft/aurory](https://moon.ly/nft/aurory)

[https://moon.ly/nft/cats-on-crack](https://moon.ly/nft/cats-on-crack)

[https://moon.ly/nft/bvdcat](https://moon.ly/nft/bvdcat)

[https://moon.ly/nft/lotus-gang-nft](https://moon.ly/nft/lotus-gang-nft)
CSS tutorial series: CSS Units and Sizing
Tags: beginners, webdev, tutorial, css
Published: 2023-01-17 14:08:54

Today's post will discuss length units, which you may have encountered in the previous post `padding: 10px` while working on the challenge.

CSS uses absolute and relative units, which are the two sorts of units that are normally used for length and size.

## What are Absolute units?
In general, absolute units are thought to be the same size at all times. There might be some exceptions, Depending on the size and quality of your screen or browser settings. 

The most commonly used absolute length unit in CSS is pixels `px`. 

| Unit | Description|
| --------- |:---------:| 
|px 	|pixels (1px = 1/96th of 1in)|
|pt	|points (1pt = 1/72 of 1in)|
|pc	|picas (1pc = 12 pt)|
|cm	|centimeters|
|mm	|millimeters|
|in 	|inches (1in = 96px = 2.54cm)|
|Q      |Quarter millimeters (1Q = 1/40th of 1cm)|

## What are relative units?
Relative length units are defined in relation to another length property, such as parent element's font size. Relative length units scale more effectively on the page

| Unit | Description|
| --------- |:---------:| 
|% 	|with reference (relative) to the parent element|
|rem	|relative to the `font-size` of the root element which is by default 16px, 1rem= 16px|
|em	|inherits the `font-size` from its parent element meaning 1em = `font-size of parent element |
|vw	|view width is relative to the viewport's width|
|vh	|view height is relative to the viewport's height|
|ex 	|relative to x-height (distance between baseline and mean line of a lowercase letter) or 1/2 of 1em|
|vmin     |vmin is 1% of the viewport's smallest dimension|
|vmax     | vmax is 1% of the viewport's largest dimension|

## Let's use examples to further clarify the  `ex`, `vh`, `vw`, `vmin` and `vmax` relative units.
### vmin & vmax
If the viewport is 900 pixels wide and 700 pixels high, the 1vmin will be 7 pixels and the vmax will be 9 pixels.

- 1vmin = 700 -99% 
 1vmin = 7 pixels 

- 1vmax = 900 -99%
 1vmax = 9 pixels 

### ex Unit
![ex unit explained](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/laafyt1k4302rw7wdhif.png)
_source_ : [Stackoverflow] (https://stackoverflow.com/questions/918612/what-is-the-value-of-the-css-ex-unit)

As mentioned in the table `ex` is the distance between baseline and mean line of a lowercase letter

### vh & vw
A web page's viewport is the portion that the user can see. On a mobile phone as compared to a computer screen, the viewport is smaller because it varies depending on the device.

Relative units are the most frequently used when creating a single webpage or in significant real-world projects. Using relative units for your layout maintain its stability making it less likely to break.
Paracetamol.js💊| #198: Explica este código JavaScript
Tags: javascript, programming, webdev, spanish
Published: 2023-01-17 14:00:00

## **<center>Explica este código JavaScript</center>**
#### <center>**Dificultad:** <mark>Básico</mark></center>

```js
const fn = arr => {
  return arr.reduce((acc, item) => {
    return acc + (item.voto ? 1 : 0)
  },0)
}

console.log(fn([
  {voto:true},
  {voto:true},
  {voto:true},
  {voto:false},
  {voto:false},
  {voto:true},
  {voto:false},
]))
```

A. `4`
B. `3`
C. `7`
D. `0`

Respuesta en el primer comentario.

---

Respuesta:
A. `4`

Hagamos nuevamente una tabla:

| `iteración` | `acc` | `item` |
|-------------|-------|--------|
| 1ra         | `0`   | `1`    |
| 2da         | `1`   | `1`    |
| 3ra         | `2`   | `1`    |
| 4ta         | `3`   | `0`    |
| 5ta         | `3`   | `0`    |
| 6ta         | `3`   | `1`    |
| 7ma         | `4`   | `0`    |
| 8va         | `4`   | `-`    |

Por cada iteración del `reduce` evaluamos si `item.voto` es `true` (1) o es `false` (0).
Así vamos sumando en cada vuelta del bucle hasta terminar con el arreglo.
⚛️ React Hooks - useState
Tags: webdev, react, javascript, beginners
Published: 2023-01-17 13:49:53

In this post, we will know and understand more about the most used Hook and the first to be created by the React team, the useState.

This is probably the Hook you'll use the most. As the name implies, it gives us the "power" to use states in functional components.

useState receives a parameter that is the initial value of the state and returns an array with two positions, the first of which is the state value and the second is a function that will be responsible for changing (change) the value of this state.

<img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IdP1EA-9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3txguvyqqn6bu4hycmv7.png" />

A feature of useState is that we can, in the function that updates the state, send a function as an argument and in this function capture the current state value in the same way as in setState in classes.

This becomes very useful when we need to update a state based on its previous value, as for example in a toggle function where each click changes the state between true and false:

<img src="https://res.cloudinary.com/practicaldev/image/fetch/s--nDxPsoV3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ta55xojjl166v3zqb7gk.png" />

<img src="https://res.cloudinary.com/practicaldev/image/fetch/s--o9usjoXv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vwhim515rm5anewlf6f1.gif" />
React Diffing Algorithm
Published: 2023-01-17 13:48:16

React uses virtual DOM, the only difference is the ability to write the screen like the real DOM, in fact, a new virtual DOM is created after every re-render. 
DOM stores the components of a website in a tree structure.

How DOM updates in React.
-On first run both virtual DOM and Real Dom tree are created
-React updates the nodes in the virtual DOM.
-Then it compares virtual DOM with the real DOM and updates the changes. This process is called reconciliation.
React uses algorithm called Diffing algorithm for reconciliation based on these points.
-Element of different type will produce different trees.
-We set which elements are static and do not need to be checked .
React checks the root element for changes and the updates depend on the types of root elements.
- For root element of different type react will scrap the old one and build a new one.
- For the element is the same, React then checks for attributes of both version and then updates the node for which the changes are there.
That's why we should should unique keys for elements so that it will be easy for React to determine changes in the elements.
Validating Json Request in axum
Published: 2023-01-20 19:28:43

---
title: Validating Json Request in axum
published: true
date: 2023-01-17 13:31:12 UTC
tags: 
canonical_url: 
---

I have been playing around with [axum](https://docs.rs/axum/latest/axum/index.html), and it has been quite a fun web framework. While using it, I came across what is a relatively common use case of validating the request JSON. However, I could not find any [extractor](https://docs.rs/axum/latest/axum/index.html#extractors) for this. Thus I decided to write my own and share it with everyone. While I haven't put it in a crate, feel free to use the code as you wish.

## Axum Extractors

An extractor allows us to pick apart the incoming request to get the parts our HTTP handler needs. More about extractors can be found [here](https://docs.rs/axum/latest/axum/extract/index.html). There are two important traits when talking about extractors:

1. [FromRequestParts](https://docs.rs/axum/latest/axum/extract/trait.FromRequestParts.html): This is used if the extractor does not need access to the request body.
2. [FromRequest](https://docs.rs/axum/latest/axum/extract/trait.FromRequest.html): This is used if the extractor does need access to the request body. (we will be using this)

## Implementation

I will use [validator](https://crates.io/crates/validator) crate for the actual validation.

Here is the code for our validated JSON extractor:

```rust
use axum::{async_trait, extract::FromRequest, Json, RequestExt};
use hyper::{Request, StatusCode};
use validator::Validate;

pub struct ValidatedJson<J>(pub J);

#[async_trait]
impl<S, B, J> FromRequest<S, B> for ValidatedJson<J>
where
    B: Send + 'static,
    S: Send + Sync,
    J: Validate + 'static,
    Json<J>: FromRequest<(), B>,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request(req: Request<B>, _state: &S) -> Result<Self, Self::Rejection> {
        let Json(data) = req
            .extract::<Json<J>, _>()
            .await
            .map_err(|_| (StatusCode::BAD_REQUEST, "Invalid JSON body"))?;
        data.validate()
            .map_err(|_| (StatusCode::BAD_REQUEST, "Invalid JSON body"))?;
        Ok(Self(data))
    }
}
```

I am using `(StatusCode, &'static str)` for error response since all the responses in my server are of this type. Feel free to use whatever you prefer.

It is important to note that extractors can use other extractors themselves. So we do not need to replicate the [Json](https://docs.rs/axum/latest/axum/struct.Json.html) extractor.

## Conclusion

As you can see, writing a custom extractor is relatively straightforward, especially when compared to writing a [tower](https://crates.io/crates/tower) middleware.
Find shortcuts references
Tags: vscode, devrel, beginners, programming
Published: 2023-01-17 13:48:09

As you code or design using your favorite software, there may be times when you want to improve your workflow through the use of shortcuts. **[QuickRef.ME](https://quickref.me/).** can help with that.


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

**QuickRef.ME provides you with most of the reference materials you need to learn about shortcuts and coding references, making your workflow even more efficient. Don't waste your time searching for references for your favorite tool. Try QuickRef.ME today. !!**
An introduction to Kubernetes, the open-source container orchestration system developed by Google
Published: 2023-01-17 13:24:48

Kubernetes is an open-source container orchestration system that was developed by Google. It can be used to manage containerized applications across a cluster of machines. It automates the deployment, scaling, and management of containerized applications.

To use Kubernetes on Google Cloud, you can use Google Kubernetes Engine (GKE) which allows you to easily create and manage a Kubernetes cluster on Google Cloud.

An example of how to use Kubernetes to manage a Java application on Google Cloud would be to first package your Java application in a Docker container.
You can use a Dockerfile to create the container image, for example:

```
FROM openjdk:8
COPY . /app
WORKDIR /app
RUN javac Main.java
CMD ["java", "Main"]
```

You can then create a Kubernetes Deployment to manage the containerized application, for example:

```
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-java-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-java-app
  template:
    metadata:
      labels:
        app: my-java-app
    spec:
      containers:
      - name: my-java-app
        image: gcr.io/my-project/my-java-app:v1
        ports:
        - containerPort: 8080

```

and a Service to define how the application can be accessed, for example:

```
apiVersion: v1
kind: Service
metadata:
  name: my-java-app
spec:
  selector:
    app: my-java-app
  ports:
  - name: http
    port: 80
    targetPort: 8080
  type: LoadBalancer

```

You can also use Kubernetes ConfigMap and Secrets to manage application configuration and secrets separately from your application code, as well as use Kubernetes resource like pod, service and replica set to control how your application is deployed and scaled.

You can use command-line tools such as 'kubectl' to interact with your Kubernetes cluster and deploy your application.


`kubectl apply -f deployment.yml
kubectl apply -f service.yml`

Please note that the above code examples are just a simple demonstration of how to use Kubernetes on GCP with a Java application, and a complete implementation will likely require additional configuration and resources.
Create and Assume Roles in AWS
Published: 2023-01-17 13:19:31

In this blog the objective in the AWS environment, utilizing policies and roles in the IAM console to restrict access to AWS resources and conclude by assuming a role and ensuring our policies are correct and that we have completed all objectives.


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


**Create the Correct S3 Restricted Policies and Roles**

1. Create the S3RestrictedPolicy IAM policy. Ensure only the appconfig buckets are accessible.
   - Select the S3 service and all S3 actions
   - Select all resources except bucket
   - Add the appconfig bucket names to the policy
2. Create the S3RestrictedRole IAM role.
   - Set the trusted entity to another AWS account
   - Add your account ID
   - For permissions, select the S3RestrictedPolicy
3. Revoke the AmazonS3FullAccess access policy from the developergroup.   	
4. Attach the S3RestrictedPolicy to the dev1 user.

**Configure IAM So the dev3 User Can Assume the Role**

1. Create the AssumeS3Policy IAM policy.
   - Select the STS service
   - Select AssumeRole under the write options
   - Add the S3RestrictedRole
2. Attach the AssumeS3Policy to the dev3 user.
3. Assume the S3RestrictedRole as the dev3 user.
   - Log in as the dev3 user
   - Switch roles to the S3RestrictedRole
   - Verify access in S3
Data Lake and Data Management
Tags: dataanalysis, datalake, dataarchitecture, storybytes
Published: 2023-01-17 13:17:13


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s4u8kvs5yqbhhcxigj6e.png)Data is everywhere and comes in many forms. Today, terabytes and petabytes of data are being generated every second, and finding storage solutions for these massive data volumes is of utmost importance. Complex machines and technologies now collect an incredible breadth of data; this is where the Data Lake and Data Warehouse come in. What are they? Let’s look at them in a none technical way. Date lake can be seen as an open mind, open to many things, many sources, unstructured and more compatible. A data warehouse can be seen as a closed mind; not available to many things, does not allow many sources, and is structured and less compatible. Data warehouses and Business Intelligence tools support reporting and analytics on historical data. In contrast, data lakes support newer use cases that leverage data for machine learning, predictions, and real-time analysis. Data Lake has emerged as a robust platform business can use to manage, mine, and monetise vast unstructured data stores for competitive advantage. As a result, the rate of adoption of Data Lake platforms by companies has increased dramatically. Data warehouses work well for specific workloads and use cases, and data lakes represent another option that serves other workloads. We are at a point now where we will be able to use data not only to review the past but understand the present and even to predict the future. The data and tools will continuously evolve to help us get there in almost real time. In reality, if you can have multiple uses of the same data. And so, you never know what you may use that data for. So, if you start with just getting the data in first and then figuring out what you want to do with it, it generally leads to a more positive outcome with that data.