id
int32
0
167k
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
153,000
sjmudd/stopwatch
stopwatch.go
String
func (s *Stopwatch) String() string { s.RLock() defer s.RUnlock() // display using local formatting if possible if s.format != nil { return s.format(s.elapsedTime) } // display using package DefaultFormat return DefaultFormat(s.elapsedTime) }
go
func (s *Stopwatch) String() string { s.RLock() defer s.RUnlock() // display using local formatting if possible if s.format != nil { return s.format(s.elapsedTime) } // display using package DefaultFormat return DefaultFormat(s.elapsedTime) }
[ "func", "(", "s", "*", "Stopwatch", ")", "String", "(", ")", "string", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "// display using local formatting if possible", "if", "s", ".", "format", "!=", "nil", "{", ...
// String gives the string representation of the duration.
[ "String", "gives", "the", "string", "representation", "of", "the", "duration", "." ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/stopwatch.go#L108-L118
153,001
sjmudd/stopwatch
stopwatch.go
IsRunning
func (s *Stopwatch) IsRunning() bool { s.RLock() defer s.RUnlock() return s.isRunning() }
go
func (s *Stopwatch) IsRunning() bool { s.RLock() defer s.RUnlock() return s.isRunning() }
[ "func", "(", "s", "*", "Stopwatch", ")", "IsRunning", "(", ")", "bool", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "return", "s", ".", "isRunning", "(", ")", "\n", "}" ]
// IsRunning is a helper function to indicate if in theory the // stopwatch is working.
[ "IsRunning", "is", "a", "helper", "function", "to", "indicate", "if", "in", "theory", "the", "stopwatch", "is", "working", "." ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/stopwatch.go#L137-L142
153,002
sjmudd/stopwatch
stopwatch.go
elapsed
func (s *Stopwatch) elapsed() time.Duration { if s.isRunning() { return time.Since(s.refTime) } return s.elapsedTime }
go
func (s *Stopwatch) elapsed() time.Duration { if s.isRunning() { return time.Since(s.refTime) } return s.elapsedTime }
[ "func", "(", "s", "*", "Stopwatch", ")", "elapsed", "(", ")", "time", ".", "Duration", "{", "if", "s", ".", "isRunning", "(", ")", "{", "return", "time", ".", "Since", "(", "s", ".", "refTime", ")", "\n", "}", "\n", "return", "s", ".", "elapsedTi...
// elapsed assumes the structure is already locked and returns the // appropriate value. That is the previously time since the stopwatch // was started if it's running, or the previously recorded elapsed // time if it's not.
[ "elapsed", "assumes", "the", "structure", "is", "already", "locked", "and", "returns", "the", "appropriate", "value", ".", "That", "is", "the", "previously", "time", "since", "the", "stopwatch", "was", "started", "if", "it", "s", "running", "or", "the", "pre...
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/stopwatch.go#L148-L153
153,003
sjmudd/stopwatch
stopwatch.go
ElapsedSeconds
func (s *Stopwatch) ElapsedSeconds() float64 { s.RLock() defer s.RUnlock() return s.Elapsed().Seconds() }
go
func (s *Stopwatch) ElapsedSeconds() float64 { s.RLock() defer s.RUnlock() return s.Elapsed().Seconds() }
[ "func", "(", "s", "*", "Stopwatch", ")", "ElapsedSeconds", "(", ")", "float64", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "return", "s", ".", "Elapsed", "(", ")", ".", "Seconds", "(", ")", "\n", "}" ]
// ElapsedSeconds is a helper function returns the number of seconds // since starting.
[ "ElapsedSeconds", "is", "a", "helper", "function", "returns", "the", "number", "of", "seconds", "since", "starting", "." ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/stopwatch.go#L165-L170
153,004
sjmudd/stopwatch
stopwatch.go
ElapsedMilliSeconds
func (s *Stopwatch) ElapsedMilliSeconds() float64 { s.RLock() defer s.RUnlock() return float64(s.Elapsed() / time.Millisecond) }
go
func (s *Stopwatch) ElapsedMilliSeconds() float64 { s.RLock() defer s.RUnlock() return float64(s.Elapsed() / time.Millisecond) }
[ "func", "(", "s", "*", "Stopwatch", ")", "ElapsedMilliSeconds", "(", ")", "float64", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "return", "float64", "(", "s", ".", "Elapsed", "(", ")", "/", "time", ".", ...
// ElapsedMilliSeconds is a helper function returns the number of // milliseconds since starting.
[ "ElapsedMilliSeconds", "is", "a", "helper", "function", "returns", "the", "number", "of", "milliseconds", "since", "starting", "." ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/stopwatch.go#L174-L179
153,005
sjmudd/stopwatch
stopwatch.go
AddElapsedSince
func (s *Stopwatch) AddElapsedSince(t time.Time) { s.Lock() defer s.Unlock() s.elapsedTime += time.Since(t) }
go
func (s *Stopwatch) AddElapsedSince(t time.Time) { s.Lock() defer s.Unlock() s.elapsedTime += time.Since(t) }
[ "func", "(", "s", "*", "Stopwatch", ")", "AddElapsedSince", "(", "t", "time", ".", "Time", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "s", ".", "elapsedTime", "+=", "time", ".", "Since", "(", "t", ...
// AddElapsed just adds an elapsed time to the value that's been stored.
[ "AddElapsed", "just", "adds", "an", "elapsed", "time", "to", "the", "value", "that", "s", "been", "stored", "." ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/stopwatch.go#L182-L187
153,006
autograde/kit
exercise/command_line.go
CommandLine
func CommandLine(t *testing.T, sc *score.Score, answers Commands) { defer sc.WriteString(os.Stdout) defer sc.WriteJSON(os.Stdout) for i := range answers { cmdArgs := strings.Split(answers[i].Command, " ") cmd := exec.Command(cmdArgs[0]) cmd.Args = cmdArgs var sout, serr bytes.Buffer cmd.Stdout, cmd.Stderr = &sout, &serr err := cmd.Run() if err != nil { t.Errorf("%v\n%v: %v.\n", sc.TestName, err, serr.String()) sc.Dec() continue } outStr := sout.String() // Compare output with expected output switch answers[i].Search { case ResultEquals: if outStr != answers[i].Result { t.Errorf("%v: \ngot: %v \nwant: %v \nfor command: %v\n", sc.TestName, outStr, answers[i].Result, answers[i].Command) sc.Dec() } case ResultContains: if !strings.Contains(outStr, answers[i].Result) { t.Errorf("%v: \nResult does not contain: %v \nfor command: %v\n", sc.TestName, answers[i].Result, answers[i].Command) sc.Dec() } case ResultDoesNotContain: if strings.Contains(outStr, answers[i].Result) { t.Errorf("%v: \nResult contains: %v \nfor command: %v\n", sc.TestName, answers[i].Result, answers[i].Command) sc.Dec() } } } }
go
func CommandLine(t *testing.T, sc *score.Score, answers Commands) { defer sc.WriteString(os.Stdout) defer sc.WriteJSON(os.Stdout) for i := range answers { cmdArgs := strings.Split(answers[i].Command, " ") cmd := exec.Command(cmdArgs[0]) cmd.Args = cmdArgs var sout, serr bytes.Buffer cmd.Stdout, cmd.Stderr = &sout, &serr err := cmd.Run() if err != nil { t.Errorf("%v\n%v: %v.\n", sc.TestName, err, serr.String()) sc.Dec() continue } outStr := sout.String() // Compare output with expected output switch answers[i].Search { case ResultEquals: if outStr != answers[i].Result { t.Errorf("%v: \ngot: %v \nwant: %v \nfor command: %v\n", sc.TestName, outStr, answers[i].Result, answers[i].Command) sc.Dec() } case ResultContains: if !strings.Contains(outStr, answers[i].Result) { t.Errorf("%v: \nResult does not contain: %v \nfor command: %v\n", sc.TestName, answers[i].Result, answers[i].Command) sc.Dec() } case ResultDoesNotContain: if strings.Contains(outStr, answers[i].Result) { t.Errorf("%v: \nResult contains: %v \nfor command: %v\n", sc.TestName, answers[i].Result, answers[i].Command) sc.Dec() } } } }
[ "func", "CommandLine", "(", "t", "*", "testing", ".", "T", ",", "sc", "*", "score", ".", "Score", ",", "answers", "Commands", ")", "{", "defer", "sc", ".", "WriteString", "(", "os", ".", "Stdout", ")", "\n", "defer", "sc", ".", "WriteJSON", "(", "o...
// CommandLine computes the score for a set of command line exercises // that students provided. The function requires the list of commands // and their expected answers, and a Score object. The function // will produce both string output and JSON output.
[ "CommandLine", "computes", "the", "score", "for", "a", "set", "of", "command", "line", "exercises", "that", "students", "provided", ".", "The", "function", "requires", "the", "list", "of", "commands", "and", "their", "expected", "answers", "and", "a", "Score",...
fdbad708e80aa3574e6f43dd9302bb607683361b
https://github.com/autograde/kit/blob/fdbad708e80aa3574e6f43dd9302bb607683361b/exercise/command_line.go#L31-L71
153,007
autograde/kit
score/parse.go
Parse
func Parse(s, secret string) (*Score, error) { if strings.Contains(s, secret) { var sc Score err := json.Unmarshal([]byte(s), &sc) if err == nil { if sc.Secret == secret { sc.Secret = hiddenSecret // overwrite secret } return &sc, nil } if strings.Contains(err.Error(), secret) { // this is probably not necessary, but to be safe return nil, errors.New("error suppressed to avoid revealing secret") } return nil, err } return nil, ErrScoreNotFound }
go
func Parse(s, secret string) (*Score, error) { if strings.Contains(s, secret) { var sc Score err := json.Unmarshal([]byte(s), &sc) if err == nil { if sc.Secret == secret { sc.Secret = hiddenSecret // overwrite secret } return &sc, nil } if strings.Contains(err.Error(), secret) { // this is probably not necessary, but to be safe return nil, errors.New("error suppressed to avoid revealing secret") } return nil, err } return nil, ErrScoreNotFound }
[ "func", "Parse", "(", "s", ",", "secret", "string", ")", "(", "*", "Score", ",", "error", ")", "{", "if", "strings", ".", "Contains", "(", "s", ",", "secret", ")", "{", "var", "sc", "Score", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", ...
// Parse returns a score object for the provided JSON string s // which contains secret.
[ "Parse", "returns", "a", "score", "object", "for", "the", "provided", "JSON", "string", "s", "which", "contains", "secret", "." ]
fdbad708e80aa3574e6f43dd9302bb607683361b
https://github.com/autograde/kit/blob/fdbad708e80aa3574e6f43dd9302bb607683361b/score/parse.go#L18-L35
153,008
twpayne/gopolyline
polyline/polyline.go
DecodeUints
func DecodeUints(s string) ([]uint, error) { xs := make([]uint, 0) var x, shift uint for i, c := range []byte(s) { switch { case 63 <= c && c < 95: xs = append(xs, x+(uint(c)-63)<<shift) x = 0 shift = 0 case 95 <= c && c < 127: x += (uint(c) - 95) << shift shift += 5 default: return nil, &InvalidCharacterError{i, c} } } if shift != 0 { return nil, &UnterminatedError{} } return xs, nil }
go
func DecodeUints(s string) ([]uint, error) { xs := make([]uint, 0) var x, shift uint for i, c := range []byte(s) { switch { case 63 <= c && c < 95: xs = append(xs, x+(uint(c)-63)<<shift) x = 0 shift = 0 case 95 <= c && c < 127: x += (uint(c) - 95) << shift shift += 5 default: return nil, &InvalidCharacterError{i, c} } } if shift != 0 { return nil, &UnterminatedError{} } return xs, nil }
[ "func", "DecodeUints", "(", "s", "string", ")", "(", "[", "]", "uint", ",", "error", ")", "{", "xs", ":=", "make", "(", "[", "]", "uint", ",", "0", ")", "\n", "var", "x", ",", "shift", "uint", "\n", "for", "i", ",", "c", ":=", "range", "[", ...
// DecodeUnits decodes a slice of uints from a string.
[ "DecodeUnits", "decodes", "a", "slice", "of", "uints", "from", "a", "string", "." ]
5e3c0a8d4937e989699da2acee1e2861dbb2dc58
https://github.com/twpayne/gopolyline/blob/5e3c0a8d4937e989699da2acee1e2861dbb2dc58/polyline/polyline.go#L29-L49
153,009
twpayne/gopolyline
polyline/polyline.go
DecodeInts
func DecodeInts(s string) ([]int, error) { xs, err := DecodeUints(s) if err != nil { return nil, err } ys := make([]int, len(xs)) for i, u := range xs { if u&1 == 0 { ys[i] = int(u >> 1) } else { ys[i] = -int((u + 1) >> 1) } } return ys, nil }
go
func DecodeInts(s string) ([]int, error) { xs, err := DecodeUints(s) if err != nil { return nil, err } ys := make([]int, len(xs)) for i, u := range xs { if u&1 == 0 { ys[i] = int(u >> 1) } else { ys[i] = -int((u + 1) >> 1) } } return ys, nil }
[ "func", "DecodeInts", "(", "s", "string", ")", "(", "[", "]", "int", ",", "error", ")", "{", "xs", ",", "err", ":=", "DecodeUints", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ys", ":=", ...
// DecodeInts decodes a slice of ints from a string.
[ "DecodeInts", "decodes", "a", "slice", "of", "ints", "from", "a", "string", "." ]
5e3c0a8d4937e989699da2acee1e2861dbb2dc58
https://github.com/twpayne/gopolyline/blob/5e3c0a8d4937e989699da2acee1e2861dbb2dc58/polyline/polyline.go#L52-L66
153,010
twpayne/gopolyline
polyline/polyline.go
EncodeUint
func EncodeUint(x uint) string { bs := make([]byte, 0, 7) for ; x >= 32; x >>= 5 { bs = append(bs, byte((x&31)+95)) } bs = append(bs, byte(x+63)) return string(bs) }
go
func EncodeUint(x uint) string { bs := make([]byte, 0, 7) for ; x >= 32; x >>= 5 { bs = append(bs, byte((x&31)+95)) } bs = append(bs, byte(x+63)) return string(bs) }
[ "func", "EncodeUint", "(", "x", "uint", ")", "string", "{", "bs", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "7", ")", "\n", "for", ";", "x", ">=", "32", ";", "x", ">>=", "5", "{", "bs", "=", "append", "(", "bs", ",", "byte", "(", ...
// EncodeUnit encodes a single uint as a string.
[ "EncodeUnit", "encodes", "a", "single", "uint", "as", "a", "string", "." ]
5e3c0a8d4937e989699da2acee1e2861dbb2dc58
https://github.com/twpayne/gopolyline/blob/5e3c0a8d4937e989699da2acee1e2861dbb2dc58/polyline/polyline.go#L88-L95
153,011
twpayne/gopolyline
polyline/polyline.go
EncodeUints
func EncodeUints(xs []uint) string { ss := make([]string, len(xs)) for i, x := range xs { ss[i] = EncodeUint(x) } return strings.Join(ss, "") }
go
func EncodeUints(xs []uint) string { ss := make([]string, len(xs)) for i, x := range xs { ss[i] = EncodeUint(x) } return strings.Join(ss, "") }
[ "func", "EncodeUints", "(", "xs", "[", "]", "uint", ")", "string", "{", "ss", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "xs", ")", ")", "\n", "for", "i", ",", "x", ":=", "range", "xs", "{", "ss", "[", "i", "]", "=", "EncodeUint"...
// EncodeUnits encodes a slice of uints as a string.
[ "EncodeUnits", "encodes", "a", "slice", "of", "uints", "as", "a", "string", "." ]
5e3c0a8d4937e989699da2acee1e2861dbb2dc58
https://github.com/twpayne/gopolyline/blob/5e3c0a8d4937e989699da2acee1e2861dbb2dc58/polyline/polyline.go#L98-L104
153,012
twpayne/gopolyline
polyline/polyline.go
EncodeInt
func EncodeInt(x int) string { y := uint(x) << 1 if x < 0 { y = ^y } return EncodeUint(y) }
go
func EncodeInt(x int) string { y := uint(x) << 1 if x < 0 { y = ^y } return EncodeUint(y) }
[ "func", "EncodeInt", "(", "x", "int", ")", "string", "{", "y", ":=", "uint", "(", "x", ")", "<<", "1", "\n", "if", "x", "<", "0", "{", "y", "=", "^", "y", "\n", "}", "\n", "return", "EncodeUint", "(", "y", ")", "\n", "}" ]
// EncodeInt encodes a single int as a string.
[ "EncodeInt", "encodes", "a", "single", "int", "as", "a", "string", "." ]
5e3c0a8d4937e989699da2acee1e2861dbb2dc58
https://github.com/twpayne/gopolyline/blob/5e3c0a8d4937e989699da2acee1e2861dbb2dc58/polyline/polyline.go#L107-L113
153,013
twpayne/gopolyline
polyline/polyline.go
EncodeInts
func EncodeInts(xs []int) string { ss := make([]string, len(xs)) for i, x := range xs { ss[i] = EncodeInt(x) } return strings.Join(ss, "") }
go
func EncodeInts(xs []int) string { ss := make([]string, len(xs)) for i, x := range xs { ss[i] = EncodeInt(x) } return strings.Join(ss, "") }
[ "func", "EncodeInts", "(", "xs", "[", "]", "int", ")", "string", "{", "ss", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "xs", ")", ")", "\n", "for", "i", ",", "x", ":=", "range", "xs", "{", "ss", "[", "i", "]", "=", "EncodeInt", ...
// EncodeInts encodes a slice of ints as a string.
[ "EncodeInts", "encodes", "a", "slice", "of", "ints", "as", "a", "string", "." ]
5e3c0a8d4937e989699da2acee1e2861dbb2dc58
https://github.com/twpayne/gopolyline/blob/5e3c0a8d4937e989699da2acee1e2861dbb2dc58/polyline/polyline.go#L116-L122
153,014
schollz/org.eclipse.paho.mqtt.golang
token.go
Wait
func (b *baseToken) Wait() bool { b.m.Lock() defer b.m.Unlock() if !b.ready { <-b.complete b.ready = true } return b.ready }
go
func (b *baseToken) Wait() bool { b.m.Lock() defer b.m.Unlock() if !b.ready { <-b.complete b.ready = true } return b.ready }
[ "func", "(", "b", "*", "baseToken", ")", "Wait", "(", ")", "bool", "{", "b", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "m", ".", "Unlock", "(", ")", "\n", "if", "!", "b", ".", "ready", "{", "<-", "b", ".", "complete", "\n", ...
// Wait will wait indefinitely for the Token to complete, ie the Publish // to be sent and confirmed receipt from the broker
[ "Wait", "will", "wait", "indefinitely", "for", "the", "Token", "to", "complete", "ie", "the", "Publish", "to", "be", "sent", "and", "confirmed", "receipt", "from", "the", "broker" ]
6d626954dc988ae6c25b0fdaabdb64f144c438b0
https://github.com/schollz/org.eclipse.paho.mqtt.golang/blob/6d626954dc988ae6c25b0fdaabdb64f144c438b0/token.go#L49-L57
153,015
schollz/org.eclipse.paho.mqtt.golang
token.go
WaitTimeout
func (b *baseToken) WaitTimeout(d time.Duration) bool { b.m.Lock() defer b.m.Unlock() if !b.ready { select { case <-b.complete: b.ready = true case <-time.After(d): } } return b.ready }
go
func (b *baseToken) WaitTimeout(d time.Duration) bool { b.m.Lock() defer b.m.Unlock() if !b.ready { select { case <-b.complete: b.ready = true case <-time.After(d): } } return b.ready }
[ "func", "(", "b", "*", "baseToken", ")", "WaitTimeout", "(", "d", "time", ".", "Duration", ")", "bool", "{", "b", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "m", ".", "Unlock", "(", ")", "\n", "if", "!", "b", ".", "ready", "{",...
// WaitTimeout takes a time in ms to wait for the flow associated with the // Token to complete, returns true if it returned before the timeout or // returns false if the timeout occurred. In the case of a timeout the Token // does not have an error set in case the caller wishes to wait again
[ "WaitTimeout", "takes", "a", "time", "in", "ms", "to", "wait", "for", "the", "flow", "associated", "with", "the", "Token", "to", "complete", "returns", "true", "if", "it", "returned", "before", "the", "timeout", "or", "returns", "false", "if", "the", "time...
6d626954dc988ae6c25b0fdaabdb64f144c438b0
https://github.com/schollz/org.eclipse.paho.mqtt.golang/blob/6d626954dc988ae6c25b0fdaabdb64f144c438b0/token.go#L63-L74
153,016
autograde/kit
score/score.go
IncBy
func (s *Score) IncBy(n int) { if s.Score+n < s.MaxScore { s.Score += n } else { s.Score = s.MaxScore } }
go
func (s *Score) IncBy(n int) { if s.Score+n < s.MaxScore { s.Score += n } else { s.Score = s.MaxScore } }
[ "func", "(", "s", "*", "Score", ")", "IncBy", "(", "n", "int", ")", "{", "if", "s", ".", "Score", "+", "n", "<", "s", ".", "MaxScore", "{", "s", ".", "Score", "+=", "n", "\n", "}", "else", "{", "s", ".", "Score", "=", "s", ".", "MaxScore", ...
// IncBy increments score n times or until score equals MaxScore.
[ "IncBy", "increments", "score", "n", "times", "or", "until", "score", "equals", "MaxScore", "." ]
fdbad708e80aa3574e6f43dd9302bb607683361b
https://github.com/autograde/kit/blob/fdbad708e80aa3574e6f43dd9302bb607683361b/score/score.go#L80-L86
153,017
autograde/kit
score/score.go
DecBy
func (s *Score) DecBy(n int) { if s.Score-n > 0 { s.Score -= n } else { s.Score = 0 } }
go
func (s *Score) DecBy(n int) { if s.Score-n > 0 { s.Score -= n } else { s.Score = 0 } }
[ "func", "(", "s", "*", "Score", ")", "DecBy", "(", "n", "int", ")", "{", "if", "s", ".", "Score", "-", "n", ">", "0", "{", "s", ".", "Score", "-=", "n", "\n", "}", "else", "{", "s", ".", "Score", "=", "0", "\n", "}", "\n", "}" ]
// DecBy decrements score n times or until Score equals zero.
[ "DecBy", "decrements", "score", "n", "times", "or", "until", "Score", "equals", "zero", "." ]
fdbad708e80aa3574e6f43dd9302bb607683361b
https://github.com/autograde/kit/blob/fdbad708e80aa3574e6f43dd9302bb607683361b/score/score.go#L103-L109
153,018
autograde/kit
score/score.go
WriteString
func (s *Score) WriteString(w io.Writer) { // check if calling func paniced before calling this if r := recover(); r != nil { // reset score for paniced functions s.Score = 0 } fmt.Fprintf(w, "%v\n", s) }
go
func (s *Score) WriteString(w io.Writer) { // check if calling func paniced before calling this if r := recover(); r != nil { // reset score for paniced functions s.Score = 0 } fmt.Fprintf(w, "%v\n", s) }
[ "func", "(", "s", "*", "Score", ")", "WriteString", "(", "w", "io", ".", "Writer", ")", "{", "// check if calling func paniced before calling this", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "// reset score for paniced functions", "s", ...
// WriteString writes the string representation of s to w.
[ "WriteString", "writes", "the", "string", "representation", "of", "s", "to", "w", "." ]
fdbad708e80aa3574e6f43dd9302bb607683361b
https://github.com/autograde/kit/blob/fdbad708e80aa3574e6f43dd9302bb607683361b/score/score.go#L118-L125
153,019
autograde/kit
score/score.go
WriteJSON
func (s *Score) WriteJSON(w io.Writer) { // check if calling func paniced before calling this if r := recover(); r != nil { // reset score for paniced functions s.Score = 0 } b, err := json.Marshal(s) if err != nil { fmt.Fprintf(w, "json.Marshal error: \n%v\n", err) } fmt.Fprintf(w, "\n%s\n", b) }
go
func (s *Score) WriteJSON(w io.Writer) { // check if calling func paniced before calling this if r := recover(); r != nil { // reset score for paniced functions s.Score = 0 } b, err := json.Marshal(s) if err != nil { fmt.Fprintf(w, "json.Marshal error: \n%v\n", err) } fmt.Fprintf(w, "\n%s\n", b) }
[ "func", "(", "s", "*", "Score", ")", "WriteJSON", "(", "w", "io", ".", "Writer", ")", "{", "// check if calling func paniced before calling this", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "// reset score for paniced functions", "s", "....
// WriteJSON writes the JSON representation of s to w.
[ "WriteJSON", "writes", "the", "JSON", "representation", "of", "s", "to", "w", "." ]
fdbad708e80aa3574e6f43dd9302bb607683361b
https://github.com/autograde/kit/blob/fdbad708e80aa3574e6f43dd9302bb607683361b/score/score.go#L128-L139
153,020
autograde/kit
score/totalscore.go
Total
func Total(scores []*Score) uint8 { totalWeight := float32(0) var max, score, weight []float32 for _, ts := range scores { totalWeight += float32(ts.Weight) weight = append(weight, float32(ts.Weight)) score = append(score, float32(ts.Score)) max = append(max, float32(ts.MaxScore)) } total := float32(0) for i := 0; i < len(scores); i++ { if score[i] > max[i] { score[i] = max[i] } total += ((score[i] / max[i]) * (weight[i] / totalWeight)) } return uint8(total * 100) }
go
func Total(scores []*Score) uint8 { totalWeight := float32(0) var max, score, weight []float32 for _, ts := range scores { totalWeight += float32(ts.Weight) weight = append(weight, float32(ts.Weight)) score = append(score, float32(ts.Score)) max = append(max, float32(ts.MaxScore)) } total := float32(0) for i := 0; i < len(scores); i++ { if score[i] > max[i] { score[i] = max[i] } total += ((score[i] / max[i]) * (weight[i] / totalWeight)) } return uint8(total * 100) }
[ "func", "Total", "(", "scores", "[", "]", "*", "Score", ")", "uint8", "{", "totalWeight", ":=", "float32", "(", "0", ")", "\n", "var", "max", ",", "score", ",", "weight", "[", "]", "float32", "\n", "for", "_", ",", "ts", ":=", "range", "scores", ...
// Total returns the total score computed over the set of scores provided. // The total is a grade in the range 0-100.
[ "Total", "returns", "the", "total", "score", "computed", "over", "the", "set", "of", "scores", "provided", ".", "The", "total", "is", "a", "grade", "in", "the", "range", "0", "-", "100", "." ]
fdbad708e80aa3574e6f43dd9302bb607683361b
https://github.com/autograde/kit/blob/fdbad708e80aa3574e6f43dd9302bb607683361b/score/totalscore.go#L5-L24
153,021
schollz/org.eclipse.paho.mqtt.golang
memstore.go
Close
func (store *MemoryStore) Close() { store.Lock() defer store.Unlock() chkcond(store.opened) store.opened = false DEBUG.Println(STR, "memorystore closed") }
go
func (store *MemoryStore) Close() { store.Lock() defer store.Unlock() chkcond(store.opened) store.opened = false DEBUG.Println(STR, "memorystore closed") }
[ "func", "(", "store", "*", "MemoryStore", ")", "Close", "(", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "chkcond", "(", "store", ".", "opened", ")", "\n", "store", ".", "opened", "=", "false", ...
// Close will disallow modifications to the state of the store.
[ "Close", "will", "disallow", "modifications", "to", "the", "state", "of", "the", "store", "." ]
6d626954dc988ae6c25b0fdaabdb64f144c438b0
https://github.com/schollz/org.eclipse.paho.mqtt.golang/blob/6d626954dc988ae6c25b0fdaabdb64f144c438b0/memstore.go#L105-L111
153,022
schollz/org.eclipse.paho.mqtt.golang
memstore.go
Reset
func (store *MemoryStore) Reset() { store.Lock() defer store.Unlock() chkcond(store.opened) store.messages = make(map[string]packets.ControlPacket) WARN.Println(STR, "memorystore wiped") }
go
func (store *MemoryStore) Reset() { store.Lock() defer store.Unlock() chkcond(store.opened) store.messages = make(map[string]packets.ControlPacket) WARN.Println(STR, "memorystore wiped") }
[ "func", "(", "store", "*", "MemoryStore", ")", "Reset", "(", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "chkcond", "(", "store", ".", "opened", ")", "\n", "store", ".", "messages", "=", "make", ...
// Reset eliminates all persisted message data in the store.
[ "Reset", "eliminates", "all", "persisted", "message", "data", "in", "the", "store", "." ]
6d626954dc988ae6c25b0fdaabdb64f144c438b0
https://github.com/schollz/org.eclipse.paho.mqtt.golang/blob/6d626954dc988ae6c25b0fdaabdb64f144c438b0/memstore.go#L114-L120
153,023
favclip/golidator
v1/builtins.go
ReqFactory
func ReqFactory(e *ReqErrorOption) ValidationFunc { if e == nil { e = &ReqErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.ReqError == nil { e.ReqError = ReqError } return func(t *Target, param string) error { v := t.FieldValue switch v.Kind() { case reflect.String: if v.String() == "" { return e.ReqError(t.FieldInfo, v.String()) } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if v.Int() == 0 { return e.ReqError(t.FieldInfo, fmt.Sprintf("%d", v.Int())) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: if v.Uint() == 0 { return e.ReqError(t.FieldInfo, fmt.Sprintf("%d", v.Uint())) } case reflect.Float32, reflect.Float64: if v.Float() == 0 { return e.ReqError(t.FieldInfo, fmt.Sprintf("%f", v.Float())) } case reflect.Bool: // :) case reflect.Array, reflect.Slice: if v.Len() == 0 { return e.ReqError(t.FieldInfo, v.Len()) } case reflect.Struct: // t.FieldValue is de-referenced ofv := t.StructValue.Field(t.FieldIndex) if ofv.Kind() == reflect.Ptr && ofv.IsNil() { return e.ReqError(t.FieldInfo, "nil") } default: return e.UnsupportedTypeError("req", t.FieldInfo) } return nil } }
go
func ReqFactory(e *ReqErrorOption) ValidationFunc { if e == nil { e = &ReqErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.ReqError == nil { e.ReqError = ReqError } return func(t *Target, param string) error { v := t.FieldValue switch v.Kind() { case reflect.String: if v.String() == "" { return e.ReqError(t.FieldInfo, v.String()) } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if v.Int() == 0 { return e.ReqError(t.FieldInfo, fmt.Sprintf("%d", v.Int())) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: if v.Uint() == 0 { return e.ReqError(t.FieldInfo, fmt.Sprintf("%d", v.Uint())) } case reflect.Float32, reflect.Float64: if v.Float() == 0 { return e.ReqError(t.FieldInfo, fmt.Sprintf("%f", v.Float())) } case reflect.Bool: // :) case reflect.Array, reflect.Slice: if v.Len() == 0 { return e.ReqError(t.FieldInfo, v.Len()) } case reflect.Struct: // t.FieldValue is de-referenced ofv := t.StructValue.Field(t.FieldIndex) if ofv.Kind() == reflect.Ptr && ofv.IsNil() { return e.ReqError(t.FieldInfo, "nil") } default: return e.UnsupportedTypeError("req", t.FieldInfo) } return nil } }
[ "func", "ReqFactory", "(", "e", "*", "ReqErrorOption", ")", "ValidationFunc", "{", "if", "e", "==", "nil", "{", "e", "=", "&", "ReqErrorOption", "{", "}", "\n", "}", "\n", "if", "e", ".", "UnsupportedTypeErrorOption", "==", "nil", "{", "e", ".", "Unsup...
// ReqFactory returns function validate parameter. it must not be empty.
[ "ReqFactory", "returns", "function", "validate", "parameter", ".", "it", "must", "not", "be", "empty", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/builtins.go#L49-L97
153,024
favclip/golidator
v1/builtins.go
DefaultFactory
func DefaultFactory(e *DefaultErrorOption) ValidationFunc { if e == nil { e = &DefaultErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.ParamParseErrorOption == nil { e.ParamParseErrorOption = &ParamParseErrorOption{ParamParseError} } if e.DefaultError == nil { e.DefaultError = DefaultError } return func(t *Target, param string) error { v := t.FieldValue switch v.Kind() { case reflect.String: if !v.CanAddr() { return e.DefaultError(t.FieldInfo) } if v.String() == "" { v.SetString(param) } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if !v.CanAddr() { return e.DefaultError(t.FieldInfo) } pInt, err := strconv.ParseInt(param, 0, 64) if err != nil { return e.ParamParseError("d", t.FieldInfo, "int") } if v.Int() == 0 { v.SetInt(pInt) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: if !v.CanAddr() { return e.DefaultError(t.FieldInfo) } pUint, err := strconv.ParseUint(param, 0, 64) if err != nil { return e.ParamParseError("d", t.FieldInfo, "uint") } if v.Uint() == 0 { v.SetUint(pUint) } case reflect.Float32, reflect.Float64: if !v.CanAddr() { return e.DefaultError(t.FieldInfo) } pFloat, err := strconv.ParseFloat(param, 64) if err != nil { return e.ParamParseError("d", t.FieldInfo, "float") } if v.Float() == 0 { v.SetFloat(pFloat) } default: return e.UnsupportedTypeError("default", t.FieldInfo) } return nil } }
go
func DefaultFactory(e *DefaultErrorOption) ValidationFunc { if e == nil { e = &DefaultErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.ParamParseErrorOption == nil { e.ParamParseErrorOption = &ParamParseErrorOption{ParamParseError} } if e.DefaultError == nil { e.DefaultError = DefaultError } return func(t *Target, param string) error { v := t.FieldValue switch v.Kind() { case reflect.String: if !v.CanAddr() { return e.DefaultError(t.FieldInfo) } if v.String() == "" { v.SetString(param) } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if !v.CanAddr() { return e.DefaultError(t.FieldInfo) } pInt, err := strconv.ParseInt(param, 0, 64) if err != nil { return e.ParamParseError("d", t.FieldInfo, "int") } if v.Int() == 0 { v.SetInt(pInt) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: if !v.CanAddr() { return e.DefaultError(t.FieldInfo) } pUint, err := strconv.ParseUint(param, 0, 64) if err != nil { return e.ParamParseError("d", t.FieldInfo, "uint") } if v.Uint() == 0 { v.SetUint(pUint) } case reflect.Float32, reflect.Float64: if !v.CanAddr() { return e.DefaultError(t.FieldInfo) } pFloat, err := strconv.ParseFloat(param, 64) if err != nil { return e.ParamParseError("d", t.FieldInfo, "float") } if v.Float() == 0 { v.SetFloat(pFloat) } default: return e.UnsupportedTypeError("default", t.FieldInfo) } return nil } }
[ "func", "DefaultFactory", "(", "e", "*", "DefaultErrorOption", ")", "ValidationFunc", "{", "if", "e", "==", "nil", "{", "e", "=", "&", "DefaultErrorOption", "{", "}", "\n", "}", "\n", "if", "e", ".", "UnsupportedTypeErrorOption", "==", "nil", "{", "e", "...
// DefaultFactory returns function set default value.
[ "DefaultFactory", "returns", "function", "set", "default", "value", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/builtins.go#L107-L169
153,025
favclip/golidator
v1/builtins.go
MinFactory
func MinFactory(e *MinErrorOption) ValidationFunc { if e == nil { e = &MinErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.ParamParseErrorOption == nil { e.ParamParseErrorOption = &ParamParseErrorOption{ParamParseError} } if e.MinError == nil { e.MinError = MinError } return func(t *Target, param string) error { v := t.FieldValue switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: pInt, err := strconv.ParseInt(param, 0, 64) if err != nil { return e.ParamParseError("min", t.FieldInfo, "number") } if v.Int() < pInt { return e.MinError(t.FieldInfo, v.Int(), pInt) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: pUint, err := strconv.ParseUint(param, 0, 64) if err != nil { return e.ParamParseError("min", t.FieldInfo, "number") } if v.Uint() < pUint { return e.MinError(t.FieldInfo, v.Uint(), pUint) } case reflect.Float32, reflect.Float64: pFloat, err := strconv.ParseFloat(param, 64) if err != nil { return e.ParamParseError("min", t.FieldInfo, "number") } if v.Float() < pFloat { return e.MinError(t.FieldInfo, v.Float(), pFloat) } default: return e.UnsupportedTypeError("min", t.FieldInfo) } return nil } }
go
func MinFactory(e *MinErrorOption) ValidationFunc { if e == nil { e = &MinErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.ParamParseErrorOption == nil { e.ParamParseErrorOption = &ParamParseErrorOption{ParamParseError} } if e.MinError == nil { e.MinError = MinError } return func(t *Target, param string) error { v := t.FieldValue switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: pInt, err := strconv.ParseInt(param, 0, 64) if err != nil { return e.ParamParseError("min", t.FieldInfo, "number") } if v.Int() < pInt { return e.MinError(t.FieldInfo, v.Int(), pInt) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: pUint, err := strconv.ParseUint(param, 0, 64) if err != nil { return e.ParamParseError("min", t.FieldInfo, "number") } if v.Uint() < pUint { return e.MinError(t.FieldInfo, v.Uint(), pUint) } case reflect.Float32, reflect.Float64: pFloat, err := strconv.ParseFloat(param, 64) if err != nil { return e.ParamParseError("min", t.FieldInfo, "number") } if v.Float() < pFloat { return e.MinError(t.FieldInfo, v.Float(), pFloat) } default: return e.UnsupportedTypeError("min", t.FieldInfo) } return nil } }
[ "func", "MinFactory", "(", "e", "*", "MinErrorOption", ")", "ValidationFunc", "{", "if", "e", "==", "nil", "{", "e", "=", "&", "MinErrorOption", "{", "}", "\n", "}", "\n", "if", "e", ".", "UnsupportedTypeErrorOption", "==", "nil", "{", "e", ".", "Unsup...
// MinFactory returns function check minimum value.
[ "MinFactory", "returns", "function", "check", "minimum", "value", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/builtins.go#L179-L225
153,026
favclip/golidator
v1/builtins.go
MinLenFactory
func MinLenFactory(e *MinLenErrorOption) ValidationFunc { if e == nil { e = &MinLenErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.ParamParseErrorOption == nil { e.ParamParseErrorOption = &ParamParseErrorOption{ParamParseError} } if e.MinLenError == nil { e.MinLenError = MinLenError } return func(t *Target, param string) error { v := t.FieldValue switch v.Kind() { case reflect.String: if v.String() == "" { return nil // emptyの場合は無視 これはreqの役目だ } p, err := strconv.ParseInt(param, 0, 64) if err != nil { return e.ParamParseError("minLen", t.FieldInfo, "number") } if int64(utf8.RuneCountInString(v.String())) < p { return e.MinLenError(t.FieldInfo, v.String(), p) } case reflect.Array, reflect.Map, reflect.Slice: if v.Len() == 0 { return nil } p, err := strconv.ParseInt(param, 0, 64) if err != nil { return e.ParamParseError("minLen", t.FieldInfo, "number") } if int64(v.Len()) < p { return e.MinLenError(t.FieldInfo, v.Len(), p) } default: return e.UnsupportedTypeError("minLen", t.FieldInfo) } return nil } }
go
func MinLenFactory(e *MinLenErrorOption) ValidationFunc { if e == nil { e = &MinLenErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.ParamParseErrorOption == nil { e.ParamParseErrorOption = &ParamParseErrorOption{ParamParseError} } if e.MinLenError == nil { e.MinLenError = MinLenError } return func(t *Target, param string) error { v := t.FieldValue switch v.Kind() { case reflect.String: if v.String() == "" { return nil // emptyの場合は無視 これはreqの役目だ } p, err := strconv.ParseInt(param, 0, 64) if err != nil { return e.ParamParseError("minLen", t.FieldInfo, "number") } if int64(utf8.RuneCountInString(v.String())) < p { return e.MinLenError(t.FieldInfo, v.String(), p) } case reflect.Array, reflect.Map, reflect.Slice: if v.Len() == 0 { return nil } p, err := strconv.ParseInt(param, 0, 64) if err != nil { return e.ParamParseError("minLen", t.FieldInfo, "number") } if int64(v.Len()) < p { return e.MinLenError(t.FieldInfo, v.Len(), p) } default: return e.UnsupportedTypeError("minLen", t.FieldInfo) } return nil } }
[ "func", "MinLenFactory", "(", "e", "*", "MinLenErrorOption", ")", "ValidationFunc", "{", "if", "e", "==", "nil", "{", "e", "=", "&", "MinLenErrorOption", "{", "}", "\n", "}", "\n", "if", "e", ".", "UnsupportedTypeErrorOption", "==", "nil", "{", "e", ".",...
// MinLenFactory returns function check minimum length.
[ "MinLenFactory", "returns", "function", "check", "minimum", "length", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/builtins.go#L291-L335
153,027
favclip/golidator
v1/builtins.go
EmailFactory
func EmailFactory(e *EmailErrorOption) ValidationFunc { if e == nil { e = &EmailErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.EmailError == nil { e.EmailError = EmailError } return func(t *Target, param string) error { v := t.FieldValue switch v.Kind() { case reflect.String: if v.String() == "" { return nil } addr := v.String() // do validation by RFC5322 // http://www.hde.co.jp/rfc/rfc5322.php?page=17 // screening if _, err := mailp.ParseAddress(addr); err != nil { return e.EmailError(t.FieldInfo, addr) } addrSpec := strings.Split(addr, "@") if len(addrSpec) != 2 { return e.EmailError(t.FieldInfo, addr) } // check local part localPart := addrSpec[0] // divided by quoted-string style or dom-atom style if match, err := re.MatchString(`"[^\t\n\f\r\\]*"`, localPart); err == nil && match { // "\"以外の表示可能文字を認める // OK } else if match, err := re.MatchString(`^([^.\s]+\.)*([^.\s]+)$`, localPart); err != nil || !match { // (hoge.)*hoge return e.EmailError(t.FieldInfo, addr) } else { // atext check for local part for _, c := range localPart { if string(c) == "." { // "." is already checked by regexp continue } if !isAtext(c) { e.EmailError(t.FieldInfo, addr) } } } // check domain part domain := addrSpec[1] if match, err := re.MatchString(`^([^.\s]+\.)*[^.\s]+$`, domain); err != nil || !match { // (hoge.)*hoge return e.EmailError(t.FieldInfo, addr) } // atext check for domain part for _, c := range domain { if string(c) == "." { // "." is already checked by regexp continue } if !isAtext(c) { return e.EmailError(t.FieldInfo, addr) } } return nil default: return e.UnsupportedTypeError("email", t.FieldInfo) } } }
go
func EmailFactory(e *EmailErrorOption) ValidationFunc { if e == nil { e = &EmailErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.EmailError == nil { e.EmailError = EmailError } return func(t *Target, param string) error { v := t.FieldValue switch v.Kind() { case reflect.String: if v.String() == "" { return nil } addr := v.String() // do validation by RFC5322 // http://www.hde.co.jp/rfc/rfc5322.php?page=17 // screening if _, err := mailp.ParseAddress(addr); err != nil { return e.EmailError(t.FieldInfo, addr) } addrSpec := strings.Split(addr, "@") if len(addrSpec) != 2 { return e.EmailError(t.FieldInfo, addr) } // check local part localPart := addrSpec[0] // divided by quoted-string style or dom-atom style if match, err := re.MatchString(`"[^\t\n\f\r\\]*"`, localPart); err == nil && match { // "\"以外の表示可能文字を認める // OK } else if match, err := re.MatchString(`^([^.\s]+\.)*([^.\s]+)$`, localPart); err != nil || !match { // (hoge.)*hoge return e.EmailError(t.FieldInfo, addr) } else { // atext check for local part for _, c := range localPart { if string(c) == "." { // "." is already checked by regexp continue } if !isAtext(c) { e.EmailError(t.FieldInfo, addr) } } } // check domain part domain := addrSpec[1] if match, err := re.MatchString(`^([^.\s]+\.)*[^.\s]+$`, domain); err != nil || !match { // (hoge.)*hoge return e.EmailError(t.FieldInfo, addr) } // atext check for domain part for _, c := range domain { if string(c) == "." { // "." is already checked by regexp continue } if !isAtext(c) { return e.EmailError(t.FieldInfo, addr) } } return nil default: return e.UnsupportedTypeError("email", t.FieldInfo) } } }
[ "func", "EmailFactory", "(", "e", "*", "EmailErrorOption", ")", "ValidationFunc", "{", "if", "e", "==", "nil", "{", "e", "=", "&", "EmailErrorOption", "{", "}", "\n", "}", "\n", "if", "e", ".", "UnsupportedTypeErrorOption", "==", "nil", "{", "e", ".", ...
// EmailFactory returns function check value is `Email` format.
[ "EmailFactory", "returns", "function", "check", "value", "is", "Email", "format", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/builtins.go#L398-L468
153,028
favclip/golidator
v1/builtins.go
EnumFactory
func EnumFactory(e *EnumErrorOption) ValidationFunc { if e == nil { e = &EnumErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.EmptyParamErrorOption == nil { e.EmptyParamErrorOption = &EmptyParamErrorOption{EmptyParamError} } if e.EnumError == nil { e.EnumError = EnumError } return func(t *Target, param string) error { params := strings.Split(param, "|") if param == "" { return e.EmptyParamError("enum", t.FieldInfo) } v := t.FieldValue var enum func(v reflect.Value) error enum = func(v reflect.Value) error { if v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.String: val := v.String() if val == "" { // need empty checking? use req :) return nil } for _, value := range params { if val == value { return nil } } return e.EnumError(t.FieldInfo, val, params) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: val := v.Int() for _, value := range params { value2, err := strconv.ParseInt(value, 10, 0) if err != nil { return nil } if val == value2 { return nil } } return e.EnumError(t.FieldInfo, val, params) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: val := v.Uint() for _, value := range params { value2, err := strconv.ParseUint(value, 10, 0) if err != nil { return nil } if val == value2 { return nil } } return e.EnumError(t.FieldInfo, val, params) case reflect.Array, reflect.Slice: for i := 0; i < v.Len(); i++ { e := v.Index(i) err := enum(e) if err != nil { return err } } default: return e.UnsupportedTypeError("enum", t.FieldInfo) } return nil } return enum(v) } }
go
func EnumFactory(e *EnumErrorOption) ValidationFunc { if e == nil { e = &EnumErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.EmptyParamErrorOption == nil { e.EmptyParamErrorOption = &EmptyParamErrorOption{EmptyParamError} } if e.EnumError == nil { e.EnumError = EnumError } return func(t *Target, param string) error { params := strings.Split(param, "|") if param == "" { return e.EmptyParamError("enum", t.FieldInfo) } v := t.FieldValue var enum func(v reflect.Value) error enum = func(v reflect.Value) error { if v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.String: val := v.String() if val == "" { // need empty checking? use req :) return nil } for _, value := range params { if val == value { return nil } } return e.EnumError(t.FieldInfo, val, params) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: val := v.Int() for _, value := range params { value2, err := strconv.ParseInt(value, 10, 0) if err != nil { return nil } if val == value2 { return nil } } return e.EnumError(t.FieldInfo, val, params) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: val := v.Uint() for _, value := range params { value2, err := strconv.ParseUint(value, 10, 0) if err != nil { return nil } if val == value2 { return nil } } return e.EnumError(t.FieldInfo, val, params) case reflect.Array, reflect.Slice: for i := 0; i < v.Len(); i++ { e := v.Index(i) err := enum(e) if err != nil { return err } } default: return e.UnsupportedTypeError("enum", t.FieldInfo) } return nil } return enum(v) } }
[ "func", "EnumFactory", "(", "e", "*", "EnumErrorOption", ")", "ValidationFunc", "{", "if", "e", "==", "nil", "{", "e", "=", "&", "EnumErrorOption", "{", "}", "\n", "}", "\n", "if", "e", ".", "UnsupportedTypeErrorOption", "==", "nil", "{", "e", ".", "Un...
// EnumFactory returns function check value is established value.
[ "EnumFactory", "returns", "function", "check", "value", "is", "established", "value", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/builtins.go#L478-L558
153,029
autograde/kit
exercise/multiple_choice.go
MultipleChoice
func MultipleChoice(t *testing.T, sc *score.Score, fileName string, answers Choices) { defer sc.WriteString(os.Stdout) defer sc.WriteJSON(os.Stdout) // Read the whole file bytes, err := ioutil.ReadFile(fileName) if err != nil { sc.Score = 0 t.Fatalf(fmt.Sprintf("%v: error reading the file: %v", fileName, err)) return } for i := range answers { // Find the user's answer to the corresponding question number regexStr := "\n" + strconv.Itoa(answers[i].Number) + "[.)]*[ \t\v\r\n\f]*[A-Za-z]*" regex := regexp.MustCompile(regexStr) userAnswer := regex.Find(bytes) if userAnswer == nil { t.Errorf("%v %d: Answer not found.\n", sc.TestName, answers[i].Number) sc.Dec() } else { r, _ := utf8.DecodeLastRune(userAnswer) got, _ := utf8.DecodeLastRuneInString(strings.ToUpper(string(r))) if got != answers[i].Want { t.Errorf("%v %d: %q is incorrect.\n", sc.TestName, answers[i].Number, got) sc.Dec() } } } }
go
func MultipleChoice(t *testing.T, sc *score.Score, fileName string, answers Choices) { defer sc.WriteString(os.Stdout) defer sc.WriteJSON(os.Stdout) // Read the whole file bytes, err := ioutil.ReadFile(fileName) if err != nil { sc.Score = 0 t.Fatalf(fmt.Sprintf("%v: error reading the file: %v", fileName, err)) return } for i := range answers { // Find the user's answer to the corresponding question number regexStr := "\n" + strconv.Itoa(answers[i].Number) + "[.)]*[ \t\v\r\n\f]*[A-Za-z]*" regex := regexp.MustCompile(regexStr) userAnswer := regex.Find(bytes) if userAnswer == nil { t.Errorf("%v %d: Answer not found.\n", sc.TestName, answers[i].Number) sc.Dec() } else { r, _ := utf8.DecodeLastRune(userAnswer) got, _ := utf8.DecodeLastRuneInString(strings.ToUpper(string(r))) if got != answers[i].Want { t.Errorf("%v %d: %q is incorrect.\n", sc.TestName, answers[i].Number, got) sc.Dec() } } } }
[ "func", "MultipleChoice", "(", "t", "*", "testing", ".", "T", ",", "sc", "*", "score", ".", "Score", ",", "fileName", "string", ",", "answers", "Choices", ")", "{", "defer", "sc", ".", "WriteString", "(", "os", ".", "Stdout", ")", "\n", "defer", "sc"...
// MultipleChoice computes the score of a multiple choice exercise // with student answers provided in fileName, and the answers provided // in the answerKey object. The function requires a Score object, and // will produce both string output and JSON output.
[ "MultipleChoice", "computes", "the", "score", "of", "a", "multiple", "choice", "exercise", "with", "student", "answers", "provided", "in", "fileName", "and", "the", "answers", "provided", "in", "the", "answerKey", "object", ".", "The", "function", "requires", "a...
fdbad708e80aa3574e6f43dd9302bb607683361b
https://github.com/autograde/kit/blob/fdbad708e80aa3574e6f43dd9302bb607683361b/exercise/multiple_choice.go#L25-L55
153,030
favclip/golidator
validator.go
SetValidationFunc
func (vl *Validator) SetValidationFunc(name string, vf ValidationFunc) { if vl.funcs == nil { vl.funcs = make(map[string]ValidationFunc) } vl.funcs[name] = vf }
go
func (vl *Validator) SetValidationFunc(name string, vf ValidationFunc) { if vl.funcs == nil { vl.funcs = make(map[string]ValidationFunc) } vl.funcs[name] = vf }
[ "func", "(", "vl", "*", "Validator", ")", "SetValidationFunc", "(", "name", "string", ",", "vf", "ValidationFunc", ")", "{", "if", "vl", ".", "funcs", "==", "nil", "{", "vl", ".", "funcs", "=", "make", "(", "map", "[", "string", "]", "ValidationFunc", ...
// SetValidationFunc is setup tag name with ValidationFunc.
[ "SetValidationFunc", "is", "setup", "tag", "name", "with", "ValidationFunc", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/validator.go#L51-L56
153,031
favclip/golidator
validator.go
Validate
func (vl *Validator) Validate(v interface{}) error { if v == nil { return nil } rv := reflect.ValueOf(v) w := &walker{ v: vl, report: &ErrorReport{ Root: rv, Type: "https://github.com/favclip/golidator", }, ParentFieldName: "", Root: rv, Current: rv, } if err := w.walkStruct(); err != nil { return err } if len(w.report.Details) != 0 { return w.report } return nil }
go
func (vl *Validator) Validate(v interface{}) error { if v == nil { return nil } rv := reflect.ValueOf(v) w := &walker{ v: vl, report: &ErrorReport{ Root: rv, Type: "https://github.com/favclip/golidator", }, ParentFieldName: "", Root: rv, Current: rv, } if err := w.walkStruct(); err != nil { return err } if len(w.report.Details) != 0 { return w.report } return nil }
[ "func", "(", "vl", "*", "Validator", ")", "Validate", "(", "v", "interface", "{", "}", ")", "error", "{", "if", "v", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "rv", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "w", ":=", "&",...
// Validate argument value.
[ "Validate", "argument", "value", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/validator.go#L59-L83
153,032
favclip/golidator
v1/validator.go
Validate
func (vl *Validator) Validate(v interface{}) error { return vl.validateStruct(reflect.ValueOf(v)) }
go
func (vl *Validator) Validate(v interface{}) error { return vl.validateStruct(reflect.ValueOf(v)) }
[ "func", "(", "vl", "*", "Validator", ")", "Validate", "(", "v", "interface", "{", "}", ")", "error", "{", "return", "vl", ".", "validateStruct", "(", "reflect", ".", "ValueOf", "(", "v", ")", ")", "\n", "}" ]
// Validate do validate.
[ "Validate", "do", "validate", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/validator.go#L58-L60
153,033
beyang/go-astquery
ast.go
Find
func Find(nodes []ast.Node, filter Filter) []ast.Node { var found []ast.Node for _, node := range nodes { found = append(found, find(node, filter)...) } return found }
go
func Find(nodes []ast.Node, filter Filter) []ast.Node { var found []ast.Node for _, node := range nodes { found = append(found, find(node, filter)...) } return found }
[ "func", "Find", "(", "nodes", "[", "]", "ast", ".", "Node", ",", "filter", "Filter", ")", "[", "]", "ast", ".", "Node", "{", "var", "found", "[", "]", "ast", ".", "Node", "\n", "for", "_", ",", "node", ":=", "range", "nodes", "{", "found", "=",...
// Find recursively searches the AST nodes passed as the first argument and returns all // AST nodes that match the filter. It does not descend into matching nodes for additional // matching nodes.
[ "Find", "recursively", "searches", "the", "AST", "nodes", "passed", "as", "the", "first", "argument", "and", "returns", "all", "AST", "nodes", "that", "match", "the", "filter", ".", "It", "does", "not", "descend", "into", "matching", "nodes", "for", "additio...
aa6ec301d93fbe3f6b70762fcd536d2f1f209fe0
https://github.com/beyang/go-astquery/blob/aa6ec301d93fbe3f6b70762fcd536d2f1f209fe0/ast.go#L93-L99
153,034
beyang/go-astquery
ast.go
GetName
func GetName(n ast.Node) (name string, exists bool) { var ident_ interface{} if idt, exists := getStructField(n, "Name"); exists { ident_ = idt } else if idt, exists := getStructField(n, "Sel"); exists { ident_ = idt } if ident_ == nil { return "", false } nodeName, isIdent := ident_.(*ast.Ident) if !isIdent { return "", false } return nodeName.Name, true }
go
func GetName(n ast.Node) (name string, exists bool) { var ident_ interface{} if idt, exists := getStructField(n, "Name"); exists { ident_ = idt } else if idt, exists := getStructField(n, "Sel"); exists { ident_ = idt } if ident_ == nil { return "", false } nodeName, isIdent := ident_.(*ast.Ident) if !isIdent { return "", false } return nodeName.Name, true }
[ "func", "GetName", "(", "n", "ast", ".", "Node", ")", "(", "name", "string", ",", "exists", "bool", ")", "{", "var", "ident_", "interface", "{", "}", "\n", "if", "idt", ",", "exists", ":=", "getStructField", "(", "n", ",", "\"", "\"", ")", ";", "...
// GetName gets the name of a node's identifier. For TypeSpecs and FuncDecls, it looks at the .Name field. For // SelectorExpr's, it looks at the Sel field.
[ "GetName", "gets", "the", "name", "of", "a", "node", "s", "identifier", ".", "For", "TypeSpecs", "and", "FuncDecls", "it", "looks", "at", "the", ".", "Name", "field", ".", "For", "SelectorExpr", "s", "it", "looks", "at", "the", "Sel", "field", "." ]
aa6ec301d93fbe3f6b70762fcd536d2f1f209fe0
https://github.com/beyang/go-astquery/blob/aa6ec301d93fbe3f6b70762fcd536d2f1f209fe0/ast.go#L127-L143
153,035
beyang/go-astquery
ast.go
getStructField
func getStructField(v interface{}, field string) (fieldVal interface{}, exists bool) { vv := reflect.ValueOf(v) if !vv.IsValid() { return nil, false } if vv.Kind() == reflect.Ptr { vv = vv.Elem() } fv := vv.FieldByName(field) if !fv.IsValid() { return nil, false } return fv.Interface(), true }
go
func getStructField(v interface{}, field string) (fieldVal interface{}, exists bool) { vv := reflect.ValueOf(v) if !vv.IsValid() { return nil, false } if vv.Kind() == reflect.Ptr { vv = vv.Elem() } fv := vv.FieldByName(field) if !fv.IsValid() { return nil, false } return fv.Interface(), true }
[ "func", "getStructField", "(", "v", "interface", "{", "}", ",", "field", "string", ")", "(", "fieldVal", "interface", "{", "}", ",", "exists", "bool", ")", "{", "vv", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "if", "!", "vv", ".", "IsVa...
// getStructField returns the value of v's field with the given name // if it exists. v must be a struct or a pointer to a struct.
[ "getStructField", "returns", "the", "value", "of", "v", "s", "field", "with", "the", "given", "name", "if", "it", "exists", ".", "v", "must", "be", "a", "struct", "or", "a", "pointer", "to", "a", "struct", "." ]
aa6ec301d93fbe3f6b70762fcd536d2f1f209fe0
https://github.com/beyang/go-astquery/blob/aa6ec301d93fbe3f6b70762fcd536d2f1f209fe0/ast.go#L147-L160
153,036
beyang/go-astquery
ast.go
typeName
func typeName(typeExpr ast.Expr) (string, error) { switch typeExpr := typeExpr.(type) { case *ast.StarExpr: return typeName(typeExpr.X) case *ast.Ident: return typeExpr.Name, nil default: return "", fmt.Errorf("expr %+v is not a type expression", typeExpr) } }
go
func typeName(typeExpr ast.Expr) (string, error) { switch typeExpr := typeExpr.(type) { case *ast.StarExpr: return typeName(typeExpr.X) case *ast.Ident: return typeExpr.Name, nil default: return "", fmt.Errorf("expr %+v is not a type expression", typeExpr) } }
[ "func", "typeName", "(", "typeExpr", "ast", ".", "Expr", ")", "(", "string", ",", "error", ")", "{", "switch", "typeExpr", ":=", "typeExpr", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "StarExpr", ":", "return", "typeName", "(", "typeExpr", ...
// typeName returns the name of the type referenced by typeExpr.
[ "typeName", "returns", "the", "name", "of", "the", "type", "referenced", "by", "typeExpr", "." ]
aa6ec301d93fbe3f6b70762fcd536d2f1f209fe0
https://github.com/beyang/go-astquery/blob/aa6ec301d93fbe3f6b70762fcd536d2f1f209fe0/ast.go#L163-L172
153,037
schollz/org.eclipse.paho.mqtt.golang
filestore.go
Close
func (store *FileStore) Close() { store.Lock() defer store.Unlock() store.opened = false WARN.Println(STR, "store is not open") }
go
func (store *FileStore) Close() { store.Lock() defer store.Unlock() store.opened = false WARN.Println(STR, "store is not open") }
[ "func", "(", "store", "*", "FileStore", ")", "Close", "(", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "store", ".", "opened", "=", "false", "\n", "WARN", ".", "Println", "(", "STR", ",", "\"",...
// Close will disallow the FileStore from being used.
[ "Close", "will", "disallow", "the", "FileStore", "from", "being", "used", "." ]
6d626954dc988ae6c25b0fdaabdb64f144c438b0
https://github.com/schollz/org.eclipse.paho.mqtt.golang/blob/6d626954dc988ae6c25b0fdaabdb64f144c438b0/filestore.go#L74-L79
153,038
schollz/org.eclipse.paho.mqtt.golang
filestore.go
restore
func restore(store string) { files, rderr := ioutil.ReadDir(store) chkerr(rderr) for _, f := range files { fname := f.Name() if len(fname) > 4 { if fname[len(fname)-4:] == bkpExt { key := fname[0 : len(fname)-4] fulp := fullpath(store, key) msg, cerr := os.Create(fulp) chkerr(cerr) bkpp := path.Join(store, fname) bkp, oerr := os.Open(bkpp) chkerr(oerr) n, cerr := io.Copy(msg, bkp) chkerr(cerr) chkcond(n > 0) clmerr := msg.Close() chkerr(clmerr) clberr := bkp.Close() chkerr(clberr) remerr := os.Remove(bkpp) chkerr(remerr) } } } }
go
func restore(store string) { files, rderr := ioutil.ReadDir(store) chkerr(rderr) for _, f := range files { fname := f.Name() if len(fname) > 4 { if fname[len(fname)-4:] == bkpExt { key := fname[0 : len(fname)-4] fulp := fullpath(store, key) msg, cerr := os.Create(fulp) chkerr(cerr) bkpp := path.Join(store, fname) bkp, oerr := os.Open(bkpp) chkerr(oerr) n, cerr := io.Copy(msg, bkp) chkerr(cerr) chkcond(n > 0) clmerr := msg.Close() chkerr(clmerr) clberr := bkp.Close() chkerr(clberr) remerr := os.Remove(bkpp) chkerr(remerr) } } } }
[ "func", "restore", "(", "store", "string", ")", "{", "files", ",", "rderr", ":=", "ioutil", ".", "ReadDir", "(", "store", ")", "\n", "chkerr", "(", "rderr", ")", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "fname", ":=", "f", ".", "N...
// Identify .bkp files in the store and turn them into .msg files, // whether or not it overwrites an existing file. This is safe because // I'm copying the Paho Java client and they say it is.
[ "Identify", ".", "bkp", "files", "in", "the", "store", "and", "turn", "them", "into", ".", "msg", "files", "whether", "or", "not", "it", "overwrites", "an", "existing", "file", ".", "This", "is", "safe", "because", "I", "m", "copying", "the", "Paho", "...
6d626954dc988ae6c25b0fdaabdb64f144c438b0
https://github.com/schollz/org.eclipse.paho.mqtt.golang/blob/6d626954dc988ae6c25b0fdaabdb64f144c438b0/filestore.go#L227-L253
153,039
timehop/golog
log/logging.go
Fatal
func Fatal(id, description string, keysAndValues ...interface{}) { keysAndValues = append([]interface{}{"golog_id", id}, keysAndValues...) (DefaultLogger.(*logger)).fatal(1, description, keysAndValues...) }
go
func Fatal(id, description string, keysAndValues ...interface{}) { keysAndValues = append([]interface{}{"golog_id", id}, keysAndValues...) (DefaultLogger.(*logger)).fatal(1, description, keysAndValues...) }
[ "func", "Fatal", "(", "id", ",", "description", "string", ",", "keysAndValues", "...", "interface", "{", "}", ")", "{", "keysAndValues", "=", "append", "(", "[", "]", "interface", "{", "}", "{", "\"", "\"", ",", "id", "}", ",", "keysAndValues", "...", ...
// Fatal outputs a severe error message just before terminating the process. // Use judiciously.
[ "Fatal", "outputs", "a", "severe", "error", "message", "just", "before", "terminating", "the", "process", ".", "Use", "judiciously", "." ]
cbf2afa06faa6150f417216d35530706da75275a
https://github.com/timehop/golog/blob/cbf2afa06faa6150f417216d35530706da75275a/log/logging.go#L143-L146
153,040
timehop/golog
log/logging.go
New
func New(conf Config, staticKeysAndValues ...interface{}) Logger { var prefix string var flags int var formatter formatLogEvent staticArgs := make(map[string]string, 0) format := SanitizeFormat(conf.Format) if format == JsonFormat { formatter = formatLogEventAsJson // Don't mess up the json by letting logger print these: prefix = "" flags = 0 // Instead put them into the staticArgs if defaultPrefix != "" { staticArgs["prefix"] = defaultPrefix } } else if format == KeyValueFormat { formatter = formatLogEvent(formatLogEventAsKeyValue) } else { formatter = formatLogEvent(formatLogEventAsPlainText) prefix = defaultPrefix flags = defaultFlags } // Set 'ID' config as a static field, but before reading the varargs suplied // fields, so that they can override the config. if conf.ID != "" { staticArgs["golog_id"] = conf.ID } if len(staticKeysAndValues)%2 == 1 { // If there are an odd number of staticKeysAndValue, then there's probably one // missing, which means we'd interpret a value as a key, which can be bad for // logs-as-data, like metrics on staticKeys or elasticsearch. But, instead of // throwing the corrupt data out, serialize it into a string, which both // keeps the info, and maintains key-value integrity. staticKeysAndValues = []interface{}{"corruptStaticFields", flattenKeyValues(staticKeysAndValues)} } // Do this after handling prefix, so that individual loggers can override // external env variable. currentKey := "" for i, arg := range staticKeysAndValues { if i%2 == 0 { currentKey = fmt.Sprintf("%v", arg) } else { staticArgs[currentKey] = fmt.Sprintf("%v", arg) } } return &logger{ stackTrace: defaultStackTrace, level: defaultLevel, formatLogEvent: formatter, staticArgs: staticArgs, // don't touch the default logger on 'log' package // cache args to make a logger, in case it's changes with SetOutput() prefix: prefix, flags: flags, l: log.New(defaultOutput, prefix, flags), } }
go
func New(conf Config, staticKeysAndValues ...interface{}) Logger { var prefix string var flags int var formatter formatLogEvent staticArgs := make(map[string]string, 0) format := SanitizeFormat(conf.Format) if format == JsonFormat { formatter = formatLogEventAsJson // Don't mess up the json by letting logger print these: prefix = "" flags = 0 // Instead put them into the staticArgs if defaultPrefix != "" { staticArgs["prefix"] = defaultPrefix } } else if format == KeyValueFormat { formatter = formatLogEvent(formatLogEventAsKeyValue) } else { formatter = formatLogEvent(formatLogEventAsPlainText) prefix = defaultPrefix flags = defaultFlags } // Set 'ID' config as a static field, but before reading the varargs suplied // fields, so that they can override the config. if conf.ID != "" { staticArgs["golog_id"] = conf.ID } if len(staticKeysAndValues)%2 == 1 { // If there are an odd number of staticKeysAndValue, then there's probably one // missing, which means we'd interpret a value as a key, which can be bad for // logs-as-data, like metrics on staticKeys or elasticsearch. But, instead of // throwing the corrupt data out, serialize it into a string, which both // keeps the info, and maintains key-value integrity. staticKeysAndValues = []interface{}{"corruptStaticFields", flattenKeyValues(staticKeysAndValues)} } // Do this after handling prefix, so that individual loggers can override // external env variable. currentKey := "" for i, arg := range staticKeysAndValues { if i%2 == 0 { currentKey = fmt.Sprintf("%v", arg) } else { staticArgs[currentKey] = fmt.Sprintf("%v", arg) } } return &logger{ stackTrace: defaultStackTrace, level: defaultLevel, formatLogEvent: formatter, staticArgs: staticArgs, // don't touch the default logger on 'log' package // cache args to make a logger, in case it's changes with SetOutput() prefix: prefix, flags: flags, l: log.New(defaultOutput, prefix, flags), } }
[ "func", "New", "(", "conf", "Config", ",", "staticKeysAndValues", "...", "interface", "{", "}", ")", "Logger", "{", "var", "prefix", "string", "\n", "var", "flags", "int", "\n", "var", "formatter", "formatLogEvent", "\n", "staticArgs", ":=", "make", "(", "...
// New creates a new logger instance.
[ "New", "creates", "a", "new", "logger", "instance", "." ]
cbf2afa06faa6150f417216d35530706da75275a
https://github.com/timehop/golog/blob/cbf2afa06faa6150f417216d35530706da75275a/log/logging.go#L248-L314
153,041
timehop/golog
log/logging.go
SetOutput
func (s *logger) SetOutput(w io.Writer) { s.l = log.New(w, s.prefix, s.flags) }
go
func (s *logger) SetOutput(w io.Writer) { s.l = log.New(w, s.prefix, s.flags) }
[ "func", "(", "s", "*", "logger", ")", "SetOutput", "(", "w", "io", ".", "Writer", ")", "{", "s", ".", "l", "=", "log", ".", "New", "(", "w", ",", "s", ".", "prefix", ",", "s", ".", "flags", ")", "\n", "}" ]
// SetOutput sets the output destination for the logger. // // Useful to change where the log stream ends up being written to.
[ "SetOutput", "sets", "the", "output", "destination", "for", "the", "logger", ".", "Useful", "to", "change", "where", "the", "log", "stream", "ends", "up", "being", "written", "to", "." ]
cbf2afa06faa6150f417216d35530706da75275a
https://github.com/timehop/golog/blob/cbf2afa06faa6150f417216d35530706da75275a/log/logging.go#L485-L487
153,042
timehop/golog
log/logging.go
SetTimestampFlags
func (s *logger) SetTimestampFlags(flags int) { s.flags = flags s.l.SetFlags(flags) }
go
func (s *logger) SetTimestampFlags(flags int) { s.flags = flags s.l.SetFlags(flags) }
[ "func", "(", "s", "*", "logger", ")", "SetTimestampFlags", "(", "flags", "int", ")", "{", "s", ".", "flags", "=", "flags", "\n", "s", ".", "l", ".", "SetFlags", "(", "flags", ")", "\n", "}" ]
// SetFlags changes the timestamp flags on the output of the logger.
[ "SetFlags", "changes", "the", "timestamp", "flags", "on", "the", "output", "of", "the", "logger", "." ]
cbf2afa06faa6150f417216d35530706da75275a
https://github.com/timehop/golog/blob/cbf2afa06faa6150f417216d35530706da75275a/log/logging.go#L490-L493
153,043
timehop/golog
log/logging.go
expandKeyValuePairs
func expandKeyValuePairs(keyValuePairs []interface{}) string { kvPairs := make([]string, 0, len(keyValuePairs)/2) // Just ignore the last dangling kv if odd #, cuz bug. for i, kv := range keyValuePairs { if i%2 == 1 { kvPairs = append(kvPairs, fmt.Sprintf("%v='%v'", keyValuePairs[i-1], kv)) } } return strings.Join(kvPairs, " ") }
go
func expandKeyValuePairs(keyValuePairs []interface{}) string { kvPairs := make([]string, 0, len(keyValuePairs)/2) // Just ignore the last dangling kv if odd #, cuz bug. for i, kv := range keyValuePairs { if i%2 == 1 { kvPairs = append(kvPairs, fmt.Sprintf("%v='%v'", keyValuePairs[i-1], kv)) } } return strings.Join(kvPairs, " ") }
[ "func", "expandKeyValuePairs", "(", "keyValuePairs", "[", "]", "interface", "{", "}", ")", "string", "{", "kvPairs", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "keyValuePairs", ")", "/", "2", ")", "\n\n", "// Just ignore the last dan...
// expandKeyValuePairs converts a list of arguments into a string with the // format "k='v' foo='bar' bar=".
[ "expandKeyValuePairs", "converts", "a", "list", "of", "arguments", "into", "a", "string", "with", "the", "format", "k", "=", "v", "foo", "=", "bar", "bar", "=", "." ]
cbf2afa06faa6150f417216d35530706da75275a
https://github.com/timehop/golog/blob/cbf2afa06faa6150f417216d35530706da75275a/log/logging.go#L641-L652
153,044
sjmudd/stopwatch
named_stopwatch.go
Add
func (ns *NamedStopwatch) Add(name string) error { ns.Lock() defer ns.Unlock() return ns.add(name) }
go
func (ns *NamedStopwatch) Add(name string) error { ns.Lock() defer ns.Unlock() return ns.add(name) }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "Add", "(", "name", "string", ")", "error", "{", "ns", ".", "Lock", "(", ")", "\n", "defer", "ns", ".", "Unlock", "(", ")", "\n\n", "return", "ns", ".", "add", "(", "name", ")", "\n", "}" ]
// Add adds a single Stopwatch name with the given name.
[ "Add", "adds", "a", "single", "Stopwatch", "name", "with", "the", "given", "name", "." ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L50-L55
153,045
sjmudd/stopwatch
named_stopwatch.go
add
func (ns *NamedStopwatch) add(name string) error { if ns.stopwatches == nil { // create structure ns.stopwatches = make(map[string](*Stopwatch)) } else { // check for existing name if _, ok := ns.stopwatches[name]; ok { return fmt.Errorf("NamedStopwatch.add() Stopwatch name %q already exists", name) } } ns.stopwatches[name] = New(nil) return nil }
go
func (ns *NamedStopwatch) add(name string) error { if ns.stopwatches == nil { // create structure ns.stopwatches = make(map[string](*Stopwatch)) } else { // check for existing name if _, ok := ns.stopwatches[name]; ok { return fmt.Errorf("NamedStopwatch.add() Stopwatch name %q already exists", name) } } ns.stopwatches[name] = New(nil) return nil }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "add", "(", "name", "string", ")", "error", "{", "if", "ns", ".", "stopwatches", "==", "nil", "{", "// create structure", "ns", ".", "stopwatches", "=", "make", "(", "map", "[", "string", "]", "(", "*", ...
// Add adds a single Stopwatch name with the given name. // The caller is assumed to have locked the structure.
[ "Add", "adds", "a", "single", "Stopwatch", "name", "with", "the", "given", "name", ".", "The", "caller", "is", "assumed", "to", "have", "locked", "the", "structure", "." ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L59-L72
153,046
sjmudd/stopwatch
named_stopwatch.go
AddMany
func (ns *NamedStopwatch) AddMany(names []string) error { ns.Lock() defer ns.Unlock() for _, name := range names { if err := ns.add(name); err != nil { return err } } return nil }
go
func (ns *NamedStopwatch) AddMany(names []string) error { ns.Lock() defer ns.Unlock() for _, name := range names { if err := ns.add(name); err != nil { return err } } return nil }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "AddMany", "(", "names", "[", "]", "string", ")", "error", "{", "ns", ".", "Lock", "(", ")", "\n", "defer", "ns", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "name", ":=", "range", "names", "{"...
// AddMany adds several named stopwatches in one go
[ "AddMany", "adds", "several", "named", "stopwatches", "in", "one", "go" ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L75-L85
153,047
sjmudd/stopwatch
named_stopwatch.go
Exists
func (ns *NamedStopwatch) Exists(name string) bool { ns.RLock() defer ns.RUnlock() if ns == nil { return false } _, found := ns.stopwatches[name] return found }
go
func (ns *NamedStopwatch) Exists(name string) bool { ns.RLock() defer ns.RUnlock() if ns == nil { return false } _, found := ns.stopwatches[name] return found }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "Exists", "(", "name", "string", ")", "bool", "{", "ns", ".", "RLock", "(", ")", "\n", "defer", "ns", ".", "RUnlock", "(", ")", "\n\n", "if", "ns", "==", "nil", "{", "return", "false", "\n", "}", "\n...
// Exists returns true if the NamedStopwatch exists
[ "Exists", "returns", "true", "if", "the", "NamedStopwatch", "exists" ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L100-L111
153,048
sjmudd/stopwatch
named_stopwatch.go
Start
func (ns *NamedStopwatch) Start(name string) { if ns == nil { return // if we're not using stopwatches we just do nothing } ns.Lock() defer ns.Unlock() ns.start(name) }
go
func (ns *NamedStopwatch) Start(name string) { if ns == nil { return // if we're not using stopwatches we just do nothing } ns.Lock() defer ns.Unlock() ns.start(name) }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "Start", "(", "name", "string", ")", "{", "if", "ns", "==", "nil", "{", "return", "// if we're not using stopwatches we just do nothing", "\n", "}", "\n", "ns", ".", "Lock", "(", ")", "\n", "defer", "ns", ".",...
// Start starts a NamedStopwatch if it exists
[ "Start", "starts", "a", "NamedStopwatch", "if", "it", "exists" ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L114-L122
153,049
sjmudd/stopwatch
named_stopwatch.go
start
func (ns *NamedStopwatch) start(name string) { if ns == nil { return } if s, ok := ns.stopwatches[name]; ok { s.Start() } }
go
func (ns *NamedStopwatch) start(name string) { if ns == nil { return } if s, ok := ns.stopwatches[name]; ok { s.Start() } }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "start", "(", "name", "string", ")", "{", "if", "ns", "==", "nil", "{", "return", "\n", "}", "\n", "if", "s", ",", "ok", ":=", "ns", ".", "stopwatches", "[", "name", "]", ";", "ok", "{", "s", ".", ...
// start starts a NamedStopwatch if it exists. The structure is expected to be locked.
[ "start", "starts", "a", "NamedStopwatch", "if", "it", "exists", ".", "The", "structure", "is", "expected", "to", "be", "locked", "." ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L125-L132
153,050
sjmudd/stopwatch
named_stopwatch.go
StartMany
func (ns *NamedStopwatch) StartMany(names []string) { if ns == nil { return // if we're not using stopwatches we just do nothing } ns.Lock() defer ns.Unlock() for _, name := range names { ns.start(name) } }
go
func (ns *NamedStopwatch) StartMany(names []string) { if ns == nil { return // if we're not using stopwatches we just do nothing } ns.Lock() defer ns.Unlock() for _, name := range names { ns.start(name) } }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "StartMany", "(", "names", "[", "]", "string", ")", "{", "if", "ns", "==", "nil", "{", "return", "// if we're not using stopwatches we just do nothing", "\n", "}", "\n", "ns", ".", "Lock", "(", ")", "\n", "def...
// StartMany allows you to start several stopwatches in one go
[ "StartMany", "allows", "you", "to", "start", "several", "stopwatches", "in", "one", "go" ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L135-L145
153,051
sjmudd/stopwatch
named_stopwatch.go
Stop
func (ns *NamedStopwatch) Stop(name string) { if ns == nil { return // if we're not using stopwatches we just do nothing } ns.Lock() defer ns.Unlock() ns.stop(name) }
go
func (ns *NamedStopwatch) Stop(name string) { if ns == nil { return // if we're not using stopwatches we just do nothing } ns.Lock() defer ns.Unlock() ns.stop(name) }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "Stop", "(", "name", "string", ")", "{", "if", "ns", "==", "nil", "{", "return", "// if we're not using stopwatches we just do nothing", "\n", "}", "\n", "ns", ".", "Lock", "(", ")", "\n", "defer", "ns", ".", ...
// Stop stops a NamedStopwatch if it exists
[ "Stop", "stops", "a", "NamedStopwatch", "if", "it", "exists" ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L148-L156
153,052
sjmudd/stopwatch
named_stopwatch.go
stop
func (ns *NamedStopwatch) stop(name string) { if ns == nil { return } if s, ok := ns.stopwatches[name]; ok { if s.IsRunning() { s.Stop() } else { fmt.Printf("WARNING: NamedStopwatch.Stop(%q) IsRunning is false\n", name) } } }
go
func (ns *NamedStopwatch) stop(name string) { if ns == nil { return } if s, ok := ns.stopwatches[name]; ok { if s.IsRunning() { s.Stop() } else { fmt.Printf("WARNING: NamedStopwatch.Stop(%q) IsRunning is false\n", name) } } }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "stop", "(", "name", "string", ")", "{", "if", "ns", "==", "nil", "{", "return", "\n", "}", "\n", "if", "s", ",", "ok", ":=", "ns", ".", "stopwatches", "[", "name", "]", ";", "ok", "{", "if", "s", ...
// stop stops a NamedStopwatch if it exists and expects the structure to be locked.
[ "stop", "stops", "a", "NamedStopwatch", "if", "it", "exists", "and", "expects", "the", "structure", "to", "be", "locked", "." ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L159-L170
153,053
sjmudd/stopwatch
named_stopwatch.go
StopMany
func (ns *NamedStopwatch) StopMany(names []string) { if ns == nil { return // if we're not using stopwatches we just do nothing } ns.Lock() defer ns.Unlock() for _, name := range names { ns.stop(name) } }
go
func (ns *NamedStopwatch) StopMany(names []string) { if ns == nil { return // if we're not using stopwatches we just do nothing } ns.Lock() defer ns.Unlock() for _, name := range names { ns.stop(name) } }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "StopMany", "(", "names", "[", "]", "string", ")", "{", "if", "ns", "==", "nil", "{", "return", "// if we're not using stopwatches we just do nothing", "\n", "}", "\n", "ns", ".", "Lock", "(", ")", "\n", "defe...
// StopMany allows you to stop several stopwatches in one go
[ "StopMany", "allows", "you", "to", "stop", "several", "stopwatches", "in", "one", "go" ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L173-L183
153,054
sjmudd/stopwatch
named_stopwatch.go
Reset
func (ns *NamedStopwatch) Reset(name string) { if ns == nil { return // if we're not using stopwatches we just do nothing } ns.Lock() defer ns.Unlock() if ns == nil { return } if s, ok := ns.stopwatches[name]; ok { s.Reset() } }
go
func (ns *NamedStopwatch) Reset(name string) { if ns == nil { return // if we're not using stopwatches we just do nothing } ns.Lock() defer ns.Unlock() if ns == nil { return } if s, ok := ns.stopwatches[name]; ok { s.Reset() } }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "Reset", "(", "name", "string", ")", "{", "if", "ns", "==", "nil", "{", "return", "// if we're not using stopwatches we just do nothing", "\n", "}", "\n", "ns", ".", "Lock", "(", ")", "\n", "defer", "ns", ".",...
// Reset resets a NamedStopwatch if it exists
[ "Reset", "resets", "a", "NamedStopwatch", "if", "it", "exists" ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L186-L199
153,055
sjmudd/stopwatch
named_stopwatch.go
Keys
func (ns *NamedStopwatch) Keys() []string { if ns == nil { return nil } ns.RLock() defer ns.RUnlock() keys := []string{} for k := range ns.stopwatches { keys = append(keys, k) } return keys }
go
func (ns *NamedStopwatch) Keys() []string { if ns == nil { return nil } ns.RLock() defer ns.RUnlock() keys := []string{} for k := range ns.stopwatches { keys = append(keys, k) } return keys }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "Keys", "(", ")", "[", "]", "string", "{", "if", "ns", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "ns", ".", "RLock", "(", ")", "\n", "defer", "ns", ".", "RUnlock", "(", ")", "\n\n", "ke...
// Keys returns the known names of Stopwatches
[ "Keys", "returns", "the", "known", "names", "of", "Stopwatches" ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L202-L215
153,056
sjmudd/stopwatch
named_stopwatch.go
Elapsed
func (ns *NamedStopwatch) Elapsed(name string) time.Duration { if ns == nil { return time.Duration(0) } ns.RLock() defer ns.RUnlock() if s, ok := ns.stopwatches[name]; ok { return s.Elapsed() } return time.Duration(0) }
go
func (ns *NamedStopwatch) Elapsed(name string) time.Duration { if ns == nil { return time.Duration(0) } ns.RLock() defer ns.RUnlock() if s, ok := ns.stopwatches[name]; ok { return s.Elapsed() } return time.Duration(0) }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "Elapsed", "(", "name", "string", ")", "time", ".", "Duration", "{", "if", "ns", "==", "nil", "{", "return", "time", ".", "Duration", "(", "0", ")", "\n", "}", "\n", "ns", ".", "RLock", "(", ")", "\n...
// Elapsed returns the elapsed time.Duration of the named stopwatch if it exists or 0
[ "Elapsed", "returns", "the", "elapsed", "time", ".", "Duration", "of", "the", "named", "stopwatch", "if", "it", "exists", "or", "0" ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L218-L229
153,057
sjmudd/stopwatch
named_stopwatch.go
ElapsedMilliSeconds
func (ns *NamedStopwatch) ElapsedMilliSeconds(name string) float64 { if ns == nil { return float64(0) } ns.RLock() defer ns.RUnlock() if s, ok := ns.stopwatches[name]; ok { return s.ElapsedMilliSeconds() } return float64(0) }
go
func (ns *NamedStopwatch) ElapsedMilliSeconds(name string) float64 { if ns == nil { return float64(0) } ns.RLock() defer ns.RUnlock() if s, ok := ns.stopwatches[name]; ok { return s.ElapsedMilliSeconds() } return float64(0) }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "ElapsedMilliSeconds", "(", "name", "string", ")", "float64", "{", "if", "ns", "==", "nil", "{", "return", "float64", "(", "0", ")", "\n", "}", "\n", "ns", ".", "RLock", "(", ")", "\n", "defer", "ns", ...
// ElapsedMilliSeconds returns the elapsed time in milliseconds of // the named stopwatch if it exists or 0.
[ "ElapsedMilliSeconds", "returns", "the", "elapsed", "time", "in", "milliseconds", "of", "the", "named", "stopwatch", "if", "it", "exists", "or", "0", "." ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L248-L259
153,058
sjmudd/stopwatch
named_stopwatch.go
AddElapsedSince
func (ns *NamedStopwatch) AddElapsedSince(name string, t time.Time) { if ns == nil { return } ns.Lock() defer ns.Unlock() if s, ok := ns.stopwatches[name]; ok { s.AddElapsedSince(t) } }
go
func (ns *NamedStopwatch) AddElapsedSince(name string, t time.Time) { if ns == nil { return } ns.Lock() defer ns.Unlock() if s, ok := ns.stopwatches[name]; ok { s.AddElapsedSince(t) } }
[ "func", "(", "ns", "*", "NamedStopwatch", ")", "AddElapsedSince", "(", "name", "string", ",", "t", "time", ".", "Time", ")", "{", "if", "ns", "==", "nil", "{", "return", "\n", "}", "\n", "ns", ".", "Lock", "(", ")", "\n", "defer", "ns", ".", "Unl...
// AddElapsedSince adds the duration since the reference time to the given named stopwatch.
[ "AddElapsedSince", "adds", "the", "duration", "since", "the", "reference", "time", "to", "the", "given", "named", "stopwatch", "." ]
f380bf8a9be1db68878b3ac5589c0a03d041f129
https://github.com/sjmudd/stopwatch/blob/f380bf8a9be1db68878b3ac5589c0a03d041f129/named_stopwatch.go#L262-L272
153,059
augustoroman/hexdump
hexdump.go
Dump
func (c Config) Dump(buf []byte) string { N := c.Width var out bytes.Buffer rowIndex := 0 maxRowWidth := 0 for rowIndex*N < len(buf) { a, b := rowIndex*N, (rowIndex+1)*N if b > len(buf) { b = len(buf) } row := buf[a:b] hex, ascii := printable(row) if len(row) < maxRowWidth { padding := maxRowWidth*2 + maxRowWidth/4 - len(row)*2 - len(row)/4 hex += strings.Repeat(" ", padding) } maxRowWidth = len(row) fmt.Fprintf(&out, "%5d: %s | %s\n", a, hex, ascii) rowIndex++ } return out.String() }
go
func (c Config) Dump(buf []byte) string { N := c.Width var out bytes.Buffer rowIndex := 0 maxRowWidth := 0 for rowIndex*N < len(buf) { a, b := rowIndex*N, (rowIndex+1)*N if b > len(buf) { b = len(buf) } row := buf[a:b] hex, ascii := printable(row) if len(row) < maxRowWidth { padding := maxRowWidth*2 + maxRowWidth/4 - len(row)*2 - len(row)/4 hex += strings.Repeat(" ", padding) } maxRowWidth = len(row) fmt.Fprintf(&out, "%5d: %s | %s\n", a, hex, ascii) rowIndex++ } return out.String() }
[ "func", "(", "c", "Config", ")", "Dump", "(", "buf", "[", "]", "byte", ")", "string", "{", "N", ":=", "c", ".", "Width", "\n", "var", "out", "bytes", ".", "Buffer", "\n", "rowIndex", ":=", "0", "\n", "maxRowWidth", ":=", "0", "\n", "for", "rowInd...
// Dump converts the byte slice to a human-readable hex dump.
[ "Dump", "converts", "the", "byte", "slice", "to", "a", "human", "-", "readable", "hex", "dump", "." ]
cbe2021c406e47404ca4c52f01ab1bee206649be
https://github.com/augustoroman/hexdump/blob/cbe2021c406e47404ca4c52f01ab1bee206649be/hexdump.go#L22-L45
153,060
cactus/gostrftime
gostrftime.go
Strftime
func Strftime(format string, t time.Time) string { return Format(format, t) }
go
func Strftime(format string, t time.Time) string { return Format(format, t) }
[ "func", "Strftime", "(", "format", "string", ",", "t", "time", ".", "Time", ")", "string", "{", "return", "Format", "(", "format", ",", "t", ")", "\n", "}" ]
// Strftime is an alias for Format
[ "Strftime", "is", "an", "alias", "for", "Format" ]
4a229c4a330d0af7823278df35e21cdf33fcf208
https://github.com/cactus/gostrftime/blob/4a229c4a330d0af7823278df35e21cdf33fcf208/gostrftime.go#L216-L218
153,061
favclip/golidator
v1/errors.go
UnsupportedTypeError
func UnsupportedTypeError(in string, f reflect.StructField) error { return fmt.Errorf("%s: [%s] unsupported type %s", f.Name, in, f.Type.Name()) }
go
func UnsupportedTypeError(in string, f reflect.StructField) error { return fmt.Errorf("%s: [%s] unsupported type %s", f.Name, in, f.Type.Name()) }
[ "func", "UnsupportedTypeError", "(", "in", "string", ",", "f", "reflect", ".", "StructField", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", ",", "in", ",", "f", ".", "Type", ".", "Name", "(", ")", ")", ...
// UnsupportedTypeError returns an error from unsupported type.
[ "UnsupportedTypeError", "returns", "an", "error", "from", "unsupported", "type", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/errors.go#L16-L18
153,062
favclip/golidator
v1/errors.go
EmptyParamError
func EmptyParamError(in string, f reflect.StructField) error { return fmt.Errorf("%s: %s value is required", f.Name, in) }
go
func EmptyParamError(in string, f reflect.StructField) error { return fmt.Errorf("%s: %s value is required", f.Name, in) }
[ "func", "EmptyParamError", "(", "in", "string", ",", "f", "reflect", ".", "StructField", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", ",", "in", ")", "\n", "}" ]
// EmptyParamError returns an error from empty param.
[ "EmptyParamError", "returns", "an", "error", "from", "empty", "param", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/errors.go#L21-L23
153,063
favclip/golidator
v1/errors.go
ParamParseError
func ParamParseError(in string, f reflect.StructField, expected string) error { return fmt.Errorf("%s: %s value must be %s", f.Name, in, expected) }
go
func ParamParseError(in string, f reflect.StructField, expected string) error { return fmt.Errorf("%s: %s value must be %s", f.Name, in, expected) }
[ "func", "ParamParseError", "(", "in", "string", ",", "f", "reflect", ".", "StructField", ",", "expected", "string", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", ",", "in", ",", "expected", ")", "\n", "}" ...
// ParamParseError returns an error from parsing param.
[ "ParamParseError", "returns", "an", "error", "from", "parsing", "param", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/errors.go#L26-L28
153,064
favclip/golidator
v1/errors.go
ReqError
func ReqError(f reflect.StructField, actual interface{}) error { return fmt.Errorf("%s: required, actual `%v`", f.Name, actual) }
go
func ReqError(f reflect.StructField, actual interface{}) error { return fmt.Errorf("%s: required, actual `%v`", f.Name, actual) }
[ "func", "ReqError", "(", "f", "reflect", ".", "StructField", ",", "actual", "interface", "{", "}", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", ",", "actual", ")", "\n", "}" ]
// ReqError returns an error from "req" validator.
[ "ReqError", "returns", "an", "error", "from", "req", "validator", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/errors.go#L31-L33
153,065
favclip/golidator
v1/errors.go
MinError
func MinError(f reflect.StructField, actual, min interface{}) error { return fmt.Errorf("%s: %v less than %v", f.Name, actual, min) }
go
func MinError(f reflect.StructField, actual, min interface{}) error { return fmt.Errorf("%s: %v less than %v", f.Name, actual, min) }
[ "func", "MinError", "(", "f", "reflect", ".", "StructField", ",", "actual", ",", "min", "interface", "{", "}", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", ",", "actual", ",", "min", ")", "\n", "}" ]
// MinError returns an error from "min" validator.
[ "MinError", "returns", "an", "error", "from", "min", "validator", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/errors.go#L41-L43
153,066
favclip/golidator
v1/errors.go
MaxError
func MaxError(f reflect.StructField, actual, max interface{}) error { return fmt.Errorf("%s: %v greater than %v", f.Name, actual, max) }
go
func MaxError(f reflect.StructField, actual, max interface{}) error { return fmt.Errorf("%s: %v greater than %v", f.Name, actual, max) }
[ "func", "MaxError", "(", "f", "reflect", ".", "StructField", ",", "actual", ",", "max", "interface", "{", "}", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", ",", "actual", ",", "max", ")", "\n", "}" ]
// MaxError returns an error from "max" validator.
[ "MaxError", "returns", "an", "error", "from", "max", "validator", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/errors.go#L46-L48
153,067
favclip/golidator
v1/errors.go
EmailError
func EmailError(f reflect.StructField, actual string) error { return fmt.Errorf("%s: unsupported email format %s", f.Name, actual) }
go
func EmailError(f reflect.StructField, actual string) error { return fmt.Errorf("%s: unsupported email format %s", f.Name, actual) }
[ "func", "EmailError", "(", "f", "reflect", ".", "StructField", ",", "actual", "string", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", ",", "actual", ")", "\n", "}" ]
// EmailError returns an error from "email" validator.
[ "EmailError", "returns", "an", "error", "from", "email", "validator", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/errors.go#L61-L63
153,068
favclip/golidator
v1/errors.go
EnumError
func EnumError(f reflect.StructField, actual interface{}, enum []string) error { return fmt.Errorf("%s: `%v` is not member of [%v]", f.Name, actual, strings.Join(enum, ", ")) }
go
func EnumError(f reflect.StructField, actual interface{}, enum []string) error { return fmt.Errorf("%s: `%v` is not member of [%v]", f.Name, actual, strings.Join(enum, ", ")) }
[ "func", "EnumError", "(", "f", "reflect", ".", "StructField", ",", "actual", "interface", "{", "}", ",", "enum", "[", "]", "string", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", ",", "actual", ",", "str...
// EnumError returns an error from "enum" validator.
[ "EnumError", "returns", "an", "error", "from", "enum", "validator", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/v1/errors.go#L66-L68
153,069
favclip/golidator
builtins.go
ReqValidator
func ReqValidator(param string, v reflect.Value) (ValidationResult, error) { switch v.Kind() { case reflect.String: if v.String() == "" { return ValidationNG, nil } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if v.Int() == 0 { return ValidationNG, nil } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: if v.Uint() == 0 { return ValidationNG, nil } case reflect.Float32, reflect.Float64: if v.Float() == 0 { return ValidationNG, nil } case reflect.Bool: // :) case reflect.Array, reflect.Slice: if v.Len() == 0 { return ValidationNG, nil } case reflect.Struct: // :) case reflect.Ptr, reflect.Interface: if v.IsNil() { return ValidationNG, nil } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil }
go
func ReqValidator(param string, v reflect.Value) (ValidationResult, error) { switch v.Kind() { case reflect.String: if v.String() == "" { return ValidationNG, nil } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if v.Int() == 0 { return ValidationNG, nil } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: if v.Uint() == 0 { return ValidationNG, nil } case reflect.Float32, reflect.Float64: if v.Float() == 0 { return ValidationNG, nil } case reflect.Bool: // :) case reflect.Array, reflect.Slice: if v.Len() == 0 { return ValidationNG, nil } case reflect.Struct: // :) case reflect.Ptr, reflect.Interface: if v.IsNil() { return ValidationNG, nil } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil }
[ "func", "ReqValidator", "(", "param", "string", ",", "v", "reflect", ".", "Value", ")", "(", "ValidationResult", ",", "error", ")", "{", "switch", "v", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "String", ":", "if", "v", ".", "String", "(", ...
// ReqValidator check value that must not be empty.
[ "ReqValidator", "check", "value", "that", "must", "not", "be", "empty", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/builtins.go#L14-L50
153,070
favclip/golidator
builtins.go
DefaultValidator
func DefaultValidator(param string, v reflect.Value) (ValidationResult, error) { switch v.Kind() { case reflect.String: if !v.CanAddr() { return ValidationNG, nil } if v.String() == "" { v.SetString(param) } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if !v.CanAddr() { return ValidationNG, nil } pInt, err := strconv.ParseInt(param, 0, 64) if err != nil { return ValidationNG, nil } if v.Int() == 0 { v.SetInt(pInt) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: if !v.CanAddr() { return ValidationNG, nil } pUint, err := strconv.ParseUint(param, 0, 64) if err != nil { return ValidationNG, nil } if v.Uint() == 0 { v.SetUint(pUint) } case reflect.Float32, reflect.Float64: if !v.CanAddr() { return ValidationNG, nil } pFloat, err := strconv.ParseFloat(param, 64) if err != nil { return ValidationNG, nil } if v.Float() == 0 { v.SetFloat(pFloat) } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil }
go
func DefaultValidator(param string, v reflect.Value) (ValidationResult, error) { switch v.Kind() { case reflect.String: if !v.CanAddr() { return ValidationNG, nil } if v.String() == "" { v.SetString(param) } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if !v.CanAddr() { return ValidationNG, nil } pInt, err := strconv.ParseInt(param, 0, 64) if err != nil { return ValidationNG, nil } if v.Int() == 0 { v.SetInt(pInt) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: if !v.CanAddr() { return ValidationNG, nil } pUint, err := strconv.ParseUint(param, 0, 64) if err != nil { return ValidationNG, nil } if v.Uint() == 0 { v.SetUint(pUint) } case reflect.Float32, reflect.Float64: if !v.CanAddr() { return ValidationNG, nil } pFloat, err := strconv.ParseFloat(param, 64) if err != nil { return ValidationNG, nil } if v.Float() == 0 { v.SetFloat(pFloat) } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil }
[ "func", "DefaultValidator", "(", "param", "string", ",", "v", "reflect", ".", "Value", ")", "(", "ValidationResult", ",", "error", ")", "{", "switch", "v", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "String", ":", "if", "!", "v", ".", "CanAd...
// DefaultValidator set value when value is empty.
[ "DefaultValidator", "set", "value", "when", "value", "is", "empty", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/builtins.go#L53-L100
153,071
favclip/golidator
builtins.go
MinValidator
func MinValidator(param string, v reflect.Value) (ValidationResult, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: pInt, err := strconv.ParseInt(param, 0, 64) if err != nil { return 0, ErrInvalidConfigValue } if v.Int() < pInt { return ValidationNG, nil } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: pUint, err := strconv.ParseUint(param, 0, 64) if err != nil { return 0, ErrInvalidConfigValue } if v.Uint() < pUint { return ValidationNG, nil } case reflect.Float32, reflect.Float64: pFloat, err := strconv.ParseFloat(param, 64) if err != nil { return 0, ErrInvalidConfigValue } if v.Float() < pFloat { return ValidationNG, nil } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil }
go
func MinValidator(param string, v reflect.Value) (ValidationResult, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: pInt, err := strconv.ParseInt(param, 0, 64) if err != nil { return 0, ErrInvalidConfigValue } if v.Int() < pInt { return ValidationNG, nil } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: pUint, err := strconv.ParseUint(param, 0, 64) if err != nil { return 0, ErrInvalidConfigValue } if v.Uint() < pUint { return ValidationNG, nil } case reflect.Float32, reflect.Float64: pFloat, err := strconv.ParseFloat(param, 64) if err != nil { return 0, ErrInvalidConfigValue } if v.Float() < pFloat { return ValidationNG, nil } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil }
[ "func", "MinValidator", "(", "param", "string", ",", "v", "reflect", ".", "Value", ")", "(", "ValidationResult", ",", "error", ")", "{", "switch", "v", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int8", ",", "refl...
// MinValidator check value that must greater or equal than config value.
[ "MinValidator", "check", "value", "that", "must", "greater", "or", "equal", "than", "config", "value", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/builtins.go#L103-L134
153,072
favclip/golidator
builtins.go
MinLenValidator
func MinLenValidator(param string, v reflect.Value) (ValidationResult, error) { switch v.Kind() { case reflect.String: if v.String() == "" { return ValidationOK, nil // emptyの場合は無視 これはreqの役目だ } p, err := strconv.ParseInt(param, 0, 64) if err != nil { return 0, ErrInvalidConfigValue } if int64(utf8.RuneCountInString(v.String())) < p { return ValidationNG, nil } case reflect.Array, reflect.Map, reflect.Slice: if v.Len() == 0 { return ValidationOK, nil } p, err := strconv.ParseInt(param, 0, 64) if err != nil { return 0, ErrInvalidConfigValue } if int64(v.Len()) < p { return ValidationNG, nil } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil }
go
func MinLenValidator(param string, v reflect.Value) (ValidationResult, error) { switch v.Kind() { case reflect.String: if v.String() == "" { return ValidationOK, nil // emptyの場合は無視 これはreqの役目だ } p, err := strconv.ParseInt(param, 0, 64) if err != nil { return 0, ErrInvalidConfigValue } if int64(utf8.RuneCountInString(v.String())) < p { return ValidationNG, nil } case reflect.Array, reflect.Map, reflect.Slice: if v.Len() == 0 { return ValidationOK, nil } p, err := strconv.ParseInt(param, 0, 64) if err != nil { return 0, ErrInvalidConfigValue } if int64(v.Len()) < p { return ValidationNG, nil } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil }
[ "func", "MinLenValidator", "(", "param", "string", ",", "v", "reflect", ".", "Value", ")", "(", "ValidationResult", ",", "error", ")", "{", "switch", "v", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "String", ":", "if", "v", ".", "String", "(...
// MinLenValidator check value length that must greater or equal than config value.
[ "MinLenValidator", "check", "value", "length", "that", "must", "greater", "or", "equal", "than", "config", "value", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/builtins.go#L171-L200
153,073
favclip/golidator
builtins.go
EmailValidator
func EmailValidator(param string, v reflect.Value) (ValidationResult, error) { switch v.Kind() { case reflect.String: if v.String() == "" { return ValidationOK, nil } addr := v.String() // do validation by RFC5322 // http://www.hde.co.jp/rfc/rfc5322.php?page=17 // screening if _, err := mail.ParseAddress(addr); err != nil { return ValidationNG, nil } addrSpec := strings.Split(addr, "@") if len(addrSpec) != 2 { return ValidationNG, nil } // check local part localPart := addrSpec[0] // divided by quoted-string style or dom-atom style if match, err := regexp.MatchString(`"[^\t\n\f\r\\]*"`, localPart); err == nil && match { // "\"以外の表示可能文字を認める // OK } else if match, err := regexp.MatchString(`^([^.\s]+\.)*([^.\s]+)$`, localPart); err != nil || !match { // (hoge.)*hoge return ValidationNG, nil } else { // atext check for local part for _, c := range localPart { if string(c) == "." { // "." is already checked by regexp continue } if !isAtext(c) { return ValidationNG, nil } } } // check domain part domain := addrSpec[1] if match, err := regexp.MatchString(`^([^.\s]+\.)*[^.\s]+$`, domain); err != nil || !match { // (hoge.)*hoge return ValidationNG, nil } // atext check for domain part for _, c := range domain { if string(c) == "." { // "." is already checked by regexp continue } if !isAtext(c) { return ValidationNG, nil } } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil }
go
func EmailValidator(param string, v reflect.Value) (ValidationResult, error) { switch v.Kind() { case reflect.String: if v.String() == "" { return ValidationOK, nil } addr := v.String() // do validation by RFC5322 // http://www.hde.co.jp/rfc/rfc5322.php?page=17 // screening if _, err := mail.ParseAddress(addr); err != nil { return ValidationNG, nil } addrSpec := strings.Split(addr, "@") if len(addrSpec) != 2 { return ValidationNG, nil } // check local part localPart := addrSpec[0] // divided by quoted-string style or dom-atom style if match, err := regexp.MatchString(`"[^\t\n\f\r\\]*"`, localPart); err == nil && match { // "\"以外の表示可能文字を認める // OK } else if match, err := regexp.MatchString(`^([^.\s]+\.)*([^.\s]+)$`, localPart); err != nil || !match { // (hoge.)*hoge return ValidationNG, nil } else { // atext check for local part for _, c := range localPart { if string(c) == "." { // "." is already checked by regexp continue } if !isAtext(c) { return ValidationNG, nil } } } // check domain part domain := addrSpec[1] if match, err := regexp.MatchString(`^([^.\s]+\.)*[^.\s]+$`, domain); err != nil || !match { // (hoge.)*hoge return ValidationNG, nil } // atext check for domain part for _, c := range domain { if string(c) == "." { // "." is already checked by regexp continue } if !isAtext(c) { return ValidationNG, nil } } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil }
[ "func", "EmailValidator", "(", "param", "string", ",", "v", "reflect", ".", "Value", ")", "(", "ValidationResult", ",", "error", ")", "{", "switch", "v", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "String", ":", "if", "v", ".", "String", "("...
// EmailValidator check value that must be email address format.
[ "EmailValidator", "check", "value", "that", "must", "be", "email", "address", "format", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/builtins.go#L248-L306
153,074
favclip/golidator
builtins.go
EnumValidator
func EnumValidator(param string, v reflect.Value) (ValidationResult, error) { if param == "" { return 0, ErrInvalidConfigValue } params := strings.Split(param, "|") var enum func(v reflect.Value) (ValidationResult, error) enum = func(v reflect.Value) (ValidationResult, error) { if v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.String: val := v.String() if val == "" { // need empty checking? use req :) return ValidationOK, nil } for _, value := range params { if val == value { return ValidationOK, nil } } return ValidationNG, nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: val := v.Int() for _, value := range params { value2, err := strconv.ParseInt(value, 10, 0) if err != nil { return 0, ErrInvalidConfigValue } if val == value2 { return ValidationOK, nil } } return ValidationNG, nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: val := v.Uint() for _, value := range params { value2, err := strconv.ParseUint(value, 10, 0) if err != nil { return 0, ErrInvalidConfigValue } if val == value2 { return ValidationOK, nil } } return ValidationNG, nil case reflect.Array, reflect.Slice: for i := 0; i < v.Len(); i++ { e := v.Index(i) return enum(e) } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil } return enum(v) }
go
func EnumValidator(param string, v reflect.Value) (ValidationResult, error) { if param == "" { return 0, ErrInvalidConfigValue } params := strings.Split(param, "|") var enum func(v reflect.Value) (ValidationResult, error) enum = func(v reflect.Value) (ValidationResult, error) { if v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.String: val := v.String() if val == "" { // need empty checking? use req :) return ValidationOK, nil } for _, value := range params { if val == value { return ValidationOK, nil } } return ValidationNG, nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: val := v.Int() for _, value := range params { value2, err := strconv.ParseInt(value, 10, 0) if err != nil { return 0, ErrInvalidConfigValue } if val == value2 { return ValidationOK, nil } } return ValidationNG, nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: val := v.Uint() for _, value := range params { value2, err := strconv.ParseUint(value, 10, 0) if err != nil { return 0, ErrInvalidConfigValue } if val == value2 { return ValidationOK, nil } } return ValidationNG, nil case reflect.Array, reflect.Slice: for i := 0; i < v.Len(); i++ { e := v.Index(i) return enum(e) } default: return 0, ErrValidateUnsupportedType } return ValidationOK, nil } return enum(v) }
[ "func", "EnumValidator", "(", "param", "string", ",", "v", "reflect", ".", "Value", ")", "(", "ValidationResult", ",", "error", ")", "{", "if", "param", "==", "\"", "\"", "{", "return", "0", ",", "ErrInvalidConfigValue", "\n", "}", "\n\n", "params", ":="...
// EnumValidator check value that must contains in config values.
[ "EnumValidator", "check", "value", "that", "must", "contains", "in", "config", "values", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/builtins.go#L309-L371
153,075
favclip/golidator
builtins.go
RegExpValidator
func RegExpValidator(param string, v reflect.Value) (ValidationResult, error) { if param == "" { return ValidationNG, ErrInvalidConfigValue } re, err := regexp.Compile(param) if err != nil { return ValidationNG, ErrInvalidConfigValue } switch v.Kind() { case reflect.String: if v.String() == "" { return ValidationOK, nil // empty is valid. if you want to check it, use req validator. } else if !re.MatchString(v.String()) { return ValidationNG, nil } default: return ValidationNG, ErrValidateUnsupportedType } return ValidationOK, nil }
go
func RegExpValidator(param string, v reflect.Value) (ValidationResult, error) { if param == "" { return ValidationNG, ErrInvalidConfigValue } re, err := regexp.Compile(param) if err != nil { return ValidationNG, ErrInvalidConfigValue } switch v.Kind() { case reflect.String: if v.String() == "" { return ValidationOK, nil // empty is valid. if you want to check it, use req validator. } else if !re.MatchString(v.String()) { return ValidationNG, nil } default: return ValidationNG, ErrValidateUnsupportedType } return ValidationOK, nil }
[ "func", "RegExpValidator", "(", "param", "string", ",", "v", "reflect", ".", "Value", ")", "(", "ValidationResult", ",", "error", ")", "{", "if", "param", "==", "\"", "\"", "{", "return", "ValidationNG", ",", "ErrInvalidConfigValue", "\n", "}", "\n\n", "re...
// RegExpValidator check value that must valid about config regexp pattern.
[ "RegExpValidator", "check", "value", "that", "must", "valid", "about", "config", "regexp", "pattern", "." ]
a6baf8304ab7098c461aeb7e2bb722315679e978
https://github.com/favclip/golidator/blob/a6baf8304ab7098c461aeb7e2bb722315679e978/builtins.go#L374-L396
153,076
deis/controller-sdk-go
http.go
createHTTPClient
func createHTTPClient(sslVerify bool) *http.Client { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: !sslVerify}, DisableKeepAlives: true, Proxy: http.ProxyFromEnvironment, } return &http.Client{Transport: tr} }
go
func createHTTPClient(sslVerify bool) *http.Client { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: !sslVerify}, DisableKeepAlives: true, Proxy: http.ProxyFromEnvironment, } return &http.Client{Transport: tr} }
[ "func", "createHTTPClient", "(", "sslVerify", "bool", ")", "*", "http", ".", "Client", "{", "tr", ":=", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "!", "sslVerify", "}", ",", "Di...
// createHTTPClient creates a HTTP Client with proper SSL options.
[ "createHTTPClient", "creates", "a", "HTTP", "Client", "with", "proper", "SSL", "options", "." ]
c9ffa05111835e74d71a6659f1339b849a9b0a7b
https://github.com/deis/controller-sdk-go/blob/c9ffa05111835e74d71a6659f1339b849a9b0a7b/http.go#L15-L22
153,077
deis/controller-sdk-go
http.go
Healthcheck
func (c *Client) Healthcheck() error { // Make a request to /healthz and expect an ok HTTP response controllerURL := c.ControllerURL.String() // Don't double the last slash in the URL path if !strings.HasSuffix(controllerURL, "/") { controllerURL = controllerURL + "/" } req, err := http.NewRequest("GET", controllerURL+"healthz", bytes.NewBuffer(nil)) addUserAgent(&req.Header, c.UserAgent) if err != nil { return err } res, err := c.HTTPClient.Do(req) if err != nil { return err } if err = checkForErrors(res); err != nil { return err } res.Body.Close() // Update controller api version apiVersion := res.Header.Get("DEIS_API_VERSION") c.ControllerAPIVersion = apiVersion setControllerVersion(c, res.Header) return checkAPICompatibility(apiVersion, APIVersion) }
go
func (c *Client) Healthcheck() error { // Make a request to /healthz and expect an ok HTTP response controllerURL := c.ControllerURL.String() // Don't double the last slash in the URL path if !strings.HasSuffix(controllerURL, "/") { controllerURL = controllerURL + "/" } req, err := http.NewRequest("GET", controllerURL+"healthz", bytes.NewBuffer(nil)) addUserAgent(&req.Header, c.UserAgent) if err != nil { return err } res, err := c.HTTPClient.Do(req) if err != nil { return err } if err = checkForErrors(res); err != nil { return err } res.Body.Close() // Update controller api version apiVersion := res.Header.Get("DEIS_API_VERSION") c.ControllerAPIVersion = apiVersion setControllerVersion(c, res.Header) return checkAPICompatibility(apiVersion, APIVersion) }
[ "func", "(", "c", "*", "Client", ")", "Healthcheck", "(", ")", "error", "{", "// Make a request to /healthz and expect an ok HTTP response", "controllerURL", ":=", "c", ".", "ControllerURL", ".", "String", "(", ")", "\n", "// Don't double the last slash in the URL path", ...
// Healthcheck can be called to see if the controller is healthy
[ "Healthcheck", "can", "be", "called", "to", "see", "if", "the", "controller", "is", "healthy" ]
c9ffa05111835e74d71a6659f1339b849a9b0a7b
https://github.com/deis/controller-sdk-go/blob/c9ffa05111835e74d71a6659f1339b849a9b0a7b/http.go#L140-L171
153,078
deis/controller-sdk-go
whitelist/whitelist.go
List
func List(c *deis.Client, appID string) (api.Whitelist, error) { u := fmt.Sprintf("/v2/apps/%s/whitelist/", appID) res, reqErr := c.Request("GET", u, nil) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return api.Whitelist{}, reqErr } defer res.Body.Close() whitelist := api.Whitelist{} if err := json.NewDecoder(res.Body).Decode(&whitelist); err != nil { return api.Whitelist{}, err } return whitelist, reqErr }
go
func List(c *deis.Client, appID string) (api.Whitelist, error) { u := fmt.Sprintf("/v2/apps/%s/whitelist/", appID) res, reqErr := c.Request("GET", u, nil) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return api.Whitelist{}, reqErr } defer res.Body.Close() whitelist := api.Whitelist{} if err := json.NewDecoder(res.Body).Decode(&whitelist); err != nil { return api.Whitelist{}, err } return whitelist, reqErr }
[ "func", "List", "(", "c", "*", "deis", ".", "Client", ",", "appID", "string", ")", "(", "api", ".", "Whitelist", ",", "error", ")", "{", "u", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "appID", ")", "\n", "res", ",", "reqErr", ":=", "c"...
// List IP's whitelisted for an app.
[ "List", "IP", "s", "whitelisted", "for", "an", "app", "." ]
c9ffa05111835e74d71a6659f1339b849a9b0a7b
https://github.com/deis/controller-sdk-go/blob/c9ffa05111835e74d71a6659f1339b849a9b0a7b/whitelist/whitelist.go#L13-L27
153,079
deis/controller-sdk-go
whitelist/whitelist.go
Add
func Add(c *deis.Client, appID string, addresses []string) (api.Whitelist, error) { u := fmt.Sprintf("/v2/apps/%s/whitelist/", appID) req := api.Whitelist{Addresses: addresses} body, err := json.Marshal(req) if err != nil { return api.Whitelist{}, err } res, reqErr := c.Request("POST", u, body) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return api.Whitelist{}, reqErr } defer res.Body.Close() d := api.Whitelist{} if err = json.NewDecoder(res.Body).Decode(&d); err != nil { return api.Whitelist{}, err } return d, reqErr }
go
func Add(c *deis.Client, appID string, addresses []string) (api.Whitelist, error) { u := fmt.Sprintf("/v2/apps/%s/whitelist/", appID) req := api.Whitelist{Addresses: addresses} body, err := json.Marshal(req) if err != nil { return api.Whitelist{}, err } res, reqErr := c.Request("POST", u, body) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return api.Whitelist{}, reqErr } defer res.Body.Close() d := api.Whitelist{} if err = json.NewDecoder(res.Body).Decode(&d); err != nil { return api.Whitelist{}, err } return d, reqErr }
[ "func", "Add", "(", "c", "*", "deis", ".", "Client", ",", "appID", "string", ",", "addresses", "[", "]", "string", ")", "(", "api", ".", "Whitelist", ",", "error", ")", "{", "u", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "appID", ")", ...
// Add adds addresses to an app's whitelist.
[ "Add", "adds", "addresses", "to", "an", "app", "s", "whitelist", "." ]
c9ffa05111835e74d71a6659f1339b849a9b0a7b
https://github.com/deis/controller-sdk-go/blob/c9ffa05111835e74d71a6659f1339b849a9b0a7b/whitelist/whitelist.go#L30-L50
153,080
deis/controller-sdk-go
whitelist/whitelist.go
Delete
func Delete(c *deis.Client, appID string, addresses []string) error { u := fmt.Sprintf("/v2/apps/%s/whitelist/", appID) req := api.Whitelist{Addresses: addresses} body, err := json.Marshal(req) if err != nil { return err } _, reqErr := c.Request("DELETE", u, body) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return reqErr } return nil }
go
func Delete(c *deis.Client, appID string, addresses []string) error { u := fmt.Sprintf("/v2/apps/%s/whitelist/", appID) req := api.Whitelist{Addresses: addresses} body, err := json.Marshal(req) if err != nil { return err } _, reqErr := c.Request("DELETE", u, body) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return reqErr } return nil }
[ "func", "Delete", "(", "c", "*", "deis", ".", "Client", ",", "appID", "string", ",", "addresses", "[", "]", "string", ")", "error", "{", "u", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "appID", ")", "\n\n", "req", ":=", "api", ".", "White...
// Delete removes addresses from an app's whitelist.
[ "Delete", "removes", "addresses", "from", "an", "app", "s", "whitelist", "." ]
c9ffa05111835e74d71a6659f1339b849a9b0a7b
https://github.com/deis/controller-sdk-go/blob/c9ffa05111835e74d71a6659f1339b849a9b0a7b/whitelist/whitelist.go#L53-L67
153,081
deis/controller-sdk-go
releases/releases.go
Get
func Get(c *deis.Client, appID string, version int) (api.Release, error) { u := fmt.Sprintf("/v2/apps/%s/releases/v%d/", appID, version) res, reqErr := c.Request("GET", u, nil) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return api.Release{}, reqErr } defer res.Body.Close() release := api.Release{} if err := json.NewDecoder(res.Body).Decode(&release); err != nil { return api.Release{}, err } return release, reqErr }
go
func Get(c *deis.Client, appID string, version int) (api.Release, error) { u := fmt.Sprintf("/v2/apps/%s/releases/v%d/", appID, version) res, reqErr := c.Request("GET", u, nil) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return api.Release{}, reqErr } defer res.Body.Close() release := api.Release{} if err := json.NewDecoder(res.Body).Decode(&release); err != nil { return api.Release{}, err } return release, reqErr }
[ "func", "Get", "(", "c", "*", "deis", ".", "Client", ",", "appID", "string", ",", "version", "int", ")", "(", "api", ".", "Release", ",", "error", ")", "{", "u", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "appID", ",", "version", ")", "...
// Get retrieves a release of an app.
[ "Get", "retrieves", "a", "release", "of", "an", "app", "." ]
c9ffa05111835e74d71a6659f1339b849a9b0a7b
https://github.com/deis/controller-sdk-go/blob/c9ffa05111835e74d71a6659f1339b849a9b0a7b/releases/releases.go#L31-L46
153,082
deis/controller-sdk-go
releases/releases.go
Rollback
func Rollback(c *deis.Client, appID string, version int) (int, error) { u := fmt.Sprintf("/v2/apps/%s/releases/rollback/", appID) req := api.ReleaseRollback{Version: version} var err error var reqBody []byte if version != -1 { reqBody, err = json.Marshal(req) if err != nil { return -1, err } } res, reqErr := c.Request("POST", u, reqBody) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return -1, reqErr } defer res.Body.Close() response := api.ReleaseRollback{} if err = json.NewDecoder(res.Body).Decode(&response); err != nil { return -1, err } return response.Version, reqErr }
go
func Rollback(c *deis.Client, appID string, version int) (int, error) { u := fmt.Sprintf("/v2/apps/%s/releases/rollback/", appID) req := api.ReleaseRollback{Version: version} var err error var reqBody []byte if version != -1 { reqBody, err = json.Marshal(req) if err != nil { return -1, err } } res, reqErr := c.Request("POST", u, reqBody) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return -1, reqErr } defer res.Body.Close() response := api.ReleaseRollback{} if err = json.NewDecoder(res.Body).Decode(&response); err != nil { return -1, err } return response.Version, reqErr }
[ "func", "Rollback", "(", "c", "*", "deis", ".", "Client", ",", "appID", "string", ",", "version", "int", ")", "(", "int", ",", "error", ")", "{", "u", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "appID", ")", "\n\n", "req", ":=", "api", ...
// Rollback rolls back an app to a previous release. If version is -1, this rolls back to // the previous release. Otherwise, roll back to the specified version.
[ "Rollback", "rolls", "back", "an", "app", "to", "a", "previous", "release", ".", "If", "version", "is", "-", "1", "this", "rolls", "back", "to", "the", "previous", "release", ".", "Otherwise", "roll", "back", "to", "the", "specified", "version", "." ]
c9ffa05111835e74d71a6659f1339b849a9b0a7b
https://github.com/deis/controller-sdk-go/blob/c9ffa05111835e74d71a6659f1339b849a9b0a7b/releases/releases.go#L50-L78
153,083
bulletind/khabar
dbapi/available_topics/dbapi.go
GetAllTopics
func GetAllTopics() []string { session := db.Conn.Session.Copy() defer session.Close() topics := []string{} db.Conn.GetCursor( session, db.AvailableTopicCollection, utils.M{}, ).Distinct("ident", &topics) return topics }
go
func GetAllTopics() []string { session := db.Conn.Session.Copy() defer session.Close() topics := []string{} db.Conn.GetCursor( session, db.AvailableTopicCollection, utils.M{}, ).Distinct("ident", &topics) return topics }
[ "func", "GetAllTopics", "(", ")", "[", "]", "string", "{", "session", ":=", "db", ".", "Conn", ".", "Session", ".", "Copy", "(", ")", "\n", "defer", "session", ".", "Close", "(", ")", "\n\n", "topics", ":=", "[", "]", "string", "{", "}", "\n\n", ...
// GetAllTopics returns all the available topics
[ "GetAllTopics", "returns", "all", "the", "available", "topics" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/available_topics/dbapi.go#L18-L29
153,084
bulletind/khabar
dbapi/available_topics/dbapi.go
GetAppTopics
func GetAppTopics(app_name, org string) (*[]db.AvailableTopic, error) { session := db.Conn.Session.Copy() defer session.Close() query := utils.M{"app_name": app_name} var topics []db.AvailableTopic iter := db.Conn.GetCursor( session, db.AvailableTopicCollection, query, ).Select(utils.M{"ident": 1, "channels": 1}).Sort("ident").Iter() err := iter.All(&topics) // TODO: handle this error return &topics, err }
go
func GetAppTopics(app_name, org string) (*[]db.AvailableTopic, error) { session := db.Conn.Session.Copy() defer session.Close() query := utils.M{"app_name": app_name} var topics []db.AvailableTopic iter := db.Conn.GetCursor( session, db.AvailableTopicCollection, query, ).Select(utils.M{"ident": 1, "channels": 1}).Sort("ident").Iter() err := iter.All(&topics) // TODO: handle this error return &topics, err }
[ "func", "GetAppTopics", "(", "app_name", ",", "org", "string", ")", "(", "*", "[", "]", "db", ".", "AvailableTopic", ",", "error", ")", "{", "session", ":=", "db", ".", "Conn", ".", "Session", ".", "Copy", "(", ")", "\n", "defer", "session", ".", "...
// GetAppTopics returns all the available topics for the particular app
[ "GetAppTopics", "returns", "all", "the", "available", "topics", "for", "the", "particular", "app" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/available_topics/dbapi.go#L32-L47
153,085
bulletind/khabar
dbapi/available_topics/dbapi.go
GetOrgPreferences
func GetOrgPreferences(org string, appTopics *[]db.AvailableTopic, channels *[]string) (map[string]ChotaTopic, error) { // Add defaults for org level var availableTopics []string topicMap := map[string]ChotaTopic{} for _, availableTopic := range *appTopics { ct := ChotaTopic{} for _, channel := range availableTopic.Channels { ct[channel] = &TopicDetail{Locked: false, Value: true} } topicMap[availableTopic.Ident] = ct } topic := new(db.Topic) session := db.Conn.Session.Copy() defer session.Close() for _, topic := range *appTopics { availableTopics = append(availableTopics, topic.Ident) } query := utils.M{ "ident": utils.M{"$in": availableTopics}, "user": db.BLANK, "org": db.BLANK, } // Step 1 // Use global settings pass1 := db.Conn.GetCursor(session, db.TopicCollection, query).Iter() for pass1.Next(topic) { if _, ok := topicMap[topic.Ident]; ok { for _, channel := range topic.Channels { if _, ok = topicMap[topic.Ident][channel.Name]; !ok { continue } topicMap[topic.Ident][channel.Name].Default = channel.Default topicMap[topic.Ident][channel.Name].Locked = channel.Locked } } } // Step 2 // Override it with organization settings query["org"] = org pass2 := db.Conn.GetCursor(session, db.TopicCollection, query).Iter() for pass2.Next(topic) { if _, ok := topicMap[topic.Ident]; ok { for _, channel := range topic.Channels { topicMap[topic.Ident][channel.Name].Default = channel.Default // topicMap[topic.Ident][channel.Name].Value = channel.Enabled topicMap[topic.Ident][channel.Name].Locked = channel.Locked } } } return topicMap, nil }
go
func GetOrgPreferences(org string, appTopics *[]db.AvailableTopic, channels *[]string) (map[string]ChotaTopic, error) { // Add defaults for org level var availableTopics []string topicMap := map[string]ChotaTopic{} for _, availableTopic := range *appTopics { ct := ChotaTopic{} for _, channel := range availableTopic.Channels { ct[channel] = &TopicDetail{Locked: false, Value: true} } topicMap[availableTopic.Ident] = ct } topic := new(db.Topic) session := db.Conn.Session.Copy() defer session.Close() for _, topic := range *appTopics { availableTopics = append(availableTopics, topic.Ident) } query := utils.M{ "ident": utils.M{"$in": availableTopics}, "user": db.BLANK, "org": db.BLANK, } // Step 1 // Use global settings pass1 := db.Conn.GetCursor(session, db.TopicCollection, query).Iter() for pass1.Next(topic) { if _, ok := topicMap[topic.Ident]; ok { for _, channel := range topic.Channels { if _, ok = topicMap[topic.Ident][channel.Name]; !ok { continue } topicMap[topic.Ident][channel.Name].Default = channel.Default topicMap[topic.Ident][channel.Name].Locked = channel.Locked } } } // Step 2 // Override it with organization settings query["org"] = org pass2 := db.Conn.GetCursor(session, db.TopicCollection, query).Iter() for pass2.Next(topic) { if _, ok := topicMap[topic.Ident]; ok { for _, channel := range topic.Channels { topicMap[topic.Ident][channel.Name].Default = channel.Default // topicMap[topic.Ident][channel.Name].Value = channel.Enabled topicMap[topic.Ident][channel.Name].Locked = channel.Locked } } } return topicMap, nil }
[ "func", "GetOrgPreferences", "(", "org", "string", ",", "appTopics", "*", "[", "]", "db", ".", "AvailableTopic", ",", "channels", "*", "[", "]", "string", ")", "(", "map", "[", "string", "]", "ChotaTopic", ",", "error", ")", "{", "// Add defaults for org l...
// GetOrgPreferences lists all the organization preferences for the ident and channel
[ "GetOrgPreferences", "lists", "all", "the", "organization", "preferences", "for", "the", "ident", "and", "channel" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/available_topics/dbapi.go#L50-L115
153,086
bulletind/khabar
dbapi/available_topics/dbapi.go
Insert
func Insert(newTopic *db.AvailableTopic) string { return db.Conn.Insert(db.AvailableTopicCollection, newTopic) }
go
func Insert(newTopic *db.AvailableTopic) string { return db.Conn.Insert(db.AvailableTopicCollection, newTopic) }
[ "func", "Insert", "(", "newTopic", "*", "db", ".", "AvailableTopic", ")", "string", "{", "return", "db", ".", "Conn", ".", "Insert", "(", "db", ".", "AvailableTopicCollection", ",", "newTopic", ")", "\n", "}" ]
// Insert creates a new available topic
[ "Insert", "creates", "a", "new", "available", "topic" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/available_topics/dbapi.go#L247-L249
153,087
bulletind/khabar
dbapi/available_topics/dbapi.go
Delete
func Delete(doc *utils.M) error { return db.Conn.Delete(db.AvailableTopicCollection, *doc) }
go
func Delete(doc *utils.M) error { return db.Conn.Delete(db.AvailableTopicCollection, *doc) }
[ "func", "Delete", "(", "doc", "*", "utils", ".", "M", ")", "error", "{", "return", "db", ".", "Conn", ".", "Delete", "(", "db", ".", "AvailableTopicCollection", ",", "*", "doc", ")", "\n", "}" ]
// Delete removes an available topic
[ "Delete", "removes", "an", "available", "topic" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/available_topics/dbapi.go#L252-L254
153,088
bulletind/khabar
dbapi/topics/dbapi.go
Insert
func Insert(topic *db.Topic) string { return db.Conn.Insert(db.TopicCollection, topic) }
go
func Insert(topic *db.Topic) string { return db.Conn.Insert(db.TopicCollection, topic) }
[ "func", "Insert", "(", "topic", "*", "db", ".", "Topic", ")", "string", "{", "return", "db", ".", "Conn", ".", "Insert", "(", "db", ".", "TopicCollection", ",", "topic", ")", "\n", "}" ]
// Insert adds a new user or organization preference
[ "Insert", "adds", "a", "new", "user", "or", "organization", "preference" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/topics/dbapi.go#L13-L15
153,089
bulletind/khabar
dbapi/topics/dbapi.go
updateTopics
func updateTopics(query, doc utils.M) error { return db.Conn.Update(db.TopicCollection, query, doc) }
go
func updateTopics(query, doc utils.M) error { return db.Conn.Update(db.TopicCollection, query, doc) }
[ "func", "updateTopics", "(", "query", ",", "doc", "utils", ".", "M", ")", "error", "{", "return", "db", ".", "Conn", ".", "Update", "(", "db", ".", "TopicCollection", ",", "query", ",", "doc", ")", "\n", "}" ]
// updateTopics updates user or organization preferences
[ "updateTopics", "updates", "user", "or", "organization", "preferences" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/topics/dbapi.go#L142-L144
153,090
bulletind/khabar
dbapi/topics/dbapi.go
Initialize
func Initialize(user, org string) error { if user == db.BLANK { org = db.BLANK } disabled := GetAllDefault(org) preferences := []interface{}{} for _, topic := range disabled { preference := db.Topic{ User: user, Organization: org, Ident: topic.Ident, Channels: topic.Channels, } preference.PrepareSave() preferences = append(preferences, preference) } if len(preferences) > 0 { err, _ := db.Conn.InsertMulti(db.TopicCollection, preferences...) return err } return nil }
go
func Initialize(user, org string) error { if user == db.BLANK { org = db.BLANK } disabled := GetAllDefault(org) preferences := []interface{}{} for _, topic := range disabled { preference := db.Topic{ User: user, Organization: org, Ident: topic.Ident, Channels: topic.Channels, } preference.PrepareSave() preferences = append(preferences, preference) } if len(preferences) > 0 { err, _ := db.Conn.InsertMulti(db.TopicCollection, preferences...) return err } return nil }
[ "func", "Initialize", "(", "user", ",", "org", "string", ")", "error", "{", "if", "user", "==", "db", ".", "BLANK", "{", "org", "=", "db", ".", "BLANK", "\n", "}", "\n\n", "disabled", ":=", "GetAllDefault", "(", "org", ")", "\n", "preferences", ":=",...
// Initialize creates a list of "default - non-enabled" preferences for user or org
[ "Initialize", "creates", "a", "list", "of", "default", "-", "non", "-", "enabled", "preferences", "for", "user", "or", "org" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/topics/dbapi.go#L147-L173
153,091
bulletind/khabar
dbapi/topics/dbapi.go
GetAllDefault
func GetAllDefault(org string) []db.Topic { session := db.Conn.Session.Copy() defer session.Close() result := []db.Topic{} db.Conn.Get(session, db.TopicCollection, utils.M{ "org": org, "user": db.BLANK, "channels.default": false, }).All(&result) return result }
go
func GetAllDefault(org string) []db.Topic { session := db.Conn.Session.Copy() defer session.Close() result := []db.Topic{} db.Conn.Get(session, db.TopicCollection, utils.M{ "org": org, "user": db.BLANK, "channels.default": false, }).All(&result) return result }
[ "func", "GetAllDefault", "(", "org", "string", ")", "[", "]", "db", ".", "Topic", "{", "session", ":=", "db", ".", "Conn", ".", "Session", ".", "Copy", "(", ")", "\n", "defer", "session", ".", "Close", "(", ")", "\n\n", "result", ":=", "[", "]", ...
// GetAllDefault returns all the "default - non-enabled" preferences for the organization
[ "GetAllDefault", "returns", "all", "the", "default", "-", "non", "-", "enabled", "preferences", "for", "the", "organization" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/topics/dbapi.go#L176-L189
153,092
bulletind/khabar
dbapi/topics/dbapi.go
ChannelAllowed
func ChannelAllowed(user, org, app_name, ident, channelName string) bool { var available = []string{"email", "web", "push"} var preference map[string]availableTopics.ChotaTopic appTopics, err := availableTopics.GetAppTopics(app_name, org) channels := []string{} for _, idnt := range available { channels = append(channels, idnt) } preference, err = availableTopics.GetUserPreferences(user, org, appTopics, &channels) if err != nil { log.Println(err) return false } if _, ok := preference[ident]; !ok { return false } if _, ok := preference[ident][channelName]; !ok { return false } return preference[ident][channelName].Value }
go
func ChannelAllowed(user, org, app_name, ident, channelName string) bool { var available = []string{"email", "web", "push"} var preference map[string]availableTopics.ChotaTopic appTopics, err := availableTopics.GetAppTopics(app_name, org) channels := []string{} for _, idnt := range available { channels = append(channels, idnt) } preference, err = availableTopics.GetUserPreferences(user, org, appTopics, &channels) if err != nil { log.Println(err) return false } if _, ok := preference[ident]; !ok { return false } if _, ok := preference[ident][channelName]; !ok { return false } return preference[ident][channelName].Value }
[ "func", "ChannelAllowed", "(", "user", ",", "org", ",", "app_name", ",", "ident", ",", "channelName", "string", ")", "bool", "{", "var", "available", "=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "var", "pre...
// ChannelAllowed checks if the requested channel is allowed by the user for sending // out the notification
[ "ChannelAllowed", "checks", "if", "the", "requested", "channel", "is", "allowed", "by", "the", "user", "for", "sending", "out", "the", "notification" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/topics/dbapi.go#L193-L219
153,093
bulletind/khabar
dbapi/topics/dbapi.go
AddChannel
func AddChannel(ident, channelName, user, organization string) error { query := utils.M{ "org": organization, "user": user, "ident": ident, } spec := utils.M{ "$addToSet": utils.M{ "channels": db.Channel{Name: channelName, Enabled: true}, }, } result := utils.M{} _, err := db.Conn.FindAndUpdate(db.TopicCollection, query, spec, &result) return err }
go
func AddChannel(ident, channelName, user, organization string) error { query := utils.M{ "org": organization, "user": user, "ident": ident, } spec := utils.M{ "$addToSet": utils.M{ "channels": db.Channel{Name: channelName, Enabled: true}, }, } result := utils.M{} _, err := db.Conn.FindAndUpdate(db.TopicCollection, query, spec, &result) return err }
[ "func", "AddChannel", "(", "ident", ",", "channelName", ",", "user", ",", "organization", "string", ")", "error", "{", "query", ":=", "utils", ".", "M", "{", "\"", "\"", ":", "organization", ",", "\"", "\"", ":", "user", ",", "\"", "\"", ":", "ident"...
// AddChannel enables the channel for that particular ident for sending notifications
[ "AddChannel", "enables", "the", "channel", "for", "that", "particular", "ident", "for", "sending", "notifications" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/topics/dbapi.go#L283-L300
153,094
bulletind/khabar
dbapi/topics/dbapi.go
RemoveChannel
func RemoveChannel(ident, channelName, user, organization string) error { query := utils.M{ "org": organization, "user": user, "ident": ident, "channels.name": channelName, } found := new(db.Topic) err := db.Conn.GetOne( db.TopicCollection, query, found, ) err = db.Conn.Update( db.TopicCollection, query, utils.M{ "$set": utils.M{ "channels.$.enabled": false, }, }, ) return err }
go
func RemoveChannel(ident, channelName, user, organization string) error { query := utils.M{ "org": organization, "user": user, "ident": ident, "channels.name": channelName, } found := new(db.Topic) err := db.Conn.GetOne( db.TopicCollection, query, found, ) err = db.Conn.Update( db.TopicCollection, query, utils.M{ "$set": utils.M{ "channels.$.enabled": false, }, }, ) return err }
[ "func", "RemoveChannel", "(", "ident", ",", "channelName", ",", "user", ",", "organization", "string", ")", "error", "{", "query", ":=", "utils", ".", "M", "{", "\"", "\"", ":", "organization", ",", "\"", "\"", ":", "user", ",", "\"", "\"", ":", "ide...
// RemoveChannel disables the channel for that particular ident for sending // notifications
[ "RemoveChannel", "disables", "the", "channel", "for", "that", "particular", "ident", "for", "sending", "notifications" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/dbapi/topics/dbapi.go#L304-L331
153,095
bulletind/khabar
migrations/002_add_defaults_locks_to_topics.go
RemoveAppName
func RemoveAppName(db *mgo.Database) (err error) { Topics := db.C(topicsCollection) change, err := Topics.UpdateAll( bson.M{}, bson.M{ "$unset": bson.M{ "app_name": "", }, }, ) handle_errors(err) fmt.Println("Updated", change.Updated, "documents in `", topicsCollection, "` collection") return }
go
func RemoveAppName(db *mgo.Database) (err error) { Topics := db.C(topicsCollection) change, err := Topics.UpdateAll( bson.M{}, bson.M{ "$unset": bson.M{ "app_name": "", }, }, ) handle_errors(err) fmt.Println("Updated", change.Updated, "documents in `", topicsCollection, "` collection") return }
[ "func", "RemoveAppName", "(", "db", "*", "mgo", ".", "Database", ")", "(", "err", "error", ")", "{", "Topics", ":=", "db", ".", "C", "(", "topicsCollection", ")", "\n\n", "change", ",", "err", ":=", "Topics", ".", "UpdateAll", "(", "bson", ".", "M", ...
/** * Remove `app_name` from `topics` collection */
[ "Remove", "app_name", "from", "topics", "collection" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/migrations/002_add_defaults_locks_to_topics.go#L95-L109
153,096
bulletind/khabar
migrations/002_add_defaults_locks_to_topics.go
ModifyChannels
func ModifyChannels(db *mgo.Database) (err error) { Topics := db.C(topicsCollection) notNull := bson.M{"$ne": ""} query := bson.M{ "user": notNull, "org": notNull, } var topics []Topic // Modify user setting err = Topics.Find(query).All(&topics) handle_errors(err) for _, topic := range topics { channels := make([]models.Channel, 0) for _, name := range topic.Channels { channel := new(models.Channel) channel.Name = name channel.Enabled = true channels = append(channels, *channel) } Topics.Update(bson.M{"_id": topic.Id}, bson.M{ "$set": bson.M{ "channels": channels, }, }) } // fmt.Println("Updated", change.Updated, "documents in `", topicsCollection, "` collection") // Modify org setting query["user"] = "" change, err := Topics.UpdateAll( query, bson.M{ "$set": map[string][]models.Channel{ "channels": make([]models.Channel, 0), }, }, ) handle_errors(err) fmt.Println("Updated", change.Updated, "documents in `", topicsCollection, "` collection") return }
go
func ModifyChannels(db *mgo.Database) (err error) { Topics := db.C(topicsCollection) notNull := bson.M{"$ne": ""} query := bson.M{ "user": notNull, "org": notNull, } var topics []Topic // Modify user setting err = Topics.Find(query).All(&topics) handle_errors(err) for _, topic := range topics { channels := make([]models.Channel, 0) for _, name := range topic.Channels { channel := new(models.Channel) channel.Name = name channel.Enabled = true channels = append(channels, *channel) } Topics.Update(bson.M{"_id": topic.Id}, bson.M{ "$set": bson.M{ "channels": channels, }, }) } // fmt.Println("Updated", change.Updated, "documents in `", topicsCollection, "` collection") // Modify org setting query["user"] = "" change, err := Topics.UpdateAll( query, bson.M{ "$set": map[string][]models.Channel{ "channels": make([]models.Channel, 0), }, }, ) handle_errors(err) fmt.Println("Updated", change.Updated, "documents in `", topicsCollection, "` collection") return }
[ "func", "ModifyChannels", "(", "db", "*", "mgo", ".", "Database", ")", "(", "err", "error", ")", "{", "Topics", ":=", "db", ".", "C", "(", "topicsCollection", ")", "\n", "notNull", ":=", "bson", ".", "M", "{", "\"", "\"", ":", "\"", "\"", "}", "\...
/** * Modify channels array in `topics` collection */
[ "Modify", "channels", "array", "in", "topics", "collection" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/migrations/002_add_defaults_locks_to_topics.go#L135-L183
153,097
bulletind/khabar
migrations/002_add_defaults_locks_to_topics.go
RemoveLocks
func RemoveLocks(session *mgo.Session, dbName string) { var result interface{} err := session.Run(bson.D{ {"renameCollection", dbName + ".locks"}, {"to", dbName + ".temp_locks"}, }, result) if err != nil { fmt.Println("Error removing locks collection. It may have already been removed") } }
go
func RemoveLocks(session *mgo.Session, dbName string) { var result interface{} err := session.Run(bson.D{ {"renameCollection", dbName + ".locks"}, {"to", dbName + ".temp_locks"}, }, result) if err != nil { fmt.Println("Error removing locks collection. It may have already been removed") } }
[ "func", "RemoveLocks", "(", "session", "*", "mgo", ".", "Session", ",", "dbName", "string", ")", "{", "var", "result", "interface", "{", "}", "\n", "err", ":=", "session", ".", "Run", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "dbName", "+",...
/** * Remove locks collection */
[ "Remove", "locks", "collection" ]
00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99
https://github.com/bulletind/khabar/blob/00c5b5cf63101ea7489c8a2a0c52f8766f5f3a99/migrations/002_add_defaults_locks_to_topics.go#L189-L198
153,098
deis/controller-sdk-go
certs/certs.go
List
func List(c *deis.Client, results int) ([]api.Cert, int, error) { body, count, reqErr := c.LimitedRequest("/v2/certs/", results) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return []api.Cert{}, -1, reqErr } var res []api.Cert if err := json.Unmarshal([]byte(body), &res); err != nil { return []api.Cert{}, -1, err } return res, count, reqErr }
go
func List(c *deis.Client, results int) ([]api.Cert, int, error) { body, count, reqErr := c.LimitedRequest("/v2/certs/", results) if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) { return []api.Cert{}, -1, reqErr } var res []api.Cert if err := json.Unmarshal([]byte(body), &res); err != nil { return []api.Cert{}, -1, err } return res, count, reqErr }
[ "func", "List", "(", "c", "*", "deis", ".", "Client", ",", "results", "int", ")", "(", "[", "]", "api", ".", "Cert", ",", "int", ",", "error", ")", "{", "body", ",", "count", ",", "reqErr", ":=", "c", ".", "LimitedRequest", "(", "\"", "\"", ","...
// List lists certificates added to deis.
[ "List", "lists", "certificates", "added", "to", "deis", "." ]
c9ffa05111835e74d71a6659f1339b849a9b0a7b
https://github.com/deis/controller-sdk-go/blob/c9ffa05111835e74d71a6659f1339b849a9b0a7b/certs/certs.go#L13-L26
153,099
deis/controller-sdk-go
certs/certs.go
Get
func Get(c *deis.Client, name string) (api.Cert, error) { url := fmt.Sprintf("/v2/certs/%s", name) res, reqErr := c.Request("GET", url, nil) if reqErr != nil { return api.Cert{}, reqErr } defer res.Body.Close() resCert := api.Cert{} if err := json.NewDecoder(res.Body).Decode(&resCert); err != nil { return api.Cert{}, err } return resCert, reqErr }
go
func Get(c *deis.Client, name string) (api.Cert, error) { url := fmt.Sprintf("/v2/certs/%s", name) res, reqErr := c.Request("GET", url, nil) if reqErr != nil { return api.Cert{}, reqErr } defer res.Body.Close() resCert := api.Cert{} if err := json.NewDecoder(res.Body).Decode(&resCert); err != nil { return api.Cert{}, err } return resCert, reqErr }
[ "func", "Get", "(", "c", "*", "deis", ".", "Client", ",", "name", "string", ")", "(", "api", ".", "Cert", ",", "error", ")", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", "\n", "res", ",", "reqErr", ":=", "c", "....
// Get retrieves information about a certificate
[ "Get", "retrieves", "information", "about", "a", "certificate" ]
c9ffa05111835e74d71a6659f1339b849a9b0a7b
https://github.com/deis/controller-sdk-go/blob/c9ffa05111835e74d71a6659f1339b849a9b0a7b/certs/certs.go#L54-L68