Golang Basic 8 - Pointer

Golang Basic 8 - Pointer

Pointer

  • A pointer holds the memory address of a value.

Declear

  • Pointers in Golang are very similar to pointers in c/c .
    // declear a pointer
    var pointerName *dataType
    
    //get a pointer's value
    *pointerName
    
    //get a variable's physical address
    &variableName
    

    Sample

    root@go:l8/ # cat l8s1.go
    package main
    import (
        "fmt"
    )
    
    func swap(val1 *int, val2 *int){
        *val1, *val2 = *val2, *val1
    
    }
    
    func main(){
        var var1, var2 int
        var1 = 3
        var2 = 6
        fmt.Println(var1, var2)
        swap(&var1, &var2)
        fmt.Println(var1, var2)
    
    }
    root@go:l8/ # go run l8s1.go
    3 6
    6 3
    

Golang Basic 7 - Function

Golang Basic 7 - Function

Function

Function Declear

  • A function can take zero or more arguments.
  • Notice that the type comes after the variable name.
    golang
    func functionName(input_var1 DataType, input_var2 DataType) retDataType{
    // some code block here.
    return retData
    }

Call a function

functionName(input_var1, input_var2)

Sample

root@go:/develop/go/l7# cat l7s1.go
package main
import (
    "fmt"
)

func add(x int, y int) int{
    return x   y

}

func main(){
    fmt.Println(add(1, 2))

}
root@go:/develop/go/l7# go run l7s1.go
3

Same Parameters' Type

  • If all the parameters have the same data type, we can omit the type from all but the last.
func add(x, y int) int{
    return x   y
}

Sample

root@go:l7/ # cat l7s2.go
package main
import (
    "fmt"
)

func add(x , y int) int{
    return x   y

}

func main(){
    fmt.Println(add(1, 2))

}
root@go:l7/ # go run l7s2.go
3

Multi Return Values

func functionName(input_var1 DataType, input_var2 DataType) retDataType1, retDataType2{
    // some code block here.
    return retData1, retData2
}

Sample

root@go:l7/ # cat l7s3.go
package main
import (
    "fmt"
)

func swap(x , y int) (int, int){
    return y, x

}

func main(){
    var var1, var2 int = swap(1, 2)
    fmt.Println(var1, var2)

}
root@go:l7/ # go run l7s3.go
2 1

Named Return Values

func functionName(input_var1 DataType, input_var2 DataType) variableName1 DataType, variableName2 DataType{
    // some code block here.
    var variableNamel DataType = ...
    var variableName2 DataType = ...
    return
}

Sample

root@go:l7/ # cat l7s4.go
package main
import (
    "fmt"
)

func getAnswer(x , y int) (add int, div float64){
    add = x   y
    div = float64(x) / float64(y)
    return

}

func main(){
    var var1 int
    var var2 float64
    var1, var2 = getAnswer(5, 2)
    fmt.Println(var1, var2)

}
root@go:l7/ # go run l7s4.go
7 2.5

Golang Basic 4 - Basic Operators

Golang Basic 4 - Basic Operators

Arithmetic Operators

Operators

Operator Sense Description Sample Result
Addition The ‘ ’ operator adds two operands. 3 2 5
- Subtraction The ‘-‘ operator subtracts two operands. 3 - 2 1
* Multiplication The ‘*’ operator multiplies two operands. 3 * 2 6
/ Division The ‘/’ operator divides the first operand by the second. 3 / 2 1
% Modulus The ‘%’ operator returns the remainder when first operand is divided by the second. 3 % 2 1

Sample

usr@host:go/ # cat l4s1.go
package main
import (
    "fmt"
)

func main(){
    var var1 int
    var var2 int

    var1 = 3
    var2 = 2

    fmt.Printf("%d   %d = %d\n", var1, var2 , var1   var2)
    fmt.Printf("%d - %d = %d\n", var1, var2 , var1 - var2)
    fmt.Printf("%d * %d = %d\n", var1, var2 , var1 * var2)
    fmt.Printf("%d / %d = %d\n", var1, var2 , var1 / var2)
    fmt.Printf("%d %% %d = %d\n", var1, var2 , var1 % var2)

}
usr@host:go/ # go run l4s1.go
3   2 = 5
3 - 2 = 1
3 * 2 = 6
3 / 2 = 1
3 % 2 = 1

Relational Operators

Operators

Operator Sense Description Sample Result
== Equal To Operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. 1 == 3 false
!= Not Equal To Operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. 1 != 3 true
> Greater Than Operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. 1 > 3 false
< Less Than Operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. 1 < 3 true
>= Greater Than Equal To Operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. 1 >= 3 false
<= Less Than Equal To Operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. 1 <= 3 true

Sample

usr@host:go/ # cat l4s2.go
package main
import (
    "fmt"
)

func main(){
    var var1 int
    var var2 int

    var1 = 1
    var2 = 3

    fmt.Printf("%t\n", var1 == var2)
    fmt.Printf("%t\n", var1 != var2)
    fmt.Printf("%t\n", var1 > var2)
    fmt.Printf("%t\n", var1 < var2)
    fmt.Printf("%t\n", var1 >= var2)
    fmt.Printf("%t\n", var1 <= var2)
}
usr@host:go/ # go run l4s2.go
false
true
false
true
false
true

Logical Operators

Operators

Operator Sense Description Sample Result
&& Logical AND The ‘&&’ operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. true && false false
|| Logical OR The ‘||’ operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. true || false true
! Logical NOT The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it returns false. !true false

Sample

usr@host:go/ # cat l4s3.go
package main
import (
    "fmt"
)

func main(){
    var flag1 bool = true
    var flag2 bool = false

    fmt.Printf("%t\n", flag1 && flag2)
    fmt.Printf("%t\n", flag1 || flag2)
    fmt.Printf("%t\n", !flag1)
}
usr@host:go/ # go run l4s3.go
false
true
false

Bitwise Operators

Operators

Operator Sense Description Sample Result
& bitwise AND Takes two numbers as operands and does AND on every bit of two numbers. 1 & 2 0
| bitwise OR Takes two numbers as operands and does OR on every bit of two numbers. 1 | 2 3
^ bitwise XOR Takes two numbers as operands and does XOR on every bit of two numbers. 1 ^ 2 3
<< left shift Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift. 1 << 2 4
>> right shift Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift. 1 >> 2 0
&^ AND NOT This is a bit clear operator. 1 &^ 2 1

Sample

usr@host:go/ # cat l4s4.go
package main
import (
    "fmt"
)

func main(){
    var var1 int = 1
    var var2 int = 2

    fmt.Printf("%d = %04b\n", var1, var1)
    fmt.Printf("%d = %04b\n", var2, var2)

    fmt.Printf("%d : %04b\n", var1 & var2, var1 & var2)
    fmt.Printf("%d : %04b\n", var1 | var2, var1 | var2)
    fmt.Printf("%d : %04b\n", var1 ^ var2, var1 ^ var2)
    fmt.Printf("%d : %04b\n", var1 << var2, var1 << var2)
    fmt.Printf("%d : %04b\n", var1 >> var2, var1 >> var2)
    fmt.Printf("%d : %04b\n", var1 &^ var2, var1 &^ var2)
}
usr@host:go/ # go run l4s4.go
1 = 0001
2 = 0010
0 : 0000
3 : 0011
3 : 0011
4 : 0100
0 : 0000
1 : 0001

Assignment Operators

Operators

Operator Sense Description Sample Result
= Simple Assignment This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. var1 = 1 1
= Add Assignment This operator is combination of ‘ ’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. 1 = 1 2
-= Subtract Assignment This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left. 2 -= 1 1
*= Multiply Assignment This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. 1 *= 2 2
/= Division Assignment This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. 2 /= 2 1
%= Modulus Assignment This operator is combination of ‘%’ and ‘=’ operators. This operator first modulo the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. 1 %= 2 1
&= Bitwise AND Assignment This operator is combination of ‘&’ and ‘=’ operators. This operator first “Bitwise AND” the current value of the variable on the left by the value on the right and then assigns the result to the variable on the left. 1 &= 2 0
|= Bitwise Inclusive OR This operator is combination of ‘|’ and ‘=’ operators. This operator first “Bitwise Inclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. 0 |= 2 2
^= Bitwise Exclusive OR This operator is combination of ‘ and ‘=’ operators. This operator first “Bitwise Exclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. 2 ^= 2 0
  • You can use ' ', '--', after the variable name, to quickly 1/-1;

Sample

usr@host:go/ # cat l4s5.go
package main
import (
    "fmt"
)

func main(){
    var var1 int
    fmt.Printf("%d\n", var1)

    var1 = 1
    fmt.Printf("%d\n", var1)

    var1  = 1
    fmt.Printf("%d\n", var1)

    var1 -= 1
    fmt.Printf("%d\n", var1)

    var1 *= 2
    fmt.Printf("%d\n", var1)

    var1 /= 2
    fmt.Printf("%d\n", var1)

    var1 %= 2
    fmt.Printf("%d\n", var1)

    var1 &= 2
    fmt.Printf("%d\n", var1)

    var1 |= 2
    fmt.Printf("%d\n", var1)

    var1 ^= 2
    fmt.Printf("%d\n", var1)
}
usr@host:go/ # go run l4s5.go
0
1
2
1
2
1
1
0
2
0

Misc Operators

Operators

Operator Sense Description
& Get Address This operator returns the address of the variable.
* Get Pointer's Value This operator provides pointer to a variable.
<- Receive a value from the channel The name of this operator is receive. It is used to receive a value from the channel.

Sample

usr@host:go/ # cat l4s6.go
package main
import (
    "fmt"
)

func main(){
    var var1 int = 0

    fmt.Printf("value : %d\n", *&var1)
    fmt.Printf("physical : %p\n", &var1)
}
usr@host:go/ # go run l4s6.go
value : 0
physical : 0xc0000180c0

Golang Basic 6 - Basic for loop

Golang Basic 6 - Basic for loop

for loop

  • Go has only one looping construct, the for loop.
  • The basic for loop has three components separated by semicolons:
    1. the init statement: executed before the first iteration.
    2. the condition expression: evaluated before every iteration.
    3. the post statement: executed at the end of every iteration.
  • The init statement will often be a short variable declaration, and the variables declared there are visible only in the scope of the for statement.
  • The loop will stop iterating once the boolean condition evaluates to false.
  • Note: Unlike other languages like C, Java, or JavaScript there are no parentheses surrounding the three components of the for statement and the braces { } are always required.

Basic usage 1

Statement

for boolVal{
    /*
        if boolVal is true, run this code block.
        will stop while boolVal is false.
    */
    
}

Sample

root@go:l6/ # cat l6s1.go
package main
import (
    "fmt"
)

func main(){
    var i int
    for i <= 3{
        fmt.Println(i)
        i   

    }
}
root@go:l6/ # go run l6s1.go
0
1
2
3

Basic usage 2

Statement

for initial; boolVal; repeat{
    /*
        if boolVal is true, run this code block.
        will stop while boolVal is false.
    */
    
}

Sample

root@go:l6/ # cat l6s2.go
package main
import (
    "fmt"
)

func main(){
    var i int
    for i = 1; i <= 3; i   {
        fmt.Println(i)

    }

}
root@go:l6/ # go run l6s2.go
1
2
3

Break

  • You can use break statement to break current loop.

Statement

for boolVal{
    /*
        if boolVal is true, run this code block.
        will stop while boolVal is false.
    */
    
    if flag {
        // if flag is true, break the for loop.
        break
    }
}

Sample

root@go:l6/ # cat l6s3.go
package main
import (
    "fmt"
)

func main(){
    var i int
    for i = 1; i <= 3; i  {
        fmt.Println(i)
        if i == 2{
            break
        }

    }

}
root@go:l6/ # go run l6s3.go
1
2

Continue

  • You can use continue, to pass current loop, continue running next loop.

Statement

for boolVal{
    /*
        if boolVal is true, run this code block.
        will stop while boolVal is false.
    */
    
    if flag {
        // if flag is true, break the for loop.
        continue
    }
    
    /*
        if the flag is effact, you can not see the result of statements here.
    */
}

Sample

root@go:l6/ # cat l6s4.go
package main
import (
    "fmt"
)

func main(){
    var i int
    for i = 1; i <= 3; i  {
        if i == 2{
            continue

        }

        fmt.Println(i)

    }

}
root@go:l6/ # go run l6s4.go
1
3

Golang Basic 5 - If statement

Golang Basic 5 - If statement

if

if statement

if boolVal{
    // if boolVal is true, run this code block.
}

Sample

root@go:l5/ # cat l5s1.go
package main
import (
    "fmt"
)

func main(){
    var flag bool = true

    if flag {
        fmt.Printf("%t\n", flag)
    }
}
root@go:l5/ # go run l5s1.go
true

if... else...

if... else... statement

if boolVal{
    // if boolVal is true, run this code block.    
}else{
    //if boolVal is false, run this code block.
}

Sample

root@go:l5/ # cat l5s2.go
package main
import (
    "fmt"
)

func main(){
    var flag bool = false

    if flag {
        fmt.Printf("%t\n", flag)

    }else{
        fmt.Printf("%t\n", flag)

    }
}
root@go:l5/ # go run l5s2.go
false

if... else if... else...

if... else if... else... statement

if boolVal1{
    // if boolVal1 is true, run this code block.
}else if boolVal2{
    // if boolVal2 is true, run this code block.
}else{
    //if boolVal1 and boolVal2 is false, run this code block.
}

Sample

root@go:l5/ # cat l5s3.go
package main
import (
    "fmt"
)

func main(){
    var flag1 bool = false
    var flag2 bool = true

    if flag1 {
        fmt.Printf("flag 1\n")
        fmt.Printf("%t\n", flag1)
        fmt.Printf("%t\n", flag2)

    }else if flag2 {
        fmt.Printf("flag 2\n")
        fmt.Printf("%t\n", flag1)
        fmt.Printf("%t\n", flag2)

    }else{
        fmt.Printf("else\n")
        fmt.Printf("%t\n", flag1)
        fmt.Printf("%t\n", flag2)

    }
}
root@go:l5/ # go run l5s3.go
flag 2
false
true

Golang Basic 3 - Basic I-O functions

Golang Basic 3 - Basic I/O functions

About fmt package

  • Package fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler.

Import package

import "fmt"

Functions in fmt

  • You can get more information from https://golang.org/pkg/fmt/#pkg-index.
    golang
    func Errorf(format string, a ...interface{}) error
    func Fprint(w io.Writer, a ...interface{}) (n int, err error)
    func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
    func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
    func Fscan(r io.Reader, a ...interface{}) (n int, err error)
    func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error)
    func Fscanln(r io.Reader, a ...interface{}) (n int, err error)
    func Print(a ...interface{}) (n int, err error)
    func Printf(format string, a ...interface{}) (n int, err error)
    func Println(a ...interface{}) (n int, err error)
    func Scan(a ...interface{}) (n int, err error)
    func Scanf(format string, a ...interface{}) (n int, err error)
    func Scanln(a ...interface{}) (n int, err error)
    func Sprint(a ...interface{}) string
    func Sprintf(format string, a ...interface{}) string
    func Sprintln(a ...interface{}) string
    func Sscan(str string, a ...interface{}) (n int, err error)
    func Sscanf(str string, format string, a ...interface{}) (n int, err error)
    func Sscanln(str string, a ...interface{}) (n int, err error)

Format string

General

Format Sense
%v The value in a default format when printing structs, the plus flag (% v) adds field names.
%#v A Go-syntax representation of the value.
%T A Go-syntax representation of the type of the value.
%% A literal percent sign; consumes no value.

Boolean

Format Sense
%t The word true or false.

Integer

Format Sense
%b base 2
%c the character represented by the corresponding Unicode code point
%d base 10
%o base 8
%O base 8 with 0o prefi
%q a single-quoted character literal safely escaped with Go syntax
%x base 16, with lower-case letters for a-f
%X base 16, with upper-case letters for A-F
%U Unicode format: U 1234; same as "U %04X"

Floating-point and complex constituents

Format Sense
%b decimalless scientific notation with exponent a power of two, in the manner of strconv.FormatFloat with the 'b' format
%e scientific notation
%E scientific notation
%f decimal point but no exponent
%F synonym for %f
%g %e for large exponents, %f otherwise
%G %E for large exponents, %F otherwise
%x hexadecimal notation (with decimal power of two exponent)
%X upper-case hexadecimal notation

String and slice of bytes

Format Sense
%s the uninterpreted bytes of the string or slice
%q a double-quoted string safely escaped with Go syntax
%x base 16, lower-case, two characters per byte
%X base 16, upper-case, two characters per byte

Slice

Format Sense
%p address of 0th element in base 16 notation, with leading 0x

Pointer

|Format|Sense|
|:-:|:-:|
|%p|base 16 notation, with leading 0x|
- The %b, %d, %o, %x and %X verbs also work with pointers, formatting the value exactly as if it were an integer.

Basic input function

Some functions could get input from console.

func Scan(a ...interface{}) (n int, err error)
func Scanln(a ...interface{}) (n int, err error)
  • If you need set string format, you can use Scanf().
  • Scanln() will add a end of line symbol at the end of the line.

Basic output function

Some functions could print on the console.

func Print(a ...interface{}) (n int, err error)
func Printf(format string, a ...interface{}) (n int, err error)
func Println(a ...interface{}) (n int, err error)
  • If you need set string format, you can use Printf().
  • Println() will add a end of line symbol at the end of the line.

Sample

usr@host:go/ # cat l3s1.go
package main
import (
    "fmt"
)

func main(){
    var var1 int
    var var2 int

    fmt.Print("Please input two values (split with blank) : ")
    fmt.Scanln(&var1, &var2)
    fmt.Printf("%d   %d = %d\n", var1, var2, var1   var2)
}
usr@host:go/ # go run l3s1.go
Please input two values (split with blank) : 3 6
3   6 = 9

Golang Basic 2 - Basic Data Types && Variable

Golang Basic 2 - Basic Data Types && Variable

Basic Data Types

  • int, eg. 0, 1, 2, 3.
  • float32, float64, eg. 3.14159.
  • string, eg. "Hello World".
  • bool, eg. true, false.
  • rune, eg. 'a', 'b'. (char, saved as int)

Variable

Declear variable

var VariableName DataType

Set value

VariableName = Value

Sample

usr@host:go/ # cat l2s1.go
package main

import (
    "fmt"
)

func main(){
    // declear variables
    var int_val int         // declear an int variable
    var float_val float64   // declear a float variable
    var string_val string   // declear a string variable
    var bool_val bool       // declear a bool variable
    var rune_val rune       // declear a rune variable

    // set value for variables
    int_val = 3
    float_val = 1.234
    string_val = "Hello"
    bool_val = true
    rune_val = 'A'

    // print them
    fmt.Println(int_val)
    fmt.Println(float_val)
    fmt.Println(string_val)
    fmt.Println(bool_val)
    fmt.Println(rune_val)

}
usr@host:go/ # go build l2s1.go
usr@host:go/ # ./l2s1
3
1.234
Hello
true
65

Declear && Set value at the same time

    var VariableName DataType = Value

Sample

usr@host:go/ # cat l2s2.go
package main

import (
    "fmt"
)

func main(){
    // declear and set variables
    var int_val int = 3
    var float_val float64 = 1.234
    var string_val string = "Hello"
    var bool_val bool = true
    var rune_val rune = 'A'

    // print them
    fmt.Println(int_val)
    fmt.Println(float_val)
    fmt.Println(string_val)
    fmt.Println(bool_val)
    fmt.Println(rune_val)

}
usr@host:go/ # go build l2s2.go
usr@host:go/ # ./l2s2
3
1.234
Hello
true
65

Change values in variable

usr@host:go/ # cat l2s3.go
package main

import (
    "fmt"
)

func main(){
    // declear and set variable
    var int_val int = 3

    // print them
    fmt.Println(int_val)

    // set new value for variable
    int_val = 5

    // print them
    fmt.Println(int_val)

}
usr@host:go/ # go build l2s3.go
usr@host:go/ # ./l2s3
3
5

Some errors

usr@host:go/ # cat l2s4.go
package main

import (
    "fmt"
)

func main(){
    // declear and set variable
    var int_val int = 3

    // print them
    fmt.Println(int_val)

    // set new value for variable
    int_val = "abc"

    // print them
    fmt.Println(int_val)

}
usr@host:go/ # go build l2s4.go
# command-line-arguments
./l2s4.go:15:15: cannot use "abc" (type string) as type int in assignment
  • The values we set for the variable must match the data type.

Golang Basic 1 - Install && Hello World

Golang Basic 1 - Install && Hello World

What is Golang

  • Official website: https://golang.org/
  • Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.

How to install

Comments

  • 3 way to write a comments in go program.
  • // this is a single line comment
    
  • /*
    this is a
        multi line
            comment
    */
    

Hello World

usr@host:go/ # cat hello.go
package main    // if you want to run this program
import "fmt"    // import some build in packages, fmt is a packag e for print something on the screen
func main(){    // the main function, the entry of the program
    fmt.Println("Hello world.!")    // call fmt.Println to print something on the screen
}
usr@host:go/ # go build hello.go    # build the program
usr@host:go/ # ./hello  # run it
Hello world.!

Resolve the word2vec installing error

1st time I try to install word2vec

root@dev:/# pip install word2vec
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting word2vec
 Downloading https://mirrors.aliyun.com/pypi/packages/ce/51/5e2782b204015c8aef0ac830297c2f2735143ec90f592b9b3b909bb89757/word2vec-0.10.2.tar.gz (60kB)
 100% |████████████████████████████████| 61kB 1.1MB/s
 Complete output from command python setup.py egg_info:
 Traceback (most recent call last):
 File "", line 1, in 
 File "/tmp/pip-install-rj7udqcw/word2vec/setup.py", line 4, in 
 from Cython.Build import cythonize
 ModuleNotFoundError: No module named 'Cython'
----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-rj7udqcw/word2vec/

resolve it

root@dev:/# pip install Cython
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting Cython
 Downloading https://mirrors.aliyun.com/pypi/packages/e1/fd/711507fa396064bf716493861d6955af45369d2c470548e34af20b79d4d4/Cython-0.29.6-cp36-cp36m-manylinux1_x86_64.whl (2.1MB)
 100% |████████████████████████████████| 2.1MB 58.3MB/s
Installing collected packages: Cython
Successfully installed Cython-0.29.6
root@dev:/# pip install word2vec
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting word2vec
 Downloading https://mirrors.aliyun.com/pypi/packages/ce/51/5e2782b204015c8aef0ac830297c2f2735143ec90f592b9b3b909bb89757/word2vec-0.10.2.tar.gz (60kB)
 100% |████████████████████████████████| 61kB 1.4MB/s
Requirement already satisfied: cython in /usr/local/lib/python3.6/dist-packages (from word2vec) (0.29.6)
Requirement already satisfied: numpy>=1.9.2 in /usr/local/lib/python3.6/dist-packages (from word2vec) (1.15.4)
Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from word2vec) (0.20.1)
Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from word2vec) (1.1.0)
Requirement already satisfied: six in /usr/lib/python3/dist-packages (from word2vec) (1.11.0)
Building wheels for collected packages: word2vec
 Building wheel for word2vec (setup.py) ... done
 Stored in directory: /root/.cache/pip/wheels/6c/41/28/8a47f03d8b1387e2360e13f9719847eb545d0daa5f65d44ef3
Successfully built word2vec
Installing collected packages: word2vec
Successfully installed word2vec-0.10.2

Tensorflow-lite Android Object Detect 初体验

写在开始

  • 在这篇文章中, 会手把手教你如何在你的电脑上将Tensorflow-lite Android Demo给跑起来, 希望会对那些需要在Android原生应用落地的童鞋有所帮助.

准备工作

  • 下载Android Studio(我直接下的最新的)

下载地址: https://developer.android.com/studio/

  • 从github上clone Tensorflow
➜ sample ✗ git clone https://github.com/tensorflow/tensorflow.git
Cloning into 'tensorflow'...
remote: Enumerating objects: 7, done.
remote: Counting objects: 100% (7/7), done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 479815 (delta 0), reused 6 (delta 0), pack-reused 479808
Receiving objects: 100% (479815/479815), 282.03 MiB | 7.41 MiB/s, done.
Resolving deltas: 100% (385210/385210), done.
Checking out files: 100% (13949/13949), done.

导入项目, 开干.!!

  • 打开Android Studio:
  • 先别导入项目, 直接点击Configure->SDK Manager:
  • 这里需要安装SDK和NDK(其实选择Android 9.0和NDK就可以了, 我这里有些包之前装的, 直接打勾, 点ok就好):
  • 安装好SDK和NDK之后, 点击Open an existing Android Studio Project:
  • 选择我们刚刚clone下来的项目中的tensorflow/tensorflow/lite/java/demo目录:
  • 然后需要等待一会, 导入项目会自动去下载一些依赖包, 过一会右下角会有如下提示, 点击 Add root:
  • 如果一直卡在这个界面, 请点击右边那个小叉叉关闭当前的process, 并点击左上角Preferences->Appearance & Behavior->System Settings->HTTP Proxy检查你的proxy配置:
  • 如果出现找不到toolchains的错误, 请手动下载NDK覆盖原NDK目录:
    错误:
    Gradle sync failed: No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
     Consult IDE log for more details (Help | Show Log) (1 m 7 s 18 ms)
    

解决方案:

  1. 到NDK官网下载对应平台的NDK (我直接下的最新的mac版本) https://developer.android.com/ndk/downloads/?hl=zh-cn
  2. 解压文件, 并拷贝至指定目录(这里以macos为例; Windows, Linux思路一致, 请自行google)
    ➜ ndk ✗ unzip android-ndk-r16b-darwin-x86_64.zip
    ➜ ndk ✗ rm -rvf ~/Library/Android/sdk/ndk-bundle
    ➜ ndk ✗ cp -rvf android-ndk-r16b ~/Library/Android/sdk/ndk-bundle
    

改为我们手动下载的NDK之后, 点击右上角的这个按钮, sync一下:

  • 然后等一会, 会跳出这个框框要更新Gradle Plugin, 点击Update:
  • 过一会, 发现右下角报了个这个错误:
Gradle sync failed: Could not find method jackOptions() for arguments [build_c83lec3ciu5xopt1opuwlj8q5$_run_closure1$_closure6$_closure11@1b729409] on DefaultConfig_Decorated{name=main, dimension=null, minSdkVersion=DefaultApiVersion{mApiLevel=21, mCodename='null'}, targetSdkVersion=DefaultApiVersion{mApiLevel=26, mCodename='null'}, renderscriptTargetApi=null, renderscriptSupportModeEnabled=null, renderscriptSupportModeBlasEnabled=null, renderscriptNdkModeEnabled=null, versionCode=1, versionName=1.0, applicationId=android.example.com.tflitecamerademo, testApplicationId=null, testInstrumentationRunner=null, testInstrumentationRunnerArguments={}, testHandleProfiling=null, testFunctionalTest=null, signingConfig=null, resConfig=null, mBuildConfigFields={}, mResValues={}, mProguardFiles=[], mConsumerProguardFiles=[], mManifestPlaceholders={}, mWearAppUnbundled=null} of type com.android.build.gradle.internal.dsl.DefaultConfig.
 Consult IDE log for more details (Help | Show Log) (40 s 747 ms)

别慌, 我们去build.gradle(Module:app)里面将这段内容注释掉就好了, 注意画圈圈的地方:

然后再点击这个小按钮:

  • 又是一小段等待时间, 然后会发现有两个提示, 不着急, 打勾的地方, 一个一个点:
  • 然后catch到另外一个错误:
Could not find com.android.tools.build:aapt2:3.2.1-4818971.
Searched in the following locations:
 file:/Users/Kyle/Library/Android/sdk/extras/m2repository/com/android/tools/build/aapt2/3.2.1-4818971/aapt2-3.2.1-4818971.pom
 file:/Users/Kyle/Library/Android/sdk/extras/m2repository/com/android/tools/build/aapt2/3.2.1-4818971/aapt2-3.2.1-4818971-osx.jar
 file:/Users/Kyle/Library/Android/sdk/extras/google/m2repository/com/android/tools/build/aapt2/3.2.1-4818971/aapt2-3.2.1-4818971.pom
 file:/Users/Kyle/Library/Android/sdk/extras/google/m2repository/com/android/tools/build/aapt2/3.2.1-4818971/aapt2-3.2.1-4818971-osx.jar
 file:/Users/Kyle/Library/Android/sdk/extras/android/m2repository/com/android/tools/build/aapt2/3.2.1-4818971/aapt2-3.2.1-4818971.pom
 file:/Users/Kyle/Library/Android/sdk/extras/android/m2repository/com/android/tools/build/aapt2/3.2.1-4818971/aapt2-3.2.1-4818971-osx.jar
 https://jcenter.bintray.com/com/android/tools/build/aapt2/3.2.1-4818971/aapt2-3.2.1-4818971.pom
 https://jcenter.bintray.com/com/android/tools/build/aapt2/3.2.1-4818971/aapt2-3.2.1-4818971-osx.jar
 https://google.bintray.com/tensorflow/com/android/tools/build/aapt2/3.2.1-4818971/aapt2-3.2.1-4818971.pom
 https://google.bintray.com/tensorflow/com/android/tools/build/aapt2/3.2.1-4818971/aapt2-3.2.1-4818971-osx.jar
Required by:
 project :app

别慌, 只是少了点东西, 淡定的打开build.gradle(Project:demo), 加上箭头指的这行. (注意标红的两个地方, 一个是文件名, 一个是增加的内容):

然后再点击这个小按钮:

  • 然后经过一小段时间的等待, 可以发现只剩下一个warning了:
  • 既然是警告, 说明代码还是可以正常运行的, 我们继续. 试试能不能编译成apk导出来在手机上安装测试:
  • 出现打包成功的提示, 点击标红的这里, 会自动打开apk所在文件夹:
  • 然后我们将其拷贝到手机上, 安装:
  • 欧了, 跑起来:

写在结束

  • 总体上来说, 坑还是有的, 但是如果用心爬的话, 还是可以爬出来, 这只是开始, 后续想要在Android上面直接跑模型, 还有很长的路要走, 大家共勉吧.