teleren/devto huggingface dataset:
Chrome插件开发 - Messaging
Published: 2023-08-13 02:13:45

---
title: Chrome插件开发 - Messaging
published: true
date: 2022-09-03 00:00:00 UTC
tags: 
canonical_url: https://manon.icu/blog/translate/build-chrome-extensions/messaging
---

本文将了解消息发送的工作原理，比如希望和后台进行交互。如下：

![zPmZyAzG9](https://cdn.jsdelivr.net/gh/manonicu/pics@master/uPic/zPmZyAzG9.gif)

修改`src/App.jsx`

```jsx
import React, {useState} from 'react'

export default function Messaging() {
  const [message, setMessage] = useState(null)
  const backgroundRequest = () => {
    chrome.runtime.sendMessage({color}, (response) => {
      setMessage(response.msg)
    })
  }

  return (
    <>
      <button onClick={backgroundRequest}>Background request</button>
      {message && (
        <>
          <p className="text-white">{message}</p>
          <br />
        </>
      )}
    </>
  )
}
```

修改`background.js`

```js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (!request.color) {
    sendResponse({msg: `You didn't set any color`})
  }

  sendResponse({msg: `You must really like the color ${request.color}`})
})
```

## Source Code

[【Source Code】](https://github.com/rebelchris/popup-extension/tree/messaging)
Continuous Delivery vs Automated Deployment
Tags: continuousdelivery, podcast, automateddeployments
Published: 2022-09-09 12:34:15

---
title: Continuous Delivery vs Automated Deployment
published: true
date: 2022-09-03 00:00:00 UTC
tags: continuousdelivery,podcast,automateddeployments
canonical_url: https://jhall.io/archive/2022/09/03/continuous-delivery-vs-automated-deployment/
cover_image: https://jhall.io/images/bn-cans-conveyor-belt.jpg
---

I recently had a conversation with someone who works on a team using GitFlow. They’re a small team, and they seem to be producing some good software, at a pretty good pace. Still, there are times when they get a backlog of features that are ready for use, but not yet in front of customers, and it takes a small effort to merge everything from their `develop` branch to `master`, tag it, and get it deployed.

I asked if he was familiar with the concept of continuous delivery, and he assured me he was, and that he had used it several times before. So I moved on to ask about what was preventing the team from doing continuous delivery. After a few minutes of discussion, he said to me:

“You know, I don’t really think continuous deployment would help much. I mean, it only takes a few minutes to do a release manually right now, so at best it would save a few minutes every week or so.”

Ah-ha!

I had made a mistake.

I had assumed that when my conversation partner said “I’ve done continuous delivery before” it meant we had a mutual understanding of continuous delivery.

We didn’t.

My team lead friend was under the common, but mistaken, impression that continuous delivery is just another name for automated deployments.

It’s easy to understand why these two terms are often confused. From a distance, they look very similar. In fact, from a technology standpoint, they practically are the same.

So what’s the difference?

Well, the difference is in the name.

With automated deployments, the deployment of your software is automated. Nice. That’s a great thing!

But with continuous delivery, well… you deliver your software continuously.

Naturally, continuous delivery depends on automated deployments. But it’s so SO much more. Continuous delivery is the _practice_ of delivering software iteratively and incrementally, every time a small change is made. Usually multiple times per day.

For more on this, check out [MimimumCD.org](https://minimumcd.org/minimumcd/), which provides a description, and guidance, on the _minimum_ necessary to claim that you’re doing continuous delivery. I’ve also interviewed Bryan Finster, one of the organizers of the project on my podcast in [Episode 21: Minimum Viable Continuous Delivery](https://jhall.io/archive/2021/11/30/minimum-viable-continuous-delivery/).

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
ASP.NET Core - Tiny Chat App using SignalR
Tags: dotnet, csharp, aspnet, signalr
Published: 2022-09-02 23:08:39

**Warning!** This code is for demonstration purposes only.

1. Create an empty ASP.NET web app:
    ```sh
    dotnet new web -o TinyChat
    ```
2. In your `Program.cs`, add `SignalR` service, set to serve static files and map the `SignalR` hub.
    ```cs
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddSignalR();
    var app = builder.Build();

    app.UseStaticFiles();
    app.MapHub<ChatHub>("/ChatHub");
    app.Run();
    ```
3. In your project directory, add `ChatHub.cs` that contains:
    ```cs
    using Microsoft.AspNetCore.SignalR;

    public class ChatHub : Hub
    {
        // this can be invoked from the client -- web browser in our example
        public async Task SendMessage(string username, string message)
        {
            // invoke ReceiveMessage on all clients connected
            await Clients.All.SendAsync("ReceiveMessage", username, message);
        }
    }
    ```
4. Add folder `wwwroot` in the project directory. Then add `chat.html` which contains:
    ```html
    <!DOCTYPE html>
    <html>
        <head></head>
        <body>
            <input id='usernameInput' placeholder='username' />
            <input id='messageInput' placeholder='message' />
            <button id='sendButton'>Send</button>
            <ul id='conversationList'></ul>
            <script src='https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.8/signalr.min.js'></script>
            <script src='/chat.js'></script>
        </body>
    </html>
    ```
5. In `wwwroot`, add `chat.js` which contains:
    ```js
    "use strict";
    document.addEventListener('DOMContentLoaded', function() {
    var connection = new signalR.HubConnectionBuilder().withUrl("/ChatHub").build();

    // Handler for receiving a message. This will be invoked by the server.
    connection.on("ReceiveMessage", function (username, message) {
        var messageItem = document.createElement("li");
        messageItem.textContent = `${username}: ${message}`; 

        var conversationList = document.querySelector("#conversationList");
        conversationList.prepend(messageItem);
    });

    // Initiate connection and set callback for error.
    connection.start().then(function () {
        
    }).catch(function (err) {
        return console.error(err.toString());
    });

    // Handler for sending message to the server.
    document.querySelector("#sendButton").addEventListener("click", function (event) {
        var username = document.querySelector("#usernameInput").value;
        var message = document.querySelector("#messageInput").value;
        
        connection.invoke("SendMessage", username, message)
        .catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
});
    ```
6. Run the app using `dotnet run` and go to `https://localhost:<port>/chat.html`.

**Resource**
[Microsoft Docs](https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-6.0&tabs=visual-studio)
Let It Snow
Tags: adventofcode, algorithms, programming, javascript
Published: 2022-09-02 23:29:24

## [Advent of Code 2015 Day 25](https://adventofcode.com/2015/day/25)

## Part 1
1. First, I need to see more of the picture
2. Row, then column, then calculate

### First, I need to see more of the picture
Similarly to [2017 Day 3's spiral puzzle](https://adventofcode.com/2017/day/3), I need to see more of this diagonal pattern so I can identify and confirm its underlying row-and-column equations.

Based on the slice in the diagram:
```
   | 1   2   3   4   5   6  
---+---+---+---+---+---+---+
 1 |  1   3   6  10  15  21
 2 |  2   5   9  14  20
 3 |  4   8  13  19
 4 |  7  12  18
 5 | 11  17
 6 | 16
```
- The down-and-to-the-right diagonal numbers grow by multiples of 4
- Moving right in a row or down in a column increments numbers by an amount one greater than the previously incremented amount, starting from an amount based on the row and column

This animation shows me confirming and discovering the above patterns:
![Math underlying the grid](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xxod3809vk7pho3f9niw.gif)

### Row, then column, then calculate
- I need to determine which code will get stored in the row and column specified in my puzzle input
- Not the actual code right now
- But in the ordered list of codes that are generated, where mine falls

Thankfully, my animation helped me understand one way to calculate this.

To find the number in column 1 of my target row:
```
Set row as 1
For i from 1 up to but not including the target row
  Increment row by i
```

Then, to find the number in my target column:
```
Set column to row
For i from row + 1 up to but not including column plus the target column
  Increment column by i
```

Now that I have the number, I know how many times to perform the multiplication, division and remainder:
```
Set code to 20151125
For i from 1 up to but not including column
  Set code to the remainder after dividing the product of code and 252533 by 33554393
```

After all three loops, I should have the correct answer!

And that I did!
- At least, after some fiddling with the amounts
- I made a few `off-by-one` errors
- But having the diagram of initial answers helped me debug my algorithm

My working algorithm in JavaScript:
```js
const part1 = (row, col) => {
  let x = 1
  for (let i = 1; i < row; i++) { x += i }
  for (let i = row + 1; i < row + col; i++) { x += i }
  let code = 20151125
  for (let i = 1; i < x; i++) {
    code = code * 252533 % 33554393
  }
  return code
}
```

## Part 2
Since I start at the last day of the year, Part 2 is never unlocked.

However, it requires I have 49 stars, which I never anticipate fully acquiring.

## I did it!
- I solved Part 1!
- Using some mathematic patterns instead of brute-forcing a nested array of hundreds of thousands of values!

That was a delightful, diagonal puzzle!

A surprising new direction, much like the spiral one from 2017!

I hope I continue to find novel puzzles in this first year of Advent of Code.
How to Center a div.
Tags: 100daysofcode, beginners, webdev, css
Published: 2022-09-02 23:18:35

Assuming you have an HTML file created and a CSS file, create a div. Give it a class or an ID. 
Style the display property to "flex." Then define the align-items and justify-content property to “center.”


```
<!DOCTYPE html>
<html>
<head>
    <title>TO CENTER A DIV </title>
</head>
<style>
    .center{
        display: flex;
        align-items: center;
        justify-content: center;
    }
</style>

<h2>center a div</h2> 

 
 
<div class="center"><button>center the div</button></div>
 
</body>
 
</html>
```
Front-End Workflow for Next.js
Tags: webdev
Published: 2022-09-02 23:10:26

### 1) Setup

```powershell
yarn create next-app
# OR
npx create-next-app
# AND
npm i -g create-next-app
```

### 2) Pages & Routes

* Home
* About
* Others...

### 3) Layout Components

* Navigation Bar
* Header
* Footer
* Layout

### 4) Styling

* Choosing a Theme
* 404 Error Page
* Responsive Design

### 5) Database

* MongoDB
* REDIS
* MySQL
* Others...

### 6) Fetching

```javascript
// Basic Example
import fs from "fs";
import path from "path";

export async function getStaticPaths() {
	const files = fs.readdirSync(path.join("blogs"));

	const paths = files.map((filename) => ({
		params: {
			slug: filename.replace(".txt", ""),
		},
	}));

	return {
		paths,
		fallback: false,
	};
}

export async function getStaticProps(context) {
	const blog = fs.readFileSync(
		path.join("blogs", context.params.slug + ".txt"),
		"utf-8"
	);

	const content = blog;

	return {
		props: {
			content,
		},
	};
}


```

### 7) Dynamic Routing

* /Content/index.js
* /Content/[slug].js

### 8) Testing

* ES6 or ES2016+

```powershell
# Dependencies
npm install --save-dev eslint
npm install --save-dev eslint-config-next

npm run lint
```

* QUnit

```powershell
npm install --save-dev qunit
```

* Mocha experience

```
Matching "Test" file structures
```

* Others...

### 9) Deployment

* [Vercel](https://vercel.com/)
* Others...

### OTHERS

* SEO

```powershell
# Basic Example
npm i --save-dev next-seo
```

* Optimization

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w5hwfim7xny06sfb3uh6.png)
If You Want to Fix 85% of Your Problems, Read This
Tags: tooling, tutorial, programming, beginners
Published: 2022-09-02 23:02:57

##1. Have a morning ritual
Successful and innovative people follow a morning routine.
May it be a morning run, cold shower, reading, or writing an article.

Choose what suits you.

Your body needs a jumpstart to stay energized and focused, and doing any kind of physical and mental activity helps you achieve the same.

##2. Start with the most important tasks 
This will depend on the day, may it be laundry, or replying to e-mails.

This avoids hips from building up and you can free up a big chunk of time on more important tasks like solving a technical problem, working on an idea, or anything else of importance.

##3. Always take a break
Being a workaholic will reward you but is still destructive in the long run.

Your body and mind is not a robot that will run all year through and you need a rest.

Take break intervals, maybe take a 15 minutes walk/exercise, and play with your kids/friends/pet.

This will help you
- Prevent burnouts
- Regain focus
- Boost energy levels
- Improve performance 

##4. Have a daily Routine
A Daily routine is a non-negotiable activity, this may either be avoiding high-calorie food before bed, doing yoga or researching a particular topic.

##5. Keep grinding
This is the most important, whenever it seems and gets hard. Work the as** off the ground, it's just about to pay back.

Hard work, dedication, and consistency are the only key to success. Sleep late, wake up early, practice that skill, think and streamline that burning idea.

Whenever it pays off, repeat the same process and make it your daily and non-negotiable routine.

### Signing out
What are the success tricks that have worked out for you? Let's share in the comments section.

Article originally published at [https://melbite.com/fix-85%-of-your-problems](https://melbite.com/melbite/VUpUwc1jZ58rdtO5AzJ7)
Memory Palace to Next.js
Tags: nextjs, webdev
Published: 2022-09-02 22:39:37

### Quick Setup
```powershell
yarn create next-app
# OR
npx create-next-app
# AND
npm i -g create-next-app
```

#### Storage:
- Node.js
- Microsoft Visual Studio Code
- NPM (package manager)
- YARN (package manager)
- Typescript
- ES6 or ES2016+

#### Box:
- Github
- Vercel

#### Paint:
- Pure CSS
- [ChakraUI](https://chakra-ui.com/)
- [TailwindCSS](https://tailwindcss.com/)
How to create a GitHub Account
Published: 2022-09-02 22:33:08

Creating a GitHub Account is as easy as creating a Social Media Account, same way, same process.

**Step 1**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/33i9dgjs96926si9ul2z.PNG)

Visit [https://github.com/](https://github.com/) or click [GitHub](https://github.com/) to lunch GitHub website.

Click on Sign up button to continue the process.

**Step 2**

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

Complete the required data to continue the process.

Ensure you are signing up with an active email to enable you receive the OTP Code from GitHub.

After completing the OTP Verification, bravos! you now own a fresh GitHub Account.

**Step 3**

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

Congratulation, this is your GitHub dashboard, you go ahead to navigate around.
What was your win this week?
Tags: discuss, weeklyretro
Published: 2022-09-02 21:29:24

---
title: What was your win this week?
published: true
description: Got to all your meetings on time? Started a new project? Fixed a tricky bug?
tags: discuss, weeklyretro
cover_image: https://cl.ly/188e843c2985/download/Image%202019-02-15%20at%202.36.37%20PM.png
---

Hey folks!

Just to note that I've taken up [the ritual of posting](https://dev.to/michaeltharrington/ever-heard-of-ritual-posts-4gd6) this Friday series that the awesome @graciegregory was previously [regularly sharing](https://dev.to/devteam/what-was-your-win-this-week-4ol6). I'll be following the same format and am looking forward to seeing what y'all have been up to! 🙌

Looking back on this past week, what was something you were proud of accomplishing?

All wins count — big or small 🎉

Examples of 'wins' include:

- Starting a new project
- Fixing a tricky bug
- Eating a delicious meal 😋

---

Hope y'all have nice relaxing weekends!


![It's a loop of a sloth playing a banjo. The sloth is actually scratching itself but the banjo is superimposed into the picture to make it look like the sloth is playing it.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wq884ctc73luvt7zn2qz.gif)
Day 146: Hello Jenkins!
Published: 2022-09-02 22:17:10

Hi!
So today I got started learning about Jenkins as a CI/CD pipeline system it usage was completely new and I think it have a rough learning curve especially for someone not familiar with the Devops field but Today I was about to get the overview and have done the local basic installation on my machine I was thinking to shift to Circle CI for the current project in case I struggle with Jenkins but since the point of the project I'm working on is to learn new tool and technologies I would say it is still too early to decide but that also may be a possibility and something to look it in the near future.
Tomorrow I'm not sure what I will be doing but I think I will continue researching about Jenkins I may also look into Circle CI for getting the comparison but I think Circle CI may be more like Github actions so It will not be so hard to configure
I may also use the weekend to publish a new article maybe about setting up sequelize and postgres in a Typescript to help someone who may be struggling the way I did for the past week 

See you there

signing off...
Do you know DeskDock?
Tags: linux
Published: 2022-09-02 21:53:57

Did you know that you can share your desktop cursor to your Android device using the DeskDock?

i tried it on my fedora device

read instruction first:v
[instruction](https://www.fdmobileinventions.com/deskdock-server/)

first, I install Desk Dock on my android
[DeskDock PRO](https://play.google.com/store/apps/details?id=com.floriandraschbacher.deskdock.pro&hl=in&gl=US)
you can install free version btw
[DeskDock FREE](https://play.google.com/store/apps/details?id=com.floriandraschbacher.deskdock.free&hl=in&gl=US)

next, setup server
install JRE

```
sudo dnf install java-latest-openjdk.x86_64
sudo dnf install java-latest-openjdk-devel.x86_64
```

next, install adb

```
sudo dnf install android-tools.x86_64
```

download DeskDock Server and extrak it
[DeskDock Server](https://files.fdmobileinventions.com/DeskDockServer/1.3.0/DeskDockServer_1.3.0.zip)

start adb server

```
adb start-server
adb tcpip 5555
```

### run, Desk Dock Server
connect on android first

![connect on android first](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zi9b1b4jdstnver8mcnb.png)

and run server
```
java -jar DeskDockServer_1.3.0.jar
```

nice its running

![tray icon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/31y5obev7fq50dcghw97.png)


![DeskDock Setting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/op28pdqn3j0h99c3cxhg.png)

![android display](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1f1tbm8fforx4958g3n8.png)


to kill adb server

```
adb kill-server
```

have an error? try this
[https://dev.to/bukanspot/cant-load-library-usrlibjvmjava-11-openjdk-1101608-1fc35x8664liblibawtxawtso-4pco](https://dev.to/bukanspot/cant-load-library-usrlibjvmjava-11-openjdk-1101608-1fc35x8664liblibawtxawtso-4pco)

---

## reference

- [DeskDock Server](https://www.fdmobileinventions.com/deskdock-server/)
- [installing JRE](https://docs.fedoraproject.org/en-US/quick-docs/installing-java/)
- [java-11-openjdk](https://fedora.pkgs.org/35/fedora-x86_64/java-11-openjdk-11.0.12.0.7-4.fc35.x86_64.rpm.html)
- [android adb](https://developer.android.com/studio/run/device#setting-up)
📝 Reflective journal: (Java, 6-Week MERN project)
Published: 2022-09-02 21:52:28

## Learned Java (and Spring Boot)
I had the chance to learn Java in school for about 2 months.

Here are my experience and what I learned:

First of all, the fact that Java is a statically typed language was challenging to me and it took some time to get used to it because I'd only had experience of coding in JavaScript and PHP prior to that which are dynamically typed.
At the time I had started to learn Typescript so it was a great timing and it somewhat helped me grasp the concepts and apply knowledge to one another.

Second of all, it was a great opportunity to improve understanding of object oriented programming (OOP).
I thought I already knew enough, but I was actually wrong and got to learn a lot.
For example, I got to learn more in detail in when to use a static class/variable/method depending on the purpose and also to use memory efficiently, and also the concept of interface which I did not use when I used to code in PHP.
I also learned the concept of singleton class which is useful when you want only one instance of a particular class.

For the final project of Java, I decided to create an Admin API for the project I am working on on the side using Spring Boot.
I struggled more than expected especially when manipulating collections.
Java has a number of collection classes and I am still sometimes not confident in which one would be the best fit for my needs as it is easy to forget which one is sorted, order, or scalable, etc.
Also since I was used to using high-order array methods of JavaScript, manipulating data was not as smooth with Java because of lack of experience.

As I was getting a lot of errors relating to types it was very frustrating at times to be honest because when you code in just JavaScript you do not encounter those compile errors.
That, of course, could lead to unexpected run time errors so Typescript is very helpful for that and I realized the importance of it.

I was still able to complete what I wanted to create, but I will probably re-create it with node.js next time with express and Typescript as they are more of my interests and fields.


## 6-Week MERN stack project
I have also been working on a team project on the side.
We are a team of 7 people (2 backend developers and 5 frontend developers). We also have a project manager and we are conducting the project in a very real-world-like way with a scrum meeting every time discussing issue and progress, etc and also helping out each other.
This is the first time working in a team like this in an English environment and It has been a great and enjoyable experience!
I am in charge of frontend and using React.
So far we've just created components without the logics and are almost done with all the UI, so I am excited for the logic sides in collaboration with the backend team.