teleren/devto huggingface dataset:
How to query element by className in Testing Library
Tags: testinglibrary
Published: 2021-08-14 06:41:07

Testing Library默认没有通过className查询元素的方法，但是Web API原生就有啊，我们可以直接通过JavaScript来查询。

比如用CRA创建的项目，在``src/App.js``中默认会有一个欢迎界面，我们想把它删除，于是先要写一个测试定位这个元素，container返回的就是一个DOM节点，所以直接可以使用``querySelector``方法来查找子元素，只返回找到的第一个对象，没有找到返回``null``

```
describe("Clear default code", () => {
  it("omit header with className App-header", () => {
    const { container } = render(<App />);
    const header = container.querySelector(".App-header");
    expect(header).not.toBeInTheDocument();
  });
});
```

### References
* https://developer.mozilla.org/zh-CN/docs/Web/API/Document/querySelector
Lessons learned converting Sketch to SwiftUI
Tags: podcast, swift, swiftui
Published: 2021-08-19 20:44:18

---
title: Lessons learned converting Sketch to SwiftUI
published: true
date: 2021-08-14 06:29:41 UTC
tags: Podcasts,Swift,SwiftUI
canonical_url: https://peterwitham.com/swift/cs-s03-e09/
---

{% spotify spotify:episode:79HSfGCmg3vri3FEzLqjmT %}

## Season 3 Episode 9

In this episode, I go into some lessons learned and ideas from a recent live stream on CompileSwift.com, where I created some swift UI layouts.

I had a design that I had been working on in Sketch.app, one of my favorite all-time UI prototyping, layouts, design screen apps, and the problem that I always have with Sketch is that there’s no great way to be able to say export this to a SwiftUI view for me, please.

I dived into a couple of things that I found in GitHub; all those failed miserably. I couldn’t even get them to work and all sorts of library conflicts.

So that’s a separate conversation for another day. It took me longer to try and get this automated conversion thing to work than it would to do the conversion manually.

Okay, I popped open Xcode and the design in Sketch. And I said I’m just going to do this. I’m going to build this out in Xcode. I already had the primary controls on the screen that looked nothing like the design. I started applying modifiers and kudos to the chat room, the chat room, the folks that come to the chat room on the CompileSwift live stream.

Love you guys and girls, you’re just fantastic. So lovely and so helpful. I Just wanted to add that in there as a side note.

I started applying modifiers to figure out how to get the controls in SwiftUI to look like the design. We got there. Not entirely. It’s about 90% done.

So that was about an hour, an hour and a half, really not bad going at all. The lesson learned here is that sometimes it’s better to dive into creating something from scratch. Trying to export across is not always the answer, at least today.

Other advantages to this approach are, learning more about Swift and SwiftUI. You are going to learn more about using Xcode. You’re going to learn more about your design and how you implement those in apps.

These are all good things, folks. Right?

<svg viewbox="0 0 100 10" xmlns="http://www.w3.org/2000/svg" preserveaspectratio="none" role="img" aria-hidden="true"><path d="m42.19.65c2.26-.25 5.15.04 7.55.53 2.36.49 7.09 2.35 10.05 3.57 7.58 3.22 13.37 4.45 19.26 4.97 2.36.21 4.87.35 10.34-.25s10.62-2.56 10.62-2.56v-6.91h-100.01v3.03s7.2 3.26 15.84 3.05c3.92-.07 9.28-.67 13.4-2.24 2.12-.81 5.22-1.82 7.97-2.42 2.72-.63 3.95-.67 4.98-.77z" fillrule="evenodd" transform="matrix(1 0 0 -1 0 10)"></path></svg>

### Subscribe / Follow The Podcast

[![](https://secureservercdn.net/45.40.148.117/7a7.1ac.myftpupload.com/wp-content/uploads/2021/06/listen-apple.png)](https://podcasts.apple.com/us/podcast/compile-swift/id1467065787)

[![](https://secureservercdn.net/45.40.148.117/7a7.1ac.myftpupload.com/wp-content/uploads/2021/06/listen-spotify.png)](https://open.spotify.com/show/2RGHkl4UtYj0V7lPcRojzK)

**[Click here for other Audio Players](https://anchor.fm/compileswift)**
[Minecraft - Forge 1.16] Make explosion from client.
Tags: minecraft, forge, kotlin
Published: 2021-08-14 06:02:00

I built `Explosion Mod` in following sequence.

1. Receive `PlayerInteractEvent.LeftClickEmpty` in client side.
1. Send `ExplosionMessage` to server side.
1. Make explosion in server side.

Code is written in Kotlin.

First, make `ExplosionMessage` class. 
```kotlin
class ExplosionMessage(
    val x: Double,
    val y: Double,
    val z: Double
) {

    companion object {
        fun encode(message: ExplosionMessage, buf: PacketBuffer) {
            buf.writeDouble(message.x)
            buf.writeDouble(message.y)
            buf.writeDouble(message.z)
        }

        fun from(buf: PacketBuffer): ExplosionMessage {
            return ExplosionMessage(
                buf.readDouble(),
                buf.readDouble(),
                buf.readDouble()
            )
        }
    }
}
```

Prepare `SimpleChannel`.
```kotlin
class ExampleMod {

    private val channel: SimpleChannel = NetworkRegistry.newSimpleChannel(
        ResourceLocation(MOD_ID, "main"),
        { PROTOCOL_VERSION },
        PROTOCOL_VERSION::equals,
        PROTOCOL_VERSION::equals
    )

    init {
        channel.registerMessage(
            0,
            ExplosionMessage::class.java,
            ExplosionMessage::encode,
            ExplosionMessage::from,
            this::handle
        )

        MinecraftForge.EVENT_BUS.register(this)
    }

    ...
```

Receive `PlayerInteractEvent.LeftClickEmpty`.
This event is occurred in client side only.
```kotlin
    @SubscribeEvent
    fun on(event: PlayerInteractEvent.LeftClickEmpty) {
        val loc = Minecraft.getInstance().hitResult?.location
        if (loc == null) {
            return
        }

        logger.info("ExplosionMessage send: ${loc?.x} ${loc?.y} ${loc?.z} ")
        channel.sendToServer(ExplosionMessage(loc.x, loc.y, loc.z))
    }
```

Handle `ExplosionMessage`.
```kotlin
    fun handle(message: ExplosionMessage, context: Supplier<NetworkEvent.Context>) {
        logger.info("ExplosionMessage received: ${message.x} ${message.y}  ${message.z} ")

        ServerLifecycleHooks.getCurrentServer().overworld().explode(
            null,
            message.x,
            message.y,
            message.z,
            4.0F,
            Explosion.Mode.BREAK
        )
    }
```

Now we can explode any place where we want!
![Screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gejlle7atiuajq5byrkt.png)
Database Management System: Data Models
Tags: computerscience, tutorial, dbms
Published: 2021-08-14 05:19:53

## The ONLY Theory You Need 📚

Data Model is a collection of **concepts** (fundamental building blocks or general notions) that can be used to describe the *structure* of a database. Thus, it provides necessary means(ways) to achieve *data abstraction* (easy to understand for different classes of peoples: naive users, query executors, etc.)

The *structure* of a database implies *data types*, *relationships*, and *constraints*(restrictions) that apply to data that is stored.

![Image 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/99r805sfktgiendfx1wc.jpg)

> 🗯 In simple words, a data model helps us represent data using simple concepts( say objects, attributes, tables, etc.) so that the intended audience can work on it.

## Types of data models

Depending on the audience, we may need a different level of abstractions. Let me give you a real-world scenario,

Say you are hired as a database designer for your nearest shopping mall. Now you are going to perform *requirement analysis* to determine the structure of the database. After all the hardship, you will be needed to explain your database to the manager of the mall right? To him, you cannot talk about how SQL works, neither you can talk about how the data is stored physically! He will be flabbergasted.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zdhccy13k2nasqqf03tk.png)
 
> ⛑ To avoid the above situation, a better thing would be to explain to him in form of some diagrams/pictures so that he can understand and provide feedback for further iterations of the design.

Depending on the type of the audience, we can model the data into 3 different ways,

![Image 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1jyb009d7a508h9b8fce.jpg)

1. Hight Level or Conceptual Model 
    - The **highest** level of abstraction is provided.
    - Used for modeling data for naive users.
    - we use *diagrams* or *visuals* to explain our database.
    - Example: Entity-Relationship(ER) model.
2. Representational/Implementation/Logical Model
    - **Less** abstraction compared to Conceptual Model.
    - To execute *queries*, we need to understand this model.
    - Intended for programmers who are query executors.
    - Example: Relational Model, Object-Oriented Model.
3. Physical Model
    - The **lowest** level of abstraction.
    - To understand how the data is stored in the memory, we need to understand this model.
    - Intended for computer specialists as it talks about low-level details.
[Kotlin] ::class.java “Unresolved Reference: Java” error
Tags: kotlin
Published: 2021-08-14 05:17:49

I got `“Unresolved Reference: Java”` error in following code.
```
val clazz = String::class.java
```

Loading kotlin-reflect library in `build.gradle` resolved this error.
```
dependencies {
    ...
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    
    // this line
    implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    ...
}
```
Using Environment Variables
Tags: node, security, backend, javascript
Published: 2021-08-14 05:07:48

Environment variables are the most important part of your backend when it comes to deployment. They store the configuration of your server and hence should never be exposed. I am going to cite an example about using the environment variables in a node application. 
The package.json can be a place to store your environment variables but is not at all a secure option. 
###dotenv
The .env file is a special type of file used to define environment variables for your node application in a key:value format. But nodejs is unable to parse this file. Here comes dotenv which takes care of these environment variables and helps node parse the .env file.  
**1. Creating the file**
The .env file needs to be created in the root directory of your application. This file can contain your port, jwt secret key etc.
```
PORT=5000
JWT_SECRET_KEY="SHHHHHHH"
```
**2. Configuring the dotenv**
First you need to install dotenv as a dev package. 
```
npm i -D dotenv
```
You can use your environment variables by importing them from .env file. So far so good. Your starting point(app.js) can consider the change when you pivot from dev to prod. But if you have imported and used your environment variables in other files, this can cause you trouble unless you initialize dotenv in each file. This is a frequent mistake made by beginners. With some tweaks in your scripts used to start the application, this trouble can be fixed easily. 
**3. Changing scripts**
You might already have 2 scripts to run your application in dev and prod:
```
{
       "scripts": {
        "start": "node app.js",
        "dev": "node app.js"
        // For nodemon users ====
        "dev": "nodemon app.js"
    }
}
```
We need to change the dev script so that the node knows when to use your .env file
```
{
       "scripts": {
        "start": "node app.js",
        "dev": "node -r dotenv/config app.js"
        // For nodemon users ====
        "dev": "nodemon -r dotenv/config app.js"
    }
}
```
And done! 
Now you don't require the following lines of code in any file including your app.js/index.js .  
```
const dotenv = require('dotenv')
const myEnv = dotenv.config()
```
**Ensure that you ignore the file in .gitignore**
How to delete all Docker containers using a single Command
Tags: docker, linux
Published: 2021-08-14 04:50:47

There may be a many containers either running or exited in your development machine. You need to clean them up in a regular basis. 

To see the list of docker container running locally, 

```bash
docker ps
```

But it does not show the excited containers. To see them all use -a

```bash
docker ps -a
```

Finally to delete you need to pass either the id or the name of each container. Wouldn't it be nice to delete them in a loop (its the concept here but we are not using it)? YES indeed it would be. To get only the ids of all the containers we can use `-q` switch. 

So to get the list of only ids for all the containers we can use, 

```bash
docker ps -a -q 
```
or 

```bash
docker ps -aq
```
To delete we use 

```bash
docker rm container_id
```

If we want to loop (again not actual loop but a concept) through all 

```bash
docker rm $(docker ps -aq)
```

That's it - your magic command to delete all the running and exited containers in your machine.

This works in Linux (not in Windows).
LGM-Summer Of Code Experience
Published: 2021-08-14 04:33:34

Hello Everyone,

I am <a href="https://www.linkedin.com/in/rutuj-runwal/">Rutuj Runwal</a> and in this post I will be sharing my experience as an Open Source Contributor at Let's Grow More(LGM) through their Summmer of Code Program 2021.

The program was really well structured and had tons of projects to contribute from different types of fields.There were web-based projects such as <a href="https://project-zone.netlify.app/about">Project Zone</a> that suggests the user about the projects they can create based on their skills. There were also projects that had a combination of various self-reliant scripts in different languages ranging from basic scripts that do some required tasks to fully automated mega projects such as a Website Checker that detects vulnerabilities in a website.
<a href="https://hacking-scripts.netlify.app/python-scripts.html">Know More</a>

As an opensource contributor, I collaborated with many open source projects and with 100+ PR's accepted in domains ranging from Web Development to AI and ML , My LGM-SoC journey was full of great learning and improving the open source projects.
Some of the projects that I worked on are:

- <a href="https://github.com/amanosan/Discord-Bot/blob/master/README.md" target="blank">LunaBot</a> [A discord bot to educate people about the Stock Market and Crypto Market]
- <a href="https://github.com/rockingrohit9639/project-zone" target="blank">Project Zone</a> [Tensorflow.js powered web-app suggests the user about the projects they can create]
- <a href="https://hacking-scripts.netlify.app/python-scripts.html" target="blank">Hacking Scripts</a> [Provide utility scripts that might make everyday life easy]
- <a href="https://github.com/akshitagupta15june/Face-X" target="_blank">Face-X</a> [Recognition of human faces by different algorithms and frameworks.]

<img src="https://raw.githubusercontent.com/rockingrohit9639/project-zone/main/Project_Img/GIF_DEMO.gif"/>

Let's Connect: <a href="https://bit.ly/let_us_connect" style="text-decoration:none;color:red;">Linkedin</a>

Hey Reader, I have also created a **Anti-malware app**: <a href="https://dev.to/rutujr/context-menu-malware-scanner-using-python-57j2">Click Here👀</a>
How to overcome the problem of many if statements by Look up tables.
Tags: beginners, programming, codenewbie
Published: 2021-08-14 04:32:07


## Introduction
In this guide I will show you a way to overcome the many if statements which faces most of beginner programmers.

## Problem
Assume that you have a task and after you finished and tested it, you found a case which not covered, so you add an else if statement to convert it, but time after time, your code became full of if and else if statements and the makes your code not readable for others.

## Solution
One of the ways to solve this problem is **Look up table**, it's just a data structure that we store the cases of the problem with it.
**Look up table** makes our code readable because we can access the cases by direct access if we use an array.

## Example
If you want to write a program which take a number of the month and output the name of the month, for example, If you input 1, It will output January.
You can solve this problem with long If statements, But your code will not be readable like that:
```golang
if numOfMnths == 1 {
		fmt.Println("January")
} 
else if numOfMnths == 2 {
		fmt.Println("February")
}
.
.
.
```
We can solve it by **Look up table** like that:
```golang
months :=[12] string{"January", "February", ...}
fmt.Println(months[numOfMnths])
//if numOfMnths is equal 1 it will print January

```
## Conclusion
**Look up table** helps you to make your code more readable for you and others using the suitable data structure for your problem and it's very useful with simple problems.
Implementing Stack in javascript
Tags: javascript, beginners, webdev, algorithms
Published: 2021-08-14 03:44:10

Hello 👋, 

This is an article on implementing stack data structure in javascript

We already know stack is data structure. It has methods like `push`, `pop`, `top`, `size` and `isEmpty`

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3iyp6zgqunzf751vv7lc.png) 

#### push
It will insert the element at first.

#### pop
It will delete and returns the first element.

### top
It will return first element

### size 
It will return size of an stack i.e no of elements in stack

### isEmpty
It will return `true` if stack doesn't have any elements otherwise it will return `false`

```javascript
class Stack {
  constructor(){
    this.list = []
  }
  
  push(ele){
    this.list.unshift(ele)
  }
  
  pop(){
    return this.list.shift()
  }
  
  top(){
    return this.list[0]
  }
  
  size(){
    return this.list.length
  }
  
  isEmpty () {
    return this.list.length === 0
  }
  
}
```

#### Usage

```javascript
const mystack = new Stack()

mystack.isEmpty() // true
mystack.push("a") // returns undefined but it will add element to list
mystack.push("b")
mystack.push("c")
mystack.isEmpty() // false
mystack.top() // c
mystack.pop() // c
mystack.top() // b
mystack.size() // 2
```

Thank you!!
Cheers!!!
How to fix import/no-unresolved error while import jsx without extension
Tags: eslint
Published: 2021-08-14 03:26:04

在ESLint中设置了``eslint-plugin-import``扩展
```
"extends": [
  "plugin:import/recommended",
],
```

当引入一个React文件的时候会校验失败，引入的逻辑没啥特别的
```
import App from "./App";
```

具体触发的规则：
```
error  Unable to resolve path to module './App'  import/no-unresolved
```

原因比较明显，因为没有扩展名，并且没有去试着解析jsx，所以只要在设置中加上这个要求就好了。

```
"eslintConfig": {
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [
          ".js",
          ".jsx"
        ]
      }
    }
  },
}
```

### References
* https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md
* https://stackoverflow.com/questions/42264007/eslint-errorring-importing-jsx-without-extension
Aim for quality over consistency (100 Bytes Of Wisdom: Day 65)
Tags: career, journey, advice
Published: 2021-08-14 03:04:46

---
title: Aim for quality over consistency (100 Bytes Of Wisdom: Day 65)
published: true
description: Bytes of Wisdom is a project by Sam Jarman that brings together snippets of advice for software engineers
tags: career, journey, advice
//cover_image: https://direct_url_to_image.jpg
---

![#65 Aim for quality over consistency](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hukvy46v8502h4qbshk9.png)

Too often I see poor code or features tried to get by me in the name of consistency. Defending your work solely with ""its consistent"" is a fast way to make no progress. Now, if there some other reasons to do it like this, plus its consistent, then sure, that's probably fine. But if there's a way to do it better you should always strive for that. The older stuff can catch up.

Heads up: As with any terse bit of advice, there will be exceptions of course, and subtleties and nuance that can't possibly be captured in a Byte of Wisdom. This has been what I've experienced, I'd love to hear yours in the comments too!

You can catch up with all the other bytes at http://bytesofwisdom.com/
JavaScript ASYNC & DEFER Attributes
Tags: javascript, webdev
Published: 2021-08-14 02:53:04

Rendering DOM or Webpage faster is one of challenging task that every developer face🤯. One of the main factors of the slow rendering of DOM is the strategy with which we load the JavaScript because JS blocks the parsing of HTML and that’s why the DOM performance highly depends on it.

However, few keywords can be used with `script` tag to boost the performance. The `<script>` tag has two attributes that do the magic⚡️ for us : `async` and `defer`.

### Here’s what we’ll cover in this article:
* `<script>` without attributes.
* `<script>` **async** attributes.
* `<script>` **defer** attributes.

So let’s dive in!

### `<script>` without attributes

As soon as the browser encounters the `script` tag, the HTML parsing is blocked and will only start up again after the JavaScript is fetched from the server and executed.

While the Javascript is loading, the building up of the DOM is paused and that **reduces the performance** and **increases the loading time of the webpage**.

### `<script>` async attributes

Using `async` attribute downloads the script files asynchronously during HTML parsing ( in the background). After it finished downloading, **only then it paused the HTML parsing and start executing the script file** but before the window’s `load` event.

The `async` attribute **does not guarantee the order of execution of script files**. The script files will be executed asynchronously or in random order.

### `<script>` defer attributes

The `defer` attribute also downloads the script file during HTML parsing( in the background) but **will only execute it after the HTML parsing is completed** but before DOMContentLoaded event.

Using `defer` in the script tag also **assured that the scripts will be executed in the same order as they appear in the file**. This is very much useful in the scenario when one script depends on another script.

**This is how it all works:** 👇

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9e2wb430ezkn7jcfzbra.jpeg)

### Similarity

Both defer and async attribute downloads the script in **background** while the HTML parsing is going on. **Downloading of scripts this way does not block the rendering of DOM and as a result**, user can see the webpage instead of a white screen.

### Difference

`defer` :- Script execution starts after HTML parsing is finished but before the `DOMContentLoaded` event.

`async` :- Scripts execute after they finish downloading but before the window’s `load` event.

### Where async and defer use?

1. If the script files are dependent on each other, then use `defer` attribute.
2. `async` attribute is useful when we don’t care when the script loads and scripts do not rely on each other.
3. `defer` maintains the order of execution of script but `async` doesn't.

### Conclusion
Congratulations for reading until the end! In this article you’ve learned:

* Javascript async and defer
* Similarity and difference and where to use of async and defer attributes in script tag.
  
####Suggestions are highly appreciated ❤️