teleren/devto huggingface dataset:
useImmutableRefValue - 帮助你更好的使用Typescript开发React应用
Published: 2023-08-04 05:37:32

---
title: useImmutableRefValue - 帮助你更好的使用Typescript开发React应用
published: true
date: 2022-12-05 00:00:00 UTC
tags: 
canonical_url: https://manon.icu/blog/translate/react/useImmutableRefValue
---

> `useRef` 返回一个可变的 `ref` 对象，其 `.current` 属性被初始化为传入的参数（initialValue），返回的 `ref` 对象在组件的整个生命周期内保持不变。

例如：创建`VideoPlayer`组件

```tsx
import {useRef} from 'react'
import VideoPlayer from 'videoplayer'

function VideoPlayerComponent() {
  const playerRef = useRef(new VideoPlayer())
  //
}
```

对于上面的代码，在初始化组件时，调用`new VideoPlayer()`的结果将存储在`ref`中，在下一次渲染时，仍将调用`new VideoPlayer()`，但是`useef`不会再接收到其调用结果，这意味着`playerRef`可能为空。

同样的，`useState`也是存在这种情况，区别在于，`useState`可以接受初始化函数，比如

```tsx
import {useState} from 'react'
import VideoPlayer from 'videoplayer'
function VideoPlayerComponent() {
  const [player] = useState(() => new VideoPlayer())
  //
}
```

所以，在使用`playerRef`的时候，需要对它做个判断：

```tsx
import {useRef} from 'react'
import VideoPlayer from 'videoplayer'

function VideoPlayerComponent() {
  const playerRef = useRef<VideoPlayer | null>(null)

  if (playerRef.current === null) {
    playerRef.current = new VideoPlayer()
  }

  const onClick = () => {
    // Error: Object is possibly 'null'.
    playerRef.current.play()
  }
}
```

组件只会调用一次`new VideoPlayer()`并存储在`playerRef`中，但是 typescript 会检查并提示`Error: Object is possibly 'null'`

解决方法：

operation chaining - 可选链

`playerRef.current.play()` => `playerRef.current？.play()`

useImmutableRefValue

```tsx
import {useMemo, useRef} from 'react'

const useImmutableRefValue = <R,>(createRef: () => R) => {
  const ref = useRef<R>()

  const value = useMemo(() => {
    if (!ref.current) {
      ref.current = createRef()
    }

    return ref.current
    // Only one instance, no deps required.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return value
}

export default useImmutableRefValue
```

```tsx
import VideoPlayer from 'videoplayer'
import useImmutableRefValue from 'useImmutableRefValue'

function Component() {
  const player = useImmutableRefValue(() => new VideoPlayer())

  const onClick = () => {
    player.play()
  }
}
```
How to uninstall Hugo on Windows
Tags: webdev, hugo, staticwebapps, go
Published: 2022-12-05 00:08:19

It's easy like chocolate! 

**Tools we'll use**
1. [Chocolately](https://chocolatey.org/) ( Package Manager For Windows)

**3 Simple Steps**
1. Provided that you installed hugo using chocately, follow the next step.

2. Open CMD as administrator

3. Type in the following command:

>  _choco uninstall hugo_

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

Boom! You're good to go.
Upgrading one dependency causes the whole yarn.lock to change - fix
Tags: javascriptyarnlock
Published: 2023-04-22 19:29:08

---
title: Upgrading one dependency causes the whole yarn.lock to change - fix
published: true
date: 2022-12-05 00:00:00 UTC
tags: javascriptyarnlock
canonical_url: https://bstefanski.com/upgrading-one-dependency-causes-whole-yarnlock-change-fix
---

I wanted to bump a dependency in a project with a frozen yarn.lock today. I typed `yarn add libraryName@1.2.4` in the console and waited for results. It ended up updating approx. 10k lines, which was quite surprising! My first thought was to look for another solution to update a dependency because I thought maybe I had misread the commands. A couple of other alternatives, like `yarn up` or `yarn upgrade`, did not reduce the size of the diff.

When I finally looked at the content of the lock file, I saw that it only changed the things that were supposed to be changed, and the rest was just formatting and the order of dependencies and properties. Another major difference was that, in yarn, the key isn't wrapped in quotation marks. I quickly searched the internet and found one or two people with a similar problem, and in both cases, it was caused by someone using npm install instead of yarn.

Npm can use `yarn.lock` and can also **update** it and format it the way they want it to be. So a solution for this is to just ignore the size of the diff and continue on with your work calmly.

 ![Screenshot of big yarn.lock diff](https://bstefanski.com/_next/image?url=%2Fposts%2Fupgrading-one-dependency-causes-whole-yarnlock-change-fix%2Fbig-diff.png&w=1200&q=75)
<small></small>
Textures & Zoom
Tags: godot, gamedev
Published: 2022-12-04 19:23:30

Continuing to learn more than I thought that I wanted to about shaders! My initial concept of being able to just throw 5 images into walls for each room isn't going to be as simple as I had first thought. I suppose that it could be, but it looks cooler with some normalmap, metallic, roughness and emission textures. It is only complicated for me because I can't use Godot's built-in material stuff if I'm doing custom shaders to make holes in the walls. So I anticipate that I'll be spending a lot of time on the level design anyway! For now I'm looking at some stock photos of school classrooms and using Gimp to just cut out different pieces that I think will look cool in the game to make a room. I'll need to do some modeling for props like desks and stuff at some point. I also added zooming with the mouse wheel so that I could get a better look at things. The challenge for the last few days has been lighting. My shader is not behaving as expected with lights in neighboring rooms bleeding through the walls. For now I've solved this by just not having lights in each room and instead moving a single light that follows the camera position:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0lcxbwc7sjakbhn9gagu.gif)

With the walls currently having no thickness, I think that I'll add some brick to the camera facing wall around the edges so it looks less like paper thin walls. I don't have any plans on designing the outside of the building, so I'll need to limit the camera movement to prevent anyone from going too far left or right and seeing the untextured outside of the building. Maybe I'll also add a background soon that you'll be able to see through the windows. I'll add the bus loop with some school bus models eventually as the end goal for each level.
Welcome to Full Stack Web Development Internship Program by Edureka
Published: 2022-12-04 23:36:39

A developer or engineer who is capable of creating both the front end and the back end of a website is known as a "full-stack developer." One of the most difficult skills to master is full stack development. But edureka made it easier.

{% embed https://youtu.be/x8KIrPwFD54 %}
Power up your web apps with TensorFlow.js
Tags: tensorflow, javascript, machinelearning, ai
Published: 2022-12-04 23:30:57

**Are you looking to add the power of machine learning to your web applications?** Look no further than [TensorFlow.js](https://www.tensorflow.org/js), the open-source library that brings the capabilities of TensorFlow to JavaScript.

TensorFlow.js is a library for developing and training machine learning models in JavaScript. It allows web developers to create and train models directly in the browser.

## What can be achieved with TensorFlow on the Web?

For a few months I have been watching "[Made with TensorFlow.js](https://www.youtube.com/watch?v=3xvU6V18-Ac&list=PLQY2H8rRoyvzSZZuF0qJpoJxZR1NgzcZw)", a series of videos where they present products made with this library like:

- [Satellite Image Classification](https://youtu.be/9zqjgeqc-ew)
- [Grocery store recommendation](https://youtu.be/JQksipdQiGI)
- [Remote physiotherapy](https://youtu.be/HcstcWAk2a4)
- [Sentiment analysis in Twitter](https://youtu.be/p6x-_7hamjw)
- [Realistic avatars](https://youtu.be/Ns6A3yqqzQY)
- [3D MRI brain](https://youtu.be/aNAZxV8yQHM)
- [Realtime AR Sudoku solver](https://youtu.be/x-HH0kwbO-4)

Imagine yourself developing engaging and interactive user experiences using machine learning-powered features such as object recognition, natural language processing, and predictive analytics...

## What do you need to learn to use TensorFlow.js?

I've launched my [first web application](https://github.com/360macky/scanner-cam) with this technology. And I'm currently reading the "[Learning TensorFlow.js](https://www.oreilly.com/library/view/learning-tensorflowjs/9781492090786/)" book.

So far, I believe that to understand TensorFlow.js, you should have a basic understanding of machine learning concepts and techniques. This includes understanding how to train and evaluate machine learning models. It would highly recommended some knowledge of the mathematics behind common machine learning algorithms.

With this I do not mean that you should know specifically how to develop a neural network, but **having an understanding of the core concepts of machine learning is a requirement**.


To guide you better, this is a list of questions that you should be able to answer:

- What is a neural network?
- What is a machine learning model?
- What is the difference between supervised and unsupervised learning? 
- What are the differences between classification and regression?
- What is the purpose of normalization?

## Conclusion

Learning TensorFlow.js can be a valuable investment for anyone interested in using machine learning in their web applications. With its powerful, flexible API and easy-to-use tools, TensorFlow.js makes it possible to build intelligent, interactive web applications that can run on any platform.

Whether you're a machine learning expert looking to incorporate your models into web apps, or a web developer interested in incorporating the power of AI into your projects, TensorFlow.js offers a great way to get started.

So why wait? Start learning TensorFlow.js and unlock the potential of machine learning for your web applications.
Cybersecurity for Beginners | Certified Ethical Hacker CEH v11 Certification Training
Published: 2022-12-04 23:15:23

We often hear about data breaches and cases of identity theft that affect millions of consumers.  Cybersecurity is not only involved in organizations, but also in personal computers, mobile phones, and tablets. So it is important to learn cybersecurity and this is one of the highly demanding skills

{% embed https://youtu.be/NLNnvsFoc8s %}
4 FREE Resources To Boost Your Node.js Developer Career ⚡
Tags: node, javascript, beginners, webdev
Published: 2022-12-04 23:00:00

Do you want to **speed up** your **Node.js** career?

These are the resources I wish I knew when I started learning Node.js, and guess what? They are completely **FREE**:

## 1. Event Loop 🔁

An animated guide to understanding how Event Loop works under the hood.

What's better than learning through animations and graphics?

- ✍🏻 *Andrew Hu* - [https://dev.to/nodedoctors/an-animated-guide-to-nodejs-event-loop-3g62](https://dev.to/nodedoctors/an-animated-guide-to-nodejs-event-loop-3g62)
- ✍🏻 *Fabrizio Lallo* - [https://dev.to/nodedoctors/animated-nodejs-event-loop-phases-1mcp](https://dev.to/nodedoctors/animated-nodejs-event-loop-phases-1mcp)

## 2. Broken Promises 💔

Using promises correctly is crucial to maintain Node.js performance and writing clean code.

✍🏻 *James Snell & Matteo Collina*- [https://www.youtube.com/watch?v=yRyfr1Qcf34&t=1181s](https://www.youtube.com/watch?v=yRyfr1Qcf34&t=1181s)

## 3. Async Iterators 🔃

Knowing iteration protocols is essential to write more modern and idiomatic Javascript code.

✍🏻 *Luciano Mammino* - [https://github.com/lmammino/iteration-protocols-workshop](https://github.com/lmammino/iteration-protocols-workshop)

## 4. Streams 🚰

Learning streams allow us to build efficient Node.js applications.

You can build a video streaming service or ingest and transform terabytes of data, which is in great demand nowadays.

✍🏻 *Luciano Mammino* - [https://www.youtube.com/watch?v=yRyfr1Qcf34&t=1181s](https://www.youtube.com/watch?v=yRyfr1Qcf34&t=1181s)

---

_**Let's Connect**_ 🌎 
_Follow us on Twitter [@fabrizio.lallo](https://twitter.com/FabriLallo) and [@AndrewHu368](https://twitter.com/AndrewHu368) for more Node.js content_
Can you Become a Full Stack Web Developer
Published: 2022-12-04 22:52:39

A full-stack developer is knowledgeable about many different technologies. All of them, from creating a database to including images on a website, would be things you are already familiar with. You have an advantage over other developers because of your capacity for strategic thought and rapid technical judgment.

{% embed https://youtu.be/kWxZbwkXcMw %}
const let var - The difference
Published: 2022-12-04 22:50:31

In JavaScript, there are three keywords used to declare variables: **'var', 'let', and 'const'**. Each of these keywords has its own characteristics and best practices for usage. Let's explore their differences and when to use them effectively.

####**var Keyword:**

The 'var' keyword is the oldest way to declare variables in JavaScript.

- **Scope:** Variables declared with 'var' have function scope or global scope. They are accessible throughout the entire function or globally if declared outside any function.
- **Hoisting:** 'var' variables are hoisted to the top of their scope, allowing them to be accessed before their declaration.
- **Reassignment:** 'var' variables can be reassigned and updated.

Example:
```
console.log(a); // Output: undefined
var a = 10;
console.log(a); // Output: 10
```

####**let Keyword:**

The 'let' keyword was introduced in ECMAScript 6 (ES6) to overcome some of the limitations of 'var'.

- **Scope:** Variables declared with 'let' have block scope, which means they are only accessible within the block where they are defined (e.g., inside loops or conditionals).
- **Hoisting:** 'let' variables are not hoisted, so they cannot be accessed before their declaration.
- **Reassignment:** 'let' variables can be reassigned and updated within their scope.

Example.
```
console.log(b); // Output: ReferenceError: b is not defined
let b = 9;
console.log(b); // Output: 9
```

####**const Keyword:**

The 'const' keyword is used to declare constants, which are variables that cannot be reassigned once they are assigned a value.

- **Scope:** Variables declared with 'const' also have block scope.
- **Hoisting:** 'const' variables are not hoisted and need to be initialized during declaration.
- **Reassignment:** 'const' variables cannot be reassigned after initialization, making them read-only.

Example:
```
const c = 10;
console.log(c); // Output: 10

c = 9; // Error: TypeError: Assignment to constant variable.
```

**Best Practices:**

- Use 'const' for values that should not change (e.g., configuration settings, fixed values).
- Use 'let' for variables that need to be reassigned or updated within their scope.
- Minimize the use of 'var' since it has function scope and can lead to unintended consequences.

By understanding the differences and best practices of 'var', 'let', and 'const', you can write more reliable and maintainable JavaScript code. Choose the appropriate keyword based on the desired scope and mutability of your variables.
Como buscar posts no TabNews - Google Hacking
Tags: tabnews, javascript, java, news
Published: 2022-12-04 22:32:51

Certeza que para quem utiliza a plataforma do TabNews a feature mais desejada é a barra de buscas. Enquanto não temos ela implementada podemos utilizar alguns recursos do Google para encontrar o que desejamos!

## Google Hacking

Google Hacking é uma coleção de comandos que podem ser utilizados para encontrar o que você deseja. É um termo usado para descrever a arte de explorar técnicas de pesquisa avançada, operadores e algoritmos para localizar brechas de segurança em aplicativos, redes e sistemas da web, mas pode ser utilizado para encontrar qualquer coisa na internet.

Utilizamos alguns termos e characteres especiais para realizar essas buscas, seguem os principais:

- **intext:** Útil para localizar páginas que contêm certos caracteres ou strings dentro de seu texto. Exemplo: intext:“TabNews”.

- **filetype:** Este operador é usado para procurar por arquivos específicos. Exemplo: pdf, txt e etc...

- **site:** Este operador é usado para procurar em sites específicos. Exemplo: site:tabnews.com.br

- **inurl:** Este operador é usado para procurar por palavras específicas dentro de uma URL. Exemplo: inurl:“tabnews”

- **allintext:** Este operador é usado para procurar por palavras específicas dentro de um documento. Exemplo: allintext:“TabNews”

- **allinurl:** Pode ser usado para obter resultados cuja URL contém todos os caracteres especificados. Exemplo: allinurl:“tabnews”

## Realizando buscas no TabNews

### 1# Exemplo de busca: 
> JavaScript site:tabnews.com.br

Resultado:

Como resultado da busca no Google temos diversos Links da TabNews com o assunto JavaScript.

![Resultada da busca no Google com Links da TabNews com o assunto JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ul0kfd1r8ld7km7vr6bw.png)


### 2# Exemplo de busca: 
> Java intext:Spring Boot site:tabnews.com.br

Resultado:

Quando adicionamos o termo ```intext:Spring Boot``` estamos dizendo para o Google que queremos encontrar o termo Spring Boot dentro do texto do site. Como resultado temos os posts do TabNews que contém o termo "Spring Boot".

![Resultada da busca no Google com Links da TabNews com o assunto Java e também com Spring Boot em destaque](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7opcnrt898y9gnlp988v.png)


Viu como é simples? E essa técnica funciona para qualquer site!

---
Se gostou do conteúdo, compartilhe com seus amigos e deixe seu comentário!

GitHub: https://github.com/jjeanjacques10/
Medium: https://medium.com/@jjeanjacques10

Até a próxima!
Code Smell 184 - Exception Arrow Code
Tags: webdev, javascript, beginners, programming
Published: 2022-12-04 22:32:06

*Arrow code is a code smell. Exception polluting is another. This is a mortal combination.*

> TL;DR: Don't cascade your exceptions

# Problems

- Readability

- Complexity

# Solutions

1. Rewrite the nested clauses

# Context

In the same way [arrow code](https://dev.to/mcsee/code-smell-102-arrow-code-4kfk) is hard to read, handling exceptions is a usual case when we must address the topics in a cascade way.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/18a248332d86061c9cccdf5195a70ca8)
```java
class QuotesSaver {
    public void Save(string filename) {
        if (FileSystem.IsPathValid(filename)) {
            if (FileSystem.ParentDirectoryExists(filename)) {
                if (!FileSystem.Exists(filename)) {
                    this.SaveOnValidFilename(filename);
                } else {
                    throw new I0Exception("File exists: " + filename);
                }
            } else {
                throw new I0Exception("Parent directory missing at " + filename);
            }
        } else {
            throw new ArgumentException("Invalid path " + filename);
        }
    }
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/7d40861212d1d475a25d740f10c8f34e)
```java
public class QuoteseSaver {
    public void Save(string filename) {
        if (!FileSystem.IsPathValid(filename)) {
            throw new ArgumentException("Invalid path " + filename);
        } else if (!FileSystem.ParentDirectoryExists(filename)) {
            throw new I0Exception("Parent directory missing at " + filename);
        } else if (FileSystem.Exists(filename)) {
             throw new I0Exception("File exists: " + filename);
        }
        this.SaveOnValidFilename(filename);
    }
}
```

# Detection

[X] Semi-Automatic 

Some linters warn us when we have this kind of complexity

# Tags

- Exceptions

# Conclusion

Exceptions are less critical than normal cases.

If we need to read more exceptional code than normal then it is time to improve our code.

# Relations

{% post https://dev.to/mcsee/code-smell-102-arrow-code-4kfk %}

{% post https://dev.to/mcsee/code-smell-26-exceptions-polluting-pbn %}

# Disclaimer

Code Smells are just my [opinion](https://dev.to/mcsee/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned-1n3a).

# Credits

Photo by [Remy Gieling](https://unsplash.com/@gieling?) on [Unsplash](https://unsplash.com/s/photos/archer)
  
* * *

> An error doesn't become a mistake until you refuse to correct it.

_Orlando Aloysius Battista_

{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
[PWN.05] What is Canary 🦜
Published: 2022-12-04 22:30:00

**Canary** comes from a bird name called the Canary. 
Canary is used for Protecting Stack buffer.

If we exploit [RAO(Return Address Overwrite)](https://en.wikipedia.org/wiki/Buffer_overflow), We put a bunch of data into the buffer up to the return address.
so that we can exploit what we want to execute code.

BUT, What if there is a kind of Barrier like It is compromised when _something_ is tampered with.
YES, The barrier is called the Canary.

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

```c
mov rax,QWORD PTR fs:0x28
mov [rbp-0x8], rax
```
Process read a Canary value from `fs:0x28`.

```c
mov rcx, QWORD PTR [rbp-0x8]
xor rcx, QWORD PTR fs:0x28
je CODE
```

If rcx, value of rbp-0x8, is same with fs:0x28, it means **Canary** hasn't been tampered with!
Skater Obfuscator protects .NET 7 today
Published: 2022-12-04 21:50:06

.NET 7 is the latest version of .NET that was released in Nov 2022. Not only is .NET 7 a much improved version of the framework compared to its predecessors, but it also introduces some of the coolest features we've seen in some of the most popular platforms and languages. This article talks about the latest updates and new features introduced in in .NET 7.0.

Read more: http://skater.today/obfuscator_dot_net7.html
Measured - Intuitive, Type-safe Units
Tags: kotlin, showdev, opensource
Published: 2022-12-04 21:28:08

[Measured](https://nacular.github.io/measured/) is a multi-platform, Kotlin library that makes units a lot simpler and intuitive to work with. It uses the compiler to enforce correctness and lets you combine units into more complex ones using math operators. It is also extensible, making it easy to define your own units.

```kotlin
val velocity     = 5 * meters / seconds
val acceleration = 9 * meters / (seconds * seconds)
val time         = 1 * minutes

//  d = vt + ½at²
val distance     = velocity * time + 1.0/2 * acceleration * time * time

println(distance                ) // 16500 m
println(distance `as` kilometers) // 16.5 km
println(distance `as` miles     ) // 10.25262467191601 mi

println(5 * miles / hours `as` meters / seconds) // 2.2352 m/s
```

Give it a try. And leave a star or any other feedback.
Machine Learning for Identifying Good Real-Estate Deals Online
Tags: programming, ai, opensource, aws
Published: 2022-12-04 20:20:38

Hello!

I recently developed a personal project for tracking real-estate deals online and identify the good deals. 

The source code is available at https://github.com/alonstern/real-estate-tracker.

The key features of my project are its ability to track real-estate data on a daily basis and identify good deals by comparing the deals' real price with the predicted price according to my ML model. When good deals are found, the project sends a summary of all the good deals it found that day via email, so I can easily see which opportunities are worth pursuing.

The project uses AWS services such as Lambda, SES, DynamoDB, and S3 to provide its functionality and use terraform to set them up and uses Terraform to set up these services and manage their configuration. 

Made mostly for educational purposes, but maybe I could use this one day.
Thank you for reading 🙏