repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
yinqiwen/gsnova | common/netx/netx.go | DialTimeout | func DialTimeout(network string, addr string, timeout time.Duration) (net.Conn, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
conn, err := DialContext(ctx, network, addr)
cancel()
return conn, err
} | go | func DialTimeout(network string, addr string, timeout time.Duration) (net.Conn, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
conn, err := DialContext(ctx, network, addr)
cancel()
return conn, err
} | [
"func",
"DialTimeout",
"(",
"network",
"string",
",",
"addr",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"context",
".",
"Back... | // DialTimeout dials the given addr on the given net type using the configured
// dial function, timing out after the given timeout. | [
"DialTimeout",
"dials",
"the",
"given",
"addr",
"on",
"the",
"given",
"net",
"type",
"using",
"the",
"configured",
"dial",
"function",
"timing",
"out",
"after",
"the",
"given",
"timeout",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/netx/netx.go#L32-L37 | train |
yinqiwen/gsnova | common/netx/netx.go | DialContext | func DialContext(ctx context.Context, network string, addr string) (net.Conn, error) {
return dial.Load().(func(context.Context, string, string) (net.Conn, error))(ctx, network, addr)
} | go | func DialContext(ctx context.Context, network string, addr string) (net.Conn, error) {
return dial.Load().(func(context.Context, string, string) (net.Conn, error))(ctx, network, addr)
} | [
"func",
"DialContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"network",
"string",
",",
"addr",
"string",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"return",
"dial",
".",
"Load",
"(",
")",
".",
"(",
"func",
"(",
"context",
".",
"Co... | // DialContext dials the given addr on the given net type using the configured
// dial function, with the given context. | [
"DialContext",
"dials",
"the",
"given",
"addr",
"on",
"the",
"given",
"net",
"type",
"using",
"the",
"configured",
"dial",
"function",
"with",
"the",
"given",
"context",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/netx/netx.go#L49-L51 | train |
yinqiwen/gsnova | common/netx/netx.go | OverrideDial | func OverrideDial(dialFN func(ctx context.Context, net string, addr string) (net.Conn, error)) {
dial.Store(dialFN)
} | go | func OverrideDial(dialFN func(ctx context.Context, net string, addr string) (net.Conn, error)) {
dial.Store(dialFN)
} | [
"func",
"OverrideDial",
"(",
"dialFN",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"net",
"string",
",",
"addr",
"string",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
")",
"{",
"dial",
".",
"Store",
"(",
"dialFN",
")",
"\n",
"}"
] | // OverrideDial overrides the global dial function. | [
"OverrideDial",
"overrides",
"the",
"global",
"dial",
"function",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/netx/netx.go#L54-L56 | train |
yinqiwen/gsnova | common/netx/netx.go | Resolve | func Resolve(network string, addr string) (*net.TCPAddr, error) {
return resolveTCPAddr.Load().(func(string, string) (*net.TCPAddr, error))(network, addr)
} | go | func Resolve(network string, addr string) (*net.TCPAddr, error) {
return resolveTCPAddr.Load().(func(string, string) (*net.TCPAddr, error))(network, addr)
} | [
"func",
"Resolve",
"(",
"network",
"string",
",",
"addr",
"string",
")",
"(",
"*",
"net",
".",
"TCPAddr",
",",
"error",
")",
"{",
"return",
"resolveTCPAddr",
".",
"Load",
"(",
")",
".",
"(",
"func",
"(",
"string",
",",
"string",
")",
"(",
"*",
"net... | // Resolve resolves the given tcp address using the configured resolve function. | [
"Resolve",
"resolves",
"the",
"given",
"tcp",
"address",
"using",
"the",
"configured",
"resolve",
"function",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/netx/netx.go#L59-L61 | train |
yinqiwen/gsnova | common/netx/netx.go | OverrideResolve | func OverrideResolve(resolveFN func(net string, addr string) (*net.TCPAddr, error)) {
resolveTCPAddr.Store(resolveFN)
} | go | func OverrideResolve(resolveFN func(net string, addr string) (*net.TCPAddr, error)) {
resolveTCPAddr.Store(resolveFN)
} | [
"func",
"OverrideResolve",
"(",
"resolveFN",
"func",
"(",
"net",
"string",
",",
"addr",
"string",
")",
"(",
"*",
"net",
".",
"TCPAddr",
",",
"error",
")",
")",
"{",
"resolveTCPAddr",
".",
"Store",
"(",
"resolveFN",
")",
"\n",
"}"
] | // OverrideResolve overrides the global resolve function. | [
"OverrideResolve",
"overrides",
"the",
"global",
"resolve",
"function",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/netx/netx.go#L64-L66 | train |
yinqiwen/gsnova | common/channel/websocket/remote.go | WebsocketInvoke | func WebsocketInvoke(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
return
}
//logger.Info("req headers: %v", r.Header, r.R)
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
//log.WithField("err", err).Println("Upgrading to websockets")
http.Error(w, "Error Upgrading to websockets", 400)
return
}
session, err := pmux.Server(&mux.WsConn{Conn: ws}, channel.InitialPMuxConfig(&channel.DefaultServerCipher))
if nil != err {
return
}
muxSession := &mux.ProxyMuxSession{Session: session}
channel.ServProxyMuxSession(muxSession, nil, nil)
//ws.WriteMessage(websocket.CloseMessage, []byte{})
} | go | func WebsocketInvoke(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
return
}
//logger.Info("req headers: %v", r.Header, r.R)
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
//log.WithField("err", err).Println("Upgrading to websockets")
http.Error(w, "Error Upgrading to websockets", 400)
return
}
session, err := pmux.Server(&mux.WsConn{Conn: ws}, channel.InitialPMuxConfig(&channel.DefaultServerCipher))
if nil != err {
return
}
muxSession := &mux.ProxyMuxSession{Session: session}
channel.ServProxyMuxSession(muxSession, nil, nil)
//ws.WriteMessage(websocket.CloseMessage, []byte{})
} | [
"func",
"WebsocketInvoke",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"!=",
"\"",
"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"405",
")",
"\n",
"return"... | // handleWebsocket connection. Update to | [
"handleWebsocket",
"connection",
".",
"Update",
"to"
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/channel/websocket/remote.go#L20-L40 | train |
yinqiwen/gsnova | remote/web.go | indexCallback | func indexCallback(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, strings.Replace(html, "${Version}", channel.Version, -1))
} | go | func indexCallback(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, strings.Replace(html, "${Version}", channel.Version, -1))
} | [
"func",
"indexCallback",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"io",
".",
"WriteString",
"(",
"w",
",",
"strings",
".",
"Replace",
"(",
"html",
",",
"\"",
"\"",
",",
"channel",
".",
"Version",
","... | // hello world, the web server | [
"hello",
"world",
"the",
"web",
"server"
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/remote/web.go#L17-L19 | train |
yinqiwen/gsnova | local/gsnova/gsnova_unix.go | ProtectConnections | func ProtectConnections(dnsServer string, p SocketProtector) {
protector.Configure(p.Protect, dnsServer)
//p := New(protector.Protect, dnsServer)
netx.OverrideDial(protector.DialContext)
netx.OverrideResolve(protector.Resolve)
netx.OverrideListenUDP(protector.ListenUDP)
netx.OverrideDialUDP(protector.DialUDP)
} | go | func ProtectConnections(dnsServer string, p SocketProtector) {
protector.Configure(p.Protect, dnsServer)
//p := New(protector.Protect, dnsServer)
netx.OverrideDial(protector.DialContext)
netx.OverrideResolve(protector.Resolve)
netx.OverrideListenUDP(protector.ListenUDP)
netx.OverrideDialUDP(protector.DialUDP)
} | [
"func",
"ProtectConnections",
"(",
"dnsServer",
"string",
",",
"p",
"SocketProtector",
")",
"{",
"protector",
".",
"Configure",
"(",
"p",
".",
"Protect",
",",
"dnsServer",
")",
"\n",
"//p := New(protector.Protect, dnsServer)\r",
"netx",
".",
"OverrideDial",
"(",
"... | // ProtectConnections allows connections made by Lantern to be protected from
// routing via a VPN. This is useful when running Lantern as a VPN on Android,
// because it keeps Lantern's own connections from being captured by the VPN and
// resulting in an infinite loop. | [
"ProtectConnections",
"allows",
"connections",
"made",
"by",
"Lantern",
"to",
"be",
"protected",
"from",
"routing",
"via",
"a",
"VPN",
".",
"This",
"is",
"useful",
"when",
"running",
"Lantern",
"as",
"a",
"VPN",
"on",
"Android",
"because",
"it",
"keeps",
"La... | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/local/gsnova/gsnova_unix.go#L20-L27 | train |
yinqiwen/gsnova | local/gsnova/gsnova.go | SyncConfig | func SyncConfig(addr string, localDir string) (bool, error) {
return local.SyncConfig(addr, localDir)
} | go | func SyncConfig(addr string, localDir string) (bool, error) {
return local.SyncConfig(addr, localDir)
} | [
"func",
"SyncConfig",
"(",
"addr",
"string",
",",
"localDir",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"local",
".",
"SyncConfig",
"(",
"addr",
",",
"localDir",
")",
"\n",
"}"
] | //SyncConfig sync config files from running gsnova instance | [
"SyncConfig",
"sync",
"config",
"files",
"from",
"running",
"gsnova",
"instance"
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/local/gsnova/gsnova.go#L39-L41 | train |
yinqiwen/gsnova | common/protector/protected.go | cleanup | func (conn *ProtectedConnBase) cleanup() {
conn.mutex.Lock()
defer conn.mutex.Unlock()
if conn.socketFd != socketError {
//fmt.Printf("####Close %d\n", conn.socketFd)
syscall.Close(conn.socketFd)
conn.socketFd = socketError
}
} | go | func (conn *ProtectedConnBase) cleanup() {
conn.mutex.Lock()
defer conn.mutex.Unlock()
if conn.socketFd != socketError {
//fmt.Printf("####Close %d\n", conn.socketFd)
syscall.Close(conn.socketFd)
conn.socketFd = socketError
}
} | [
"func",
"(",
"conn",
"*",
"ProtectedConnBase",
")",
"cleanup",
"(",
")",
"{",
"conn",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"conn",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"conn",
".",
"socketFd",
"!=",
"socketError",
"{",
... | // cleanup is ran whenever we encounter a socket error
// we use a mutex since this connection is active in a variety
// of goroutines and to prevent any possible race conditions | [
"cleanup",
"is",
"ran",
"whenever",
"we",
"encounter",
"a",
"socket",
"error",
"we",
"use",
"a",
"mutex",
"since",
"this",
"connection",
"is",
"active",
"in",
"a",
"variety",
"of",
"goroutines",
"and",
"to",
"prevent",
"any",
"possible",
"race",
"conditions"... | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/protected.go#L90-L99 | train |
yinqiwen/gsnova | common/protector/protected.go | Resolve | func Resolve(network string, addr string) (*net.TCPAddr, error) {
host, port, err := SplitHostPort(addr)
if err != nil {
return nil, err
}
// Check if we already have the IP address
IPAddr := net.ParseIP(host)
if IPAddr != nil {
return &net.TCPAddr{IP: IPAddr, Port: port}, nil
}
// Create a datagram socket
socketFd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, 0)
if err != nil {
return nil, fmt.Errorf("Error creating socket: %v", err)
}
defer syscall.Close(socketFd)
// Here we protect the underlying socket from the
// VPN connection by passing the file descriptor
// back to Java for exclusion
err = currentProtect(socketFd)
if err != nil {
return nil, fmt.Errorf("Could not bind socket to system device: %v", err)
}
IPAddr = net.ParseIP(currentDnsServer)
if IPAddr == nil {
return nil, errors.New("invalid IP address")
}
var ip [4]byte
copy(ip[:], IPAddr.To4())
sockAddr := syscall.SockaddrInet4{Addr: ip, Port: dnsPort}
err = syscall.Connect(socketFd, &sockAddr)
if err != nil {
return nil, err
}
fd := uintptr(socketFd)
file := os.NewFile(fd, "")
defer file.Close()
// return a copy of the network connection
// represented by file
fileConn, err := net.FileConn(file)
if err != nil {
log.Printf("Error returning a copy of the network connection: %v", err)
return nil, err
}
setQueryTimeouts(fileConn)
//log.Printf("performing dns lookup...!!")
result, err := DnsLookup(host, fileConn)
if err != nil {
log.Printf("Error doing DNS resolution: %v", err)
return nil, err
}
ipAddr, err := result.PickRandomIP()
if err != nil {
log.Printf("No IP address available: %v", err)
return nil, err
}
return &net.TCPAddr{IP: ipAddr, Port: port}, nil
} | go | func Resolve(network string, addr string) (*net.TCPAddr, error) {
host, port, err := SplitHostPort(addr)
if err != nil {
return nil, err
}
// Check if we already have the IP address
IPAddr := net.ParseIP(host)
if IPAddr != nil {
return &net.TCPAddr{IP: IPAddr, Port: port}, nil
}
// Create a datagram socket
socketFd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, 0)
if err != nil {
return nil, fmt.Errorf("Error creating socket: %v", err)
}
defer syscall.Close(socketFd)
// Here we protect the underlying socket from the
// VPN connection by passing the file descriptor
// back to Java for exclusion
err = currentProtect(socketFd)
if err != nil {
return nil, fmt.Errorf("Could not bind socket to system device: %v", err)
}
IPAddr = net.ParseIP(currentDnsServer)
if IPAddr == nil {
return nil, errors.New("invalid IP address")
}
var ip [4]byte
copy(ip[:], IPAddr.To4())
sockAddr := syscall.SockaddrInet4{Addr: ip, Port: dnsPort}
err = syscall.Connect(socketFd, &sockAddr)
if err != nil {
return nil, err
}
fd := uintptr(socketFd)
file := os.NewFile(fd, "")
defer file.Close()
// return a copy of the network connection
// represented by file
fileConn, err := net.FileConn(file)
if err != nil {
log.Printf("Error returning a copy of the network connection: %v", err)
return nil, err
}
setQueryTimeouts(fileConn)
//log.Printf("performing dns lookup...!!")
result, err := DnsLookup(host, fileConn)
if err != nil {
log.Printf("Error doing DNS resolution: %v", err)
return nil, err
}
ipAddr, err := result.PickRandomIP()
if err != nil {
log.Printf("No IP address available: %v", err)
return nil, err
}
return &net.TCPAddr{IP: ipAddr, Port: port}, nil
} | [
"func",
"Resolve",
"(",
"network",
"string",
",",
"addr",
"string",
")",
"(",
"*",
"net",
".",
"TCPAddr",
",",
"error",
")",
"{",
"host",
",",
"port",
",",
"err",
":=",
"SplitHostPort",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return... | // Resolve resolves the given address using a DNS lookup on a UDP socket
// protected by the currnet Protector. | [
"Resolve",
"resolves",
"the",
"given",
"address",
"using",
"a",
"DNS",
"lookup",
"on",
"a",
"UDP",
"socket",
"protected",
"by",
"the",
"currnet",
"Protector",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/protected.go#L191-L257 | train |
yinqiwen/gsnova | common/protector/protected.go | Close | func (conn *ProtectedConn) Close() (err error) {
conn.mutex.Lock()
defer conn.mutex.Unlock()
if !conn.isClosed {
conn.isClosed = true
if conn.Conn == nil {
if conn.socketFd == socketError {
err = nil
} else {
err = syscall.Close(conn.socketFd)
// update socket fd to socketError
// to make it explicit this connection
// has been closed
conn.socketFd = socketError
}
} else {
err = conn.Conn.Close()
}
}
return err
} | go | func (conn *ProtectedConn) Close() (err error) {
conn.mutex.Lock()
defer conn.mutex.Unlock()
if !conn.isClosed {
conn.isClosed = true
if conn.Conn == nil {
if conn.socketFd == socketError {
err = nil
} else {
err = syscall.Close(conn.socketFd)
// update socket fd to socketError
// to make it explicit this connection
// has been closed
conn.socketFd = socketError
}
} else {
err = conn.Conn.Close()
}
}
return err
} | [
"func",
"(",
"conn",
"*",
"ProtectedConn",
")",
"Close",
"(",
")",
"(",
"err",
"error",
")",
"{",
"conn",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"conn",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"conn",
".",
"isClosed... | // Close is used to destroy a protected connection | [
"Close",
"is",
"used",
"to",
"destroy",
"a",
"protected",
"connection"
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/protected.go#L490-L511 | train |
yinqiwen/gsnova | common/protector/protected.go | setQueryTimeouts | func setQueryTimeouts(c net.Conn) {
now := time.Now()
c.SetReadDeadline(now.Add(readDeadline))
c.SetWriteDeadline(now.Add(writeDeadline))
} | go | func setQueryTimeouts(c net.Conn) {
now := time.Now()
c.SetReadDeadline(now.Add(readDeadline))
c.SetWriteDeadline(now.Add(writeDeadline))
} | [
"func",
"setQueryTimeouts",
"(",
"c",
"net",
".",
"Conn",
")",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"c",
".",
"SetReadDeadline",
"(",
"now",
".",
"Add",
"(",
"readDeadline",
")",
")",
"\n",
"c",
".",
"SetWriteDeadline",
"(",
"now",
... | // configure DNS query expiration | [
"configure",
"DNS",
"query",
"expiration"
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/protected.go#L514-L518 | train |
yinqiwen/gsnova | common/protector/protected.go | SplitHostPort | func SplitHostPort(addr string) (string, int, error) {
host, sPort, err := net.SplitHostPort(addr)
if err != nil {
log.Printf("Could not split network address: %v", err)
return "", 0, err
}
port, err := strconv.Atoi(sPort)
if err != nil {
log.Printf("No port number found %v", err)
return "", 0, err
}
return host, port, nil
} | go | func SplitHostPort(addr string) (string, int, error) {
host, sPort, err := net.SplitHostPort(addr)
if err != nil {
log.Printf("Could not split network address: %v", err)
return "", 0, err
}
port, err := strconv.Atoi(sPort)
if err != nil {
log.Printf("No port number found %v", err)
return "", 0, err
}
return host, port, nil
} | [
"func",
"SplitHostPort",
"(",
"addr",
"string",
")",
"(",
"string",
",",
"int",
",",
"error",
")",
"{",
"host",
",",
"sPort",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf"... | // wrapper around net.SplitHostPort that also converts
// uses strconv to convert the port to an int | [
"wrapper",
"around",
"net",
".",
"SplitHostPort",
"that",
"also",
"converts",
"uses",
"strconv",
"to",
"convert",
"the",
"port",
"to",
"an",
"int"
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/protected.go#L522-L534 | train |
yinqiwen/gsnova | common/socks/socks.go | Reject | func (conn *SocksConn) Reject() error {
if conn.socksVersion == socks4Version {
return sendSocks4aResponseRejected(conn)
}
return sendSocks5ResponseRejected(conn, SocksRepGeneralFailure)
} | go | func (conn *SocksConn) Reject() error {
if conn.socksVersion == socks4Version {
return sendSocks4aResponseRejected(conn)
}
return sendSocks5ResponseRejected(conn, SocksRepGeneralFailure)
} | [
"func",
"(",
"conn",
"*",
"SocksConn",
")",
"Reject",
"(",
")",
"error",
"{",
"if",
"conn",
".",
"socksVersion",
"==",
"socks4Version",
"{",
"return",
"sendSocks4aResponseRejected",
"(",
"conn",
")",
"\n",
"}",
"\n",
"return",
"sendSocks5ResponseRejected",
"("... | // Send a message to the proxy client that access was rejected or failed. This
// sends back a "General Failure" error code. RejectReason should be used if
// more specific error reporting is desired. | [
"Send",
"a",
"message",
"to",
"the",
"proxy",
"client",
"that",
"access",
"was",
"rejected",
"or",
"failed",
".",
"This",
"sends",
"back",
"a",
"General",
"Failure",
"error",
"code",
".",
"RejectReason",
"should",
"be",
"used",
"if",
"more",
"specific",
"e... | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L102-L107 | train |
yinqiwen/gsnova | common/socks/socks.go | RejectReason | func (conn *SocksConn) RejectReason(reason byte) error {
if conn.socksVersion == socks4Version {
return sendSocks4aResponseRejected(conn)
}
return sendSocks5ResponseRejected(conn, reason)
} | go | func (conn *SocksConn) RejectReason(reason byte) error {
if conn.socksVersion == socks4Version {
return sendSocks4aResponseRejected(conn)
}
return sendSocks5ResponseRejected(conn, reason)
} | [
"func",
"(",
"conn",
"*",
"SocksConn",
")",
"RejectReason",
"(",
"reason",
"byte",
")",
"error",
"{",
"if",
"conn",
".",
"socksVersion",
"==",
"socks4Version",
"{",
"return",
"sendSocks4aResponseRejected",
"(",
"conn",
")",
"\n",
"}",
"\n",
"return",
"sendSo... | // Send a message to the proxy client that access was rejected, with the
// specific error code indicating the reason behind the rejection.
// For SOCKS4a, the reason is ignored. | [
"Send",
"a",
"message",
"to",
"the",
"proxy",
"client",
"that",
"access",
"was",
"rejected",
"with",
"the",
"specific",
"error",
"code",
"indicating",
"the",
"reason",
"behind",
"the",
"rejection",
".",
"For",
"SOCKS4a",
"the",
"reason",
"is",
"ignored",
"."... | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L112-L117 | train |
yinqiwen/gsnova | common/socks/socks.go | ListenSocks | func ListenSocks(network, laddr string) (*SocksListener, error) {
ln, err := net.Listen(network, laddr)
if err != nil {
return nil, err
}
return NewSocksListener(ln), nil
} | go | func ListenSocks(network, laddr string) (*SocksListener, error) {
ln, err := net.Listen(network, laddr)
if err != nil {
return nil, err
}
return NewSocksListener(ln), nil
} | [
"func",
"ListenSocks",
"(",
"network",
",",
"laddr",
"string",
")",
"(",
"*",
"SocksListener",
",",
"error",
")",
"{",
"ln",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"network",
",",
"laddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"... | // Open a net.Listener according to network and laddr, and return it as a
// SocksListener. | [
"Open",
"a",
"net",
".",
"Listener",
"according",
"to",
"network",
"and",
"laddr",
"and",
"return",
"it",
"as",
"a",
"SocksListener",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L158-L164 | train |
yinqiwen/gsnova | common/socks/socks.go | socks5Handshake | func socks5Handshake(rw *bufio.ReadWriter) (req SocksRequest, err error) {
// Negotiate the authentication method.
var method byte
if method, err = socks5NegotiateAuth(rw); err != nil {
return
}
// Authenticate the client.
if err = socks5Authenticate(rw, method, &req); err != nil {
return
}
// Read the command.
err = socks5ReadCommand(rw, &req)
return
} | go | func socks5Handshake(rw *bufio.ReadWriter) (req SocksRequest, err error) {
// Negotiate the authentication method.
var method byte
if method, err = socks5NegotiateAuth(rw); err != nil {
return
}
// Authenticate the client.
if err = socks5Authenticate(rw, method, &req); err != nil {
return
}
// Read the command.
err = socks5ReadCommand(rw, &req)
return
} | [
"func",
"socks5Handshake",
"(",
"rw",
"*",
"bufio",
".",
"ReadWriter",
")",
"(",
"req",
"SocksRequest",
",",
"err",
"error",
")",
"{",
"// Negotiate the authentication method.",
"var",
"method",
"byte",
"\n",
"if",
"method",
",",
"err",
"=",
"socks5NegotiateAuth... | // socks5handshake conducts the SOCKS5 handshake up to the point where the
// client command is read and the proxy must open the outgoing connection.
// Returns a SocksRequest. | [
"socks5handshake",
"conducts",
"the",
"SOCKS5",
"handshake",
"up",
"to",
"the",
"point",
"where",
"the",
"client",
"command",
"is",
"read",
"and",
"the",
"proxy",
"must",
"open",
"the",
"outgoing",
"connection",
".",
"Returns",
"a",
"SocksRequest",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L294-L309 | train |
yinqiwen/gsnova | common/socks/socks.go | socks5NegotiateAuth | func socks5NegotiateAuth(rw *bufio.ReadWriter) (method byte, err error) {
// Validate the version.
if err = socksReadByteVerify(rw.Reader, "version", socks5Version); err != nil {
err = newTemporaryNetError("socks5NegotiateAuth: %s", err.Error())
return
}
// Read the number of methods.
var nmethods byte
if nmethods, err = socksReadByte(rw.Reader); err != nil {
err = newTemporaryNetError("socks5NegotiateAuth: Failed to read nmethods byte: %s", err.Error())
return
}
// Read the methods.
var methods []byte
if methods, err = socksReadBytes(rw.Reader, int(nmethods)); err != nil {
err = newTemporaryNetError("socks5NegotiateAuth: Failed to read methods bytes: %s", err.Error())
return
}
// Pick the most "suitable" method.
method = socksAuthNoAcceptableMethods
for _, m := range methods {
switch m {
case socksAuthNoneRequired:
// Pick Username/Password over None if the client happens to
// send both.
if method == socksAuthNoAcceptableMethods {
method = m
}
case socksAuthUsernamePassword:
method = m
}
}
// Send the negotiated method.
var msg [2]byte
msg[0] = socks5Version
msg[1] = method
if _, err = rw.Writer.Write(msg[:]); err != nil {
err = newTemporaryNetError("socks5NegotiateAuth: Failed to write negotiated method: %s", err.Error())
return
}
if err = socksFlushBuffers(rw); err != nil {
err = newTemporaryNetError("socks5NegotiateAuth: Failed to flush buffers: %s", err.Error())
return
}
return
} | go | func socks5NegotiateAuth(rw *bufio.ReadWriter) (method byte, err error) {
// Validate the version.
if err = socksReadByteVerify(rw.Reader, "version", socks5Version); err != nil {
err = newTemporaryNetError("socks5NegotiateAuth: %s", err.Error())
return
}
// Read the number of methods.
var nmethods byte
if nmethods, err = socksReadByte(rw.Reader); err != nil {
err = newTemporaryNetError("socks5NegotiateAuth: Failed to read nmethods byte: %s", err.Error())
return
}
// Read the methods.
var methods []byte
if methods, err = socksReadBytes(rw.Reader, int(nmethods)); err != nil {
err = newTemporaryNetError("socks5NegotiateAuth: Failed to read methods bytes: %s", err.Error())
return
}
// Pick the most "suitable" method.
method = socksAuthNoAcceptableMethods
for _, m := range methods {
switch m {
case socksAuthNoneRequired:
// Pick Username/Password over None if the client happens to
// send both.
if method == socksAuthNoAcceptableMethods {
method = m
}
case socksAuthUsernamePassword:
method = m
}
}
// Send the negotiated method.
var msg [2]byte
msg[0] = socks5Version
msg[1] = method
if _, err = rw.Writer.Write(msg[:]); err != nil {
err = newTemporaryNetError("socks5NegotiateAuth: Failed to write negotiated method: %s", err.Error())
return
}
if err = socksFlushBuffers(rw); err != nil {
err = newTemporaryNetError("socks5NegotiateAuth: Failed to flush buffers: %s", err.Error())
return
}
return
} | [
"func",
"socks5NegotiateAuth",
"(",
"rw",
"*",
"bufio",
".",
"ReadWriter",
")",
"(",
"method",
"byte",
",",
"err",
"error",
")",
"{",
"// Validate the version.",
"if",
"err",
"=",
"socksReadByteVerify",
"(",
"rw",
".",
"Reader",
",",
"\"",
"\"",
",",
"sock... | // socks5NegotiateAuth negotiates the authentication method and returns the
// selected method as a byte. On negotiation failures an error is returned. | [
"socks5NegotiateAuth",
"negotiates",
"the",
"authentication",
"method",
"and",
"returns",
"the",
"selected",
"method",
"as",
"a",
"byte",
".",
"On",
"negotiation",
"failures",
"an",
"error",
"is",
"returned",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L313-L364 | train |
yinqiwen/gsnova | common/socks/socks.go | socks5Authenticate | func socks5Authenticate(rw *bufio.ReadWriter, method byte, req *SocksRequest) (err error) {
switch method {
case socksAuthNoneRequired:
// Straight into reading the connect.
case socksAuthUsernamePassword:
if err = socks5AuthRFC1929(rw, req); err != nil {
return
}
case socksAuthNoAcceptableMethods:
err = newTemporaryNetError("socks5Authenticate: SOCKS method select had no compatible methods")
return
default:
err = newTemporaryNetError("socks5Authenticate: SOCKS method select picked a unsupported method 0x%02x", method)
return
}
if err = socksFlushBuffers(rw); err != nil {
err = newTemporaryNetError("socks5Authenticate: Failed to flush buffers: %s", err)
return
}
return
} | go | func socks5Authenticate(rw *bufio.ReadWriter, method byte, req *SocksRequest) (err error) {
switch method {
case socksAuthNoneRequired:
// Straight into reading the connect.
case socksAuthUsernamePassword:
if err = socks5AuthRFC1929(rw, req); err != nil {
return
}
case socksAuthNoAcceptableMethods:
err = newTemporaryNetError("socks5Authenticate: SOCKS method select had no compatible methods")
return
default:
err = newTemporaryNetError("socks5Authenticate: SOCKS method select picked a unsupported method 0x%02x", method)
return
}
if err = socksFlushBuffers(rw); err != nil {
err = newTemporaryNetError("socks5Authenticate: Failed to flush buffers: %s", err)
return
}
return
} | [
"func",
"socks5Authenticate",
"(",
"rw",
"*",
"bufio",
".",
"ReadWriter",
",",
"method",
"byte",
",",
"req",
"*",
"SocksRequest",
")",
"(",
"err",
"error",
")",
"{",
"switch",
"method",
"{",
"case",
"socksAuthNoneRequired",
":",
"// Straight into reading the con... | // socks5Authenticate authenticates the client via the chosen authentication
// mechanism. | [
"socks5Authenticate",
"authenticates",
"the",
"client",
"via",
"the",
"chosen",
"authentication",
"mechanism",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L368-L392 | train |
yinqiwen/gsnova | common/socks/socks.go | sendSocks5ResponseRejected | func sendSocks5ResponseRejected(w io.Writer, reason byte) error {
return sendSocks5Response(w, reason)
} | go | func sendSocks5ResponseRejected(w io.Writer, reason byte) error {
return sendSocks5Response(w, reason)
} | [
"func",
"sendSocks5ResponseRejected",
"(",
"w",
"io",
".",
"Writer",
",",
"reason",
"byte",
")",
"error",
"{",
"return",
"sendSocks5Response",
"(",
"w",
",",
"reason",
")",
"\n",
"}"
] | // Send a SOCKS5 response with the provided failure reason. | [
"Send",
"a",
"SOCKS5",
"response",
"with",
"the",
"provided",
"failure",
"reason",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L590-L592 | train |
yinqiwen/gsnova | common/socks/socks.go | sendSocks4aResponse | func sendSocks4aResponse(w io.Writer, code byte, addr *net.TCPAddr) error {
var resp [8]byte
resp[0] = socks4ResponseVersion
resp[1] = code
resp[2] = byte((addr.Port >> 8) & 0xff)
resp[3] = byte((addr.Port >> 0) & 0xff)
ipv4 := addr.IP.To4()
if ipv4 != nil {
resp[4] = ipv4[0]
resp[5] = ipv4[1]
resp[6] = ipv4[2]
resp[7] = ipv4[3]
}
if _, err := w.Write(resp[:]); err != nil {
err = newTemporaryNetError("sendSocks4aResponse: Failed to write response: %s", err.Error())
return err
}
return nil
} | go | func sendSocks4aResponse(w io.Writer, code byte, addr *net.TCPAddr) error {
var resp [8]byte
resp[0] = socks4ResponseVersion
resp[1] = code
resp[2] = byte((addr.Port >> 8) & 0xff)
resp[3] = byte((addr.Port >> 0) & 0xff)
ipv4 := addr.IP.To4()
if ipv4 != nil {
resp[4] = ipv4[0]
resp[5] = ipv4[1]
resp[6] = ipv4[2]
resp[7] = ipv4[3]
}
if _, err := w.Write(resp[:]); err != nil {
err = newTemporaryNetError("sendSocks4aResponse: Failed to write response: %s", err.Error())
return err
}
return nil
} | [
"func",
"sendSocks4aResponse",
"(",
"w",
"io",
".",
"Writer",
",",
"code",
"byte",
",",
"addr",
"*",
"net",
".",
"TCPAddr",
")",
"error",
"{",
"var",
"resp",
"[",
"8",
"]",
"byte",
"\n",
"resp",
"[",
"0",
"]",
"=",
"socks4ResponseVersion",
"\n",
"res... | // Send a SOCKS4a response with the given code and address. If the IP field
// inside addr is not an IPv4 address, the IP portion of the response will be
// four zero bytes. | [
"Send",
"a",
"SOCKS4a",
"response",
"with",
"the",
"given",
"code",
"and",
"address",
".",
"If",
"the",
"IP",
"field",
"inside",
"addr",
"is",
"not",
"an",
"IPv4",
"address",
"the",
"IP",
"portion",
"of",
"the",
"response",
"will",
"be",
"four",
"zero",
... | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L756-L776 | train |
yinqiwen/gsnova | common/socks/socks.go | sendSocks4aResponseGranted | func sendSocks4aResponseGranted(w io.Writer, addr *net.TCPAddr) error {
return sendSocks4aResponse(w, socks4RequestGranted, addr)
} | go | func sendSocks4aResponseGranted(w io.Writer, addr *net.TCPAddr) error {
return sendSocks4aResponse(w, socks4RequestGranted, addr)
} | [
"func",
"sendSocks4aResponseGranted",
"(",
"w",
"io",
".",
"Writer",
",",
"addr",
"*",
"net",
".",
"TCPAddr",
")",
"error",
"{",
"return",
"sendSocks4aResponse",
"(",
"w",
",",
"socks4RequestGranted",
",",
"addr",
")",
"\n",
"}"
] | // Send a SOCKS4a response code 0x5a. | [
"Send",
"a",
"SOCKS4a",
"response",
"code",
"0x5a",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L779-L781 | train |
yinqiwen/gsnova | common/socks/args.go | Get | func (args Args) Get(key string) (value string, ok bool) {
if args == nil {
return "", false
}
vals, ok := args[key]
if !ok || len(vals) == 0 {
return "", false
}
return vals[0], true
} | go | func (args Args) Get(key string) (value string, ok bool) {
if args == nil {
return "", false
}
vals, ok := args[key]
if !ok || len(vals) == 0 {
return "", false
}
return vals[0], true
} | [
"func",
"(",
"args",
"Args",
")",
"Get",
"(",
"key",
"string",
")",
"(",
"value",
"string",
",",
"ok",
"bool",
")",
"{",
"if",
"args",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}",
"\n",
"vals",
",",
"ok",
":=",
"args",
"[",
... | // Get the first value associated with the given key. If there are any values
// associated with the key, the value return has the value and ok is set to
// true. If there are no values for the given key, value is "" and ok is false.
// If you need access to multiple values, use the map directly. | [
"Get",
"the",
"first",
"value",
"associated",
"with",
"the",
"given",
"key",
".",
"If",
"there",
"are",
"any",
"values",
"associated",
"with",
"the",
"key",
"the",
"value",
"return",
"has",
"the",
"value",
"and",
"ok",
"is",
"set",
"to",
"true",
".",
"... | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/args.go#L19-L28 | train |
yinqiwen/gsnova | common/socks/args.go | Add | func (args Args) Add(key, value string) {
args[key] = append(args[key], value)
} | go | func (args Args) Add(key, value string) {
args[key] = append(args[key], value)
} | [
"func",
"(",
"args",
"Args",
")",
"Add",
"(",
"key",
",",
"value",
"string",
")",
"{",
"args",
"[",
"key",
"]",
"=",
"append",
"(",
"args",
"[",
"key",
"]",
",",
"value",
")",
"\n",
"}"
] | // Append value to the list of values for key. | [
"Append",
"value",
"to",
"the",
"list",
"of",
"values",
"for",
"key",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/args.go#L31-L33 | train |
yinqiwen/gsnova | common/socks/args.go | indexUnescaped | func indexUnescaped(s string, term []byte) (int, string, error) {
var i int
unesc := make([]byte, 0)
for i = 0; i < len(s); i++ {
b := s[i]
// A terminator byte?
if bytes.IndexByte(term, b) != -1 {
break
}
if b == '\\' {
i++
if i >= len(s) {
return 0, "", fmt.Errorf("nothing following final escape in %q", s)
}
b = s[i]
}
unesc = append(unesc, b)
}
return i, string(unesc), nil
} | go | func indexUnescaped(s string, term []byte) (int, string, error) {
var i int
unesc := make([]byte, 0)
for i = 0; i < len(s); i++ {
b := s[i]
// A terminator byte?
if bytes.IndexByte(term, b) != -1 {
break
}
if b == '\\' {
i++
if i >= len(s) {
return 0, "", fmt.Errorf("nothing following final escape in %q", s)
}
b = s[i]
}
unesc = append(unesc, b)
}
return i, string(unesc), nil
} | [
"func",
"indexUnescaped",
"(",
"s",
"string",
",",
"term",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"string",
",",
"error",
")",
"{",
"var",
"i",
"int",
"\n",
"unesc",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
")",
"\n",
"for",
"i",
"=",
... | // Return the index of the next unescaped byte in s that is in the term set, or
// else the length of the string if no terminators appear. Additionally return
// the unescaped string up to the returned index. | [
"Return",
"the",
"index",
"of",
"the",
"next",
"unescaped",
"byte",
"in",
"s",
"that",
"is",
"in",
"the",
"term",
"set",
"or",
"else",
"the",
"length",
"of",
"the",
"string",
"if",
"no",
"terminators",
"appear",
".",
"Additionally",
"return",
"the",
"une... | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/args.go#L38-L57 | train |
yinqiwen/gsnova | common/socks/args.go | backslashEscape | func backslashEscape(s string, set []byte) string {
var buf bytes.Buffer
for _, b := range []byte(s) {
if b == '\\' || bytes.IndexByte(set, b) != -1 {
buf.WriteByte('\\')
}
buf.WriteByte(b)
}
return buf.String()
} | go | func backslashEscape(s string, set []byte) string {
var buf bytes.Buffer
for _, b := range []byte(s) {
if b == '\\' || bytes.IndexByte(set, b) != -1 {
buf.WriteByte('\\')
}
buf.WriteByte(b)
}
return buf.String()
} | [
"func",
"backslashEscape",
"(",
"s",
"string",
",",
"set",
"[",
"]",
"byte",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"[",
"]",
"byte",
"(",
"s",
")",
"{",
"if",
"b",
"==",
"'\\\\'",
"... | // Escape backslashes and all the bytes that are in set. | [
"Escape",
"backslashes",
"and",
"all",
"the",
"bytes",
"that",
"are",
"in",
"set",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/args.go#L180-L189 | train |
thoas/stats | options.go | StatusCode | func (o Options) StatusCode() int {
if o.recorder != nil {
return o.recorder.Status()
}
return *o.statusCode
} | go | func (o Options) StatusCode() int {
if o.recorder != nil {
return o.recorder.Status()
}
return *o.statusCode
} | [
"func",
"(",
"o",
"Options",
")",
"StatusCode",
"(",
")",
"int",
"{",
"if",
"o",
".",
"recorder",
"!=",
"nil",
"{",
"return",
"o",
".",
"recorder",
".",
"Status",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"*",
"o",
".",
"statusCode",
"\n",
"}"
] | // StatusCode returns the response status code. | [
"StatusCode",
"returns",
"the",
"response",
"status",
"code",
"."
] | 965cb2de1678b040aefd01c448e2f10de3aec2ae | https://github.com/thoas/stats/blob/965cb2de1678b040aefd01c448e2f10de3aec2ae/options.go#L11-L17 | train |
thoas/stats | options.go | Size | func (o Options) Size() int {
if o.recorder != nil {
return o.recorder.Size()
}
return o.size
} | go | func (o Options) Size() int {
if o.recorder != nil {
return o.recorder.Size()
}
return o.size
} | [
"func",
"(",
"o",
"Options",
")",
"Size",
"(",
")",
"int",
"{",
"if",
"o",
".",
"recorder",
"!=",
"nil",
"{",
"return",
"o",
".",
"recorder",
".",
"Size",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"o",
".",
"size",
"\n",
"}"
] | // Size returns the response size. | [
"Size",
"returns",
"the",
"response",
"size",
"."
] | 965cb2de1678b040aefd01c448e2f10de3aec2ae | https://github.com/thoas/stats/blob/965cb2de1678b040aefd01c448e2f10de3aec2ae/options.go#L20-L26 | train |
thoas/stats | options.go | newOptions | func newOptions(options ...Option) *Options {
opts := &Options{}
for _, o := range options {
o(opts)
}
return opts
} | go | func newOptions(options ...Option) *Options {
opts := &Options{}
for _, o := range options {
o(opts)
}
return opts
} | [
"func",
"newOptions",
"(",
"options",
"...",
"Option",
")",
"*",
"Options",
"{",
"opts",
":=",
"&",
"Options",
"{",
"}",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"options",
"{",
"o",
"(",
"opts",
")",
"\n",
"}",
"\n",
"return",
"opts",
"\n",
"}... | // newOptions takes functional options and returns options. | [
"newOptions",
"takes",
"functional",
"options",
"and",
"returns",
"options",
"."
] | 965cb2de1678b040aefd01c448e2f10de3aec2ae | https://github.com/thoas/stats/blob/965cb2de1678b040aefd01c448e2f10de3aec2ae/options.go#L53-L59 | train |
thoas/stats | stats.go | New | func New() *Stats {
name, _ := os.Hostname()
stats := &Stats{
closed: make(chan struct{}, 1),
Uptime: time.Now(),
Pid: os.Getpid(),
ResponseCounts: map[string]int{},
TotalResponseCounts: map[string]int{},
TotalResponseTime: time.Time{},
Hostname: name,
}
go func() {
for {
select {
case <-stats.closed:
return
default:
stats.ResetResponseCounts()
time.Sleep(time.Second * 1)
}
}
}()
return stats
} | go | func New() *Stats {
name, _ := os.Hostname()
stats := &Stats{
closed: make(chan struct{}, 1),
Uptime: time.Now(),
Pid: os.Getpid(),
ResponseCounts: map[string]int{},
TotalResponseCounts: map[string]int{},
TotalResponseTime: time.Time{},
Hostname: name,
}
go func() {
for {
select {
case <-stats.closed:
return
default:
stats.ResetResponseCounts()
time.Sleep(time.Second * 1)
}
}
}()
return stats
} | [
"func",
"New",
"(",
")",
"*",
"Stats",
"{",
"name",
",",
"_",
":=",
"os",
".",
"Hostname",
"(",
")",
"\n\n",
"stats",
":=",
"&",
"Stats",
"{",
"closed",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"Uptime",
":",
"time",
... | // New constructs a new Stats structure | [
"New",
"constructs",
"a",
"new",
"Stats",
"structure"
] | 965cb2de1678b040aefd01c448e2f10de3aec2ae | https://github.com/thoas/stats/blob/965cb2de1678b040aefd01c448e2f10de3aec2ae/stats.go#L33-L60 | train |
thoas/stats | stats.go | ResetResponseCounts | func (mw *Stats) ResetResponseCounts() {
mw.mu.Lock()
defer mw.mu.Unlock()
mw.ResponseCounts = map[string]int{}
} | go | func (mw *Stats) ResetResponseCounts() {
mw.mu.Lock()
defer mw.mu.Unlock()
mw.ResponseCounts = map[string]int{}
} | [
"func",
"(",
"mw",
"*",
"Stats",
")",
"ResetResponseCounts",
"(",
")",
"{",
"mw",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mw",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"mw",
".",
"ResponseCounts",
"=",
"map",
"[",
"string",
"]",
"int",... | // ResetResponseCounts reset the response counts | [
"ResetResponseCounts",
"reset",
"the",
"response",
"counts"
] | 965cb2de1678b040aefd01c448e2f10de3aec2ae | https://github.com/thoas/stats/blob/965cb2de1678b040aefd01c448e2f10de3aec2ae/stats.go#L67-L71 | train |
thoas/stats | stats.go | Handler | func (mw *Stats) Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
beginning, recorder := mw.Begin(w)
h.ServeHTTP(recorder, r)
mw.End(beginning, WithRecorder(recorder))
})
} | go | func (mw *Stats) Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
beginning, recorder := mw.Begin(w)
h.ServeHTTP(recorder, r)
mw.End(beginning, WithRecorder(recorder))
})
} | [
"func",
"(",
"mw",
"*",
"Stats",
")",
"Handler",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
... | // Handler is a MiddlewareFunc makes Stats implement the Middleware interface. | [
"Handler",
"is",
"a",
"MiddlewareFunc",
"makes",
"Stats",
"implement",
"the",
"Middleware",
"interface",
"."
] | 965cb2de1678b040aefd01c448e2f10de3aec2ae | https://github.com/thoas/stats/blob/965cb2de1678b040aefd01c448e2f10de3aec2ae/stats.go#L74-L82 | train |
thoas/stats | stats.go | Begin | func (mw *Stats) Begin(w http.ResponseWriter) (time.Time, ResponseWriter) {
start := time.Now()
writer := NewRecorderResponseWriter(w, 200)
return start, writer
} | go | func (mw *Stats) Begin(w http.ResponseWriter) (time.Time, ResponseWriter) {
start := time.Now()
writer := NewRecorderResponseWriter(w, 200)
return start, writer
} | [
"func",
"(",
"mw",
"*",
"Stats",
")",
"Begin",
"(",
"w",
"http",
".",
"ResponseWriter",
")",
"(",
"time",
".",
"Time",
",",
"ResponseWriter",
")",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"writer",
":=",
"NewRecorderResponseWriter",
"(... | // Begin starts a recorder | [
"Begin",
"starts",
"a",
"recorder"
] | 965cb2de1678b040aefd01c448e2f10de3aec2ae | https://github.com/thoas/stats/blob/965cb2de1678b040aefd01c448e2f10de3aec2ae/stats.go#L94-L100 | train |
thoas/stats | stats.go | End | func (mw *Stats) End(start time.Time, opts ...Option) {
options := newOptions(opts...)
responseTime := time.Since(start)
mw.mu.Lock()
defer mw.mu.Unlock()
// If Hijacked connection do not count in response time
if options.StatusCode() != 0 {
statusCode := fmt.Sprintf("%d", options.StatusCode())
mw.ResponseCounts[statusCode]++
mw.TotalResponseCounts[statusCode]++
mw.TotalResponseTime = mw.TotalResponseTime.Add(responseTime)
mw.TotalResponseSize += int64(options.Size())
}
} | go | func (mw *Stats) End(start time.Time, opts ...Option) {
options := newOptions(opts...)
responseTime := time.Since(start)
mw.mu.Lock()
defer mw.mu.Unlock()
// If Hijacked connection do not count in response time
if options.StatusCode() != 0 {
statusCode := fmt.Sprintf("%d", options.StatusCode())
mw.ResponseCounts[statusCode]++
mw.TotalResponseCounts[statusCode]++
mw.TotalResponseTime = mw.TotalResponseTime.Add(responseTime)
mw.TotalResponseSize += int64(options.Size())
}
} | [
"func",
"(",
"mw",
"*",
"Stats",
")",
"End",
"(",
"start",
"time",
".",
"Time",
",",
"opts",
"...",
"Option",
")",
"{",
"options",
":=",
"newOptions",
"(",
"opts",
"...",
")",
"\n\n",
"responseTime",
":=",
"time",
".",
"Since",
"(",
"start",
")",
"... | // End closes the recorder with a specific status | [
"End",
"closes",
"the",
"recorder",
"with",
"a",
"specific",
"status"
] | 965cb2de1678b040aefd01c448e2f10de3aec2ae | https://github.com/thoas/stats/blob/965cb2de1678b040aefd01c448e2f10de3aec2ae/stats.go#L103-L120 | train |
thoas/stats | stats.go | MeasureSince | func (mw *Stats) MeasureSince(key string, start time.Time) {
mw.MeasureSinceWithLabels(key, start, nil)
} | go | func (mw *Stats) MeasureSince(key string, start time.Time) {
mw.MeasureSinceWithLabels(key, start, nil)
} | [
"func",
"(",
"mw",
"*",
"Stats",
")",
"MeasureSince",
"(",
"key",
"string",
",",
"start",
"time",
".",
"Time",
")",
"{",
"mw",
".",
"MeasureSinceWithLabels",
"(",
"key",
",",
"start",
",",
"nil",
")",
"\n",
"}"
] | // MeasureSince method for execution time recording | [
"MeasureSince",
"method",
"for",
"execution",
"time",
"recording"
] | 965cb2de1678b040aefd01c448e2f10de3aec2ae | https://github.com/thoas/stats/blob/965cb2de1678b040aefd01c448e2f10de3aec2ae/stats.go#L123-L125 | train |
thoas/stats | stats.go | MeasureSinceWithLabels | func (mw *Stats) MeasureSinceWithLabels(key string, start time.Time, labels []Label) {
labels = append(labels, Label{"host", mw.Hostname})
elapsed := time.Since(start)
mw.mu.Lock()
defer mw.mu.Unlock()
mw.MetricsCounts[key]++
mw.MetricsTimers[key] = mw.MetricsTimers[key].Add(elapsed)
} | go | func (mw *Stats) MeasureSinceWithLabels(key string, start time.Time, labels []Label) {
labels = append(labels, Label{"host", mw.Hostname})
elapsed := time.Since(start)
mw.mu.Lock()
defer mw.mu.Unlock()
mw.MetricsCounts[key]++
mw.MetricsTimers[key] = mw.MetricsTimers[key].Add(elapsed)
} | [
"func",
"(",
"mw",
"*",
"Stats",
")",
"MeasureSinceWithLabels",
"(",
"key",
"string",
",",
"start",
"time",
".",
"Time",
",",
"labels",
"[",
"]",
"Label",
")",
"{",
"labels",
"=",
"append",
"(",
"labels",
",",
"Label",
"{",
"\"",
"\"",
",",
"mw",
"... | // MeasureSinceWithLabels method for execution time recording with custom labels | [
"MeasureSinceWithLabels",
"method",
"for",
"execution",
"time",
"recording",
"with",
"custom",
"labels"
] | 965cb2de1678b040aefd01c448e2f10de3aec2ae | https://github.com/thoas/stats/blob/965cb2de1678b040aefd01c448e2f10de3aec2ae/stats.go#L128-L137 | train |
thoas/stats | stats.go | Data | func (mw *Stats) Data() *Data {
mw.mu.RLock()
responseCounts := make(map[string]int, len(mw.ResponseCounts))
totalResponseCounts := make(map[string]int, len(mw.TotalResponseCounts))
totalMetricsCounts := make(map[string]int, len(mw.MetricsCounts))
metricsCounts := make(map[string]float64, len(mw.MetricsCounts))
now := time.Now()
uptime := now.Sub(mw.Uptime)
count := 0
for code, current := range mw.ResponseCounts {
responseCounts[code] = current
count += current
}
totalCount := 0
for code, count := range mw.TotalResponseCounts {
totalResponseCounts[code] = count
totalCount += count
}
totalResponseTime := mw.TotalResponseTime.Sub(time.Time{})
totalResponseSize := mw.TotalResponseSize
averageResponseTime := time.Duration(0)
averageResponseSize := int64(0)
if totalCount > 0 {
avgNs := int64(totalResponseTime) / int64(totalCount)
averageResponseTime = time.Duration(avgNs)
averageResponseSize = int64(totalResponseSize) / int64(totalCount)
}
for key, count := range mw.MetricsCounts {
totalMetric := mw.MetricsTimers[key].Sub(time.Time{})
avgNs := int64(totalMetric) / int64(count)
metricsCounts[key] = time.Duration(avgNs).Seconds()
totalMetricsCounts[key] = count
}
mw.mu.RUnlock()
r := &Data{
Pid: mw.Pid,
UpTime: uptime.String(),
UpTimeSec: uptime.Seconds(),
Time: now.String(),
TimeUnix: now.Unix(),
StatusCodeCount: responseCounts,
TotalStatusCodeCount: totalResponseCounts,
Count: count,
TotalCount: totalCount,
TotalResponseTime: totalResponseTime.String(),
TotalResponseSize: totalResponseSize,
TotalResponseTimeSec: totalResponseTime.Seconds(),
TotalMetricsCounts: totalMetricsCounts,
AverageResponseSize: averageResponseSize,
AverageResponseTime: averageResponseTime.String(),
AverageResponseTimeSec: averageResponseTime.Seconds(),
AverageMetricsTimers: metricsCounts,
}
return r
} | go | func (mw *Stats) Data() *Data {
mw.mu.RLock()
responseCounts := make(map[string]int, len(mw.ResponseCounts))
totalResponseCounts := make(map[string]int, len(mw.TotalResponseCounts))
totalMetricsCounts := make(map[string]int, len(mw.MetricsCounts))
metricsCounts := make(map[string]float64, len(mw.MetricsCounts))
now := time.Now()
uptime := now.Sub(mw.Uptime)
count := 0
for code, current := range mw.ResponseCounts {
responseCounts[code] = current
count += current
}
totalCount := 0
for code, count := range mw.TotalResponseCounts {
totalResponseCounts[code] = count
totalCount += count
}
totalResponseTime := mw.TotalResponseTime.Sub(time.Time{})
totalResponseSize := mw.TotalResponseSize
averageResponseTime := time.Duration(0)
averageResponseSize := int64(0)
if totalCount > 0 {
avgNs := int64(totalResponseTime) / int64(totalCount)
averageResponseTime = time.Duration(avgNs)
averageResponseSize = int64(totalResponseSize) / int64(totalCount)
}
for key, count := range mw.MetricsCounts {
totalMetric := mw.MetricsTimers[key].Sub(time.Time{})
avgNs := int64(totalMetric) / int64(count)
metricsCounts[key] = time.Duration(avgNs).Seconds()
totalMetricsCounts[key] = count
}
mw.mu.RUnlock()
r := &Data{
Pid: mw.Pid,
UpTime: uptime.String(),
UpTimeSec: uptime.Seconds(),
Time: now.String(),
TimeUnix: now.Unix(),
StatusCodeCount: responseCounts,
TotalStatusCodeCount: totalResponseCounts,
Count: count,
TotalCount: totalCount,
TotalResponseTime: totalResponseTime.String(),
TotalResponseSize: totalResponseSize,
TotalResponseTimeSec: totalResponseTime.Seconds(),
TotalMetricsCounts: totalMetricsCounts,
AverageResponseSize: averageResponseSize,
AverageResponseTime: averageResponseTime.String(),
AverageResponseTimeSec: averageResponseTime.Seconds(),
AverageMetricsTimers: metricsCounts,
}
return r
} | [
"func",
"(",
"mw",
"*",
"Stats",
")",
"Data",
"(",
")",
"*",
"Data",
"{",
"mw",
".",
"mu",
".",
"RLock",
"(",
")",
"\n\n",
"responseCounts",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
",",
"len",
"(",
"mw",
".",
"ResponseCounts",
")",
... | // Data returns the data serializable structure | [
"Data",
"returns",
"the",
"data",
"serializable",
"structure"
] | 965cb2de1678b040aefd01c448e2f10de3aec2ae | https://github.com/thoas/stats/blob/965cb2de1678b040aefd01c448e2f10de3aec2ae/stats.go#L162-L227 | train |
anthonynsimon/bild | segment/thresholding.go | Threshold | func Threshold(img image.Image, level uint8) *image.Gray {
src := clone.AsRGBA(img)
bounds := src.Bounds()
dst := image.NewGray(bounds)
for y := 0; y < bounds.Dy(); y++ {
for x := 0; x < bounds.Dx(); x++ {
srcPos := y*src.Stride + x*4
dstPos := y*dst.Stride + x
c := src.Pix[srcPos : srcPos+4]
r := util.Rank(color.RGBA{c[0], c[1], c[2], c[3]})
// transparent pixel is always white
if c[0] == 0 && c[1] == 0 && c[2] == 0 && c[3] == 0 {
dst.Pix[dstPos] = 0xFF
continue
}
if uint8(r) >= level {
dst.Pix[dstPos] = 0xFF
} else {
dst.Pix[dstPos] = 0x00
}
}
}
return dst
} | go | func Threshold(img image.Image, level uint8) *image.Gray {
src := clone.AsRGBA(img)
bounds := src.Bounds()
dst := image.NewGray(bounds)
for y := 0; y < bounds.Dy(); y++ {
for x := 0; x < bounds.Dx(); x++ {
srcPos := y*src.Stride + x*4
dstPos := y*dst.Stride + x
c := src.Pix[srcPos : srcPos+4]
r := util.Rank(color.RGBA{c[0], c[1], c[2], c[3]})
// transparent pixel is always white
if c[0] == 0 && c[1] == 0 && c[2] == 0 && c[3] == 0 {
dst.Pix[dstPos] = 0xFF
continue
}
if uint8(r) >= level {
dst.Pix[dstPos] = 0xFF
} else {
dst.Pix[dstPos] = 0x00
}
}
}
return dst
} | [
"func",
"Threshold",
"(",
"img",
"image",
".",
"Image",
",",
"level",
"uint8",
")",
"*",
"image",
".",
"Gray",
"{",
"src",
":=",
"clone",
".",
"AsRGBA",
"(",
"img",
")",
"\n",
"bounds",
":=",
"src",
".",
"Bounds",
"(",
")",
"\n\n",
"dst",
":=",
"... | // Threshold returns a grayscale image in which values from the param img that are
// smaller than the param level are set to black and values larger than or equal to
// it are set to white.
// Level must be of the range 0 to 255. | [
"Threshold",
"returns",
"a",
"grayscale",
"image",
"in",
"which",
"values",
"from",
"the",
"param",
"img",
"that",
"are",
"smaller",
"than",
"the",
"param",
"level",
"are",
"set",
"to",
"black",
"and",
"values",
"larger",
"than",
"or",
"equal",
"to",
"it",... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/segment/thresholding.go#L16-L45 | train |
anthonynsimon/bild | transform/shear.go | ShearH | func ShearH(img image.Image, angle float64) *image.RGBA {
src := clone.AsRGBA(img)
srcW, srcH := src.Bounds().Dx(), src.Bounds().Dy()
// Supersample, currently hard set to 2x
srcW, srcH = srcW*2, srcH*2
src = Resize(src, srcW, srcH, NearestNeighbor)
// Calculate shear factor
kx := math.Tan(angle * (math.Pi / 180))
dstW, dstH := srcW+int(float64(srcH)*math.Abs(kx)), srcH
dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH))
pivotX := float64(dstW) / 2
pivotY := float64(dstH) / 2
// Calculate offset since we are resizing the bounds to
// fit the sheared image.
dx := (dstW - srcW) / 2
dy := (dstH - srcH) / 2
parallel.Line(dstH, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < dstW; x++ {
// Move positions to revolve around pivot
ix := x - int(pivotX) - dx
iy := y - int(pivotY) - dy
// Apply linear transformation
ix = ix + int(float64(iy)*kx)
// Move positions back to image coordinates
ix += int(pivotX)
iy += int(pivotY)
if ix < 0 || ix >= srcW || iy < 0 || iy >= srcH {
continue
}
srcPos := iy*src.Stride + ix*4
dstPos := y*dst.Stride + x*4
dst.Pix[dstPos+0] = src.Pix[srcPos+0]
dst.Pix[dstPos+1] = src.Pix[srcPos+1]
dst.Pix[dstPos+2] = src.Pix[srcPos+2]
dst.Pix[dstPos+3] = src.Pix[srcPos+3]
}
}
})
// Downsample to original bounds as part of the Supersampling
dst = Resize(dst, dstW/2, dstH/2, Linear)
return dst
} | go | func ShearH(img image.Image, angle float64) *image.RGBA {
src := clone.AsRGBA(img)
srcW, srcH := src.Bounds().Dx(), src.Bounds().Dy()
// Supersample, currently hard set to 2x
srcW, srcH = srcW*2, srcH*2
src = Resize(src, srcW, srcH, NearestNeighbor)
// Calculate shear factor
kx := math.Tan(angle * (math.Pi / 180))
dstW, dstH := srcW+int(float64(srcH)*math.Abs(kx)), srcH
dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH))
pivotX := float64(dstW) / 2
pivotY := float64(dstH) / 2
// Calculate offset since we are resizing the bounds to
// fit the sheared image.
dx := (dstW - srcW) / 2
dy := (dstH - srcH) / 2
parallel.Line(dstH, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < dstW; x++ {
// Move positions to revolve around pivot
ix := x - int(pivotX) - dx
iy := y - int(pivotY) - dy
// Apply linear transformation
ix = ix + int(float64(iy)*kx)
// Move positions back to image coordinates
ix += int(pivotX)
iy += int(pivotY)
if ix < 0 || ix >= srcW || iy < 0 || iy >= srcH {
continue
}
srcPos := iy*src.Stride + ix*4
dstPos := y*dst.Stride + x*4
dst.Pix[dstPos+0] = src.Pix[srcPos+0]
dst.Pix[dstPos+1] = src.Pix[srcPos+1]
dst.Pix[dstPos+2] = src.Pix[srcPos+2]
dst.Pix[dstPos+3] = src.Pix[srcPos+3]
}
}
})
// Downsample to original bounds as part of the Supersampling
dst = Resize(dst, dstW/2, dstH/2, Linear)
return dst
} | [
"func",
"ShearH",
"(",
"img",
"image",
".",
"Image",
",",
"angle",
"float64",
")",
"*",
"image",
".",
"RGBA",
"{",
"src",
":=",
"clone",
".",
"AsRGBA",
"(",
"img",
")",
"\n",
"srcW",
",",
"srcH",
":=",
"src",
".",
"Bounds",
"(",
")",
".",
"Dx",
... | // ShearH applies a shear linear transformation along the horizontal axis,
// the parameter angle is the shear angle to be applied.
// The transformation will be applied with the center of the image as the pivot. | [
"ShearH",
"applies",
"a",
"shear",
"linear",
"transformation",
"along",
"the",
"horizontal",
"axis",
"the",
"parameter",
"angle",
"is",
"the",
"shear",
"angle",
"to",
"be",
"applied",
".",
"The",
"transformation",
"will",
"be",
"applied",
"with",
"the",
"cente... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/transform/shear.go#L14-L69 | train |
anthonynsimon/bild | transform/translate.go | Translate | func Translate(img image.Image, dx, dy int) *image.RGBA {
src := clone.AsRGBA(img)
if dx == 0 && dy == 0 {
return src
}
w, h := src.Bounds().Dx(), src.Bounds().Dy()
dst := image.NewRGBA(src.Bounds())
parallel.Line(h, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < w; x++ {
ix, iy := x-dx, y+dy
if ix < 0 || ix >= w || iy < 0 || iy >= h {
continue
}
srcPos := iy*src.Stride + ix*4
dstPos := y*src.Stride + x*4
copy(dst.Pix[dstPos:dstPos+4], src.Pix[srcPos:srcPos+4])
}
}
})
return dst
} | go | func Translate(img image.Image, dx, dy int) *image.RGBA {
src := clone.AsRGBA(img)
if dx == 0 && dy == 0 {
return src
}
w, h := src.Bounds().Dx(), src.Bounds().Dy()
dst := image.NewRGBA(src.Bounds())
parallel.Line(h, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < w; x++ {
ix, iy := x-dx, y+dy
if ix < 0 || ix >= w || iy < 0 || iy >= h {
continue
}
srcPos := iy*src.Stride + ix*4
dstPos := y*src.Stride + x*4
copy(dst.Pix[dstPos:dstPos+4], src.Pix[srcPos:srcPos+4])
}
}
})
return dst
} | [
"func",
"Translate",
"(",
"img",
"image",
".",
"Image",
",",
"dx",
",",
"dy",
"int",
")",
"*",
"image",
".",
"RGBA",
"{",
"src",
":=",
"clone",
".",
"AsRGBA",
"(",
"img",
")",
"\n\n",
"if",
"dx",
"==",
"0",
"&&",
"dy",
"==",
"0",
"{",
"return",... | // Translate repositions a copy of the provided image by dx on the x-axis and
// by dy on the y-axis and returns the result. The bounds from the provided image
// will be kept.
// A positive dx value moves the image towards the right and a positive dy value
// moves the image upwards. | [
"Translate",
"repositions",
"a",
"copy",
"of",
"the",
"provided",
"image",
"by",
"dx",
"on",
"the",
"x",
"-",
"axis",
"and",
"by",
"dy",
"on",
"the",
"y",
"-",
"axis",
"and",
"returns",
"the",
"result",
".",
"The",
"bounds",
"from",
"the",
"provided",
... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/transform/translate.go#L15-L43 | train |
anthonynsimon/bild | noise/noise.go | Generate | func Generate(width, height int, o *Options) *image.RGBA {
dst := image.NewRGBA(image.Rect(0, 0, width, height))
// Get options or defaults
noiseFn := Uniform
monochrome := false
if o != nil {
if o.NoiseFn != nil {
noiseFn = o.NoiseFn
}
monochrome = o.Monochrome
}
rand.Seed(time.Now().UTC().UnixNano())
if monochrome {
fillMonochrome(dst, noiseFn)
} else {
fillColored(dst, noiseFn)
}
return dst
} | go | func Generate(width, height int, o *Options) *image.RGBA {
dst := image.NewRGBA(image.Rect(0, 0, width, height))
// Get options or defaults
noiseFn := Uniform
monochrome := false
if o != nil {
if o.NoiseFn != nil {
noiseFn = o.NoiseFn
}
monochrome = o.Monochrome
}
rand.Seed(time.Now().UTC().UnixNano())
if monochrome {
fillMonochrome(dst, noiseFn)
} else {
fillColored(dst, noiseFn)
}
return dst
} | [
"func",
"Generate",
"(",
"width",
",",
"height",
"int",
",",
"o",
"*",
"Options",
")",
"*",
"image",
".",
"RGBA",
"{",
"dst",
":=",
"image",
".",
"NewRGBA",
"(",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
")",
"... | // Generate returns an image of the parameter width and height filled
// with the values from a noise function.
// If no options are provided, defaults will be used. | [
"Generate",
"returns",
"an",
"image",
"of",
"the",
"parameter",
"width",
"and",
"height",
"filled",
"with",
"the",
"values",
"from",
"a",
"noise",
"function",
".",
"If",
"no",
"options",
"are",
"provided",
"defaults",
"will",
"be",
"used",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/noise/noise.go#L49-L71 | train |
anthonynsimon/bild | histogram/histogram.go | Max | func (h *Histogram) Max() int {
var max int
if len(h.Bins) > 0 {
max = h.Bins[0]
for i := 1; i < len(h.Bins); i++ {
if h.Bins[i] > max {
max = h.Bins[i]
}
}
}
return max
} | go | func (h *Histogram) Max() int {
var max int
if len(h.Bins) > 0 {
max = h.Bins[0]
for i := 1; i < len(h.Bins); i++ {
if h.Bins[i] > max {
max = h.Bins[i]
}
}
}
return max
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"Max",
"(",
")",
"int",
"{",
"var",
"max",
"int",
"\n",
"if",
"len",
"(",
"h",
".",
"Bins",
")",
">",
"0",
"{",
"max",
"=",
"h",
".",
"Bins",
"[",
"0",
"]",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
... | // Max returns the highest count found in the histogram bins. | [
"Max",
"returns",
"the",
"highest",
"count",
"found",
"in",
"the",
"histogram",
"bins",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/histogram/histogram.go#L25-L36 | train |
anthonynsimon/bild | histogram/histogram.go | Min | func (h *Histogram) Min() int {
var min int
if len(h.Bins) > 0 {
min = h.Bins[0]
for i := 1; i < len(h.Bins); i++ {
if h.Bins[i] < min {
min = h.Bins[i]
}
}
}
return min
} | go | func (h *Histogram) Min() int {
var min int
if len(h.Bins) > 0 {
min = h.Bins[0]
for i := 1; i < len(h.Bins); i++ {
if h.Bins[i] < min {
min = h.Bins[i]
}
}
}
return min
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"Min",
"(",
")",
"int",
"{",
"var",
"min",
"int",
"\n",
"if",
"len",
"(",
"h",
".",
"Bins",
")",
">",
"0",
"{",
"min",
"=",
"h",
".",
"Bins",
"[",
"0",
"]",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
... | // Min returns the lowest count found in the histogram bins. | [
"Min",
"returns",
"the",
"lowest",
"count",
"found",
"in",
"the",
"histogram",
"bins",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/histogram/histogram.go#L39-L50 | train |
anthonynsimon/bild | histogram/histogram.go | Cumulative | func (h *Histogram) Cumulative() *Histogram {
binCount := len(h.Bins)
out := Histogram{make([]int, binCount)}
if binCount > 0 {
out.Bins[0] = h.Bins[0]
}
for i := 1; i < binCount; i++ {
out.Bins[i] = out.Bins[i-1] + h.Bins[i]
}
return &out
} | go | func (h *Histogram) Cumulative() *Histogram {
binCount := len(h.Bins)
out := Histogram{make([]int, binCount)}
if binCount > 0 {
out.Bins[0] = h.Bins[0]
}
for i := 1; i < binCount; i++ {
out.Bins[i] = out.Bins[i-1] + h.Bins[i]
}
return &out
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"Cumulative",
"(",
")",
"*",
"Histogram",
"{",
"binCount",
":=",
"len",
"(",
"h",
".",
"Bins",
")",
"\n",
"out",
":=",
"Histogram",
"{",
"make",
"(",
"[",
"]",
"int",
",",
"binCount",
")",
"}",
"\n\n",
"if... | // Cumulative returns a new Histogram in which each bin is the cumulative
// value of its previous bins | [
"Cumulative",
"returns",
"a",
"new",
"Histogram",
"in",
"which",
"each",
"bin",
"is",
"the",
"cumulative",
"value",
"of",
"its",
"previous",
"bins"
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/histogram/histogram.go#L54-L67 | train |
anthonynsimon/bild | histogram/histogram.go | Image | func (h *Histogram) Image() *image.Gray {
dstW, dstH := len(h.Bins), len(h.Bins)
dst := image.NewGray(image.Rect(0, 0, dstW, dstH))
max := h.Max()
if max == 0 {
max = 1
}
for x := 0; x < dstW; x++ {
value := ((h.Bins[x] << 16 / max) * dstH) >> 16
// Fill from the bottom up
for y := dstH - 1; y > dstH-value-1; y-- {
dst.Pix[y*dst.Stride+x] = 0xFF
}
}
return dst
} | go | func (h *Histogram) Image() *image.Gray {
dstW, dstH := len(h.Bins), len(h.Bins)
dst := image.NewGray(image.Rect(0, 0, dstW, dstH))
max := h.Max()
if max == 0 {
max = 1
}
for x := 0; x < dstW; x++ {
value := ((h.Bins[x] << 16 / max) * dstH) >> 16
// Fill from the bottom up
for y := dstH - 1; y > dstH-value-1; y-- {
dst.Pix[y*dst.Stride+x] = 0xFF
}
}
return dst
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"Image",
"(",
")",
"*",
"image",
".",
"Gray",
"{",
"dstW",
",",
"dstH",
":=",
"len",
"(",
"h",
".",
"Bins",
")",
",",
"len",
"(",
"h",
".",
"Bins",
")",
"\n",
"dst",
":=",
"image",
".",
"NewGray",
"(",... | // Image returns a grayscale image representation of the Histogram.
// The width and height of the image will be equivalent to the number of Bins in the Histogram. | [
"Image",
"returns",
"a",
"grayscale",
"image",
"representation",
"of",
"the",
"Histogram",
".",
"The",
"width",
"and",
"height",
"of",
"the",
"image",
"will",
"be",
"equivalent",
"to",
"the",
"number",
"of",
"Bins",
"in",
"the",
"Histogram",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/histogram/histogram.go#L71-L88 | train |
anthonynsimon/bild | histogram/histogram.go | NewRGBAHistogram | func NewRGBAHistogram(img image.Image) *RGBAHistogram {
src := clone.AsRGBA(img)
binCount := 256
r := Histogram{make([]int, binCount)}
g := Histogram{make([]int, binCount)}
b := Histogram{make([]int, binCount)}
a := Histogram{make([]int, binCount)}
for y := 0; y < src.Bounds().Dy(); y++ {
for x := 0; x < src.Bounds().Dx(); x++ {
pos := y*src.Stride + x*4
r.Bins[src.Pix[pos+0]]++
g.Bins[src.Pix[pos+1]]++
b.Bins[src.Pix[pos+2]]++
a.Bins[src.Pix[pos+3]]++
}
}
return &RGBAHistogram{R: r, G: g, B: b, A: a}
} | go | func NewRGBAHistogram(img image.Image) *RGBAHistogram {
src := clone.AsRGBA(img)
binCount := 256
r := Histogram{make([]int, binCount)}
g := Histogram{make([]int, binCount)}
b := Histogram{make([]int, binCount)}
a := Histogram{make([]int, binCount)}
for y := 0; y < src.Bounds().Dy(); y++ {
for x := 0; x < src.Bounds().Dx(); x++ {
pos := y*src.Stride + x*4
r.Bins[src.Pix[pos+0]]++
g.Bins[src.Pix[pos+1]]++
b.Bins[src.Pix[pos+2]]++
a.Bins[src.Pix[pos+3]]++
}
}
return &RGBAHistogram{R: r, G: g, B: b, A: a}
} | [
"func",
"NewRGBAHistogram",
"(",
"img",
"image",
".",
"Image",
")",
"*",
"RGBAHistogram",
"{",
"src",
":=",
"clone",
".",
"AsRGBA",
"(",
"img",
")",
"\n\n",
"binCount",
":=",
"256",
"\n",
"r",
":=",
"Histogram",
"{",
"make",
"(",
"[",
"]",
"int",
","... | // NewRGBAHistogram constructs a RGBAHistogram out of the provided image.
// A sub-histogram is created per RGBA channel with 256 bins each. | [
"NewRGBAHistogram",
"constructs",
"a",
"RGBAHistogram",
"out",
"of",
"the",
"provided",
"image",
".",
"A",
"sub",
"-",
"histogram",
"is",
"created",
"per",
"RGBA",
"channel",
"with",
"256",
"bins",
"each",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/histogram/histogram.go#L92-L112 | train |
anthonynsimon/bild | histogram/histogram.go | Cumulative | func (h *RGBAHistogram) Cumulative() *RGBAHistogram {
binCount := len(h.R.Bins)
r := Histogram{make([]int, binCount)}
g := Histogram{make([]int, binCount)}
b := Histogram{make([]int, binCount)}
a := Histogram{make([]int, binCount)}
out := RGBAHistogram{R: r, G: g, B: b, A: a}
if binCount > 0 {
out.R.Bins[0] = h.R.Bins[0]
out.G.Bins[0] = h.G.Bins[0]
out.B.Bins[0] = h.B.Bins[0]
out.A.Bins[0] = h.A.Bins[0]
}
for i := 1; i < binCount; i++ {
out.R.Bins[i] = out.R.Bins[i-1] + h.R.Bins[i]
out.G.Bins[i] = out.G.Bins[i-1] + h.G.Bins[i]
out.B.Bins[i] = out.B.Bins[i-1] + h.B.Bins[i]
out.A.Bins[i] = out.A.Bins[i-1] + h.A.Bins[i]
}
return &out
} | go | func (h *RGBAHistogram) Cumulative() *RGBAHistogram {
binCount := len(h.R.Bins)
r := Histogram{make([]int, binCount)}
g := Histogram{make([]int, binCount)}
b := Histogram{make([]int, binCount)}
a := Histogram{make([]int, binCount)}
out := RGBAHistogram{R: r, G: g, B: b, A: a}
if binCount > 0 {
out.R.Bins[0] = h.R.Bins[0]
out.G.Bins[0] = h.G.Bins[0]
out.B.Bins[0] = h.B.Bins[0]
out.A.Bins[0] = h.A.Bins[0]
}
for i := 1; i < binCount; i++ {
out.R.Bins[i] = out.R.Bins[i-1] + h.R.Bins[i]
out.G.Bins[i] = out.G.Bins[i-1] + h.G.Bins[i]
out.B.Bins[i] = out.B.Bins[i-1] + h.B.Bins[i]
out.A.Bins[i] = out.A.Bins[i-1] + h.A.Bins[i]
}
return &out
} | [
"func",
"(",
"h",
"*",
"RGBAHistogram",
")",
"Cumulative",
"(",
")",
"*",
"RGBAHistogram",
"{",
"binCount",
":=",
"len",
"(",
"h",
".",
"R",
".",
"Bins",
")",
"\n\n",
"r",
":=",
"Histogram",
"{",
"make",
"(",
"[",
"]",
"int",
",",
"binCount",
")",
... | // Cumulative returns a new RGBAHistogram in which each bin is the cumulative
// value of its previous bins per channel. | [
"Cumulative",
"returns",
"a",
"new",
"RGBAHistogram",
"in",
"which",
"each",
"bin",
"is",
"the",
"cumulative",
"value",
"of",
"its",
"previous",
"bins",
"per",
"channel",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/histogram/histogram.go#L116-L141 | train |
anthonynsimon/bild | histogram/histogram.go | Image | func (h *RGBAHistogram) Image() *image.RGBA {
if len(h.R.Bins) != 256 || len(h.G.Bins) != 256 ||
len(h.B.Bins) != 256 || len(h.A.Bins) != 256 {
panic("RGBAHistogram bins length not equal to 256")
}
dstW, dstH := 256, 256
dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH))
maxR := h.R.Max()
if maxR == 0 {
maxR = 1
}
maxG := h.G.Max()
if maxG == 0 {
maxG = 1
}
maxB := h.B.Max()
if maxB == 0 {
maxB = 1
}
for x := 0; x < dstW; x++ {
binHeightR := ((h.R.Bins[x] << 16 / maxR) * dstH) >> 16
binHeightG := ((h.G.Bins[x] << 16 / maxG) * dstH) >> 16
binHeightB := ((h.B.Bins[x] << 16 / maxB) * dstH) >> 16
// Fill from the bottom up
for y := dstH - 1; y >= 0; y-- {
pos := y*dst.Stride + x*4
iy := dstH - 1 - y
if iy < binHeightR {
dst.Pix[pos+0] = 0xFF
}
if iy < binHeightG {
dst.Pix[pos+1] = 0xFF
}
if iy < binHeightB {
dst.Pix[pos+2] = 0xFF
}
dst.Pix[pos+3] = 0xFF
}
}
return dst
} | go | func (h *RGBAHistogram) Image() *image.RGBA {
if len(h.R.Bins) != 256 || len(h.G.Bins) != 256 ||
len(h.B.Bins) != 256 || len(h.A.Bins) != 256 {
panic("RGBAHistogram bins length not equal to 256")
}
dstW, dstH := 256, 256
dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH))
maxR := h.R.Max()
if maxR == 0 {
maxR = 1
}
maxG := h.G.Max()
if maxG == 0 {
maxG = 1
}
maxB := h.B.Max()
if maxB == 0 {
maxB = 1
}
for x := 0; x < dstW; x++ {
binHeightR := ((h.R.Bins[x] << 16 / maxR) * dstH) >> 16
binHeightG := ((h.G.Bins[x] << 16 / maxG) * dstH) >> 16
binHeightB := ((h.B.Bins[x] << 16 / maxB) * dstH) >> 16
// Fill from the bottom up
for y := dstH - 1; y >= 0; y-- {
pos := y*dst.Stride + x*4
iy := dstH - 1 - y
if iy < binHeightR {
dst.Pix[pos+0] = 0xFF
}
if iy < binHeightG {
dst.Pix[pos+1] = 0xFF
}
if iy < binHeightB {
dst.Pix[pos+2] = 0xFF
}
dst.Pix[pos+3] = 0xFF
}
}
return dst
} | [
"func",
"(",
"h",
"*",
"RGBAHistogram",
")",
"Image",
"(",
")",
"*",
"image",
".",
"RGBA",
"{",
"if",
"len",
"(",
"h",
".",
"R",
".",
"Bins",
")",
"!=",
"256",
"||",
"len",
"(",
"h",
".",
"G",
".",
"Bins",
")",
"!=",
"256",
"||",
"len",
"("... | // Image returns an RGBA image representation of the RGBAHistogram.
// An image width of 256 represents the 256 Bins per channel and the
// image height of 256 represents the max normalized histogram value per channel.
// Each RGB channel from the histogram is mapped to its corresponding channel in the image,
// so that for example if the red channel is extracted from the image, it corresponds to the
// red channel histogram. | [
"Image",
"returns",
"an",
"RGBA",
"image",
"representation",
"of",
"the",
"RGBAHistogram",
".",
"An",
"image",
"width",
"of",
"256",
"represents",
"the",
"256",
"Bins",
"per",
"channel",
"and",
"the",
"image",
"height",
"of",
"256",
"represents",
"the",
"max... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/histogram/histogram.go#L149-L194 | train |
anthonynsimon/bild | convolution/kernel.go | NewKernel | func NewKernel(width, height int) *Kernel {
return &Kernel{make([]float64, width*height), width, height}
} | go | func NewKernel(width, height int) *Kernel {
return &Kernel{make([]float64, width*height), width, height}
} | [
"func",
"NewKernel",
"(",
"width",
",",
"height",
"int",
")",
"*",
"Kernel",
"{",
"return",
"&",
"Kernel",
"{",
"make",
"(",
"[",
"]",
"float64",
",",
"width",
"*",
"height",
")",
",",
"width",
",",
"height",
"}",
"\n",
"}"
] | // NewKernel returns a kernel of the provided length. | [
"NewKernel",
"returns",
"a",
"kernel",
"of",
"the",
"provided",
"length",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/convolution/kernel.go#L21-L23 | train |
anthonynsimon/bild | convolution/kernel.go | Normalized | func (k *Kernel) Normalized() Matrix {
sum := k.Absum()
w := k.Width
h := k.Height
nk := NewKernel(w, h)
// avoid division by 0
if sum == 0 {
sum = 1
}
for i := 0; i < w*h; i++ {
nk.Matrix[i] = k.Matrix[i] / sum
}
return nk
} | go | func (k *Kernel) Normalized() Matrix {
sum := k.Absum()
w := k.Width
h := k.Height
nk := NewKernel(w, h)
// avoid division by 0
if sum == 0 {
sum = 1
}
for i := 0; i < w*h; i++ {
nk.Matrix[i] = k.Matrix[i] / sum
}
return nk
} | [
"func",
"(",
"k",
"*",
"Kernel",
")",
"Normalized",
"(",
")",
"Matrix",
"{",
"sum",
":=",
"k",
".",
"Absum",
"(",
")",
"\n",
"w",
":=",
"k",
".",
"Width",
"\n",
"h",
":=",
"k",
".",
"Height",
"\n",
"nk",
":=",
"NewKernel",
"(",
"w",
",",
"h",... | // Normalized returns a new Kernel with normalized values. | [
"Normalized",
"returns",
"a",
"new",
"Kernel",
"with",
"normalized",
"values",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/convolution/kernel.go#L33-L49 | train |
anthonynsimon/bild | convolution/kernel.go | At | func (k *Kernel) At(x, y int) float64 {
return k.Matrix[y*k.Width+x]
} | go | func (k *Kernel) At(x, y int) float64 {
return k.Matrix[y*k.Width+x]
} | [
"func",
"(",
"k",
"*",
"Kernel",
")",
"At",
"(",
"x",
",",
"y",
"int",
")",
"float64",
"{",
"return",
"k",
".",
"Matrix",
"[",
"y",
"*",
"k",
".",
"Width",
"+",
"x",
"]",
"\n",
"}"
] | // At returns the matrix value at position x, y. | [
"At",
"returns",
"the",
"matrix",
"value",
"at",
"position",
"x",
"y",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/convolution/kernel.go#L62-L64 | train |
anthonynsimon/bild | convolution/kernel.go | String | func (k *Kernel) String() string {
result := ""
stride := k.MaxX()
height := k.MaxY()
for y := 0; y < height; y++ {
result += fmt.Sprintf("\n")
for x := 0; x < stride; x++ {
result += fmt.Sprintf("%-8.4f", k.At(x, y))
}
}
return result
} | go | func (k *Kernel) String() string {
result := ""
stride := k.MaxX()
height := k.MaxY()
for y := 0; y < height; y++ {
result += fmt.Sprintf("\n")
for x := 0; x < stride; x++ {
result += fmt.Sprintf("%-8.4f", k.At(x, y))
}
}
return result
} | [
"func",
"(",
"k",
"*",
"Kernel",
")",
"String",
"(",
")",
"string",
"{",
"result",
":=",
"\"",
"\"",
"\n",
"stride",
":=",
"k",
".",
"MaxX",
"(",
")",
"\n",
"height",
":=",
"k",
".",
"MaxY",
"(",
")",
"\n",
"for",
"y",
":=",
"0",
";",
"y",
... | // String returns the string representation of the matrix. | [
"String",
"returns",
"the",
"string",
"representation",
"of",
"the",
"matrix",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/convolution/kernel.go#L67-L78 | train |
anthonynsimon/bild | convolution/kernel.go | Absum | func (k *Kernel) Absum() float64 {
var sum float64
for _, v := range k.Matrix {
sum += math.Abs(v)
}
return sum
} | go | func (k *Kernel) Absum() float64 {
var sum float64
for _, v := range k.Matrix {
sum += math.Abs(v)
}
return sum
} | [
"func",
"(",
"k",
"*",
"Kernel",
")",
"Absum",
"(",
")",
"float64",
"{",
"var",
"sum",
"float64",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"k",
".",
"Matrix",
"{",
"sum",
"+=",
"math",
".",
"Abs",
"(",
"v",
")",
"\n",
"}",
"\n",
"return",
"... | // Absum returns the absolute cumulative value of the kernel. | [
"Absum",
"returns",
"the",
"absolute",
"cumulative",
"value",
"of",
"the",
"kernel",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/convolution/kernel.go#L81-L87 | train |
anthonynsimon/bild | effect/effect.go | Invert | func Invert(src image.Image) *image.RGBA {
fn := func(c color.RGBA) color.RGBA {
return color.RGBA{255 - c.R, 255 - c.G, 255 - c.B, c.A}
}
img := adjust.Apply(src, fn)
return img
} | go | func Invert(src image.Image) *image.RGBA {
fn := func(c color.RGBA) color.RGBA {
return color.RGBA{255 - c.R, 255 - c.G, 255 - c.B, c.A}
}
img := adjust.Apply(src, fn)
return img
} | [
"func",
"Invert",
"(",
"src",
"image",
".",
"Image",
")",
"*",
"image",
".",
"RGBA",
"{",
"fn",
":=",
"func",
"(",
"c",
"color",
".",
"RGBA",
")",
"color",
".",
"RGBA",
"{",
"return",
"color",
".",
"RGBA",
"{",
"255",
"-",
"c",
".",
"R",
",",
... | // Invert returns a negated version of the image. | [
"Invert",
"returns",
"a",
"negated",
"version",
"of",
"the",
"image",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/effect/effect.go#L20-L28 | train |
anthonynsimon/bild | effect/effect.go | Grayscale | func Grayscale(img image.Image) *image.Gray {
src := clone.AsRGBA(img)
bounds := src.Bounds()
srcW, srcH := bounds.Dx(), bounds.Dy()
if bounds.Empty() {
return &image.Gray{}
}
dst := image.NewGray(bounds)
parallel.Line(srcH, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < srcW; x++ {
srcPos := y*src.Stride + x*4
dstPos := y*dst.Stride + x
c := 0.3*float64(src.Pix[srcPos+0]) + 0.6*float64(src.Pix[srcPos+1]) + 0.1*float64(src.Pix[srcPos+2])
dst.Pix[dstPos] = uint8(c + 0.5)
}
}
})
return dst
} | go | func Grayscale(img image.Image) *image.Gray {
src := clone.AsRGBA(img)
bounds := src.Bounds()
srcW, srcH := bounds.Dx(), bounds.Dy()
if bounds.Empty() {
return &image.Gray{}
}
dst := image.NewGray(bounds)
parallel.Line(srcH, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < srcW; x++ {
srcPos := y*src.Stride + x*4
dstPos := y*dst.Stride + x
c := 0.3*float64(src.Pix[srcPos+0]) + 0.6*float64(src.Pix[srcPos+1]) + 0.1*float64(src.Pix[srcPos+2])
dst.Pix[dstPos] = uint8(c + 0.5)
}
}
})
return dst
} | [
"func",
"Grayscale",
"(",
"img",
"image",
".",
"Image",
")",
"*",
"image",
".",
"Gray",
"{",
"src",
":=",
"clone",
".",
"AsRGBA",
"(",
"img",
")",
"\n",
"bounds",
":=",
"src",
".",
"Bounds",
"(",
")",
"\n",
"srcW",
",",
"srcH",
":=",
"bounds",
".... | // Grayscale returns a copy of the image in Grayscale using the weights
// 0.3R + 0.6G + 0.1B as a heuristic. | [
"Grayscale",
"returns",
"a",
"copy",
"of",
"the",
"image",
"in",
"Grayscale",
"using",
"the",
"weights",
"0",
".",
"3R",
"+",
"0",
".",
"6G",
"+",
"0",
".",
"1B",
"as",
"a",
"heuristic",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/effect/effect.go#L32-L56 | train |
anthonynsimon/bild | effect/effect.go | Sepia | func Sepia(img image.Image) *image.RGBA {
fn := func(c color.RGBA) color.RGBA {
// Cache values as float64
var fc [3]float64
fc[0] = float64(c.R)
fc[1] = float64(c.G)
fc[2] = float64(c.B)
// Calculate out color based on heuristic
outRed := fc[0]*0.393 + fc[1]*0.769 + fc[2]*0.189
outGreen := fc[0]*0.349 + fc[1]*0.686 + fc[2]*0.168
outBlue := fc[0]*0.272 + fc[1]*0.534 + fc[2]*0.131
// Clamp ceiled values before returning
return color.RGBA{
R: uint8(f64.Clamp(outRed+0.5, 0, 255)),
G: uint8(f64.Clamp(outGreen+0.5, 0, 255)),
B: uint8(f64.Clamp(outBlue+0.5, 0, 255)),
A: c.A,
}
}
dst := adjust.Apply(img, fn)
return dst
} | go | func Sepia(img image.Image) *image.RGBA {
fn := func(c color.RGBA) color.RGBA {
// Cache values as float64
var fc [3]float64
fc[0] = float64(c.R)
fc[1] = float64(c.G)
fc[2] = float64(c.B)
// Calculate out color based on heuristic
outRed := fc[0]*0.393 + fc[1]*0.769 + fc[2]*0.189
outGreen := fc[0]*0.349 + fc[1]*0.686 + fc[2]*0.168
outBlue := fc[0]*0.272 + fc[1]*0.534 + fc[2]*0.131
// Clamp ceiled values before returning
return color.RGBA{
R: uint8(f64.Clamp(outRed+0.5, 0, 255)),
G: uint8(f64.Clamp(outGreen+0.5, 0, 255)),
B: uint8(f64.Clamp(outBlue+0.5, 0, 255)),
A: c.A,
}
}
dst := adjust.Apply(img, fn)
return dst
} | [
"func",
"Sepia",
"(",
"img",
"image",
".",
"Image",
")",
"*",
"image",
".",
"RGBA",
"{",
"fn",
":=",
"func",
"(",
"c",
"color",
".",
"RGBA",
")",
"color",
".",
"RGBA",
"{",
"// Cache values as float64",
"var",
"fc",
"[",
"3",
"]",
"float64",
"\n",
... | // Sepia returns a copy of the image in Sepia tone. | [
"Sepia",
"returns",
"a",
"copy",
"of",
"the",
"image",
"in",
"Sepia",
"tone",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/effect/effect.go#L59-L84 | train |
anthonynsimon/bild | effect/effect.go | EdgeDetection | func EdgeDetection(src image.Image, radius float64) *image.RGBA {
if radius <= 0 {
return image.NewRGBA(src.Bounds())
}
length := int(math.Ceil(2*radius + 1))
k := convolution.NewKernel(length, length)
for x := 0; x < length; x++ {
for y := 0; y < length; y++ {
v := -1.0
if x == length/2 && y == length/2 {
v = float64(length*length) - 1
}
k.Matrix[y*length+x] = v
}
}
return convolution.Convolve(src, k, &convolution.Options{Bias: 0, Wrap: false, KeepAlpha: false})
} | go | func EdgeDetection(src image.Image, radius float64) *image.RGBA {
if radius <= 0 {
return image.NewRGBA(src.Bounds())
}
length := int(math.Ceil(2*radius + 1))
k := convolution.NewKernel(length, length)
for x := 0; x < length; x++ {
for y := 0; y < length; y++ {
v := -1.0
if x == length/2 && y == length/2 {
v = float64(length*length) - 1
}
k.Matrix[y*length+x] = v
}
}
return convolution.Convolve(src, k, &convolution.Options{Bias: 0, Wrap: false, KeepAlpha: false})
} | [
"func",
"EdgeDetection",
"(",
"src",
"image",
".",
"Image",
",",
"radius",
"float64",
")",
"*",
"image",
".",
"RGBA",
"{",
"if",
"radius",
"<=",
"0",
"{",
"return",
"image",
".",
"NewRGBA",
"(",
"src",
".",
"Bounds",
"(",
")",
")",
"\n",
"}",
"\n\n... | // EdgeDetection returns a copy of the image with its edges highlighted. | [
"EdgeDetection",
"returns",
"a",
"copy",
"of",
"the",
"image",
"with",
"its",
"edges",
"highlighted",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/effect/effect.go#L87-L106 | train |
anthonynsimon/bild | effect/effect.go | Sharpen | func Sharpen(src image.Image) *image.RGBA {
k := convolution.Kernel{
Matrix: []float64{
0, -1, 0,
-1, 5, -1,
0, -1, 0,
},
Width: 3,
Height: 3,
}
return convolution.Convolve(src, &k, &convolution.Options{Bias: 0, Wrap: false})
} | go | func Sharpen(src image.Image) *image.RGBA {
k := convolution.Kernel{
Matrix: []float64{
0, -1, 0,
-1, 5, -1,
0, -1, 0,
},
Width: 3,
Height: 3,
}
return convolution.Convolve(src, &k, &convolution.Options{Bias: 0, Wrap: false})
} | [
"func",
"Sharpen",
"(",
"src",
"image",
".",
"Image",
")",
"*",
"image",
".",
"RGBA",
"{",
"k",
":=",
"convolution",
".",
"Kernel",
"{",
"Matrix",
":",
"[",
"]",
"float64",
"{",
"0",
",",
"-",
"1",
",",
"0",
",",
"-",
"1",
",",
"5",
",",
"-",... | // Sharpen returns a sharpened copy of the image by detecting its edges and adding it to the original. | [
"Sharpen",
"returns",
"a",
"sharpened",
"copy",
"of",
"the",
"image",
"by",
"detecting",
"its",
"edges",
"and",
"adding",
"it",
"to",
"the",
"original",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/effect/effect.go#L125-L137 | train |
anthonynsimon/bild | effect/effect.go | UnsharpMask | func UnsharpMask(img image.Image, radius, amount float64) *image.RGBA {
amount = f64.Clamp(amount, 0, 10)
blurred := blur.Gaussian(img, 5*radius) // scale radius by matching factor
bounds := img.Bounds()
src := clone.AsRGBA(img)
dst := image.NewRGBA(bounds)
w, h := bounds.Dx(), bounds.Dy()
parallel.Line(h, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < w; x++ {
pos := y*dst.Stride + x*4
r := float64(src.Pix[pos+0])
g := float64(src.Pix[pos+1])
b := float64(src.Pix[pos+2])
a := float64(src.Pix[pos+3])
rBlur := float64(blurred.Pix[pos+0])
gBlur := float64(blurred.Pix[pos+1])
bBlur := float64(blurred.Pix[pos+2])
aBlur := float64(blurred.Pix[pos+3])
r = r + (r-rBlur)*amount
g = g + (g-gBlur)*amount
b = b + (b-bBlur)*amount
a = a + (a-aBlur)*amount
dst.Pix[pos+0] = uint8(f64.Clamp(r, 0, 255))
dst.Pix[pos+1] = uint8(f64.Clamp(g, 0, 255))
dst.Pix[pos+2] = uint8(f64.Clamp(b, 0, 255))
dst.Pix[pos+3] = uint8(f64.Clamp(a, 0, 255))
}
}
})
return dst
} | go | func UnsharpMask(img image.Image, radius, amount float64) *image.RGBA {
amount = f64.Clamp(amount, 0, 10)
blurred := blur.Gaussian(img, 5*radius) // scale radius by matching factor
bounds := img.Bounds()
src := clone.AsRGBA(img)
dst := image.NewRGBA(bounds)
w, h := bounds.Dx(), bounds.Dy()
parallel.Line(h, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < w; x++ {
pos := y*dst.Stride + x*4
r := float64(src.Pix[pos+0])
g := float64(src.Pix[pos+1])
b := float64(src.Pix[pos+2])
a := float64(src.Pix[pos+3])
rBlur := float64(blurred.Pix[pos+0])
gBlur := float64(blurred.Pix[pos+1])
bBlur := float64(blurred.Pix[pos+2])
aBlur := float64(blurred.Pix[pos+3])
r = r + (r-rBlur)*amount
g = g + (g-gBlur)*amount
b = b + (b-bBlur)*amount
a = a + (a-aBlur)*amount
dst.Pix[pos+0] = uint8(f64.Clamp(r, 0, 255))
dst.Pix[pos+1] = uint8(f64.Clamp(g, 0, 255))
dst.Pix[pos+2] = uint8(f64.Clamp(b, 0, 255))
dst.Pix[pos+3] = uint8(f64.Clamp(a, 0, 255))
}
}
})
return dst
} | [
"func",
"UnsharpMask",
"(",
"img",
"image",
".",
"Image",
",",
"radius",
",",
"amount",
"float64",
")",
"*",
"image",
".",
"RGBA",
"{",
"amount",
"=",
"f64",
".",
"Clamp",
"(",
"amount",
",",
"0",
",",
"10",
")",
"\n\n",
"blurred",
":=",
"blur",
".... | // UnsharpMask returns a copy of the image with its high-frecuency components amplified.
// Parameter radius corresponds to the radius to be samples per pixel.
// Parameter amount is the normalized strength of the effect. A value of 0.0 will leave
// the image untouched and a value of 1.0 will fully apply the unsharp mask. | [
"UnsharpMask",
"returns",
"a",
"copy",
"of",
"the",
"image",
"with",
"its",
"high",
"-",
"frecuency",
"components",
"amplified",
".",
"Parameter",
"radius",
"corresponds",
"to",
"the",
"radius",
"to",
"be",
"samples",
"per",
"pixel",
".",
"Parameter",
"amount"... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/effect/effect.go#L143-L182 | train |
anthonynsimon/bild | effect/effect.go | Median | func Median(img image.Image, radius float64) *image.RGBA {
fn := func(neighbors []color.RGBA) color.RGBA {
util.SortRGBA(neighbors, 0, len(neighbors)-1)
return neighbors[len(neighbors)/2]
}
result := spatialFilter(img, radius, fn)
return result
} | go | func Median(img image.Image, radius float64) *image.RGBA {
fn := func(neighbors []color.RGBA) color.RGBA {
util.SortRGBA(neighbors, 0, len(neighbors)-1)
return neighbors[len(neighbors)/2]
}
result := spatialFilter(img, radius, fn)
return result
} | [
"func",
"Median",
"(",
"img",
"image",
".",
"Image",
",",
"radius",
"float64",
")",
"*",
"image",
".",
"RGBA",
"{",
"fn",
":=",
"func",
"(",
"neighbors",
"[",
"]",
"color",
".",
"RGBA",
")",
"color",
".",
"RGBA",
"{",
"util",
".",
"SortRGBA",
"(",
... | // Median returns a new image in which each pixel is the median of its neighbors.
// The parameter radius corresponds to the radius of the neighbor area to be searched,
// for example a radius of R will result in a search window length of 2R+1 for each dimension. | [
"Median",
"returns",
"a",
"new",
"image",
"in",
"which",
"each",
"pixel",
"is",
"the",
"median",
"of",
"its",
"neighbors",
".",
"The",
"parameter",
"radius",
"corresponds",
"to",
"the",
"radius",
"of",
"the",
"neighbor",
"area",
"to",
"be",
"searched",
"fo... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/effect/effect.go#L216-L225 | train |
anthonynsimon/bild | effect/effect.go | spatialFilter | func spatialFilter(img image.Image, radius float64, pickerFn func(neighbors []color.RGBA) color.RGBA) *image.RGBA {
if radius <= 0 {
return clone.AsRGBA(img)
}
padding := int(radius + 0.5)
src := clone.Pad(img, padding, padding, clone.EdgeExtend)
kernelSize := int(2*radius + 1 + 0.5)
bounds := img.Bounds()
dst := image.NewRGBA(bounds)
w, h := bounds.Dx(), bounds.Dy()
neighborsCount := kernelSize * kernelSize
parallel.Line(h, func(start, end int) {
for y := start + padding; y < end+padding; y++ {
for x := padding; x < w+padding; x++ {
neighbors := make([]color.RGBA, neighborsCount)
i := 0
for ky := 0; ky < kernelSize; ky++ {
for kx := 0; kx < kernelSize; kx++ {
ix := x - kernelSize>>1 + kx
iy := y - kernelSize>>1 + ky
ipos := iy*src.Stride + ix*4
neighbors[i] = color.RGBA{
R: src.Pix[ipos+0],
G: src.Pix[ipos+1],
B: src.Pix[ipos+2],
A: src.Pix[ipos+3],
}
i++
}
}
c := pickerFn(neighbors)
pos := (y-padding)*dst.Stride + (x-padding)*4
dst.Pix[pos+0] = c.R
dst.Pix[pos+1] = c.G
dst.Pix[pos+2] = c.B
dst.Pix[pos+3] = c.A
}
}
})
return dst
} | go | func spatialFilter(img image.Image, radius float64, pickerFn func(neighbors []color.RGBA) color.RGBA) *image.RGBA {
if radius <= 0 {
return clone.AsRGBA(img)
}
padding := int(radius + 0.5)
src := clone.Pad(img, padding, padding, clone.EdgeExtend)
kernelSize := int(2*radius + 1 + 0.5)
bounds := img.Bounds()
dst := image.NewRGBA(bounds)
w, h := bounds.Dx(), bounds.Dy()
neighborsCount := kernelSize * kernelSize
parallel.Line(h, func(start, end int) {
for y := start + padding; y < end+padding; y++ {
for x := padding; x < w+padding; x++ {
neighbors := make([]color.RGBA, neighborsCount)
i := 0
for ky := 0; ky < kernelSize; ky++ {
for kx := 0; kx < kernelSize; kx++ {
ix := x - kernelSize>>1 + kx
iy := y - kernelSize>>1 + ky
ipos := iy*src.Stride + ix*4
neighbors[i] = color.RGBA{
R: src.Pix[ipos+0],
G: src.Pix[ipos+1],
B: src.Pix[ipos+2],
A: src.Pix[ipos+3],
}
i++
}
}
c := pickerFn(neighbors)
pos := (y-padding)*dst.Stride + (x-padding)*4
dst.Pix[pos+0] = c.R
dst.Pix[pos+1] = c.G
dst.Pix[pos+2] = c.B
dst.Pix[pos+3] = c.A
}
}
})
return dst
} | [
"func",
"spatialFilter",
"(",
"img",
"image",
".",
"Image",
",",
"radius",
"float64",
",",
"pickerFn",
"func",
"(",
"neighbors",
"[",
"]",
"color",
".",
"RGBA",
")",
"color",
".",
"RGBA",
")",
"*",
"image",
".",
"RGBA",
"{",
"if",
"radius",
"<=",
"0"... | // spatialFilter goes through each pixel on an image collecting its neighbors and picking one
// based on the function provided. The resulting image is then returned.
// The parameter radius corresponds to the radius of the neighbor area to be searched,
// for example a radius of R will result in a search window length of 2R+1 for each dimension.
// The parameter pickerFn is the function that receives the list of neighbors and returns the selected
// neighbor to be used for the resulting image. | [
"spatialFilter",
"goes",
"through",
"each",
"pixel",
"on",
"an",
"image",
"collecting",
"its",
"neighbors",
"and",
"picking",
"one",
"based",
"on",
"the",
"function",
"provided",
".",
"The",
"resulting",
"image",
"is",
"then",
"returned",
".",
"The",
"paramete... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/effect/effect.go#L261-L311 | train |
anthonynsimon/bild | util/util.go | SortRGBA | func SortRGBA(data []color.RGBA, min, max int) {
if min > max {
return
}
p := partitionRGBASlice(data, min, max)
SortRGBA(data, min, p-1)
SortRGBA(data, p+1, max)
} | go | func SortRGBA(data []color.RGBA, min, max int) {
if min > max {
return
}
p := partitionRGBASlice(data, min, max)
SortRGBA(data, min, p-1)
SortRGBA(data, p+1, max)
} | [
"func",
"SortRGBA",
"(",
"data",
"[",
"]",
"color",
".",
"RGBA",
",",
"min",
",",
"max",
"int",
")",
"{",
"if",
"min",
">",
"max",
"{",
"return",
"\n",
"}",
"\n",
"p",
":=",
"partitionRGBASlice",
"(",
"data",
",",
"min",
",",
"max",
")",
"\n",
... | // SortRGBA sorts a slice of RGBA values.
// Parameter min and max correspond to the start and end slice indices
// that determine the range to be sorted. | [
"SortRGBA",
"sorts",
"a",
"slice",
"of",
"RGBA",
"values",
".",
"Parameter",
"min",
"and",
"max",
"correspond",
"to",
"the",
"start",
"and",
"end",
"slice",
"indices",
"that",
"determine",
"the",
"range",
"to",
"be",
"sorted",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/util/util.go#L13-L20 | train |
anthonynsimon/bild | util/util.go | Rank | func Rank(c color.RGBA) float64 {
return float64(c.R)*0.3 + float64(c.G)*0.6 + float64(c.B)*0.1
} | go | func Rank(c color.RGBA) float64 {
return float64(c.R)*0.3 + float64(c.G)*0.6 + float64(c.B)*0.1
} | [
"func",
"Rank",
"(",
"c",
"color",
".",
"RGBA",
")",
"float64",
"{",
"return",
"float64",
"(",
"c",
".",
"R",
")",
"*",
"0.3",
"+",
"float64",
"(",
"c",
".",
"G",
")",
"*",
"0.6",
"+",
"float64",
"(",
"c",
".",
"B",
")",
"*",
"0.1",
"\n",
"... | // Rank a color based on a color perception heuristic. | [
"Rank",
"a",
"color",
"based",
"on",
"a",
"color",
"perception",
"heuristic",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/util/util.go#L41-L43 | train |
anthonynsimon/bild | util/util.go | RGBAToString | func RGBAToString(img *image.RGBA) string {
var result string
result += fmt.Sprintf("\nBounds: %v", img.Bounds())
result += fmt.Sprintf("\nStride: %v", img.Stride)
for y := 0; y < img.Bounds().Dy(); y++ {
result += "\n"
for x := 0; x < img.Bounds().Dx(); x++ {
pos := y*img.Stride + x*4
result += fmt.Sprintf("%#X, ", img.Pix[pos+0])
result += fmt.Sprintf("%#X, ", img.Pix[pos+1])
result += fmt.Sprintf("%#X, ", img.Pix[pos+2])
result += fmt.Sprintf("%#X, ", img.Pix[pos+3])
}
}
result += "\n"
return result
} | go | func RGBAToString(img *image.RGBA) string {
var result string
result += fmt.Sprintf("\nBounds: %v", img.Bounds())
result += fmt.Sprintf("\nStride: %v", img.Stride)
for y := 0; y < img.Bounds().Dy(); y++ {
result += "\n"
for x := 0; x < img.Bounds().Dx(); x++ {
pos := y*img.Stride + x*4
result += fmt.Sprintf("%#X, ", img.Pix[pos+0])
result += fmt.Sprintf("%#X, ", img.Pix[pos+1])
result += fmt.Sprintf("%#X, ", img.Pix[pos+2])
result += fmt.Sprintf("%#X, ", img.Pix[pos+3])
}
}
result += "\n"
return result
} | [
"func",
"RGBAToString",
"(",
"img",
"*",
"image",
".",
"RGBA",
")",
"string",
"{",
"var",
"result",
"string",
"\n",
"result",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"img",
".",
"Bounds",
"(",
")",
")",
"\n",
"result",
"+=",
"fmt"... | // RGBAToString returns a string representation of the Hex values contained in an image.RGBA. | [
"RGBAToString",
"returns",
"a",
"string",
"representation",
"of",
"the",
"Hex",
"values",
"contained",
"in",
"an",
"image",
".",
"RGBA",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/util/util.go#L46-L62 | train |
anthonynsimon/bild | util/util.go | RGBASlicesEqual | func RGBASlicesEqual(a, b []color.RGBA) bool {
if a == nil && b == nil {
return true
}
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
} | go | func RGBASlicesEqual(a, b []color.RGBA) bool {
if a == nil && b == nil {
return true
}
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
} | [
"func",
"RGBASlicesEqual",
"(",
"a",
",",
"b",
"[",
"]",
"color",
".",
"RGBA",
")",
"bool",
"{",
"if",
"a",
"==",
"nil",
"&&",
"b",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",... | // RGBASlicesEqual returns true if the parameter RGBA color slices a and b match
// or false if otherwise. | [
"RGBASlicesEqual",
"returns",
"true",
"if",
"the",
"parameter",
"RGBA",
"color",
"slices",
"a",
"and",
"b",
"match",
"or",
"false",
"if",
"otherwise",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/util/util.go#L66-L82 | train |
anthonynsimon/bild | util/util.go | GrayImageEqual | func GrayImageEqual(a, b *image.Gray) bool {
if !a.Rect.Eq(b.Rect) {
return false
}
for i := 0; i < len(a.Pix); i++ {
if a.Pix[i] != b.Pix[i] {
return false
}
}
return true
} | go | func GrayImageEqual(a, b *image.Gray) bool {
if !a.Rect.Eq(b.Rect) {
return false
}
for i := 0; i < len(a.Pix); i++ {
if a.Pix[i] != b.Pix[i] {
return false
}
}
return true
} | [
"func",
"GrayImageEqual",
"(",
"a",
",",
"b",
"*",
"image",
".",
"Gray",
")",
"bool",
"{",
"if",
"!",
"a",
".",
"Rect",
".",
"Eq",
"(",
"b",
".",
"Rect",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
... | // GrayImageEqual returns true if the parameter images a and b match
// or false if otherwise. | [
"GrayImageEqual",
"returns",
"true",
"if",
"the",
"parameter",
"images",
"a",
"and",
"b",
"match",
"or",
"false",
"if",
"otherwise",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/util/util.go#L86-L97 | train |
anthonynsimon/bild | util/util.go | RGBAImageEqual | func RGBAImageEqual(a, b *image.RGBA) bool {
if !a.Rect.Eq(b.Rect) {
return false
}
for y := 0; y < a.Bounds().Dy(); y++ {
for x := 0; x < a.Bounds().Dx(); x++ {
pos := y*a.Stride + x*4
if a.Pix[pos+0] != b.Pix[pos+0] {
return false
}
if a.Pix[pos+1] != b.Pix[pos+1] {
return false
}
if a.Pix[pos+2] != b.Pix[pos+2] {
return false
}
if a.Pix[pos+3] != b.Pix[pos+3] {
return false
}
}
}
return true
} | go | func RGBAImageEqual(a, b *image.RGBA) bool {
if !a.Rect.Eq(b.Rect) {
return false
}
for y := 0; y < a.Bounds().Dy(); y++ {
for x := 0; x < a.Bounds().Dx(); x++ {
pos := y*a.Stride + x*4
if a.Pix[pos+0] != b.Pix[pos+0] {
return false
}
if a.Pix[pos+1] != b.Pix[pos+1] {
return false
}
if a.Pix[pos+2] != b.Pix[pos+2] {
return false
}
if a.Pix[pos+3] != b.Pix[pos+3] {
return false
}
}
}
return true
} | [
"func",
"RGBAImageEqual",
"(",
"a",
",",
"b",
"*",
"image",
".",
"RGBA",
")",
"bool",
"{",
"if",
"!",
"a",
".",
"Rect",
".",
"Eq",
"(",
"b",
".",
"Rect",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"y",
":=",
"0",
";",
"y",
"<",
... | // RGBAImageEqual returns true if the parameter images a and b match
// or false if otherwise. | [
"RGBAImageEqual",
"returns",
"true",
"if",
"the",
"parameter",
"images",
"a",
"and",
"b",
"match",
"or",
"false",
"if",
"otherwise",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/util/util.go#L101-L124 | train |
anthonynsimon/bild | util/stack.go | Push | func (s *Stack) Push(value interface{}) {
s.top = &stackElement{value, s.top}
s.size++
} | go | func (s *Stack) Push(value interface{}) {
s.top = &stackElement{value, s.top}
s.size++
} | [
"func",
"(",
"s",
"*",
"Stack",
")",
"Push",
"(",
"value",
"interface",
"{",
"}",
")",
"{",
"s",
".",
"top",
"=",
"&",
"stackElement",
"{",
"value",
",",
"s",
".",
"top",
"}",
"\n",
"s",
".",
"size",
"++",
"\n",
"}"
] | // Push a new value onto the stack | [
"Push",
"a",
"new",
"value",
"onto",
"the",
"stack"
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/util/stack.go#L20-L23 | train |
anthonynsimon/bild | util/stack.go | Pop | func (s *Stack) Pop() interface{} {
if s.size > 0 {
value := s.top.value
s.top = s.top.next
s.size--
return value
}
return nil
} | go | func (s *Stack) Pop() interface{} {
if s.size > 0 {
value := s.top.value
s.top = s.top.next
s.size--
return value
}
return nil
} | [
"func",
"(",
"s",
"*",
"Stack",
")",
"Pop",
"(",
")",
"interface",
"{",
"}",
"{",
"if",
"s",
".",
"size",
">",
"0",
"{",
"value",
":=",
"s",
".",
"top",
".",
"value",
"\n",
"s",
".",
"top",
"=",
"s",
".",
"top",
".",
"next",
"\n",
"s",
".... | // Pop the most recently pushed value from the stack | [
"Pop",
"the",
"most",
"recently",
"pushed",
"value",
"from",
"the",
"stack"
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/util/stack.go#L26-L34 | train |
anthonynsimon/bild | fcolor/rgbaf64.go | NewRGBAF64 | func NewRGBAF64(r, g, b, a uint8) RGBAF64 {
return RGBAF64{float64(r) / 255, float64(g) / 255, float64(b) / 255, float64(a) / 255}
} | go | func NewRGBAF64(r, g, b, a uint8) RGBAF64 {
return RGBAF64{float64(r) / 255, float64(g) / 255, float64(b) / 255, float64(a) / 255}
} | [
"func",
"NewRGBAF64",
"(",
"r",
",",
"g",
",",
"b",
",",
"a",
"uint8",
")",
"RGBAF64",
"{",
"return",
"RGBAF64",
"{",
"float64",
"(",
"r",
")",
"/",
"255",
",",
"float64",
"(",
"g",
")",
"/",
"255",
",",
"float64",
"(",
"b",
")",
"/",
"255",
... | // NewRGBAF64 returns a new RGBAF64 color based on the provided uint8 values.
// uint8 value 0 maps to 0, 128 to 0.5 and 255 to 1.0. | [
"NewRGBAF64",
"returns",
"a",
"new",
"RGBAF64",
"color",
"based",
"on",
"the",
"provided",
"uint8",
"values",
".",
"uint8",
"value",
"0",
"maps",
"to",
"0",
"128",
"to",
"0",
".",
"5",
"and",
"255",
"to",
"1",
".",
"0",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/fcolor/rgbaf64.go#L13-L15 | train |
anthonynsimon/bild | fcolor/rgbaf64.go | Clamp | func (c *RGBAF64) Clamp() {
c.R = f64.Clamp(c.R, 0, 1)
c.G = f64.Clamp(c.G, 0, 1)
c.B = f64.Clamp(c.B, 0, 1)
c.A = f64.Clamp(c.A, 0, 1)
} | go | func (c *RGBAF64) Clamp() {
c.R = f64.Clamp(c.R, 0, 1)
c.G = f64.Clamp(c.G, 0, 1)
c.B = f64.Clamp(c.B, 0, 1)
c.A = f64.Clamp(c.A, 0, 1)
} | [
"func",
"(",
"c",
"*",
"RGBAF64",
")",
"Clamp",
"(",
")",
"{",
"c",
".",
"R",
"=",
"f64",
".",
"Clamp",
"(",
"c",
".",
"R",
",",
"0",
",",
"1",
")",
"\n",
"c",
".",
"G",
"=",
"f64",
".",
"Clamp",
"(",
"c",
".",
"G",
",",
"0",
",",
"1"... | // Clamp limits the channel values of the RGBAF64 color to the range 0.0 to 1.0. | [
"Clamp",
"limits",
"the",
"channel",
"values",
"of",
"the",
"RGBAF64",
"color",
"to",
"the",
"range",
"0",
".",
"0",
"to",
"1",
".",
"0",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/fcolor/rgbaf64.go#L18-L23 | train |
anthonynsimon/bild | imgio/io.go | JPEGEncoder | func JPEGEncoder(quality int) Encoder {
return func(w io.Writer, img image.Image) error {
return jpeg.Encode(w, img, &jpeg.Options{Quality: quality})
}
} | go | func JPEGEncoder(quality int) Encoder {
return func(w io.Writer, img image.Image) error {
return jpeg.Encode(w, img, &jpeg.Options{Quality: quality})
}
} | [
"func",
"JPEGEncoder",
"(",
"quality",
"int",
")",
"Encoder",
"{",
"return",
"func",
"(",
"w",
"io",
".",
"Writer",
",",
"img",
"image",
".",
"Image",
")",
"error",
"{",
"return",
"jpeg",
".",
"Encode",
"(",
"w",
",",
"img",
",",
"&",
"jpeg",
".",
... | // JPEGEncoder returns an encoder to JPEG given the argument 'quality' | [
"JPEGEncoder",
"returns",
"an",
"encoder",
"to",
"JPEG",
"given",
"the",
"argument",
"quality"
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/imgio/io.go#L40-L44 | train |
anthonynsimon/bild | imgio/io.go | PNGEncoder | func PNGEncoder() Encoder {
return func(w io.Writer, img image.Image) error {
return png.Encode(w, img)
}
} | go | func PNGEncoder() Encoder {
return func(w io.Writer, img image.Image) error {
return png.Encode(w, img)
}
} | [
"func",
"PNGEncoder",
"(",
")",
"Encoder",
"{",
"return",
"func",
"(",
"w",
"io",
".",
"Writer",
",",
"img",
"image",
".",
"Image",
")",
"error",
"{",
"return",
"png",
".",
"Encode",
"(",
"w",
",",
"img",
")",
"\n",
"}",
"\n",
"}"
] | // PNGEncoder returns an encoder to PNG | [
"PNGEncoder",
"returns",
"an",
"encoder",
"to",
"PNG"
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/imgio/io.go#L47-L51 | train |
anthonynsimon/bild | imgio/io.go | BMPEncoder | func BMPEncoder() Encoder {
return func(w io.Writer, img image.Image) error {
return bmp.Encode(w, img)
}
} | go | func BMPEncoder() Encoder {
return func(w io.Writer, img image.Image) error {
return bmp.Encode(w, img)
}
} | [
"func",
"BMPEncoder",
"(",
")",
"Encoder",
"{",
"return",
"func",
"(",
"w",
"io",
".",
"Writer",
",",
"img",
"image",
".",
"Image",
")",
"error",
"{",
"return",
"bmp",
".",
"Encode",
"(",
"w",
",",
"img",
")",
"\n",
"}",
"\n",
"}"
] | // BMPEncoder returns an encoder to BMP | [
"BMPEncoder",
"returns",
"an",
"encoder",
"to",
"BMP"
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/imgio/io.go#L54-L58 | train |
anthonynsimon/bild | parallel/parallel.go | Line | func Line(length int, fn func(start, end int)) {
procs := runtime.GOMAXPROCS(0)
counter := length
partSize := length / procs
if procs <= 1 || partSize <= procs {
fn(0, length)
} else {
var wg sync.WaitGroup
for counter > 0 {
start := counter - partSize
end := counter
if start < 0 {
start = 0
}
counter -= partSize
wg.Add(1)
go func() {
defer wg.Done()
fn(start, end)
}()
}
wg.Wait()
}
} | go | func Line(length int, fn func(start, end int)) {
procs := runtime.GOMAXPROCS(0)
counter := length
partSize := length / procs
if procs <= 1 || partSize <= procs {
fn(0, length)
} else {
var wg sync.WaitGroup
for counter > 0 {
start := counter - partSize
end := counter
if start < 0 {
start = 0
}
counter -= partSize
wg.Add(1)
go func() {
defer wg.Done()
fn(start, end)
}()
}
wg.Wait()
}
} | [
"func",
"Line",
"(",
"length",
"int",
",",
"fn",
"func",
"(",
"start",
",",
"end",
"int",
")",
")",
"{",
"procs",
":=",
"runtime",
".",
"GOMAXPROCS",
"(",
"0",
")",
"\n",
"counter",
":=",
"length",
"\n",
"partSize",
":=",
"length",
"/",
"procs",
"\... | // Line dispatches a parameter fn into multiple goroutines by splitting the parameter length
// by the number of available CPUs and assigning the length parts into each fn. | [
"Line",
"dispatches",
"a",
"parameter",
"fn",
"into",
"multiple",
"goroutines",
"by",
"splitting",
"the",
"parameter",
"length",
"by",
"the",
"number",
"of",
"available",
"CPUs",
"and",
"assigning",
"the",
"length",
"parts",
"into",
"each",
"fn",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/parallel/parallel.go#L15-L39 | train |
anthonynsimon/bild | transform/rotate.go | FlipH | func FlipH(img image.Image) *image.RGBA {
bounds := img.Bounds()
src := clone.AsRGBA(img)
dst := image.NewRGBA(bounds)
w, h := dst.Bounds().Dx(), dst.Bounds().Dy()
parallel.Line(h, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < w; x++ {
iy := y * dst.Stride
pos := iy + (x * 4)
flippedX := w - x - 1
flippedPos := iy + (flippedX * 4)
dst.Pix[pos+0] = src.Pix[flippedPos+0]
dst.Pix[pos+1] = src.Pix[flippedPos+1]
dst.Pix[pos+2] = src.Pix[flippedPos+2]
dst.Pix[pos+3] = src.Pix[flippedPos+3]
}
}
})
return dst
} | go | func FlipH(img image.Image) *image.RGBA {
bounds := img.Bounds()
src := clone.AsRGBA(img)
dst := image.NewRGBA(bounds)
w, h := dst.Bounds().Dx(), dst.Bounds().Dy()
parallel.Line(h, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < w; x++ {
iy := y * dst.Stride
pos := iy + (x * 4)
flippedX := w - x - 1
flippedPos := iy + (flippedX * 4)
dst.Pix[pos+0] = src.Pix[flippedPos+0]
dst.Pix[pos+1] = src.Pix[flippedPos+1]
dst.Pix[pos+2] = src.Pix[flippedPos+2]
dst.Pix[pos+3] = src.Pix[flippedPos+3]
}
}
})
return dst
} | [
"func",
"FlipH",
"(",
"img",
"image",
".",
"Image",
")",
"*",
"image",
".",
"RGBA",
"{",
"bounds",
":=",
"img",
".",
"Bounds",
"(",
")",
"\n",
"src",
":=",
"clone",
".",
"AsRGBA",
"(",
"img",
")",
"\n",
"dst",
":=",
"image",
".",
"NewRGBA",
"(",
... | // FlipH returns a horizontally flipped version of the image. | [
"FlipH",
"returns",
"a",
"horizontally",
"flipped",
"version",
"of",
"the",
"image",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/transform/rotate.go#L125-L148 | train |
anthonynsimon/bild | math/f64/clamp.go | Clamp | func Clamp(value, min, max float64) float64 {
if value > max {
return max
}
if value < min {
return min
}
return value
} | go | func Clamp(value, min, max float64) float64 {
if value > max {
return max
}
if value < min {
return min
}
return value
} | [
"func",
"Clamp",
"(",
"value",
",",
"min",
",",
"max",
"float64",
")",
"float64",
"{",
"if",
"value",
">",
"max",
"{",
"return",
"max",
"\n",
"}",
"\n",
"if",
"value",
"<",
"min",
"{",
"return",
"min",
"\n",
"}",
"\n",
"return",
"value",
"\n",
"}... | // Clamp returns the value if it fits within the parameters min and max.
// Otherwise returns the closest boundary parameter value. | [
"Clamp",
"returns",
"the",
"value",
"if",
"it",
"fits",
"within",
"the",
"parameters",
"min",
"and",
"max",
".",
"Otherwise",
"returns",
"the",
"closest",
"boundary",
"parameter",
"value",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/math/f64/clamp.go#L6-L14 | train |
anthonynsimon/bild | blend/blend.go | Normal | func Normal(bg image.Image, fg image.Image) *image.RGBA {
dst := blend(bg, fg, func(c0, c1 fcolor.RGBAF64) fcolor.RGBAF64 {
return alphaComp(c0, c1)
})
return dst
} | go | func Normal(bg image.Image, fg image.Image) *image.RGBA {
dst := blend(bg, fg, func(c0, c1 fcolor.RGBAF64) fcolor.RGBAF64 {
return alphaComp(c0, c1)
})
return dst
} | [
"func",
"Normal",
"(",
"bg",
"image",
".",
"Image",
",",
"fg",
"image",
".",
"Image",
")",
"*",
"image",
".",
"RGBA",
"{",
"dst",
":=",
"blend",
"(",
"bg",
",",
"fg",
",",
"func",
"(",
"c0",
",",
"c1",
"fcolor",
".",
"RGBAF64",
")",
"fcolor",
"... | // Normal combines the foreground and background images by placing the foreground over the
// background using alpha compositing. The resulting image is then returned. | [
"Normal",
"combines",
"the",
"foreground",
"and",
"background",
"images",
"by",
"placing",
"the",
"foreground",
"over",
"the",
"background",
"using",
"alpha",
"compositing",
".",
"The",
"resulting",
"image",
"is",
"then",
"returned",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/blend/blend.go#L16-L22 | train |
anthonynsimon/bild | blend/blend.go | Add | func Add(bg image.Image, fg image.Image) *image.RGBA {
dst := blend(bg, fg, func(c0, c1 fcolor.RGBAF64) fcolor.RGBAF64 {
r := c0.R + c1.R
g := c0.G + c1.G
b := c0.B + c1.B
c2 := fcolor.RGBAF64{R: r, G: g, B: b, A: c1.A}
return alphaComp(c0, c2)
})
return dst
} | go | func Add(bg image.Image, fg image.Image) *image.RGBA {
dst := blend(bg, fg, func(c0, c1 fcolor.RGBAF64) fcolor.RGBAF64 {
r := c0.R + c1.R
g := c0.G + c1.G
b := c0.B + c1.B
c2 := fcolor.RGBAF64{R: r, G: g, B: b, A: c1.A}
return alphaComp(c0, c2)
})
return dst
} | [
"func",
"Add",
"(",
"bg",
"image",
".",
"Image",
",",
"fg",
"image",
".",
"Image",
")",
"*",
"image",
".",
"RGBA",
"{",
"dst",
":=",
"blend",
"(",
"bg",
",",
"fg",
",",
"func",
"(",
"c0",
",",
"c1",
"fcolor",
".",
"RGBAF64",
")",
"fcolor",
".",... | // Add combines the foreground and background images by adding their values and
// returns the resulting image. | [
"Add",
"combines",
"the",
"foreground",
"and",
"background",
"images",
"by",
"adding",
"their",
"values",
"and",
"returns",
"the",
"resulting",
"image",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/blend/blend.go#L26-L37 | train |
anthonynsimon/bild | blend/blend.go | Opacity | func Opacity(bg image.Image, fg image.Image, percent float64) *image.RGBA {
percent = f64.Clamp(percent, 0, 1.0)
dst := blend(bg, fg, func(c0, c1 fcolor.RGBAF64) fcolor.RGBAF64 {
r := c1.R*percent + (1-percent)*c0.R
g := c1.G*percent + (1-percent)*c0.G
b := c1.B*percent + (1-percent)*c0.B
c2 := fcolor.RGBAF64{R: r, G: g, B: b, A: c1.A}
return alphaComp(c0, c2)
})
return dst
} | go | func Opacity(bg image.Image, fg image.Image, percent float64) *image.RGBA {
percent = f64.Clamp(percent, 0, 1.0)
dst := blend(bg, fg, func(c0, c1 fcolor.RGBAF64) fcolor.RGBAF64 {
r := c1.R*percent + (1-percent)*c0.R
g := c1.G*percent + (1-percent)*c0.G
b := c1.B*percent + (1-percent)*c0.B
c2 := fcolor.RGBAF64{R: r, G: g, B: b, A: c1.A}
return alphaComp(c0, c2)
})
return dst
} | [
"func",
"Opacity",
"(",
"bg",
"image",
".",
"Image",
",",
"fg",
"image",
".",
"Image",
",",
"percent",
"float64",
")",
"*",
"image",
".",
"RGBA",
"{",
"percent",
"=",
"f64",
".",
"Clamp",
"(",
"percent",
",",
"0",
",",
"1.0",
")",
"\n\n",
"dst",
... | // Opacity returns an image which blends the two input images by the percentage provided.
// Percent must be of range 0 <= percent <= 1.0 | [
"Opacity",
"returns",
"an",
"image",
"which",
"blends",
"the",
"two",
"input",
"images",
"by",
"the",
"percentage",
"provided",
".",
"Percent",
"must",
"be",
"of",
"range",
"0",
"<",
"=",
"percent",
"<",
"=",
"1",
".",
"0"
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/blend/blend.go#L286-L299 | train |
anthonynsimon/bild | blend/blend.go | blend | func blend(bg image.Image, fg image.Image, fn func(fcolor.RGBAF64, fcolor.RGBAF64) fcolor.RGBAF64) *image.RGBA {
bgBounds := bg.Bounds()
fgBounds := fg.Bounds()
var w, h int
if bgBounds.Dx() < fgBounds.Dx() {
w = bgBounds.Dx()
} else {
w = fgBounds.Dx()
}
if bgBounds.Dy() < fgBounds.Dy() {
h = bgBounds.Dy()
} else {
h = fgBounds.Dy()
}
bgSrc := clone.AsRGBA(bg)
fgSrc := clone.AsRGBA(fg)
dst := image.NewRGBA(image.Rect(0, 0, w, h))
parallel.Line(h, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < w; x++ {
bgPos := y*bgSrc.Stride + x*4
fgPos := y*fgSrc.Stride + x*4
result := fn(
fcolor.NewRGBAF64(bgSrc.Pix[bgPos+0], bgSrc.Pix[bgPos+1], bgSrc.Pix[bgPos+2], bgSrc.Pix[bgPos+3]),
fcolor.NewRGBAF64(fgSrc.Pix[fgPos+0], fgSrc.Pix[fgPos+1], fgSrc.Pix[fgPos+2], fgSrc.Pix[fgPos+3]))
result.Clamp()
dstPos := y*dst.Stride + x*4
dst.Pix[dstPos+0] = uint8(result.R * 255)
dst.Pix[dstPos+1] = uint8(result.G * 255)
dst.Pix[dstPos+2] = uint8(result.B * 255)
dst.Pix[dstPos+3] = uint8(result.A * 255)
}
}
})
return dst
} | go | func blend(bg image.Image, fg image.Image, fn func(fcolor.RGBAF64, fcolor.RGBAF64) fcolor.RGBAF64) *image.RGBA {
bgBounds := bg.Bounds()
fgBounds := fg.Bounds()
var w, h int
if bgBounds.Dx() < fgBounds.Dx() {
w = bgBounds.Dx()
} else {
w = fgBounds.Dx()
}
if bgBounds.Dy() < fgBounds.Dy() {
h = bgBounds.Dy()
} else {
h = fgBounds.Dy()
}
bgSrc := clone.AsRGBA(bg)
fgSrc := clone.AsRGBA(fg)
dst := image.NewRGBA(image.Rect(0, 0, w, h))
parallel.Line(h, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < w; x++ {
bgPos := y*bgSrc.Stride + x*4
fgPos := y*fgSrc.Stride + x*4
result := fn(
fcolor.NewRGBAF64(bgSrc.Pix[bgPos+0], bgSrc.Pix[bgPos+1], bgSrc.Pix[bgPos+2], bgSrc.Pix[bgPos+3]),
fcolor.NewRGBAF64(fgSrc.Pix[fgPos+0], fgSrc.Pix[fgPos+1], fgSrc.Pix[fgPos+2], fgSrc.Pix[fgPos+3]))
result.Clamp()
dstPos := y*dst.Stride + x*4
dst.Pix[dstPos+0] = uint8(result.R * 255)
dst.Pix[dstPos+1] = uint8(result.G * 255)
dst.Pix[dstPos+2] = uint8(result.B * 255)
dst.Pix[dstPos+3] = uint8(result.A * 255)
}
}
})
return dst
} | [
"func",
"blend",
"(",
"bg",
"image",
".",
"Image",
",",
"fg",
"image",
".",
"Image",
",",
"fn",
"func",
"(",
"fcolor",
".",
"RGBAF64",
",",
"fcolor",
".",
"RGBAF64",
")",
"fcolor",
".",
"RGBAF64",
")",
"*",
"image",
".",
"RGBA",
"{",
"bgBounds",
":... | // Blend two images together by applying the provided function for each pixel.
// If images differ in size, the minimum width and height will be picked from each one
// when creating the resulting image. | [
"Blend",
"two",
"images",
"together",
"by",
"applying",
"the",
"provided",
"function",
"for",
"each",
"pixel",
".",
"If",
"images",
"differ",
"in",
"size",
"the",
"minimum",
"width",
"and",
"height",
"will",
"be",
"picked",
"from",
"each",
"one",
"when",
"... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/blend/blend.go#L334-L375 | train |
anthonynsimon/bild | blend/blend.go | alphaComp | func alphaComp(bg, fg fcolor.RGBAF64) fcolor.RGBAF64 {
fg.Clamp()
fga := fg.A
r := (fg.R * fga / 1) + ((1 - fga) * bg.R / 1)
g := (fg.G * fga / 1) + ((1 - fga) * bg.G / 1)
b := (fg.B * fga / 1) + ((1 - fga) * bg.B / 1)
a := bg.A + fga
return fcolor.RGBAF64{R: r, G: g, B: b, A: a}
} | go | func alphaComp(bg, fg fcolor.RGBAF64) fcolor.RGBAF64 {
fg.Clamp()
fga := fg.A
r := (fg.R * fga / 1) + ((1 - fga) * bg.R / 1)
g := (fg.G * fga / 1) + ((1 - fga) * bg.G / 1)
b := (fg.B * fga / 1) + ((1 - fga) * bg.B / 1)
a := bg.A + fga
return fcolor.RGBAF64{R: r, G: g, B: b, A: a}
} | [
"func",
"alphaComp",
"(",
"bg",
",",
"fg",
"fcolor",
".",
"RGBAF64",
")",
"fcolor",
".",
"RGBAF64",
"{",
"fg",
".",
"Clamp",
"(",
")",
"\n",
"fga",
":=",
"fg",
".",
"A",
"\n\n",
"r",
":=",
"(",
"fg",
".",
"R",
"*",
"fga",
"/",
"1",
")",
"+",
... | // alphaComp returns a new color after compositing the two colors
// based on the foreground's alpha channel. | [
"alphaComp",
"returns",
"a",
"new",
"color",
"after",
"compositing",
"the",
"two",
"colors",
"based",
"on",
"the",
"foreground",
"s",
"alpha",
"channel",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/blend/blend.go#L379-L389 | train |
anthonynsimon/bild | adjust/adjustment.go | Gamma | func Gamma(src image.Image, gamma float64) *image.RGBA {
gamma = math.Max(0.00001, gamma)
lookup := make([]uint8, 256)
for i := 0; i < 256; i++ {
lookup[i] = uint8(f64.Clamp(math.Pow(float64(i)/255, 1.0/gamma)*255, 0, 255))
}
fn := func(c color.RGBA) color.RGBA {
return color.RGBA{lookup[c.R], lookup[c.G], lookup[c.B], c.A}
}
img := Apply(src, fn)
return img
} | go | func Gamma(src image.Image, gamma float64) *image.RGBA {
gamma = math.Max(0.00001, gamma)
lookup := make([]uint8, 256)
for i := 0; i < 256; i++ {
lookup[i] = uint8(f64.Clamp(math.Pow(float64(i)/255, 1.0/gamma)*255, 0, 255))
}
fn := func(c color.RGBA) color.RGBA {
return color.RGBA{lookup[c.R], lookup[c.G], lookup[c.B], c.A}
}
img := Apply(src, fn)
return img
} | [
"func",
"Gamma",
"(",
"src",
"image",
".",
"Image",
",",
"gamma",
"float64",
")",
"*",
"image",
".",
"RGBA",
"{",
"gamma",
"=",
"math",
".",
"Max",
"(",
"0.00001",
",",
"gamma",
")",
"\n\n",
"lookup",
":=",
"make",
"(",
"[",
"]",
"uint8",
",",
"2... | // Gamma returns a gamma corrected copy of the image. Provided gamma param must be larger than 0. | [
"Gamma",
"returns",
"a",
"gamma",
"corrected",
"copy",
"of",
"the",
"image",
".",
"Provided",
"gamma",
"param",
"must",
"be",
"larger",
"than",
"0",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/adjust/adjustment.go#L32-L48 | train |
anthonynsimon/bild | adjust/adjustment.go | Hue | func Hue(img image.Image, change int) *image.RGBA {
fn := func(c color.RGBA) color.RGBA {
h, s, l := util.RGBToHSL(c)
h = float64((int(h) + change) % 360)
outColor := util.HSLToRGB(h, s, l)
outColor.A = c.A
return outColor
}
return Apply(img, fn)
} | go | func Hue(img image.Image, change int) *image.RGBA {
fn := func(c color.RGBA) color.RGBA {
h, s, l := util.RGBToHSL(c)
h = float64((int(h) + change) % 360)
outColor := util.HSLToRGB(h, s, l)
outColor.A = c.A
return outColor
}
return Apply(img, fn)
} | [
"func",
"Hue",
"(",
"img",
"image",
".",
"Image",
",",
"change",
"int",
")",
"*",
"image",
".",
"RGBA",
"{",
"fn",
":=",
"func",
"(",
"c",
"color",
".",
"RGBA",
")",
"color",
".",
"RGBA",
"{",
"h",
",",
"s",
",",
"l",
":=",
"util",
".",
"RGBT... | // Hue adjusts the overall hue of the provided image and returns the result.
// Parameter change is the amount of change to be applied and is of the range
// -360 to 360. It corresponds to the hue angle in the HSL color model. | [
"Hue",
"adjusts",
"the",
"overall",
"hue",
"of",
"the",
"provided",
"image",
"and",
"returns",
"the",
"result",
".",
"Parameter",
"change",
"is",
"the",
"amount",
"of",
"change",
"to",
"be",
"applied",
"and",
"is",
"of",
"the",
"range",
"-",
"360",
"to",... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/adjust/adjustment.go#L72-L82 | train |
anthonynsimon/bild | clone/clone.go | AsRGBA | func AsRGBA(src image.Image) *image.RGBA {
bounds := src.Bounds()
img := image.NewRGBA(bounds)
draw.Draw(img, bounds, src, bounds.Min, draw.Src)
return img
} | go | func AsRGBA(src image.Image) *image.RGBA {
bounds := src.Bounds()
img := image.NewRGBA(bounds)
draw.Draw(img, bounds, src, bounds.Min, draw.Src)
return img
} | [
"func",
"AsRGBA",
"(",
"src",
"image",
".",
"Image",
")",
"*",
"image",
".",
"RGBA",
"{",
"bounds",
":=",
"src",
".",
"Bounds",
"(",
")",
"\n",
"img",
":=",
"image",
".",
"NewRGBA",
"(",
"bounds",
")",
"\n",
"draw",
".",
"Draw",
"(",
"img",
",",
... | // AsRGBA returns an RGBA copy of the supplied image. | [
"AsRGBA",
"returns",
"an",
"RGBA",
"copy",
"of",
"the",
"supplied",
"image",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/clone/clone.go#L24-L29 | train |
anthonynsimon/bild | adjust/apply.go | Apply | func Apply(img image.Image, fn func(color.RGBA) color.RGBA) *image.RGBA {
bounds := img.Bounds()
dst := clone.AsRGBA(img)
w, h := bounds.Dx(), bounds.Dy()
parallel.Line(h, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < w; x++ {
dstPos := y*dst.Stride + x*4
c := color.RGBA{}
c.R = dst.Pix[dstPos+0]
c.G = dst.Pix[dstPos+1]
c.B = dst.Pix[dstPos+2]
c.A = dst.Pix[dstPos+3]
c = fn(c)
dst.Pix[dstPos+0] = c.R
dst.Pix[dstPos+1] = c.G
dst.Pix[dstPos+2] = c.B
dst.Pix[dstPos+3] = c.A
}
}
})
return dst
} | go | func Apply(img image.Image, fn func(color.RGBA) color.RGBA) *image.RGBA {
bounds := img.Bounds()
dst := clone.AsRGBA(img)
w, h := bounds.Dx(), bounds.Dy()
parallel.Line(h, func(start, end int) {
for y := start; y < end; y++ {
for x := 0; x < w; x++ {
dstPos := y*dst.Stride + x*4
c := color.RGBA{}
c.R = dst.Pix[dstPos+0]
c.G = dst.Pix[dstPos+1]
c.B = dst.Pix[dstPos+2]
c.A = dst.Pix[dstPos+3]
c = fn(c)
dst.Pix[dstPos+0] = c.R
dst.Pix[dstPos+1] = c.G
dst.Pix[dstPos+2] = c.B
dst.Pix[dstPos+3] = c.A
}
}
})
return dst
} | [
"func",
"Apply",
"(",
"img",
"image",
".",
"Image",
",",
"fn",
"func",
"(",
"color",
".",
"RGBA",
")",
"color",
".",
"RGBA",
")",
"*",
"image",
".",
"RGBA",
"{",
"bounds",
":=",
"img",
".",
"Bounds",
"(",
")",
"\n",
"dst",
":=",
"clone",
".",
"... | // Apply returns a copy of the provided image after applying the provided color function to each pixel. | [
"Apply",
"returns",
"a",
"copy",
"of",
"the",
"provided",
"image",
"after",
"applying",
"the",
"provided",
"color",
"function",
"to",
"each",
"pixel",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/adjust/apply.go#L12-L40 | train |
anthonynsimon/bild | util/colormodel.go | RGBToHSL | func RGBToHSL(c color.RGBA) (float64, float64, float64) {
r, g, b := float64(c.R)/255, float64(c.G)/255, float64(c.B)/255
max := math.Max(r, math.Max(g, b))
min := math.Min(r, math.Min(g, b))
delta := max - min
var h, s, l float64
l = (max + min) / 2
// Achromatic
if delta <= 0 {
return h, s, l
}
// Should it be smaller than or equals instead?
if l < 0.5 {
s = delta / (max + min)
} else {
s = delta / (2 - max - min)
}
if r >= max {
h = (g - b) / delta
} else if g >= max {
h = (b-r)/delta + 2
} else {
h = (r-g)/delta + 4
}
h *= 60
if h < 0 {
h += 360
}
return h, s, l
} | go | func RGBToHSL(c color.RGBA) (float64, float64, float64) {
r, g, b := float64(c.R)/255, float64(c.G)/255, float64(c.B)/255
max := math.Max(r, math.Max(g, b))
min := math.Min(r, math.Min(g, b))
delta := max - min
var h, s, l float64
l = (max + min) / 2
// Achromatic
if delta <= 0 {
return h, s, l
}
// Should it be smaller than or equals instead?
if l < 0.5 {
s = delta / (max + min)
} else {
s = delta / (2 - max - min)
}
if r >= max {
h = (g - b) / delta
} else if g >= max {
h = (b-r)/delta + 2
} else {
h = (r-g)/delta + 4
}
h *= 60
if h < 0 {
h += 360
}
return h, s, l
} | [
"func",
"RGBToHSL",
"(",
"c",
"color",
".",
"RGBA",
")",
"(",
"float64",
",",
"float64",
",",
"float64",
")",
"{",
"r",
",",
"g",
",",
"b",
":=",
"float64",
"(",
"c",
".",
"R",
")",
"/",
"255",
",",
"float64",
"(",
"c",
".",
"G",
")",
"/",
... | // RGBToHSL converts from RGB to HSL color model.
// Parameter c is the RGBA color and must implement the color.RGBA interface.
// Returned values h, s and l correspond to the hue, saturation and lightness.
// The hue is of range 0 to 360 and the saturation and lightness are of range 0.0 to 1.0. | [
"RGBToHSL",
"converts",
"from",
"RGB",
"to",
"HSL",
"color",
"model",
".",
"Parameter",
"c",
"is",
"the",
"RGBA",
"color",
"and",
"must",
"implement",
"the",
"color",
".",
"RGBA",
"interface",
".",
"Returned",
"values",
"h",
"s",
"and",
"l",
"correspond",
... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/util/colormodel.go#L14-L49 | train |
anthonynsimon/bild | util/colormodel.go | HSLToRGB | func HSLToRGB(h, s, l float64) color.RGBA {
var r, g, b float64
if s == 0 {
r = l
g = l
b = l
} else {
var temp0, temp1 float64
if l < 0.5 {
temp0 = l * (1 + s)
} else {
temp0 = (l + s) - (s * l)
}
temp1 = 2*l - temp0
h /= 360
hueFn := func(v float64) float64 {
if v < 0 {
v++
} else if v > 1 {
v--
}
if v < 1.0/6.0 {
return temp1 + (temp0-temp1)*6*v
}
if v < 1.0/2.0 {
return temp0
}
if v < 2.0/3.0 {
return temp1 + (temp0-temp1)*(2.0/3.0-v)*6
}
return temp1
}
r = hueFn(h + 1.0/3.0)
g = hueFn(h)
b = hueFn(h - 1.0/3.0)
}
outR := uint8(f64.Clamp(r*255+0.5, 0, 255))
outG := uint8(f64.Clamp(g*255+0.5, 0, 255))
outB := uint8(f64.Clamp(b*255+0.5, 0, 255))
return color.RGBA{outR, outG, outB, 0xFF}
} | go | func HSLToRGB(h, s, l float64) color.RGBA {
var r, g, b float64
if s == 0 {
r = l
g = l
b = l
} else {
var temp0, temp1 float64
if l < 0.5 {
temp0 = l * (1 + s)
} else {
temp0 = (l + s) - (s * l)
}
temp1 = 2*l - temp0
h /= 360
hueFn := func(v float64) float64 {
if v < 0 {
v++
} else if v > 1 {
v--
}
if v < 1.0/6.0 {
return temp1 + (temp0-temp1)*6*v
}
if v < 1.0/2.0 {
return temp0
}
if v < 2.0/3.0 {
return temp1 + (temp0-temp1)*(2.0/3.0-v)*6
}
return temp1
}
r = hueFn(h + 1.0/3.0)
g = hueFn(h)
b = hueFn(h - 1.0/3.0)
}
outR := uint8(f64.Clamp(r*255+0.5, 0, 255))
outG := uint8(f64.Clamp(g*255+0.5, 0, 255))
outB := uint8(f64.Clamp(b*255+0.5, 0, 255))
return color.RGBA{outR, outG, outB, 0xFF}
} | [
"func",
"HSLToRGB",
"(",
"h",
",",
"s",
",",
"l",
"float64",
")",
"color",
".",
"RGBA",
"{",
"var",
"r",
",",
"g",
",",
"b",
"float64",
"\n",
"if",
"s",
"==",
"0",
"{",
"r",
"=",
"l",
"\n",
"g",
"=",
"l",
"\n",
"b",
"=",
"l",
"\n",
"}",
... | // HSLToRGB converts from HSL to RGB color model.
// Parameter h is the hue and its range is from 0 to 360 degrees.
// Parameter s is the saturation and its range is from 0.0 to 1.0.
// Parameter l is the lightness and its range is from 0.0 to 1.0. | [
"HSLToRGB",
"converts",
"from",
"HSL",
"to",
"RGB",
"color",
"model",
".",
"Parameter",
"h",
"is",
"the",
"hue",
"and",
"its",
"range",
"is",
"from",
"0",
"to",
"360",
"degrees",
".",
"Parameter",
"s",
"is",
"the",
"saturation",
"and",
"its",
"range",
... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/util/colormodel.go#L55-L103 | train |
anthonynsimon/bild | util/colormodel.go | HSVToRGB | func HSVToRGB(h, s, v float64) color.RGBA {
var i, f, p, q, t float64
// Achromatic
if s == 0 {
outV := uint8(f64.Clamp(v*255+0.5, 0, 255))
return color.RGBA{outV, outV, outV, 0xFF}
}
h /= 60
i = math.Floor(h)
f = h - i
p = v * (1 - s)
q = v * (1 - s*f)
t = v * (1 - s*(1-f))
var r, g, b float64
switch i {
case 0:
r = v
g = t
b = p
case 1:
r = q
g = v
b = p
case 2:
r = p
g = v
b = t
case 3:
r = p
g = q
b = v
case 4:
r = t
g = p
b = v
default:
r = v
g = p
b = q
}
outR := uint8(f64.Clamp(r*255+0.5, 0, 255))
outG := uint8(f64.Clamp(g*255+0.5, 0, 255))
outB := uint8(f64.Clamp(b*255+0.5, 0, 255))
return color.RGBA{outR, outG, outB, 0xFF}
} | go | func HSVToRGB(h, s, v float64) color.RGBA {
var i, f, p, q, t float64
// Achromatic
if s == 0 {
outV := uint8(f64.Clamp(v*255+0.5, 0, 255))
return color.RGBA{outV, outV, outV, 0xFF}
}
h /= 60
i = math.Floor(h)
f = h - i
p = v * (1 - s)
q = v * (1 - s*f)
t = v * (1 - s*(1-f))
var r, g, b float64
switch i {
case 0:
r = v
g = t
b = p
case 1:
r = q
g = v
b = p
case 2:
r = p
g = v
b = t
case 3:
r = p
g = q
b = v
case 4:
r = t
g = p
b = v
default:
r = v
g = p
b = q
}
outR := uint8(f64.Clamp(r*255+0.5, 0, 255))
outG := uint8(f64.Clamp(g*255+0.5, 0, 255))
outB := uint8(f64.Clamp(b*255+0.5, 0, 255))
return color.RGBA{outR, outG, outB, 0xFF}
} | [
"func",
"HSVToRGB",
"(",
"h",
",",
"s",
",",
"v",
"float64",
")",
"color",
".",
"RGBA",
"{",
"var",
"i",
",",
"f",
",",
"p",
",",
"q",
",",
"t",
"float64",
"\n\n",
"// Achromatic",
"if",
"s",
"==",
"0",
"{",
"outV",
":=",
"uint8",
"(",
"f64",
... | // HSVToRGB converts from HSV to RGB color model.
// Parameter h is the hue and its range is from 0 to 360 degrees.
// Parameter s is the saturation and its range is from 0.0 to 1.0.
// Parameter v is the value and its range is from 0.0 to 1.0. | [
"HSVToRGB",
"converts",
"from",
"HSV",
"to",
"RGB",
"color",
"model",
".",
"Parameter",
"h",
"is",
"the",
"hue",
"and",
"its",
"range",
"is",
"from",
"0",
"to",
"360",
"degrees",
".",
"Parameter",
"s",
"is",
"the",
"saturation",
"and",
"its",
"range",
... | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/util/colormodel.go#L152-L200 | train |
anthonynsimon/bild | blur/blur.go | Gaussian | func Gaussian(src image.Image, radius float64) *image.RGBA {
if radius <= 0 {
return clone.AsRGBA(src)
}
length := int(math.Ceil(2*radius + 1))
k := convolution.NewKernel(length, length)
gaussianFn := func(x, y, sigma float64) float64 {
return math.Exp(-(x*x/sigma + y*y/sigma))
}
for x := 0; x < length; x++ {
for y := 0; y < length; y++ {
k.Matrix[y*length+x] = gaussianFn(float64(x)-radius, float64(y)-radius, 4*radius)
}
}
return convolution.Convolve(src, k.Normalized(), &convolution.Options{Bias: 0, Wrap: false, KeepAlpha: false})
} | go | func Gaussian(src image.Image, radius float64) *image.RGBA {
if radius <= 0 {
return clone.AsRGBA(src)
}
length := int(math.Ceil(2*radius + 1))
k := convolution.NewKernel(length, length)
gaussianFn := func(x, y, sigma float64) float64 {
return math.Exp(-(x*x/sigma + y*y/sigma))
}
for x := 0; x < length; x++ {
for y := 0; y < length; y++ {
k.Matrix[y*length+x] = gaussianFn(float64(x)-radius, float64(y)-radius, 4*radius)
}
}
return convolution.Convolve(src, k.Normalized(), &convolution.Options{Bias: 0, Wrap: false, KeepAlpha: false})
} | [
"func",
"Gaussian",
"(",
"src",
"image",
".",
"Image",
",",
"radius",
"float64",
")",
"*",
"image",
".",
"RGBA",
"{",
"if",
"radius",
"<=",
"0",
"{",
"return",
"clone",
".",
"AsRGBA",
"(",
"src",
")",
"\n",
"}",
"\n\n",
"length",
":=",
"int",
"(",
... | // Gaussian returns a smoothly blurred version of the image using
// a Gaussian function. Radius must be larger than 0. | [
"Gaussian",
"returns",
"a",
"smoothly",
"blurred",
"version",
"of",
"the",
"image",
"using",
"a",
"Gaussian",
"function",
".",
"Radius",
"must",
"be",
"larger",
"than",
"0",
"."
] | 3a6867030b45db250c7619233c6056b46a980667 | https://github.com/anthonynsimon/bild/blob/3a6867030b45db250c7619233c6056b46a980667/blur/blur.go#L33-L53 | train |
graphql-go/handler | graphcoolPlayground.go | renderPlayground | func renderPlayground(w http.ResponseWriter, r *http.Request) {
t := template.New("Playground")
t, err := t.Parse(graphcoolPlaygroundTemplate)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
d := playgroundData{
PlaygroundVersion: graphcoolPlaygroundVersion,
Endpoint: r.URL.Path,
SubscriptionEndpoint: fmt.Sprintf("ws://%v/subscriptions", r.Host),
SetTitle: true,
}
err = t.ExecuteTemplate(w, "index", d)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
} | go | func renderPlayground(w http.ResponseWriter, r *http.Request) {
t := template.New("Playground")
t, err := t.Parse(graphcoolPlaygroundTemplate)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
d := playgroundData{
PlaygroundVersion: graphcoolPlaygroundVersion,
Endpoint: r.URL.Path,
SubscriptionEndpoint: fmt.Sprintf("ws://%v/subscriptions", r.Host),
SetTitle: true,
}
err = t.ExecuteTemplate(w, "index", d)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
} | [
"func",
"renderPlayground",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"t",
":=",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"t",
",",
"err",
":=",
"t",
".",
"Parse",
"(",
"graphcoolPlaygroundTe... | // renderPlayground renders the Playground GUI | [
"renderPlayground",
"renders",
"the",
"Playground",
"GUI"
] | c1267356e6539d975e83bbea383c2bbb861dce5b | https://github.com/graphql-go/handler/blob/c1267356e6539d975e83bbea383c2bbb861dce5b/graphcoolPlayground.go#L17-L37 | train |
graphql-go/handler | handler.go | NewRequestOptions | func NewRequestOptions(r *http.Request) *RequestOptions {
if reqOpt := getFromForm(r.URL.Query()); reqOpt != nil {
return reqOpt
}
if r.Method != http.MethodPost {
return &RequestOptions{}
}
if r.Body == nil {
return &RequestOptions{}
}
// TODO: improve Content-Type handling
contentTypeStr := r.Header.Get("Content-Type")
contentTypeTokens := strings.Split(contentTypeStr, ";")
contentType := contentTypeTokens[0]
switch contentType {
case ContentTypeGraphQL:
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return &RequestOptions{}
}
return &RequestOptions{
Query: string(body),
}
case ContentTypeFormURLEncoded:
if err := r.ParseForm(); err != nil {
return &RequestOptions{}
}
if reqOpt := getFromForm(r.PostForm); reqOpt != nil {
return reqOpt
}
return &RequestOptions{}
case ContentTypeJSON:
fallthrough
default:
var opts RequestOptions
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return &opts
}
err = json.Unmarshal(body, &opts)
if err != nil {
// Probably `variables` was sent as a string instead of an object.
// So, we try to be polite and try to parse that as a JSON string
var optsCompatible requestOptionsCompatibility
json.Unmarshal(body, &optsCompatible)
json.Unmarshal([]byte(optsCompatible.Variables), &opts.Variables)
}
return &opts
}
} | go | func NewRequestOptions(r *http.Request) *RequestOptions {
if reqOpt := getFromForm(r.URL.Query()); reqOpt != nil {
return reqOpt
}
if r.Method != http.MethodPost {
return &RequestOptions{}
}
if r.Body == nil {
return &RequestOptions{}
}
// TODO: improve Content-Type handling
contentTypeStr := r.Header.Get("Content-Type")
contentTypeTokens := strings.Split(contentTypeStr, ";")
contentType := contentTypeTokens[0]
switch contentType {
case ContentTypeGraphQL:
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return &RequestOptions{}
}
return &RequestOptions{
Query: string(body),
}
case ContentTypeFormURLEncoded:
if err := r.ParseForm(); err != nil {
return &RequestOptions{}
}
if reqOpt := getFromForm(r.PostForm); reqOpt != nil {
return reqOpt
}
return &RequestOptions{}
case ContentTypeJSON:
fallthrough
default:
var opts RequestOptions
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return &opts
}
err = json.Unmarshal(body, &opts)
if err != nil {
// Probably `variables` was sent as a string instead of an object.
// So, we try to be polite and try to parse that as a JSON string
var optsCompatible requestOptionsCompatibility
json.Unmarshal(body, &optsCompatible)
json.Unmarshal([]byte(optsCompatible.Variables), &opts.Variables)
}
return &opts
}
} | [
"func",
"NewRequestOptions",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"*",
"RequestOptions",
"{",
"if",
"reqOpt",
":=",
"getFromForm",
"(",
"r",
".",
"URL",
".",
"Query",
"(",
")",
")",
";",
"reqOpt",
"!=",
"nil",
"{",
"return",
"reqOpt",
"\n",
"}... | // RequestOptions Parses a http.Request into GraphQL request options struct | [
"RequestOptions",
"Parses",
"a",
"http",
".",
"Request",
"into",
"GraphQL",
"request",
"options",
"struct"
] | c1267356e6539d975e83bbea383c2bbb861dce5b | https://github.com/graphql-go/handler/blob/c1267356e6539d975e83bbea383c2bbb861dce5b/handler.go#L67-L123 | train |
graphql-go/handler | handler.go | ContextHandler | func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// get query
opts := NewRequestOptions(r)
// execute graphql query
params := graphql.Params{
Schema: *h.Schema,
RequestString: opts.Query,
VariableValues: opts.Variables,
OperationName: opts.OperationName,
Context: ctx,
}
if h.rootObjectFn != nil {
params.RootObject = h.rootObjectFn(ctx, r)
}
result := graphql.Do(params)
if formatErrorFn := h.formatErrorFn; formatErrorFn != nil && len(result.Errors) > 0 {
formatted := make([]gqlerrors.FormattedError, len(result.Errors))
for i, formattedError := range result.Errors {
formatted[i] = formatErrorFn(formattedError.OriginalError())
}
result.Errors = formatted
}
if h.graphiql {
acceptHeader := r.Header.Get("Accept")
_, raw := r.URL.Query()["raw"]
if !raw && !strings.Contains(acceptHeader, "application/json") && strings.Contains(acceptHeader, "text/html") {
renderGraphiQL(w, params)
return
}
}
if h.playground {
acceptHeader := r.Header.Get("Accept")
_, raw := r.URL.Query()["raw"]
if !raw && !strings.Contains(acceptHeader, "application/json") && strings.Contains(acceptHeader, "text/html") {
renderPlayground(w, r)
return
}
}
// use proper JSON Header
w.Header().Add("Content-Type", "application/json; charset=utf-8")
var buff []byte
if h.pretty {
w.WriteHeader(http.StatusOK)
buff, _ = json.MarshalIndent(result, "", "\t")
w.Write(buff)
} else {
w.WriteHeader(http.StatusOK)
buff, _ = json.Marshal(result)
w.Write(buff)
}
if h.resultCallbackFn != nil {
h.resultCallbackFn(ctx, ¶ms, result, buff)
}
} | go | func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// get query
opts := NewRequestOptions(r)
// execute graphql query
params := graphql.Params{
Schema: *h.Schema,
RequestString: opts.Query,
VariableValues: opts.Variables,
OperationName: opts.OperationName,
Context: ctx,
}
if h.rootObjectFn != nil {
params.RootObject = h.rootObjectFn(ctx, r)
}
result := graphql.Do(params)
if formatErrorFn := h.formatErrorFn; formatErrorFn != nil && len(result.Errors) > 0 {
formatted := make([]gqlerrors.FormattedError, len(result.Errors))
for i, formattedError := range result.Errors {
formatted[i] = formatErrorFn(formattedError.OriginalError())
}
result.Errors = formatted
}
if h.graphiql {
acceptHeader := r.Header.Get("Accept")
_, raw := r.URL.Query()["raw"]
if !raw && !strings.Contains(acceptHeader, "application/json") && strings.Contains(acceptHeader, "text/html") {
renderGraphiQL(w, params)
return
}
}
if h.playground {
acceptHeader := r.Header.Get("Accept")
_, raw := r.URL.Query()["raw"]
if !raw && !strings.Contains(acceptHeader, "application/json") && strings.Contains(acceptHeader, "text/html") {
renderPlayground(w, r)
return
}
}
// use proper JSON Header
w.Header().Add("Content-Type", "application/json; charset=utf-8")
var buff []byte
if h.pretty {
w.WriteHeader(http.StatusOK)
buff, _ = json.MarshalIndent(result, "", "\t")
w.Write(buff)
} else {
w.WriteHeader(http.StatusOK)
buff, _ = json.Marshal(result)
w.Write(buff)
}
if h.resultCallbackFn != nil {
h.resultCallbackFn(ctx, ¶ms, result, buff)
}
} | [
"func",
"(",
"h",
"*",
"Handler",
")",
"ContextHandler",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"// get query",
"opts",
":=",
"NewRequestOptions",
"(",
"r",
")",
... | // ContextHandler provides an entrypoint into executing graphQL queries with a
// user-provided context. | [
"ContextHandler",
"provides",
"an",
"entrypoint",
"into",
"executing",
"graphQL",
"queries",
"with",
"a",
"user",
"-",
"provided",
"context",
"."
] | c1267356e6539d975e83bbea383c2bbb861dce5b | https://github.com/graphql-go/handler/blob/c1267356e6539d975e83bbea383c2bbb861dce5b/handler.go#L127-L189 | train |
graphql-go/handler | handler.go | ServeHTTP | func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.ContextHandler(r.Context(), w, r)
} | go | func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.ContextHandler(r.Context(), w, r)
} | [
"func",
"(",
"h",
"*",
"Handler",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"h",
".",
"ContextHandler",
"(",
"r",
".",
"Context",
"(",
")",
",",
"w",
",",
"r",
")",
"\n",
"}"
] | // ServeHTTP provides an entrypoint into executing graphQL queries. | [
"ServeHTTP",
"provides",
"an",
"entrypoint",
"into",
"executing",
"graphQL",
"queries",
"."
] | c1267356e6539d975e83bbea383c2bbb861dce5b | https://github.com/graphql-go/handler/blob/c1267356e6539d975e83bbea383c2bbb861dce5b/handler.go#L192-L194 | train |
graphql-go/handler | graphiql.go | renderGraphiQL | func renderGraphiQL(w http.ResponseWriter, params graphql.Params) {
t := template.New("GraphiQL")
t, err := t.Parse(graphiqlTemplate)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Create variables string
vars, err := json.MarshalIndent(params.VariableValues, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
varsString := string(vars)
if varsString == "null" {
varsString = ""
}
// Create result string
var resString string
if params.RequestString == "" {
resString = ""
} else {
result, err := json.MarshalIndent(graphql.Do(params), "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
resString = string(result)
}
d := graphiqlData{
GraphiqlVersion: graphiqlVersion,
QueryString: params.RequestString,
ResultString: resString,
VariablesString: varsString,
OperationName: params.OperationName,
}
err = t.ExecuteTemplate(w, "index", d)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
} | go | func renderGraphiQL(w http.ResponseWriter, params graphql.Params) {
t := template.New("GraphiQL")
t, err := t.Parse(graphiqlTemplate)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Create variables string
vars, err := json.MarshalIndent(params.VariableValues, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
varsString := string(vars)
if varsString == "null" {
varsString = ""
}
// Create result string
var resString string
if params.RequestString == "" {
resString = ""
} else {
result, err := json.MarshalIndent(graphql.Do(params), "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
resString = string(result)
}
d := graphiqlData{
GraphiqlVersion: graphiqlVersion,
QueryString: params.RequestString,
ResultString: resString,
VariablesString: varsString,
OperationName: params.OperationName,
}
err = t.ExecuteTemplate(w, "index", d)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
} | [
"func",
"renderGraphiQL",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"params",
"graphql",
".",
"Params",
")",
"{",
"t",
":=",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"t",
",",
"err",
":=",
"t",
".",
"Parse",
"(",
"graphiqlTemplate",
")... | // renderGraphiQL renders the GraphiQL GUI | [
"renderGraphiQL",
"renders",
"the",
"GraphiQL",
"GUI"
] | c1267356e6539d975e83bbea383c2bbb861dce5b | https://github.com/graphql-go/handler/blob/c1267356e6539d975e83bbea383c2bbb861dce5b/graphiql.go#L21-L66 | train |
josharian/impl | impl.go | gofmt | func (p Pkg) gofmt(e ast.Expr) string {
var buf bytes.Buffer
printer.Fprint(&buf, p.FileSet, e)
return buf.String()
} | go | func (p Pkg) gofmt(e ast.Expr) string {
var buf bytes.Buffer
printer.Fprint(&buf, p.FileSet, e)
return buf.String()
} | [
"func",
"(",
"p",
"Pkg",
")",
"gofmt",
"(",
"e",
"ast",
".",
"Expr",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"printer",
".",
"Fprint",
"(",
"&",
"buf",
",",
"p",
".",
"FileSet",
",",
"e",
")",
"\n",
"return",
"buf",
".",... | // gofmt pretty-prints e. | [
"gofmt",
"pretty",
"-",
"prints",
"e",
"."
] | 3d0f908298c49598b6aa84f101c69670e15d1d03 | https://github.com/josharian/impl/blob/3d0f908298c49598b6aa84f101c69670e15d1d03/impl.go#L139-L143 | train |
josharian/impl | impl.go | funcs | func funcs(iface string, srcDir string) ([]Func, error) {
// Special case for the built-in error interface.
if iface == "error" {
return errorInterface, nil
}
// Locate the interface.
path, id, err := findInterface(iface, srcDir)
if err != nil {
return nil, err
}
// Parse the package and find the interface declaration.
p, spec, err := typeSpec(path, id, srcDir)
if err != nil {
return nil, fmt.Errorf("interface %s not found: %s", iface, err)
}
idecl, ok := spec.Type.(*ast.InterfaceType)
if !ok {
return nil, fmt.Errorf("not an interface: %s", iface)
}
if idecl.Methods == nil {
return nil, fmt.Errorf("empty interface: %s", iface)
}
var fns []Func
for _, fndecl := range idecl.Methods.List {
if len(fndecl.Names) == 0 {
// Embedded interface: recurse
embedded, err := funcs(p.fullType(fndecl.Type), srcDir)
if err != nil {
return nil, err
}
fns = append(fns, embedded...)
continue
}
fn := p.funcsig(fndecl)
fns = append(fns, fn)
}
return fns, nil
} | go | func funcs(iface string, srcDir string) ([]Func, error) {
// Special case for the built-in error interface.
if iface == "error" {
return errorInterface, nil
}
// Locate the interface.
path, id, err := findInterface(iface, srcDir)
if err != nil {
return nil, err
}
// Parse the package and find the interface declaration.
p, spec, err := typeSpec(path, id, srcDir)
if err != nil {
return nil, fmt.Errorf("interface %s not found: %s", iface, err)
}
idecl, ok := spec.Type.(*ast.InterfaceType)
if !ok {
return nil, fmt.Errorf("not an interface: %s", iface)
}
if idecl.Methods == nil {
return nil, fmt.Errorf("empty interface: %s", iface)
}
var fns []Func
for _, fndecl := range idecl.Methods.List {
if len(fndecl.Names) == 0 {
// Embedded interface: recurse
embedded, err := funcs(p.fullType(fndecl.Type), srcDir)
if err != nil {
return nil, err
}
fns = append(fns, embedded...)
continue
}
fn := p.funcsig(fndecl)
fns = append(fns, fn)
}
return fns, nil
} | [
"func",
"funcs",
"(",
"iface",
"string",
",",
"srcDir",
"string",
")",
"(",
"[",
"]",
"Func",
",",
"error",
")",
"{",
"// Special case for the built-in error interface.",
"if",
"iface",
"==",
"\"",
"\"",
"{",
"return",
"errorInterface",
",",
"nil",
"\n",
"}"... | // funcs returns the set of methods required to implement iface.
// It is called funcs rather than methods because the
// function descriptions are functions; there is no receiver. | [
"funcs",
"returns",
"the",
"set",
"of",
"methods",
"required",
"to",
"implement",
"iface",
".",
"It",
"is",
"called",
"funcs",
"rather",
"than",
"methods",
"because",
"the",
"function",
"descriptions",
"are",
"functions",
";",
"there",
"is",
"no",
"receiver",
... | 3d0f908298c49598b6aa84f101c69670e15d1d03 | https://github.com/josharian/impl/blob/3d0f908298c49598b6aa84f101c69670e15d1d03/impl.go#L227-L269 | train |
josharian/impl | impl.go | genStubs | func genStubs(recv string, fns []Func) []byte {
var buf bytes.Buffer
for _, fn := range fns {
meth := Method{Recv: recv, Func: fn}
tmpl.Execute(&buf, meth)
}
pretty, err := format.Source(buf.Bytes())
if err != nil {
panic(err)
}
return pretty
} | go | func genStubs(recv string, fns []Func) []byte {
var buf bytes.Buffer
for _, fn := range fns {
meth := Method{Recv: recv, Func: fn}
tmpl.Execute(&buf, meth)
}
pretty, err := format.Source(buf.Bytes())
if err != nil {
panic(err)
}
return pretty
} | [
"func",
"genStubs",
"(",
"recv",
"string",
",",
"fns",
"[",
"]",
"Func",
")",
"[",
"]",
"byte",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"_",
",",
"fn",
":=",
"range",
"fns",
"{",
"meth",
":=",
"Method",
"{",
"Recv",
":",
"recv",
... | // genStubs prints nicely formatted method stubs
// for fns using receiver expression recv.
// If recv is not a valid receiver expression,
// genStubs will panic. | [
"genStubs",
"prints",
"nicely",
"formatted",
"method",
"stubs",
"for",
"fns",
"using",
"receiver",
"expression",
"recv",
".",
"If",
"recv",
"is",
"not",
"a",
"valid",
"receiver",
"expression",
"genStubs",
"will",
"panic",
"."
] | 3d0f908298c49598b6aa84f101c69670e15d1d03 | https://github.com/josharian/impl/blob/3d0f908298c49598b6aa84f101c69670e15d1d03/impl.go#L282-L294 | train |
josharian/impl | impl.go | validReceiver | func validReceiver(recv string) bool {
if recv == "" {
// The parse will parse empty receivers, but we don't want to accept them,
// since it won't generate a usable code snippet.
return false
}
fset := token.NewFileSet()
_, err := parser.ParseFile(fset, "", "package hack\nfunc ("+recv+") Foo()", 0)
return err == nil
} | go | func validReceiver(recv string) bool {
if recv == "" {
// The parse will parse empty receivers, but we don't want to accept them,
// since it won't generate a usable code snippet.
return false
}
fset := token.NewFileSet()
_, err := parser.ParseFile(fset, "", "package hack\nfunc ("+recv+") Foo()", 0)
return err == nil
} | [
"func",
"validReceiver",
"(",
"recv",
"string",
")",
"bool",
"{",
"if",
"recv",
"==",
"\"",
"\"",
"{",
"// The parse will parse empty receivers, but we don't want to accept them,",
"// since it won't generate a usable code snippet.",
"return",
"false",
"\n",
"}",
"\n",
"fse... | // validReceiver reports whether recv is a valid receiver expression. | [
"validReceiver",
"reports",
"whether",
"recv",
"is",
"a",
"valid",
"receiver",
"expression",
"."
] | 3d0f908298c49598b6aa84f101c69670e15d1d03 | https://github.com/josharian/impl/blob/3d0f908298c49598b6aa84f101c69670e15d1d03/impl.go#L297-L306 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.