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

news/2024/5/19 20:46:15/文章来源:https://blog.csdn.net/techdashen/article/details/131928653
alt

题图来自[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(f64i32);

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([]string0len(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, 0len(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, 0len(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(13);
    mymap.insert(26);
    mymap.insert(34);
    mymap.insert(41);
    
    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(13);
    mymap.insert(26);
    mymap.insert(34);
    mymap.insert(41);
    
    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{falsetrue}, map[int]float64{11.022.0}, &Bar{"Babar"}}

 list := []Foo{
  {9"Bye", []bool{falsetrue}, map[int]float64{11.022.0}, &Bar{"Babar"}},
  {9"Hello", []bool{falsefalse}, map[int]float64{11.022.0}, &Bar{"Babar"}},
  {9"Hello", []bool{falsetrue}, map[int]float64{13.022.0}, &Bar{"Babar"}},
  {9"Hello", []bool{falsetrue}, map[int]float64{11.052.0}, &Bar{"Babar"}},
  {9"Hello", []bool{falsetrue}, map[int]float64{11.022.0}, &Bar{"Batman"}},
  {9"Hello", []bool{falsetrue}, map[int]float64{11.022.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, 1023000, 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![112233];

    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![1731];
    println!("x: {:?}", x);

    let y: HashSet<_> = x.into_iter().collect();
    println!("y: {:?}", y);
}
x: [1731]
y: {173}

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, 0len(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 = 11223311
 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()
}
2211222233221111
22113311

fn main() {
    let mut x = vec![12343222222];
    x.sort();
    x.dedup();

    println!("{:?}", x);
}

[1, 2, 3, 4]

or

use itertools::Itertools;

fn main() {
    let x = vec![12343222222];
    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");

参考资料

[1]

题图来自: 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 多平台发布

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_335083.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Jmeter(二十三):快速生成测试报告

一、jmeter配置 首先要保证jmeter命令是ok的,如果你在cmd中输入jmeter -v,有出现如下截图所示的信息,那就说明jmeter环境ok; 二、jmeter执行结合命令 生成HTML测试报告 1.完成脚本的调试、参数化、断言等操作。然后在聚合报告中指定日志文件存储路径,路径中最好不要包含有…

Fatdog64 Linux 814发布

导读Fatdog64 Linux是一个小型、桌面、64位的Linux发行版。 最初是作为Puppy Linux的衍生品&#xff0c;并增加了一些应用程序。该项目最新的版本&#xff0c;Fatdog64 814&#xff0c;是8xx系列的最后一个版本&#xff0c;未来的版本将转向9xx基础。 尽管它是该系列的最后一个…

【C#】微软的Roslyn 是个啥?

一、说明 Roslyn 是微软重写的C#编译器并开源。 Roslyn 是 C# 和 Visual Basic.NET 开源编译器的代号。以下是它如何在过去十年企业Microsoft的最黑暗中开始&#xff0c;并成为所有C#&#xff08;和VB&#xff09;的开源&#xff0c;跨平台&#xff0c;公共语言引擎&#xff0c…

Training-Time-Friendly Network for Real-Time Object Detection 论文学习

1. 解决了什么问题&#xff1f; 目前的目标检测器很少能做到快速训练、快速推理&#xff0c;并同时保持准确率。直觉上&#xff0c;推理越快的检测器应该训练也很快&#xff0c;但大多数的实时检测器反而需要更长的训练时间。准确率高的检测器大致可分为两类&#xff1a;推理时…

STM32MP157驱动开发——按键驱动(工作队列)

文章目录 “工作队列”机制&#xff1a;内核函数work_struct 结构体定义 work使用 work &#xff1a;schedule_workworkqueue 其他函数 工作队列方式的按键驱动程序(stm32mp157)编程思路button_test.cgpio_key_drv.cMakefile修改设备树文件编译测试 “工作队列”机制&#xff1…

【stable diffusion】保姆级入门课程05-Stable diffusion(SD)图生图-涂鸦重绘的用法

1.什么是涂鸦重绘 涂鸦重绘又称手涂蒙版。 简单来说&#xff0c;局部重绘手涂蒙版 就是涂鸦局部重绘的结合体&#xff0c;这个功能的出现是为了解决用户不想改变整张图片的情况下&#xff0c;对多个元素进行修改。 功能支持&#xff1a; 1.支持蒙版功能 2.笔刷决定绘制的元素…

DB-GPT:强强联合Langchain-Vicuna的应用实战开源项目,彻底改变与数据库的交互方式

今天看到 蚂蚁科技 Magic 开源的DB-GPT项目&#xff0c;觉得创意很好&#xff0c;集成了当前LLM的主流技术&#xff0c;主要如下 Langchain&#xff1a; 构建在LLM之上的应用开发框架HuggingFace: 模型标准&#xff0c;提供大模型管理功能Vicuna: 一个令GPT-4惊艳的开源聊天机…

如何在3ds max中创建可用于真人场景的巨型机器人:第 3 部分

推荐&#xff1a; NSDT场景编辑器助你快速搭建可二次开发的3D应用场景 1. 创建腿部装备 步骤 1 打开 3ds Max。 打开在本教程最后一部分中保存的文件。 打开 3ds Max 步骤 2 转到创建> 系统并单击骨骼。 创建>系统 步骤 3 为的 侧视口中的腿&#xff0c;如下图所示…

更省更快更安全的云服务器,一站式集中管理,随时随地远程——站斧云桌面

随着全球化和数字化经济的发展&#xff0c;越来越多的企业开始海外扩张和拓展国际市场。而云服务器作为一种高效、灵活且可靠的IT基础设施方案&#xff0c;已成为出海企业不可或缺的重要工具。这里就为大家介绍云服务器在出海企业中的几个使用场景。 1.全球范围内协同办公 对…

开源大模型LLaMA 2会扮演类似Android的角色么?

在AI大模型没有商业模式&#xff1f;等文章中&#xff0c;我多次表达过这样一个观点&#xff1a;不要把大模型的未来应用方式比喻成公有云&#xff0c;大模型最终会是云端操作系统的核心&#xff08;新通用计算平台&#xff09;&#xff0c;而它的落地形式会很像过去的沃森&…

python绘制地图时添加比例尺

目前为止我没有找到cartopy包自动添加地图比例尺的方式&#xff0c;我结合别人的代码写了这个手动添加比例尺的函数&#xff0c;个人觉得在外观上比线段比例尺漂亮一些。之所以是手动的&#xff0c;是因为这种方法不会根据你的地图坐标系和投影自动生成比例尺&#xff0c;而需要…

Windows如何安装Django及如何创建项目

目录 1、Windows安装Django--pip命令行 2、创建项目 2.1、终端创建项目 2.2、在Pycharm中创建项目 2.3、二者创建的项目有何不同 2.4、项目目录说明 1、Windows安装Django--pip命令行 安装Django有两种方式&#xff1a; pip命令行【推荐--简单】手动安装【稍微复杂一丢丢…

高效协作处理缓存清理需求:生产者-消费者模式助力多模块缓存管理

在现代应用系统中&#xff0c;缓存是提高性能和减少数据库负载的重要手段之一。然而&#xff0c;缓存的数据在某些情况下可能会过期或者变得无效&#xff0c;因此需要及时进行清理。在复杂的应用系统中&#xff0c;可能有多个系统、多个模块产生缓存清理需求&#xff0c;而这些…

机器学习原理(1)集成学习基本方法

一.什么是集成学习 集成学习&#xff08;ensemble learning&#xff09;通过将多个学习器进行组合来完成学习任务。下图显示集成学习的一般结构&#xff08;取自周志华老师的西瓜书&#xff09;&#xff0c;个体学习器通常由一种现有的学习算法从训练数据产生&#xff0c;例如…

window10脚本转服务教程

先说下脚本/我们启动的一些三方服务转window本机服务目前我了解到的好处 一键设置开机自启、随用随启、延时自启解决一些服务类应用启动后会阻塞当前dos窗口导致桌面一直要开着的问题脚本化服务注册&#xff0c;方便管理&#xff0c;统一运维… 1. 实践涉及内容介绍 编写好的…

蓝牙HID配对过程

配对通常调用分两步 &#xff11;. Bluetooth AdapterService.cancelDiscovery btif_dm_cancel_discovery BTfM_CancelInquiry BTA_DM_SEARCH_CANCEL_CMPL_EVT BTM_BLI_INQ_CANCEL_EVT BTM_BLI_INQ_DONE_EVT discovery_state_changed_cb btif_dm_cancel_discovery BTA_DM_SE…

CBC字节翻转攻击介绍 例题

知识导入&#xff08;AES-CBC模式&#xff09; 加密过程 1、首先将明文分组(常见的以16字节为一组)&#xff0c;位数不足的使用特殊字符填充。 2、生成一个随机的初始化向量(IV)和一个密钥。 3、将IV和第一组明文异或。 4、用key对3中xor后产生的密文加密。 5、用4中产生的密文…

如何在3ds max中创建可用于真人场景的巨型机器人:第 1部分

推荐&#xff1a; NSDT场景编辑器助你快速搭建可二次开发的3D应用场景 1. 创建主体 步骤 1 打开 3ds Max。 打开 3ds Max 步骤 2 在左侧视口中&#xff0c;按键盘上的 Alt-B 键。它 打开视口配置窗口。 打开“锁定缩放/平移”和“匹配位图”选项。单击“文件”并转到参考 …

刷题小总结

数组 数组是存放在连续内存空间上的相同类型数据的集合。 经典题目&#xff1a; 二分查找 双指针法 滑动窗口 模拟行为 链表 链表的种类主要为&#xff1a;单链表&#xff0c;双链表&#xff0c;循环链表链表的存储方式&#xff1a;链表的节点在内存中是分散存储的&…

github gitlab 多用户多平台切换

一、背景 我需要用账号1 来登录并管理github 账号 我需要用账号2 来登录并管理gitlab 账号 二、设置账号 邮箱 设置账号1用户名与邮箱 git config --global user.name "miaojiang" git config --global user.email "187133163.com" 三、生成本地密钥…