Rust vs Go:常用语法对比(六)

题图来自[1]
101. Load from HTTP GET request into a string
Make an HTTP request with method GET to URL u, then store the body of the response in string s.
发起http请求
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
)
func main() {
u := "http://" + localhost + "/hello?name=Inigo+Montoya"
res, err := http.Get(u)
check(err)
buffer, err := ioutil.ReadAll(res.Body)
res.Body.Close()
check(err)
s := string(buffer)
fmt.Println("GET response:", res.StatusCode, s)
}
const localhost = "127.0.0.1:3000"
func init() {
http.HandleFunc("/hello", myHandler)
startServer()
}
func myHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello %s", r.FormValue("name"))
}
func startServer() {
listener, err := net.Listen("tcp", localhost)
check(err)
go http.Serve(listener, nil)
}
func check(err error) {
if err != nil {
panic(err)
}
}
res has type *http.Response. buffer has type []byte. It is idiomatic and strongly recommended to check errors at each step.
GET response: 200 Hello Inigo Montoya
extern crate reqwest;
use reqwest::Client;
let client = Client::new();
let s = client.get(u).send().and_then(|res| res.text())?;
or
[dependencies]
ureq = "1.0"
let s = ureq::get(u).call().into_string()?;
or
[dependencies]
error-chain = "0.12.4"
reqwest = { version = "0.11.2", features = ["blocking"] }
use error_chain::error_chain;
use std::io::Read;
let mut response = reqwest::blocking::get(u)?;
let mut s = String::new();
response.read_to_string(&mut s)?;
102. Load from HTTP GET request into a file
Make an HTTP request with method GET to URL u, then store the body of the response in file result.txt. Try to save the data as it arrives if possible, without having all its content in memory at once.
发起http请求
package main
import (
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
)
func main() {
err := saveGetResponse()
check(err)
err = readFile()
check(err)
fmt.Println("Done.")
}
func saveGetResponse() error {
u := "http://" + localhost + "/hello?name=Inigo+Montoya"
fmt.Println("Making GET request")
resp, err := http.Get(u)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("Status: %v", resp.Status)
}
fmt.Println("Saving data to file")
out, err := os.Create("/tmp/result.txt")
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
func readFile() error {
fmt.Println("Reading file")
buffer, err := ioutil.ReadFile("/tmp/result.txt")
if err != nil {
return err
}
fmt.Printf("Saved data is %q\n", string(buffer))
return nil
}
const localhost = "127.0.0.1:3000"
func init() {
http.HandleFunc("/hello", myHandler)
startServer()
}
func myHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello %s", r.FormValue("name"))
}
func startServer() {
listener, err := net.Listen("tcp", localhost)
check(err)
go http.Serve(listener, nil)
}
func check(err error) {
if err != nil {
panic(err)
}
}
resp has type *
http.Response. It is idiomatic and strongly recommended to check errors at each step, except for the calls to Close.
Making GET request
Saving data to file
Reading file
Saved data is "Hello Inigo Montoya"
Done.
extern crate reqwest;
use reqwest::Client;
use std::fs::File;
let client = Client::new();
match client.get(&u).send() {
Ok(res) => {
let file = File::create("result.txt")?;
::std::io::copy(res, file)?;
},
Err(e) => eprintln!("failed to send request: {}", e),
};
105. Current executable name
Assign to string s the name of the currently executing program (but not its full path).
当前可执行文件名称
将当前正在执行的程序的名称分配给字符串s(但不是它的完整路径)。
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
var s string
path := os.Args[0]
s = filepath.Base(path)
fmt.Println(s)
}
play
fn get_exec_name() -> Option<String> {
std::env::current_exe()
.ok()
.and_then(|pb| pb.file_name().map(|s| s.to_os_string()))
.and_then(|s| s.into_string().ok())
}
fn main() -> () {
let s = get_exec_name().unwrap();
println!("{}", s);
}
playground
or
fn main() {
let s = std::env::current_exe()
.expect("Can't get the exec path")
.file_name()
.expect("Can't get the exec name")
.to_string_lossy()
.into_owned();
println!("{}", s);
}
playground
106. Get program working directory
Assign to string dir the path of the working directory. (This is not necessarily the folder containing the executable itself)
获取程序的工作路径
package main
import (
"fmt"
"os"
)
func main() {
dir, err := os.Getwd()
fmt.Println(dir, err)
}
/ <nil>
use std::env;
fn main() {
let dir = env::current_dir().unwrap();
println!("{:?}", dir);
}
"/playground"
107. Get folder containing current program
Assign to string dir the path of the folder containing the currently running executable. (This is not necessarily the working directory, though.)
获取包含当前程序的文件夹
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
var dir string
programPath := os.Args[0]
absolutePath, err := filepath.Abs(programPath)
if err != nil {
panic(err)
}
dir = filepath.Dir(absolutePath)
fmt.Println(dir)
}
/tmpfs
let dir = std::env::current_exe()?
.canonicalize()
.expect("the current exe should exist")
.parent()
.expect("the current exe should be a file")
.to_string_lossy()
.to_owned();
Rust doesn't represent paths as Strings, so we need to convert the Path returned from Path::parent. This code chooses to do this lossily, replacing characters it doesn't recognize with �
109. Number of bytes of a type
Set n to the number of bytes of a variable t (of type T).
获取某个类型的字节数
package main
import (
"fmt"
"reflect"
)
func main() {
var t T
tType := reflect.TypeOf(t)
n := tType.Size()
fmt.Println("A", tType, "object is", n, "bytes.")
}
type Person struct {
FirstName string
Age int
}
// T is a type alias, to stick to the idiom statement.
// T has the same memory footprint per value as Person.
type T Person
A main.T object is 24 bytes.
// T has (8 + 4) == 12 bytes of data
struct T(f64, i32);
fn main() {
let n = ::std::mem::size_of::<T>();
println!("{} bytes", n);
// T has size 16, which is "the offset in bytes between successive elements in an array with item type T"
}
16 bytes
110. Check if string is blank
Set boolean blank to true if string s is empty, or null, or contains only whitespace ; false otherwise.
检查字符串是否空白
package main
import (
"fmt"
"strings"
)
func main() {
for _, s := range []string{
"",
"a",
" ",
"\t \n",
"_",
} {
blank := strings.TrimSpace(s) == ""
if blank {
fmt.Printf("%q is blank\n", s)
} else {
fmt.Printf("%q is not blank\n", s)
}
}
}
"" is blank
"a" is not blank
" " is blank
"\t \n" is blank
"_" is not blank
fn main() {
let list = vec!["", " ", " ", "\t", "\n", "a", " b "];
for s in list {
let blank = s.trim().is_empty();
if blank {
println!("{:?}\tis blank", s)
} else {
println!("{:?}\tis not blank", s)
}
}
}
"" is blank
" " is blank
" " is blank
"\t" is blank
"\n" is blank
"a" is not blank
" b " is not blank
111. Launch other program
From current process, run program x with command-line parameters "a", "b".
运行其他程序
package main
import (
"fmt"
"os/exec"
)
func main() {
err := exec.Command("x", "a", "b").Run()
fmt.Println(err)
}
exec: "x": executable file not found in $PATH
use std::process::Command;
fn main() {
let child = Command::new("ls")
.args(&["/etc"])
.spawn()
.expect("failed to execute process");
let output = child.wait_with_output().expect("Failed to wait on child");
let output = String::from_utf8(output.stdout).unwrap();
println!("{}", output);
}
X11
adduser.conf
alternatives
apt
bash.bashrc
bash_completion.d
bindresvport.blacklist
ca-certificates
ca-certificates.conf
cron.d
cron.daily
debconf.conf
debian_version
default
deluser.conf
dpkg
e2scrub.conf
emacs
environment
ethertypes
fstab
gai.conf
group
group-
gshadow
gshadow-
gss
host.conf
hostname
hosts
init.d
inputrc
issue
issue.net
kernel
ld.so.cache
ld.so.conf
ld.so.conf.d
ldap
legal
libaudit.conf
localtime
logcheck
login.defs
logrotate.d
lsb-release
machine-id
magic
magic.mime
mailcap
mailcap.order
mime.types
mke2fs.conf
mtab
networks
nsswitch.conf
opt
os-release
pam.conf
pam.d
passwd
passwd-
perl
profile
profile.d
protocols
python2.7
rc0.d
rc1.d
rc2.d
rc3.d
rc4.d
rc5.d
rc6.d
rcS.d
resolv.conf
rmt
rpc
security
selinux
services
shadow
shadow-
shells
skel
ssh
ssl
subgid
subgid-
subuid
subuid-
sysctl.conf
sysctl.d
systemd
terminfo
timezone
update-motd.d
xattr.conf
xdg
or
use std::process::Command;
fn main() {
let output = Command::new("ls")
.args(&["/etc"])
.output()
.expect("failed to execute process");
let output = String::from_utf8(output.stdout).unwrap();
println!("{}", output);
}
or
use std::process::Command;
fn main() {
let status = Command::new("ls")
.args(&["/etc"])
.status()
.expect("failed to execute process");
// exit code is outputted after _ls_ runs
println!("{}", status);
}
112. Iterate over map entries, ordered by keys
Print each key k with its value x from an associative array mymap, in ascending order of k.
遍历map,按key排序
package main
import (
"fmt"
"sort"
)
func main() {
mymap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
keys := make([]string, 0, len(mymap))
for k := range mymap {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
x := mymap[k]
fmt.Println("Key =", k, ", Value =", x)
}
}
Key = four , Value = 4
Key = one , Value = 1
Key = three , Value = 3
Key = two , Value = 2
use std::collections::BTreeMap;
fn main() {
let mut mymap = BTreeMap::new();
mymap.insert("one", 1);
mymap.insert("two", 2);
mymap.insert("three", 3);
mymap.insert("four", 4);
mymap.insert("five", 5);
mymap.insert("six", 6);
// Iterate over map entries, ordered by keys, which is NOT the numerical order
for (k, x) in mymap {
println!("({}, {})", k, x);
}
}
(five, 5)
(four, 4)
(one, 1)
(six, 6)
(three, 3)
(two, 2)
113. Iterate over map entries, ordered by values
Print each key k with its value x from an associative array mymap, in ascending order of x. Note that multiple entries may exist for the same value x.
遍历map,按值排序
package main
import (
"fmt"
"sort"
)
type entry struct {
key string
value int
}
type entries []entry
func (list entries) Len() int { return len(list) }
func (list entries) Less(i, j int) bool { return list[i].value < list[j].value }
func (list entries) Swap(i, j int) { list[i], list[j] = list[j], list[i] }
func main() {
mymap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"dos": 2,
"deux": 2,
}
entries := make(entries, 0, len(mymap))
for k, x := range mymap {
entries = append(entries, entry{key: k, value: x})
}
sort.Sort(entries)
for _, e := range entries {
fmt.Println("Key =", e.key, ", Value =", e.value)
}
}
Key = one , Value = 1
Key = dos , Value = 2
Key = deux , Value = 2
Key = two , Value = 2
Key = three , Value = 3
Key = four , Value = 4
or
package main
import (
"fmt"
"sort"
)
func main() {
mymap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"dos": 2,
"deux": 2,
}
type entry struct {
key string
value int
}
entries := make([]entry, 0, len(mymap))
for k, x := range mymap {
entries = append(entries, entry{key: k, value: x})
}
sort.Slice(entries, func(i, j int) bool {
return entries[i].value < entries[j].value
})
for _, e := range entries {
fmt.Println("Key =", e.key, ", Value =", e.value)
}
}
Key = one , Value = 1
Key = two , Value = 2
Key = dos , Value = 2
Key = deux , Value = 2
Key = three , Value = 3
Key = four , Value = 4
use itertools::Itertools;
use std::collections::HashMap;
fn main() {
let mut mymap = HashMap::new();
mymap.insert(1, 3);
mymap.insert(2, 6);
mymap.insert(3, 4);
mymap.insert(4, 1);
for (k, x) in mymap.iter().sorted_by_key(|x| x.1) {
println!("[{},{}]", k, x);
}
}
[4,1]
[1,3]
[3,4]
[2,6]
or
use std::collections::HashMap;
fn main() {
let mut mymap = HashMap::new();
mymap.insert(1, 3);
mymap.insert(2, 6);
mymap.insert(3, 4);
mymap.insert(4, 1);
let mut items: Vec<_> = mymap.iter().collect();
items.sort_by_key(|item| item.1);
for (k, x) in items {
println!("[{},{}]", k, x);
}
}
[4,1]
[1,3]
[3,4]
[2,6]
114. Test deep equality
Set boolean b to true if objects x and y contain the same values, recursively comparing all referenced elements in x and y. Tell if the code correctly handles recursive types.
深度判等
package main
import (
"fmt"
"reflect"
)
func main() {
x := Foo{9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}}
list := []Foo{
{9, "Bye", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}},
{9, "Hello", []bool{false, false}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}},
{9, "Hello", []bool{false, true}, map[int]float64{1: 3.0, 2: 2.0}, &Bar{"Babar"}},
{9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 5: 2.0}, &Bar{"Babar"}},
{9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Batman"}},
{9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}},
}
for i, y := range list {
b := reflect.DeepEqual(x, y)
if b {
fmt.Println("x deep equals list[", i, "]")
} else {
fmt.Println("x doesn't deep equal list[", i, "]")
}
}
}
type Foo struct {
int
str string
bools []bool
mapping map[int]float64
bar *Bar
}
type Bar struct {
name string
}
x doesn't deep equal list[ 0 ]
x doesn't deep equal list[ 1 ]
x doesn't deep equal list[ 2 ]
x doesn't deep equal list[ 3 ]
x doesn't deep equal list[ 4 ]
x deep equals list[ 5 ]
let b = x == y;
The == operator can only be used by having a type implement PartialEq.
115. Compare dates
Set boolean b to true if date d1 is strictly before date d2 ; false otherwise.
日期比较
package main
import (
"fmt"
"time"
)
func main() {
d1 := time.Now()
d2 := time.Date(2020, time.November, 10, 23, 0, 0, 0, time.UTC)
b := d1.Before(d2)
fmt.Println(b)
}
true
extern crate chrono;
use chrono::prelude::*;
let b = d1 < d2;
doc -- Struct chrono::Date[2]
116. Remove occurrences of word from string
Remove all occurrences of string w from string s1, and store the result in s2.
去除指定字符串
package main
import "fmt"
import "strings"
func main() {
var s1 = "foobar"
var w = "foo"
s2 := strings.Replace(s1, w, "", -1)
fmt.Println(s2)
}
bar
fn main() {
let s1 = "foobar";
let w = "foo";
let s2 = s1.replace(w, "");
println!("{}", s2);
}
bar
or
fn main() {
let s1 = "foobar";
let w = "foo";
let s2 = str::replace(s1, w, "");
println!("{}", s2);
}
bar
117. Get list size
获取list的大小
package main
import "fmt"
func main() {
// x is a slice
x := []string{"a", "b", "c"}
n := len(x)
fmt.Println(n)
// y is an array
y := [4]string{"a", "b", "c"}
n = len(y)
fmt.Println(n)
}
3
4
fn main() {
let x = vec![11, 22, 33];
let n = x.len();
println!("x has {} elements", n);
}
x has 3 elements
118. List to set
Create set y from list x. x may contain duplicates. y is unordered and has no repeated values.
从list到set
package main
import "fmt"
func main() {
x := []string{"b", "a", "b", "c"}
fmt.Println("x =", x)
y := make(map[string]struct{}, len(x))
for _, v := range x {
y[v] = struct{}{}
}
fmt.Println("y =", y)
}
x = [b a b c]
y = map[a:{} b:{} c:{}]
use std::collections::HashSet;
fn main() {
let x: Vec<i32> = vec![1, 7, 3, 1];
println!("x: {:?}", x);
let y: HashSet<_> = x.into_iter().collect();
println!("y: {:?}", y);
}
x: [1, 7, 3, 1]
y: {1, 7, 3}
119. Deduplicate list
Remove duplicates from list x. Explain if original order is preserved.
list去重
package main
import "fmt"
func main() {
type T string
x := []T{"b", "a", "b", "c"}
fmt.Println("x =", x)
y := make(map[T]struct{}, len(x))
for _, v := range x {
y[v] = struct{}{}
}
x2 := make([]T, 0, len(y))
for _, v := range x {
if _, ok := y[v]; ok {
x2 = append(x2, v)
delete(y, v)
}
}
x = x2
fmt.Println("x =", x)
}
x = [b a b c]
x = [b a c]
or
package main
import "fmt"
func main() {
type T string
x := []T{"b", "a", "b", "b", "c", "b", "a"}
fmt.Println("x =", x)
seen := make(map[T]bool)
j := 0
for _, v := range x {
if !seen[v] {
x[j] = v
j++
seen[v] = true
}
}
x = x[:j]
fmt.Println("x =", x)
}
x = [b a b b c b a]
x = [b a c]
or
package main
import "fmt"
type T *int64
func main() {
var a, b, c, d int64 = 11, 22, 33, 11
x := []T{&b, &a, &b, &b, &c, &b, &a, &d}
print(x)
seen := make(map[T]bool)
j := 0
for _, v := range x {
if !seen[v] {
x[j] = v
j++
seen[v] = true
}
}
for i := j; i < len(x); i++ {
// Avoid memory leak
x[i] = nil
}
x = x[:j]
// Now x has only distinct pointers (even if some point to int64 values that are the same)
print(x)
}
func print(a []T) {
glue := ""
for _, p := range a {
fmt.Printf("%s%d", glue, *p)
glue = ", "
}
fmt.Println()
}
22, 11, 22, 22, 33, 22, 11, 11
22, 11, 33, 11
fn main() {
let mut x = vec![1, 2, 3, 4, 3, 2, 2, 2, 2, 2, 2];
x.sort();
x.dedup();
println!("{:?}", x);
}
[1, 2, 3, 4]
or
use itertools::Itertools;
fn main() {
let x = vec![1, 2, 3, 4, 3, 2, 2, 2, 2, 2, 2];
let dedup: Vec<_> = x.iter().unique().collect();
println!("{:?}", dedup);
}
[1, 2, 3, 4]
120. Read integer from stdin
Read an integer value from the standard input into variable n
从标准输入中读取整数
package main
import (
"fmt"
"io/ioutil"
"os"
)
// This string simulates the keyboard entry.
var userInput string = `42 017`
func main() {
var i int
_, err := fmt.Scan(&i)
fmt.Println(i, err)
// The second value starts with 0, thus is interpreted as octal!
var j int
_, err = fmt.Scan(&j)
fmt.Println(j, err)
}
// The Go Playground doesn't actually read os.Stdin, so this
// workaround writes some data on virtual FS in a file, and then
// sets this file as the new Stdin.
//
// Note that the init func is run before main.
func init() {
err := ioutil.WriteFile("/tmp/stdin", []byte(userInput), 0644)
if err != nil {
panic(err)
}
fileIn, err := os.Open("/tmp/stdin")
if err != nil {
panic(err)
}
os.Stdin = fileIn
}
42 <nil>
15 <nil>
or
package main
import (
"fmt"
"io/ioutil"
"os"
)
// This string simulates the keyboard entry.
var userInput string = `42 017`
func main() {
var i int
_, err := fmt.Scanf("%d", &i)
fmt.Println(i, err)
var j int
_, err = fmt.Scanf("%d", &j)
fmt.Println(j, err)
}
// The Go Playground doesn't actually read os.Stdin, so this
// workaround writes some data on virtual FS in a file, and then
// sets this file as the new Stdin.
//
// Note that the init func is run before main.
func init() {
err := ioutil.WriteFile("/tmp/stdin", []byte(userInput), 0644)
if err != nil {
panic(err)
}
fileIn, err := os.Open("/tmp/stdin")
if err != nil {
panic(err)
}
os.Stdin = fileIn
}
42 <nil>
17 <nil>
fn get_input() -> String {
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).expect("Failed");
buffer
}
let n = get_input().trim().parse::<i64>().unwrap();
or
use std::io;
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let n: i32 = input.trim().parse().unwrap();s
or
use std::io::BufRead;
let n: i32 = std::io::stdin()
.lock()
.lines()
.next()
.expect("stdin should be available")
.expect("couldn't read from stdin")
.trim()
.parse()
.expect("input was not an integer");
参考资料
题图来自: https://picx.zhimg.com/v2-363b653b2429b2f8073bc067b6c55f2d_720w.jpg?source=172ae18b
[2]doc -- Struct chrono::Date: https://docs.rs/chrono/0.4.3/chrono/struct.Date.html
本文由 mdnice 多平台发布
相关文章:

Rust vs Go:常用语法对比(六)
题图来自[1] 101. Load from HTTP GET request into a string Make an HTTP request with method GET to URL u, then store the body of the response in string s. 发起http请求 package mainimport ( "fmt" "io/ioutil" "net" "net/http…...

css元素定位:通过元素的标签或者元素的id、class属性定位
前言 大部分人在使用selenium定位元素时,用的是xpath元素定位方式,因为xpath元素定位方式基本能解决定位的需求。xpath元素定位方式更直观,更好理解一些。 css元素定位方式往往被忽略掉了,其实css元素定位方式也有它的价值&…...
java享元模式
在Java中实现享元模式,可以通过创建一个享元工厂(FlyweightFactory)和享元对象(Flyweight)来完成。享元模式用于共享可复用对象,以节省内存和提高性能。 下面是一个简单的示例: 首先ÿ…...

ESP32(MicroPython) 两轮差速五自由度机械臂小车
这次的项目在软件上没多少调整,但本人希望分享一下硬件上的经验。 小车使用两轮差速底盘,驱动轮在小车中间,前后都要万向轮。这种形式可以实现0转弯半径,但受万向轮及用于加高的铜柱的规格限制,两个万向轮难以调到相同…...
mysql基本函数(五)
目录 一、数字函数二、字符函数三、日期时间函数3.1 获取系统日期时间的函数3.2 日期格式化函数3.3 日期偏移计算3.4 日期之间相隔的天数 四、条件函数4.1 IF语句4.2 条件语句 一、数字函数 函数功能用例ABS绝对值ABS(-100)ROUND四舍五入ROUND(4.62)FLOOR向下取值FLOOR(9.9)CE…...

liteflow 2.10 配置中心简单记录
除nacos是一个key 同时管理chain和script node外,可以理解为配置文件整体放到一个key下nacos下的文件必须是xml格式,系统只实现了xml parser其它etcd,zk,Apollo 是两个namespace/path(chain及script node各一)下多个key,每个key对应一个chain/node所有配置中心的核心代码…...
【C++】引用、内联函数等
文章目录 一、引用1.引用概念2.引用特性3.引用时的权限问题4 .使用场景5 .引用和指针的联系与区别 二、内联函数1.概念2.注意点 三、auto关键字1.概念2.auto的使用细则 四、 基于范围的for循环1.概念2.范围for的使用条件 五、 指针空值nullptr1.概念2.使用注意 一、引用 1.引用…...

RocketMQ教程-(4)-主题(Topic)
本文介绍 Apache RocketMQ 中主题(Topic)的定义、模型关系、内部属性、行为约束、版本兼容性及使用建议。 定义 主题是 Apache RocketMQ 中消息传输和存储的顶层容器,用于标识同一类业务逻辑的消息。 主题的作用主要如下: 定义…...

睡眠健康数据分析
项目背景 背景描述 本数据集涵盖了与睡眠和日常习惯有关的诸多变量。如性别、年龄、职业、睡眠时间、睡眠质量、身体活动水平、压力水平、BMI类别、血压、心率、每日步数、以及是否有睡眠障碍等细节。 数据集的主要特征: 综合睡眠指标: 探索睡眠持续时…...
Spring Boot 3.x 系列【47】启动流程 | 启动监听器
有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot版本3.1.0 源码地址:https://gitee.com/pearl-organization/study-spring-boot3 文章目录 1. 前言2. 核心类2.1 SpringApplicationRunListener2.2 ApplicationStartup2.3 ApplicationListener3. 执行流程3.1 获取监…...
【KD】知识蒸馏与迁移学习的不同
知识蒸馏与迁移学习的不同 (1)数据域不同. 知识蒸馏中的知识通常是在同一个目标数据集上进行迁移,而迁移学习中的知识往往是在不同目标的数据集上进行转移. (2)网络结构不同. 知识蒸馏的两个网络可以是同构或者异构的,而迁移学习通常是在单个网络上利用其…...

计算机内存中的缓存Cache Memories
这篇写一下计算机系统中的缓存Cache应用场景和实现方式介绍。 Memory hierarchy 在讲缓存之前,首先要了解计算机中的内存结构层次Memory hierarchy。也就是下图金字塔形状的结构。 从上到下,内存层次结构如下: 寄存器:这是计算机…...

Flask的send file和send_from_directory的区别
可以自行查看flask 文档。 send file高效; send from directory安全,且适用于静态资源交互。 都是实现相同的功能的。 send_file send_from_directory...

Java 队列
基本介绍 数组模拟队列 思路分析 代码实现 import java.util.Scanner;public class Test {public static void main(String[] args) {// 创建一个队列ArrayQueue queue new ArrayQueue(3);int select;Scanner scanner new Scanner(System.in);boolean loop true;while (lo…...

【算法基础:搜索与图论】3.6 二分图(染色法判定二分图匈牙利算法)
文章目录 二分图介绍染色法判定二分图例题:860. 染色法判定二分图 匈牙利匹配二分图最大匹配匈牙利匹配算法思想例题:861. 二分图的最大匹配 二分图介绍 https://oi-wiki.org/graph/bi-graph/ 二分图是图论中的一个概念,它的所有节点可以被…...
SpringMVC 怎么和 AJAX 相互调用的
通过 Jackson 框架就可以把 Java 里面的对象直接转化成 Js 可以识别的 Json 对象。 步骤如下 : a、加入 Jackson.jar b、在配置文件中配置 json 的映射 c、在接受 Ajax 方法里面可以直接返回 Object,List 等,但方法前面要加上ResponseBody 详细步骤: …...

UCDOS和WPS推动计算机领域的汉字化发展,中文编程该谁力扛大旗?
你还记得UCDOS吗? 从DOS时代过来的人,还知道UCDOS的,现在可能已经是中年人了! 当时,鲍岳桥的UCDOS可以称得上是中国的国产操作系统。 在Windows还没来得及进入中国市场时,UCDOS可以说是走向了巅峰时刻&a…...

golang+layui提升界面美化度--[推荐]
一、背景 golanglayui提升界面美化度--[推荐]; golang后端写的页面很难看,如何好看点呢,那就是layui https://layui.dev/ 也是一个简单上手容易使用的框架,类似jquery,对于后端开发来说满足使用需求 二、使用注意点…...

42. 接雨水
题目介绍 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 示例 1: 输入:height [0,1,0,2,1,0,1,3,2,1,2,1] 输出:6 解释:上面是由数组 [0,1,0,2,1,0,1,3…...
Python学习阶段路线和内容
Python学习阶段路线和内容 这是我的看法和认识,供参考。 Python学习路线主要分为三个阶段:入门阶段、提高阶段和深入阶段。 入门阶段 入门阶段需要学习Python的基本语法,掌握变量和数据类型、条件语句和循环语句、函数和模块等内容。并通过…...

深入浅出Asp.Net Core MVC应用开发系列-AspNetCore中的日志记录
ASP.NET Core 是一个跨平台的开源框架,用于在 Windows、macOS 或 Linux 上生成基于云的新式 Web 应用。 ASP.NET Core 中的日志记录 .NET 通过 ILogger API 支持高性能结构化日志记录,以帮助监视应用程序行为和诊断问题。 可以通过配置不同的记录提供程…...

通过Wrangler CLI在worker中创建数据库和表
官方使用文档:Getting started Cloudflare D1 docs 创建数据库 在命令行中执行完成之后,会在本地和远程创建数据库: npx wranglerlatest d1 create prod-d1-tutorial 在cf中就可以看到数据库: 现在,您的Cloudfla…...
uni-app学习笔记二十二---使用vite.config.js全局导入常用依赖
在前面的练习中,每个页面需要使用ref,onShow等生命周期钩子函数时都需要像下面这样导入 import {onMounted, ref} from "vue" 如果不想每个页面都导入,需要使用node.js命令npm安装unplugin-auto-import npm install unplugin-au…...

visual studio 2022更改主题为深色
visual studio 2022更改主题为深色 点击visual studio 上方的 工具-> 选项 在选项窗口中,选择 环境 -> 常规 ,将其中的颜色主题改成深色 点击确定,更改完成...

屋顶变身“发电站” ,中天合创屋面分布式光伏发电项目顺利并网!
5月28日,中天合创屋面分布式光伏发电项目顺利并网发电,该项目位于内蒙古自治区鄂尔多斯市乌审旗,项目利用中天合创聚乙烯、聚丙烯仓库屋面作为场地建设光伏电站,总装机容量为9.96MWp。 项目投运后,每年可节约标煤3670…...

深入解析C++中的extern关键字:跨文件共享变量与函数的终极指南
🚀 C extern 关键字深度解析:跨文件编程的终极指南 📅 更新时间:2025年6月5日 🏷️ 标签:C | extern关键字 | 多文件编程 | 链接与声明 | 现代C 文章目录 前言🔥一、extern 是什么?&…...

Android 之 kotlin 语言学习笔记三(Kotlin-Java 互操作)
参考官方文档:https://developer.android.google.cn/kotlin/interop?hlzh-cn 一、Java(供 Kotlin 使用) 1、不得使用硬关键字 不要使用 Kotlin 的任何硬关键字作为方法的名称 或字段。允许使用 Kotlin 的软关键字、修饰符关键字和特殊标识…...

关键领域软件测试的突围之路:如何破解安全与效率的平衡难题
在数字化浪潮席卷全球的今天,软件系统已成为国家关键领域的核心战斗力。不同于普通商业软件,这些承载着国家安全使命的软件系统面临着前所未有的质量挑战——如何在确保绝对安全的前提下,实现高效测试与快速迭代?这一命题正考验着…...

解读《网络安全法》最新修订,把握网络安全新趋势
《网络安全法》自2017年施行以来,在维护网络空间安全方面发挥了重要作用。但随着网络环境的日益复杂,网络攻击、数据泄露等事件频发,现行法律已难以完全适应新的风险挑战。 2025年3月28日,国家网信办会同相关部门起草了《网络安全…...

Qemu arm操作系统开发环境
使用qemu虚拟arm硬件比较合适。 步骤如下: 安装qemu apt install qemu-system安装aarch64-none-elf-gcc 需要手动下载,下载地址:https://developer.arm.com/-/media/Files/downloads/gnu/13.2.rel1/binrel/arm-gnu-toolchain-13.2.rel1-x…...