repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
nicksnyder/go-i18n
v2/i18n/bundle.go
LoadMessageFile
func (b *Bundle) LoadMessageFile(path string) (*MessageFile, error) { buf, err := ioutil.ReadFile(path) if err != nil { return nil, err } return b.ParseMessageFileBytes(buf, path) }
go
func (b *Bundle) LoadMessageFile(path string) (*MessageFile, error) { buf, err := ioutil.ReadFile(path) if err != nil { return nil, err } return b.ParseMessageFileBytes(buf, path) }
[ "func", "(", "b", "*", "Bundle", ")", "LoadMessageFile", "(", "path", "string", ")", "(", "*", "MessageFile", ",", "error", ")", "{", "buf", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return...
// LoadMessageFile loads the bytes from path // and then calls ParseMessageFileBytes.
[ "LoadMessageFile", "loads", "the", "bytes", "from", "path", "and", "then", "calls", "ParseMessageFileBytes", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/i18n/bundle.go#L49-L55
train
nicksnyder/go-i18n
v2/i18n/bundle.go
MustLoadMessageFile
func (b *Bundle) MustLoadMessageFile(path string) { if _, err := b.LoadMessageFile(path); err != nil { panic(err) } }
go
func (b *Bundle) MustLoadMessageFile(path string) { if _, err := b.LoadMessageFile(path); err != nil { panic(err) } }
[ "func", "(", "b", "*", "Bundle", ")", "MustLoadMessageFile", "(", "path", "string", ")", "{", "if", "_", ",", "err", ":=", "b", ".", "LoadMessageFile", "(", "path", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}"...
// MustLoadMessageFile is similar to LoadTranslationFile // except it panics if an error happens.
[ "MustLoadMessageFile", "is", "similar", "to", "LoadTranslationFile", "except", "it", "panics", "if", "an", "error", "happens", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/i18n/bundle.go#L59-L63
train
nicksnyder/go-i18n
v2/i18n/bundle.go
ParseMessageFileBytes
func (b *Bundle) ParseMessageFileBytes(buf []byte, path string) (*MessageFile, error) { messageFile, err := internal.ParseMessageFileBytes(buf, path, b.unmarshalFuncs) if err != nil { return nil, err } if err := b.AddMessages(messageFile.Tag, messageFile.Messages...); err != nil { return nil, err } return messageFile, nil }
go
func (b *Bundle) ParseMessageFileBytes(buf []byte, path string) (*MessageFile, error) { messageFile, err := internal.ParseMessageFileBytes(buf, path, b.unmarshalFuncs) if err != nil { return nil, err } if err := b.AddMessages(messageFile.Tag, messageFile.Messages...); err != nil { return nil, err } return messageFile, nil }
[ "func", "(", "b", "*", "Bundle", ")", "ParseMessageFileBytes", "(", "buf", "[", "]", "byte", ",", "path", "string", ")", "(", "*", "MessageFile", ",", "error", ")", "{", "messageFile", ",", "err", ":=", "internal", ".", "ParseMessageFileBytes", "(", "buf...
// ParseMessageFileBytes parses the bytes in buf to add translations to the bundle. // // The format of the file is everything after the last ".". // // The language tag of the file is everything after the second to last "." or after the last path separator, but before the format.
[ "ParseMessageFileBytes", "parses", "the", "bytes", "in", "buf", "to", "add", "translations", "to", "the", "bundle", ".", "The", "format", "of", "the", "file", "is", "everything", "after", "the", "last", ".", ".", "The", "language", "tag", "of", "the", "fil...
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/i18n/bundle.go#L73-L82
train
nicksnyder/go-i18n
v2/i18n/bundle.go
MustParseMessageFileBytes
func (b *Bundle) MustParseMessageFileBytes(buf []byte, path string) { if _, err := b.ParseMessageFileBytes(buf, path); err != nil { panic(err) } }
go
func (b *Bundle) MustParseMessageFileBytes(buf []byte, path string) { if _, err := b.ParseMessageFileBytes(buf, path); err != nil { panic(err) } }
[ "func", "(", "b", "*", "Bundle", ")", "MustParseMessageFileBytes", "(", "buf", "[", "]", "byte", ",", "path", "string", ")", "{", "if", "_", ",", "err", ":=", "b", ".", "ParseMessageFileBytes", "(", "buf", ",", "path", ")", ";", "err", "!=", "nil", ...
// MustParseMessageFileBytes is similar to ParseMessageFileBytes // except it panics if an error happens.
[ "MustParseMessageFileBytes", "is", "similar", "to", "ParseMessageFileBytes", "except", "it", "panics", "if", "an", "error", "happens", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/i18n/bundle.go#L86-L90
train
nicksnyder/go-i18n
v2/i18n/bundle.go
AddMessages
func (b *Bundle) AddMessages(tag language.Tag, messages ...*Message) error { pluralRule := b.pluralRules.Rule(tag) if pluralRule == nil { return fmt.Errorf("no plural rule registered for %s", tag) } if b.messageTemplates == nil { b.messageTemplates = map[language.Tag]map[string]*internal.MessageTemplate{} } if b.messageTemplates[tag] == nil { b.messageTemplates[tag] = map[string]*internal.MessageTemplate{} b.addTag(tag) } for _, m := range messages { b.messageTemplates[tag][m.ID] = internal.NewMessageTemplate(m) } return nil }
go
func (b *Bundle) AddMessages(tag language.Tag, messages ...*Message) error { pluralRule := b.pluralRules.Rule(tag) if pluralRule == nil { return fmt.Errorf("no plural rule registered for %s", tag) } if b.messageTemplates == nil { b.messageTemplates = map[language.Tag]map[string]*internal.MessageTemplate{} } if b.messageTemplates[tag] == nil { b.messageTemplates[tag] = map[string]*internal.MessageTemplate{} b.addTag(tag) } for _, m := range messages { b.messageTemplates[tag][m.ID] = internal.NewMessageTemplate(m) } return nil }
[ "func", "(", "b", "*", "Bundle", ")", "AddMessages", "(", "tag", "language", ".", "Tag", ",", "messages", "...", "*", "Message", ")", "error", "{", "pluralRule", ":=", "b", ".", "pluralRules", ".", "Rule", "(", "tag", ")", "\n", "if", "pluralRule", "...
// AddMessages adds messages for a language. // It is useful if your messages are in a format not supported by ParseMessageFileBytes.
[ "AddMessages", "adds", "messages", "for", "a", "language", ".", "It", "is", "useful", "if", "your", "messages", "are", "in", "a", "format", "not", "supported", "by", "ParseMessageFileBytes", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/i18n/bundle.go#L94-L110
train
nicksnyder/go-i18n
v2/i18n/bundle.go
MustAddMessages
func (b *Bundle) MustAddMessages(tag language.Tag, messages ...*Message) { if err := b.AddMessages(tag, messages...); err != nil { panic(err) } }
go
func (b *Bundle) MustAddMessages(tag language.Tag, messages ...*Message) { if err := b.AddMessages(tag, messages...); err != nil { panic(err) } }
[ "func", "(", "b", "*", "Bundle", ")", "MustAddMessages", "(", "tag", "language", ".", "Tag", ",", "messages", "...", "*", "Message", ")", "{", "if", "err", ":=", "b", ".", "AddMessages", "(", "tag", ",", "messages", "...", ")", ";", "err", "!=", "n...
// MustAddMessages is similar to AddMessages except it panics if an error happens.
[ "MustAddMessages", "is", "similar", "to", "AddMessages", "except", "it", "panics", "if", "an", "error", "happens", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/i18n/bundle.go#L113-L117
train
nicksnyder/go-i18n
i18n/language/operands.go
NequalsAny
func (o *Operands) NequalsAny(any ...int64) bool { for _, i := range any { if o.I == i && o.T == 0 { return true } } return false }
go
func (o *Operands) NequalsAny(any ...int64) bool { for _, i := range any { if o.I == i && o.T == 0 { return true } } return false }
[ "func", "(", "o", "*", "Operands", ")", "NequalsAny", "(", "any", "...", "int64", ")", "bool", "{", "for", "_", ",", "i", ":=", "range", "any", "{", "if", "o", ".", "I", "==", "i", "&&", "o", ".", "T", "==", "0", "{", "return", "true", "\n", ...
// NequalsAny returns true if o represents an integer equal to any of the arguments.
[ "NequalsAny", "returns", "true", "if", "o", "represents", "an", "integer", "equal", "to", "any", "of", "the", "arguments", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/language/operands.go#L20-L27
train
nicksnyder/go-i18n
i18n/language/operands.go
NmodEqualsAny
func (o *Operands) NmodEqualsAny(mod int64, any ...int64) bool { modI := o.I % mod for _, i := range any { if modI == i && o.T == 0 { return true } } return false }
go
func (o *Operands) NmodEqualsAny(mod int64, any ...int64) bool { modI := o.I % mod for _, i := range any { if modI == i && o.T == 0 { return true } } return false }
[ "func", "(", "o", "*", "Operands", ")", "NmodEqualsAny", "(", "mod", "int64", ",", "any", "...", "int64", ")", "bool", "{", "modI", ":=", "o", ".", "I", "%", "mod", "\n", "for", "_", ",", "i", ":=", "range", "any", "{", "if", "modI", "==", "i",...
// NmodEqualsAny returns true if o represents an integer equal to any of the arguments modulo mod.
[ "NmodEqualsAny", "returns", "true", "if", "o", "represents", "an", "integer", "equal", "to", "any", "of", "the", "arguments", "modulo", "mod", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/language/operands.go#L30-L38
train
nicksnyder/go-i18n
v2/internal/message.go
NewMessage
func NewMessage(data interface{}) (*Message, error) { m := &Message{} if err := m.unmarshalInterface(data); err != nil { return nil, err } return m, nil }
go
func NewMessage(data interface{}) (*Message, error) { m := &Message{} if err := m.unmarshalInterface(data); err != nil { return nil, err } return m, nil }
[ "func", "NewMessage", "(", "data", "interface", "{", "}", ")", "(", "*", "Message", ",", "error", ")", "{", "m", ":=", "&", "Message", "{", "}", "\n", "if", "err", ":=", "m", ".", "unmarshalInterface", "(", "data", ")", ";", "err", "!=", "nil", "...
// NewMessage parses data and returns a new message.
[ "NewMessage", "parses", "data", "and", "returns", "a", "new", "message", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/internal/message.go#L47-L53
train
nicksnyder/go-i18n
v2/internal/message.go
MustNewMessage
func MustNewMessage(data interface{}) *Message { m, err := NewMessage(data) if err != nil { panic(err) } return m }
go
func MustNewMessage(data interface{}) *Message { m, err := NewMessage(data) if err != nil { panic(err) } return m }
[ "func", "MustNewMessage", "(", "data", "interface", "{", "}", ")", "*", "Message", "{", "m", ",", "err", ":=", "NewMessage", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "m", "\n", "}...
// MustNewMessage is similar to NewMessage except it panics if an error happens.
[ "MustNewMessage", "is", "similar", "to", "NewMessage", "except", "it", "panics", "if", "an", "error", "happens", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/internal/message.go#L56-L62
train
nicksnyder/go-i18n
v2/internal/message.go
unmarshalInterface
func (m *Message) unmarshalInterface(v interface{}) error { strdata, err := stringMap(v) if err != nil { return err } for k, v := range strdata { switch strings.ToLower(k) { case "id": m.ID = v case "description": m.Description = v case "hash": m.Hash = v case "leftdelim": m.LeftDelim = v case "rightdelim": m.RightDelim = v case "zero": m.Zero = v case "one": m.One = v case "two": m.Two = v case "few": m.Few = v case "many": m.Many = v case "other": m.Other = v } } return nil }
go
func (m *Message) unmarshalInterface(v interface{}) error { strdata, err := stringMap(v) if err != nil { return err } for k, v := range strdata { switch strings.ToLower(k) { case "id": m.ID = v case "description": m.Description = v case "hash": m.Hash = v case "leftdelim": m.LeftDelim = v case "rightdelim": m.RightDelim = v case "zero": m.Zero = v case "one": m.One = v case "two": m.Two = v case "few": m.Few = v case "many": m.Many = v case "other": m.Other = v } } return nil }
[ "func", "(", "m", "*", "Message", ")", "unmarshalInterface", "(", "v", "interface", "{", "}", ")", "error", "{", "strdata", ",", "err", ":=", "stringMap", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", ...
// unmarshalInterface unmarshals a message from data.
[ "unmarshalInterface", "unmarshals", "a", "message", "from", "data", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/internal/message.go#L65-L97
train
nicksnyder/go-i18n
v2/internal/message_template.go
NewMessageTemplate
func NewMessageTemplate(m *Message) *MessageTemplate { pluralTemplates := map[plural.Form]*Template{} setPluralTemplate(pluralTemplates, plural.Zero, m.Zero) setPluralTemplate(pluralTemplates, plural.One, m.One) setPluralTemplate(pluralTemplates, plural.Two, m.Two) setPluralTemplate(pluralTemplates, plural.Few, m.Few) setPluralTemplate(pluralTemplates, plural.Many, m.Many) setPluralTemplate(pluralTemplates, plural.Other, m.Other) if len(pluralTemplates) == 0 { return nil } return &MessageTemplate{ Message: m, PluralTemplates: pluralTemplates, } }
go
func NewMessageTemplate(m *Message) *MessageTemplate { pluralTemplates := map[plural.Form]*Template{} setPluralTemplate(pluralTemplates, plural.Zero, m.Zero) setPluralTemplate(pluralTemplates, plural.One, m.One) setPluralTemplate(pluralTemplates, plural.Two, m.Two) setPluralTemplate(pluralTemplates, plural.Few, m.Few) setPluralTemplate(pluralTemplates, plural.Many, m.Many) setPluralTemplate(pluralTemplates, plural.Other, m.Other) if len(pluralTemplates) == 0 { return nil } return &MessageTemplate{ Message: m, PluralTemplates: pluralTemplates, } }
[ "func", "NewMessageTemplate", "(", "m", "*", "Message", ")", "*", "MessageTemplate", "{", "pluralTemplates", ":=", "map", "[", "plural", ".", "Form", "]", "*", "Template", "{", "}", "\n", "setPluralTemplate", "(", "pluralTemplates", ",", "plural", ".", "Zero...
// NewMessageTemplate returns a new message template.
[ "NewMessageTemplate", "returns", "a", "new", "message", "template", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/internal/message_template.go#L19-L34
train
nicksnyder/go-i18n
v2/internal/message_template.go
Execute
func (mt *MessageTemplate) Execute(pluralForm plural.Form, data interface{}, funcs template.FuncMap) (string, error) { t := mt.PluralTemplates[pluralForm] if t == nil { return "", pluralFormNotFoundError{ pluralForm: pluralForm, messageID: mt.Message.ID, } } if err := t.parse(mt.LeftDelim, mt.RightDelim, funcs); err != nil { return "", err } if t.Template == nil { return t.Src, nil } var buf bytes.Buffer if err := t.Template.Execute(&buf, data); err != nil { return "", err } return buf.String(), nil }
go
func (mt *MessageTemplate) Execute(pluralForm plural.Form, data interface{}, funcs template.FuncMap) (string, error) { t := mt.PluralTemplates[pluralForm] if t == nil { return "", pluralFormNotFoundError{ pluralForm: pluralForm, messageID: mt.Message.ID, } } if err := t.parse(mt.LeftDelim, mt.RightDelim, funcs); err != nil { return "", err } if t.Template == nil { return t.Src, nil } var buf bytes.Buffer if err := t.Template.Execute(&buf, data); err != nil { return "", err } return buf.String(), nil }
[ "func", "(", "mt", "*", "MessageTemplate", ")", "Execute", "(", "pluralForm", "plural", ".", "Form", ",", "data", "interface", "{", "}", ",", "funcs", "template", ".", "FuncMap", ")", "(", "string", ",", "error", ")", "{", "t", ":=", "mt", ".", "Plur...
// Execute executes the template for the plural form and template data.
[ "Execute", "executes", "the", "template", "for", "the", "plural", "form", "and", "template", "data", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/internal/message_template.go#L52-L71
train
nicksnyder/go-i18n
v2/internal/plural/operands.go
NewOperands
func NewOperands(number interface{}) (*Operands, error) { switch number := number.(type) { case int: return newOperandsInt64(int64(number)), nil case int8: return newOperandsInt64(int64(number)), nil case int16: return newOperandsInt64(int64(number)), nil case int32: return newOperandsInt64(int64(number)), nil case int64: return newOperandsInt64(number), nil case string: return newOperandsString(number) case float32, float64: return nil, fmt.Errorf("floats should be formatted into a string") default: return nil, fmt.Errorf("invalid type %T; expected integer or string", number) } }
go
func NewOperands(number interface{}) (*Operands, error) { switch number := number.(type) { case int: return newOperandsInt64(int64(number)), nil case int8: return newOperandsInt64(int64(number)), nil case int16: return newOperandsInt64(int64(number)), nil case int32: return newOperandsInt64(int64(number)), nil case int64: return newOperandsInt64(number), nil case string: return newOperandsString(number) case float32, float64: return nil, fmt.Errorf("floats should be formatted into a string") default: return nil, fmt.Errorf("invalid type %T; expected integer or string", number) } }
[ "func", "NewOperands", "(", "number", "interface", "{", "}", ")", "(", "*", "Operands", ",", "error", ")", "{", "switch", "number", ":=", "number", ".", "(", "type", ")", "{", "case", "int", ":", "return", "newOperandsInt64", "(", "int64", "(", "number...
// NewOperands returns the operands for number.
[ "NewOperands", "returns", "the", "operands", "for", "number", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/internal/plural/operands.go#L52-L71
train
nicksnyder/go-i18n
i18n/language/codegen/xml.go
Name
func (pg *PluralGroup) Name() string { n := strings.Title(pg.Locales) return strings.Replace(n, " ", "", -1) }
go
func (pg *PluralGroup) Name() string { n := strings.Title(pg.Locales) return strings.Replace(n, " ", "", -1) }
[ "func", "(", "pg", "*", "PluralGroup", ")", "Name", "(", ")", "string", "{", "n", ":=", "strings", ".", "Title", "(", "pg", ".", "Locales", ")", "\n", "return", "strings", ".", "Replace", "(", "n", ",", "\" \"", ",", "\"\"", ",", "-", "1", ")", ...
// Name returns a unique name for this plural group.
[ "Name", "returns", "a", "unique", "name", "for", "this", "plural", "group", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/language/codegen/xml.go#L23-L26
train
nicksnyder/go-i18n
i18n/language/codegen/xml.go
Condition
func (pr *PluralRule) Condition() string { i := strings.Index(pr.Rule, "@") return pr.Rule[:i] }
go
func (pr *PluralRule) Condition() string { i := strings.Index(pr.Rule, "@") return pr.Rule[:i] }
[ "func", "(", "pr", "*", "PluralRule", ")", "Condition", "(", ")", "string", "{", "i", ":=", "strings", ".", "Index", "(", "pr", ".", "Rule", ",", "\"@\"", ")", "\n", "return", "pr", ".", "Rule", "[", ":", "i", "]", "\n", "}" ]
// Condition returns the condition where the PluralRule applies.
[ "Condition", "returns", "the", "condition", "where", "the", "PluralRule", "applies", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/language/codegen/xml.go#L45-L48
train
nicksnyder/go-i18n
i18n/language/codegen/xml.go
Examples
func (pr *PluralRule) Examples() (integer []string, decimal []string) { ex := strings.Replace(pr.Rule, ", …", "", -1) ddelim := "@decimal" if i := strings.Index(ex, ddelim); i > 0 { dex := strings.TrimSpace(ex[i+len(ddelim):]) decimal = strings.Split(dex, ", ") ex = ex[:i] } idelim := "@integer" if i := strings.Index(ex, idelim); i > 0 { iex := strings.TrimSpace(ex[i+len(idelim):]) integer = strings.Split(iex, ", ") } return integer, decimal }
go
func (pr *PluralRule) Examples() (integer []string, decimal []string) { ex := strings.Replace(pr.Rule, ", …", "", -1) ddelim := "@decimal" if i := strings.Index(ex, ddelim); i > 0 { dex := strings.TrimSpace(ex[i+len(ddelim):]) decimal = strings.Split(dex, ", ") ex = ex[:i] } idelim := "@integer" if i := strings.Index(ex, idelim); i > 0 { iex := strings.TrimSpace(ex[i+len(idelim):]) integer = strings.Split(iex, ", ") } return integer, decimal }
[ "func", "(", "pr", "*", "PluralRule", ")", "Examples", "(", ")", "(", "integer", "[", "]", "string", ",", "decimal", "[", "]", "string", ")", "{", "ex", ":=", "strings", ".", "Replace", "(", "pr", ".", "Rule", ",", "\", …\", ", " ", "\"", ", ", "...
// Examples returns the integer and decimal exmaples for the PLuralRule.
[ "Examples", "returns", "the", "integer", "and", "decimal", "exmaples", "for", "the", "PLuralRule", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/language/codegen/xml.go#L51-L65
train
nicksnyder/go-i18n
v2/goi18n/merge_command.go
activeDst
func activeDst(src, dst *internal.MessageTemplate, pluralRule *plural.Rule) (active *internal.MessageTemplate, translateMessageTemplate *internal.MessageTemplate) { pluralForms := pluralRule.PluralForms if len(src.PluralTemplates) == 1 { pluralForms = map[plural.Form]struct{}{ plural.Other: {}, } } for pluralForm := range pluralForms { dt := dst.PluralTemplates[pluralForm] if dt == nil || dt.Src == "" { if translateMessageTemplate == nil { translateMessageTemplate = &internal.MessageTemplate{ Message: &i18n.Message{ ID: src.ID, Description: src.Description, Hash: src.Hash, }, PluralTemplates: make(map[plural.Form]*internal.Template), } } translateMessageTemplate.PluralTemplates[pluralForm] = src.PluralTemplates[plural.Other] continue } if active == nil { active = &internal.MessageTemplate{ Message: &i18n.Message{ ID: src.ID, Description: src.Description, Hash: src.Hash, }, PluralTemplates: make(map[plural.Form]*internal.Template), } } active.PluralTemplates[pluralForm] = dt } return }
go
func activeDst(src, dst *internal.MessageTemplate, pluralRule *plural.Rule) (active *internal.MessageTemplate, translateMessageTemplate *internal.MessageTemplate) { pluralForms := pluralRule.PluralForms if len(src.PluralTemplates) == 1 { pluralForms = map[plural.Form]struct{}{ plural.Other: {}, } } for pluralForm := range pluralForms { dt := dst.PluralTemplates[pluralForm] if dt == nil || dt.Src == "" { if translateMessageTemplate == nil { translateMessageTemplate = &internal.MessageTemplate{ Message: &i18n.Message{ ID: src.ID, Description: src.Description, Hash: src.Hash, }, PluralTemplates: make(map[plural.Form]*internal.Template), } } translateMessageTemplate.PluralTemplates[pluralForm] = src.PluralTemplates[plural.Other] continue } if active == nil { active = &internal.MessageTemplate{ Message: &i18n.Message{ ID: src.ID, Description: src.Description, Hash: src.Hash, }, PluralTemplates: make(map[plural.Form]*internal.Template), } } active.PluralTemplates[pluralForm] = dt } return }
[ "func", "activeDst", "(", "src", ",", "dst", "*", "internal", ".", "MessageTemplate", ",", "pluralRule", "*", "plural", ".", "Rule", ")", "(", "active", "*", "internal", ".", "MessageTemplate", ",", "translateMessageTemplate", "*", "internal", ".", "MessageTem...
// activeDst returns the active part of the dst and whether dst is a complete translation of src.
[ "activeDst", "returns", "the", "active", "part", "of", "the", "dst", "and", "whether", "dst", "is", "a", "complete", "translation", "of", "src", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/goi18n/merge_command.go#L249-L285
train
nicksnyder/go-i18n
i18n/language/plural.go
NewPlural
func NewPlural(src string) (Plural, error) { switch src { case "zero": return Zero, nil case "one": return One, nil case "two": return Two, nil case "few": return Few, nil case "many": return Many, nil case "other": return Other, nil } return Invalid, fmt.Errorf("invalid plural category %s", src) }
go
func NewPlural(src string) (Plural, error) { switch src { case "zero": return Zero, nil case "one": return One, nil case "two": return Two, nil case "few": return Few, nil case "many": return Many, nil case "other": return Other, nil } return Invalid, fmt.Errorf("invalid plural category %s", src) }
[ "func", "NewPlural", "(", "src", "string", ")", "(", "Plural", ",", "error", ")", "{", "switch", "src", "{", "case", "\"zero\"", ":", "return", "Zero", ",", "nil", "\n", "case", "\"one\"", ":", "return", "One", ",", "nil", "\n", "case", "\"two\"", ":...
// NewPlural returns src as a Plural // or Invalid and a non-nil error if src is not a valid Plural.
[ "NewPlural", "returns", "src", "as", "a", "Plural", "or", "Invalid", "and", "a", "non", "-", "nil", "error", "if", "src", "is", "not", "a", "valid", "Plural", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/language/plural.go#L24-L40
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
New
func New() *Bundle { return &Bundle{ translations: make(map[string]map[string]translation.Translation), fallbackTranslations: make(map[string]map[string]translation.Translation), } }
go
func New() *Bundle { return &Bundle{ translations: make(map[string]map[string]translation.Translation), fallbackTranslations: make(map[string]map[string]translation.Translation), } }
[ "func", "New", "(", ")", "*", "Bundle", "{", "return", "&", "Bundle", "{", "translations", ":", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "translation", ".", "Translation", ")", ",", "fallbackTranslations", ":", "make", "(", "m...
// New returns an empty bundle.
[ "New", "returns", "an", "empty", "bundle", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L35-L40
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
MustLoadTranslationFile
func (b *Bundle) MustLoadTranslationFile(filename string) { if err := b.LoadTranslationFile(filename); err != nil { panic(err) } }
go
func (b *Bundle) MustLoadTranslationFile(filename string) { if err := b.LoadTranslationFile(filename); err != nil { panic(err) } }
[ "func", "(", "b", "*", "Bundle", ")", "MustLoadTranslationFile", "(", "filename", "string", ")", "{", "if", "err", ":=", "b", ".", "LoadTranslationFile", "(", "filename", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "...
// MustLoadTranslationFile is similar to LoadTranslationFile // except it panics if an error happens.
[ "MustLoadTranslationFile", "is", "similar", "to", "LoadTranslationFile", "except", "it", "panics", "if", "an", "error", "happens", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L44-L48
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
deleteLeadingComments
func deleteLeadingComments(ext string, buf []byte) []byte { if ext != ".yaml" { return buf } for { buf = bytes.TrimLeftFunc(buf, unicode.IsSpace) if buf[0] == '#' { buf = deleteLine(buf) } else { break } } return buf }
go
func deleteLeadingComments(ext string, buf []byte) []byte { if ext != ".yaml" { return buf } for { buf = bytes.TrimLeftFunc(buf, unicode.IsSpace) if buf[0] == '#' { buf = deleteLine(buf) } else { break } } return buf }
[ "func", "deleteLeadingComments", "(", "ext", "string", ",", "buf", "[", "]", "byte", ")", "[", "]", "byte", "{", "if", "ext", "!=", "\".yaml\"", "{", "return", "buf", "\n", "}", "\n", "for", "{", "buf", "=", "bytes", ".", "TrimLeftFunc", "(", "buf", ...
// deleteLeadingComments deletes leading newlines and comments in buf. // It only works for ext == ".yaml".
[ "deleteLeadingComments", "deletes", "leading", "newlines", "and", "comments", "in", "buf", ".", "It", "only", "works", "for", "ext", "==", ".", "yaml", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L129-L144
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
Translations
func (b *Bundle) Translations() map[string]map[string]translation.Translation { t := make(map[string]map[string]translation.Translation) b.RLock() for tag, translations := range b.translations { t[tag] = make(map[string]translation.Translation) for id, translation := range translations { t[tag][id] = translation } } b.RUnlock() return t }
go
func (b *Bundle) Translations() map[string]map[string]translation.Translation { t := make(map[string]map[string]translation.Translation) b.RLock() for tag, translations := range b.translations { t[tag] = make(map[string]translation.Translation) for id, translation := range translations { t[tag][id] = translation } } b.RUnlock() return t }
[ "func", "(", "b", "*", "Bundle", ")", "Translations", "(", ")", "map", "[", "string", "]", "map", "[", "string", "]", "translation", ".", "Translation", "{", "t", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "translation",...
// Translations returns all translations in the bundle.
[ "Translations", "returns", "all", "translations", "in", "the", "bundle", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L233-L244
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
LanguageTags
func (b *Bundle) LanguageTags() []string { var tags []string b.RLock() for k := range b.translations { tags = append(tags, k) } b.RUnlock() return tags }
go
func (b *Bundle) LanguageTags() []string { var tags []string b.RLock() for k := range b.translations { tags = append(tags, k) } b.RUnlock() return tags }
[ "func", "(", "b", "*", "Bundle", ")", "LanguageTags", "(", ")", "[", "]", "string", "{", "var", "tags", "[", "]", "string", "\n", "b", ".", "RLock", "(", ")", "\n", "for", "k", ":=", "range", "b", ".", "translations", "{", "tags", "=", "append", ...
// LanguageTags returns the tags of all languages that that have been added.
[ "LanguageTags", "returns", "the", "tags", "of", "all", "languages", "that", "that", "have", "been", "added", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L247-L255
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
LanguageTranslationIDs
func (b *Bundle) LanguageTranslationIDs(languageTag string) []string { var ids []string b.RLock() for id := range b.translations[languageTag] { ids = append(ids, id) } b.RUnlock() return ids }
go
func (b *Bundle) LanguageTranslationIDs(languageTag string) []string { var ids []string b.RLock() for id := range b.translations[languageTag] { ids = append(ids, id) } b.RUnlock() return ids }
[ "func", "(", "b", "*", "Bundle", ")", "LanguageTranslationIDs", "(", "languageTag", "string", ")", "[", "]", "string", "{", "var", "ids", "[", "]", "string", "\n", "b", ".", "RLock", "(", ")", "\n", "for", "id", ":=", "range", "b", ".", "translations...
// LanguageTranslationIDs returns the ids of all translations that have been added for a given language.
[ "LanguageTranslationIDs", "returns", "the", "ids", "of", "all", "translations", "that", "have", "been", "added", "for", "a", "given", "language", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L258-L266
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
Tfunc
func (b *Bundle) Tfunc(pref string, prefs ...string) (TranslateFunc, error) { tfunc, _, err := b.TfuncAndLanguage(pref, prefs...) return tfunc, err }
go
func (b *Bundle) Tfunc(pref string, prefs ...string) (TranslateFunc, error) { tfunc, _, err := b.TfuncAndLanguage(pref, prefs...) return tfunc, err }
[ "func", "(", "b", "*", "Bundle", ")", "Tfunc", "(", "pref", "string", ",", "prefs", "...", "string", ")", "(", "TranslateFunc", ",", "error", ")", "{", "tfunc", ",", "_", ",", "err", ":=", "b", ".", "TfuncAndLanguage", "(", "pref", ",", "prefs", "....
// Tfunc is similar to TfuncAndLanguage except is doesn't return the Language.
[ "Tfunc", "is", "similar", "to", "TfuncAndLanguage", "except", "is", "doesn", "t", "return", "the", "Language", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L287-L290
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
supportedLanguage
func (b *Bundle) supportedLanguage(pref string, prefs ...string) *language.Language { lang := b.translatedLanguage(pref) if lang == nil { for _, pref := range prefs { lang = b.translatedLanguage(pref) if lang != nil { break } } } return lang }
go
func (b *Bundle) supportedLanguage(pref string, prefs ...string) *language.Language { lang := b.translatedLanguage(pref) if lang == nil { for _, pref := range prefs { lang = b.translatedLanguage(pref) if lang != nil { break } } } return lang }
[ "func", "(", "b", "*", "Bundle", ")", "supportedLanguage", "(", "pref", "string", ",", "prefs", "...", "string", ")", "*", "language", ".", "Language", "{", "lang", ":=", "b", ".", "translatedLanguage", "(", "pref", ")", "\n", "if", "lang", "==", "nil"...
// supportedLanguage returns the first language which // has a non-zero number of translations in the bundle.
[ "supportedLanguage", "returns", "the", "first", "language", "which", "has", "a", "non", "-", "zero", "number", "of", "translations", "in", "the", "bundle", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L316-L327
train
nicksnyder/go-i18n
v2/internal/plural/rules.go
Rule
func (r Rules) Rule(tag language.Tag) *Rule { t := tag for { if rule := r[t]; rule != nil { return rule } t = t.Parent() if t.IsRoot() { break } } base, _ := tag.Base() baseTag, _ := language.Parse(base.String()) return r[baseTag] }
go
func (r Rules) Rule(tag language.Tag) *Rule { t := tag for { if rule := r[t]; rule != nil { return rule } t = t.Parent() if t.IsRoot() { break } } base, _ := tag.Base() baseTag, _ := language.Parse(base.String()) return r[baseTag] }
[ "func", "(", "r", "Rules", ")", "Rule", "(", "tag", "language", ".", "Tag", ")", "*", "Rule", "{", "t", ":=", "tag", "\n", "for", "{", "if", "rule", ":=", "r", "[", "t", "]", ";", "rule", "!=", "nil", "{", "return", "rule", "\n", "}", "\n", ...
// Rule returns the closest matching plural rule for the language tag // or nil if no rule could be found.
[ "Rule", "returns", "the", "closest", "matching", "plural", "rule", "for", "the", "language", "tag", "or", "nil", "if", "no", "rule", "could", "be", "found", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/internal/plural/rules.go#L10-L24
train
jdkato/prose
tag/tag.go
ReadTagged
func ReadTagged(text, sep string) TupleSlice { t := TupleSlice{} for _, sent := range strings.Split(text, "\n") { tokens := []string{} tags := []string{} for _, token := range strings.Split(sent, " ") { parts := strings.Split(token, sep) tokens = append(tokens, parts[0]) tags = append(tags, parts[1]) } t = append(t, [][]string{tokens, tags}) } return t }
go
func ReadTagged(text, sep string) TupleSlice { t := TupleSlice{} for _, sent := range strings.Split(text, "\n") { tokens := []string{} tags := []string{} for _, token := range strings.Split(sent, " ") { parts := strings.Split(token, sep) tokens = append(tokens, parts[0]) tags = append(tags, parts[1]) } t = append(t, [][]string{tokens, tags}) } return t }
[ "func", "ReadTagged", "(", "text", ",", "sep", "string", ")", "TupleSlice", "{", "t", ":=", "TupleSlice", "{", "}", "\n", "for", "_", ",", "sent", ":=", "range", "strings", ".", "Split", "(", "text", ",", "\"\\n\"", ")", "\\n", "\n", "{", "tokens", ...
// ReadTagged converts pre-tagged input into a TupleSlice suitable for training.
[ "ReadTagged", "converts", "pre", "-", "tagged", "input", "into", "a", "TupleSlice", "suitable", "for", "training", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tag/tag.go#L24-L37
train
jdkato/prose
tokenize/regexp.go
Tokenize
func (r RegexpTokenizer) Tokenize(text string) []string { var tokens []string if r.gaps { temp := r.regex.Split(text, -1) if r.discard { for _, s := range temp { if s != "" { tokens = append(tokens, s) } } } else { tokens = temp } } else { tokens = r.regex.FindAllString(text, -1) } return tokens }
go
func (r RegexpTokenizer) Tokenize(text string) []string { var tokens []string if r.gaps { temp := r.regex.Split(text, -1) if r.discard { for _, s := range temp { if s != "" { tokens = append(tokens, s) } } } else { tokens = temp } } else { tokens = r.regex.FindAllString(text, -1) } return tokens }
[ "func", "(", "r", "RegexpTokenizer", ")", "Tokenize", "(", "text", "string", ")", "[", "]", "string", "{", "var", "tokens", "[", "]", "string", "\n", "if", "r", ".", "gaps", "{", "temp", ":=", "r", ".", "regex", ".", "Split", "(", "text", ",", "-...
// Tokenize splits text into a slice of tokens according to its regexp pattern.
[ "Tokenize", "splits", "text", "into", "a", "slice", "of", "tokens", "according", "to", "its", "regexp", "pattern", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/regexp.go#L23-L40
train
jdkato/prose
tokenize/regexp.go
NewBlanklineTokenizer
func NewBlanklineTokenizer() *RegexpTokenizer { return &RegexpTokenizer{ regex: regexp.MustCompile(`\s*\n\s*\n\s*`), gaps: true, discard: true} }
go
func NewBlanklineTokenizer() *RegexpTokenizer { return &RegexpTokenizer{ regex: regexp.MustCompile(`\s*\n\s*\n\s*`), gaps: true, discard: true} }
[ "func", "NewBlanklineTokenizer", "(", ")", "*", "RegexpTokenizer", "{", "return", "&", "RegexpTokenizer", "{", "regex", ":", "regexp", ".", "MustCompile", "(", "`\\s*\\n\\s*\\n\\s*`", ")", ",", "gaps", ":", "true", ",", "discard", ":", "true", "}", "\n", "}"...
// NewBlanklineTokenizer is a RegexpTokenizer constructor. // // This tokenizer splits on any sequence of blank lines.
[ "NewBlanklineTokenizer", "is", "a", "RegexpTokenizer", "constructor", ".", "This", "tokenizer", "splits", "on", "any", "sequence", "of", "blank", "lines", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/regexp.go#L45-L48
train
jdkato/prose
chunk/chunk.go
quadsString
func quadsString(tagged []tag.Token) string { tagQuads := "" for _, tok := range tagged { padding := "" pos := tok.Tag switch len(pos) { case 0: padding = "____" // should not exist case 1: padding = "___" case 2: padding = "__" case 3: padding = "_" case 4: // no padding required default: pos = pos[:4] // longer than 4 ... truncate! } tagQuads += pos + padding } return tagQuads }
go
func quadsString(tagged []tag.Token) string { tagQuads := "" for _, tok := range tagged { padding := "" pos := tok.Tag switch len(pos) { case 0: padding = "____" // should not exist case 1: padding = "___" case 2: padding = "__" case 3: padding = "_" case 4: // no padding required default: pos = pos[:4] // longer than 4 ... truncate! } tagQuads += pos + padding } return tagQuads }
[ "func", "quadsString", "(", "tagged", "[", "]", "tag", ".", "Token", ")", "string", "{", "tagQuads", ":=", "\"\"", "\n", "for", "_", ",", "tok", ":=", "range", "tagged", "{", "padding", ":=", "\"\"", "\n", "pos", ":=", "tok", ".", "Tag", "\n", "swi...
// quadString creates a string containing all of the tags, each padded to 4 // characters wide.
[ "quadString", "creates", "a", "string", "containing", "all", "of", "the", "tags", "each", "padded", "to", "4", "characters", "wide", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/chunk/chunk.go#L13-L34
train
jdkato/prose
chunk/chunk.go
Chunk
func Chunk(tagged []tag.Token, rx *regexp.Regexp) []string { chunks := []string{} for _, loc := range Locate(tagged, rx) { res := "" for t, tt := range tagged[loc[0]:loc[1]] { if t != 0 { res += " " } res += tt.Text } chunks = append(chunks, res) } return chunks }
go
func Chunk(tagged []tag.Token, rx *regexp.Regexp) []string { chunks := []string{} for _, loc := range Locate(tagged, rx) { res := "" for t, tt := range tagged[loc[0]:loc[1]] { if t != 0 { res += " " } res += tt.Text } chunks = append(chunks, res) } return chunks }
[ "func", "Chunk", "(", "tagged", "[", "]", "tag", ".", "Token", ",", "rx", "*", "regexp", ".", "Regexp", ")", "[", "]", "string", "{", "chunks", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "loc", ":=", "range", "Locate", "(", "tag...
// Chunk returns a slice containing the chunks of interest according to the // regexp. // // This is a convenience wrapper around Locate, which should be used if you // need access the to the in-text locations of each chunk.
[ "Chunk", "returns", "a", "slice", "containing", "the", "chunks", "of", "interest", "according", "to", "the", "regexp", ".", "This", "is", "a", "convenience", "wrapper", "around", "Locate", "which", "should", "be", "used", "if", "you", "need", "access", "the"...
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/chunk/chunk.go#L48-L61
train
jdkato/prose
chunk/chunk.go
Locate
func Locate(tagged []tag.Token, rx *regexp.Regexp) [][]int { rx.Longest() // make sure we find the longest possible sequences rs := rx.FindAllStringIndex(quadsString(tagged), -1) for i, ii := range rs { for j := range ii { // quadsString makes every offset 4x what it should be rs[i][j] /= 4 } } return rs }
go
func Locate(tagged []tag.Token, rx *regexp.Regexp) [][]int { rx.Longest() // make sure we find the longest possible sequences rs := rx.FindAllStringIndex(quadsString(tagged), -1) for i, ii := range rs { for j := range ii { // quadsString makes every offset 4x what it should be rs[i][j] /= 4 } } return rs }
[ "func", "Locate", "(", "tagged", "[", "]", "tag", ".", "Token", ",", "rx", "*", "regexp", ".", "Regexp", ")", "[", "]", "[", "]", "int", "{", "rx", ".", "Longest", "(", ")", "\n", "rs", ":=", "rx", ".", "FindAllStringIndex", "(", "quadsString", "...
// Locate finds the chunks of interest according to the regexp.
[ "Locate", "finds", "the", "chunks", "of", "interest", "according", "to", "the", "regexp", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/chunk/chunk.go#L64-L74
train
jdkato/prose
transform/title.go
Title
func (tc *TitleConverter) Title(s string) string { idx, pos := 0, 0 t := sanitizer.Replace(s) end := len(t) return splitRE.ReplaceAllStringFunc(s, func(m string) string { sm := strings.ToLower(m) pos = strings.Index(t[idx:], m) + idx prev := charAt(t, pos-1) ext := utf8.RuneCountInString(m) idx = pos + ext if tc.ignore(sm, pos == 0 || idx == end) && (prev == ' ' || prev == '-' || prev == '/') && charAt(t, pos-2) != ':' && charAt(t, pos-2) != '-' && (charAt(t, pos+ext) != '-' || charAt(t, pos-1) == '-') { return sm } return toTitle(m, prev) }) }
go
func (tc *TitleConverter) Title(s string) string { idx, pos := 0, 0 t := sanitizer.Replace(s) end := len(t) return splitRE.ReplaceAllStringFunc(s, func(m string) string { sm := strings.ToLower(m) pos = strings.Index(t[idx:], m) + idx prev := charAt(t, pos-1) ext := utf8.RuneCountInString(m) idx = pos + ext if tc.ignore(sm, pos == 0 || idx == end) && (prev == ' ' || prev == '-' || prev == '/') && charAt(t, pos-2) != ':' && charAt(t, pos-2) != '-' && (charAt(t, pos+ext) != '-' || charAt(t, pos-1) == '-') { return sm } return toTitle(m, prev) }) }
[ "func", "(", "tc", "*", "TitleConverter", ")", "Title", "(", "s", "string", ")", "string", "{", "idx", ",", "pos", ":=", "0", ",", "0", "\n", "t", ":=", "sanitizer", ".", "Replace", "(", "s", ")", "\n", "end", ":=", "len", "(", "t", ")", "\n", ...
// Title returns a copy of the string s in title case format.
[ "Title", "returns", "a", "copy", "of", "the", "string", "s", "in", "title", "case", "format", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/transform/title.go#L43-L61
train
jdkato/prose
transform/title.go
charAt
func charAt(s string, i int) byte { if i >= 0 && i < len(s) { return s[i] } return s[0] }
go
func charAt(s string, i int) byte { if i >= 0 && i < len(s) { return s[i] } return s[0] }
[ "func", "charAt", "(", "s", "string", ",", "i", "int", ")", "byte", "{", "if", "i", ">=", "0", "&&", "i", "<", "len", "(", "s", ")", "{", "return", "s", "[", "i", "]", "\n", "}", "\n", "return", "s", "[", "0", "]", "\n", "}" ]
// charAt returns the ith character of s, if it exists. Otherwise, it returns // the first character.
[ "charAt", "returns", "the", "ith", "character", "of", "s", "if", "it", "exists", ".", "Otherwise", "it", "returns", "the", "first", "character", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/transform/title.go#L96-L101
train
jdkato/prose
transform/title.go
toTitle
func toTitle(m string, prev byte) string { r, size := utf8.DecodeRuneInString(m) return string(unicode.ToTitle(r)) + m[size:] }
go
func toTitle(m string, prev byte) string { r, size := utf8.DecodeRuneInString(m) return string(unicode.ToTitle(r)) + m[size:] }
[ "func", "toTitle", "(", "m", "string", ",", "prev", "byte", ")", "string", "{", "r", ",", "size", ":=", "utf8", ".", "DecodeRuneInString", "(", "m", ")", "\n", "return", "string", "(", "unicode", ".", "ToTitle", "(", "r", ")", ")", "+", "m", "[", ...
// toTitle returns a copy of the string m with its first Unicode letter mapped // to its title case.
[ "toTitle", "returns", "a", "copy", "of", "the", "string", "m", "with", "its", "first", "Unicode", "letter", "mapped", "to", "its", "title", "case", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/transform/title.go#L105-L108
train
jdkato/prose
tag/aptag.go
NewAveragedPerceptron
func NewAveragedPerceptron(weights map[string]map[string]float64, tags map[string]string, classes []string) *AveragedPerceptron { return &AveragedPerceptron{ totals: make(map[string]float64), stamps: make(map[string]float64), classes: classes, tagMap: tags, weights: weights} }
go
func NewAveragedPerceptron(weights map[string]map[string]float64, tags map[string]string, classes []string) *AveragedPerceptron { return &AveragedPerceptron{ totals: make(map[string]float64), stamps: make(map[string]float64), classes: classes, tagMap: tags, weights: weights} }
[ "func", "NewAveragedPerceptron", "(", "weights", "map", "[", "string", "]", "map", "[", "string", "]", "float64", ",", "tags", "map", "[", "string", "]", "string", ",", "classes", "[", "]", "string", ")", "*", "AveragedPerceptron", "{", "return", "&", "A...
// NewAveragedPerceptron creates a new AveragedPerceptron model.
[ "NewAveragedPerceptron", "creates", "a", "new", "AveragedPerceptron", "model", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tag/aptag.go#L48-L53
train
jdkato/prose
tag/aptag.go
NewPerceptronTagger
func NewPerceptronTagger() *PerceptronTagger { var wts map[string]map[string]float64 var tags map[string]string var classes []string dec := model.GetAsset("classes.gob") util.CheckError(dec.Decode(&classes)) dec = model.GetAsset("tags.gob") util.CheckError(dec.Decode(&tags)) dec = model.GetAsset("weights.gob") util.CheckError(dec.Decode(&wts)) return &PerceptronTagger{model: NewAveragedPerceptron(wts, tags, classes)} }
go
func NewPerceptronTagger() *PerceptronTagger { var wts map[string]map[string]float64 var tags map[string]string var classes []string dec := model.GetAsset("classes.gob") util.CheckError(dec.Decode(&classes)) dec = model.GetAsset("tags.gob") util.CheckError(dec.Decode(&tags)) dec = model.GetAsset("weights.gob") util.CheckError(dec.Decode(&wts)) return &PerceptronTagger{model: NewAveragedPerceptron(wts, tags, classes)} }
[ "func", "NewPerceptronTagger", "(", ")", "*", "PerceptronTagger", "{", "var", "wts", "map", "[", "string", "]", "map", "[", "string", "]", "float64", "\n", "var", "tags", "map", "[", "string", "]", "string", "\n", "var", "classes", "[", "]", "string", ...
// NewPerceptronTagger creates a new PerceptronTagger and loads the built-in // AveragedPerceptron model.
[ "NewPerceptronTagger", "creates", "a", "new", "PerceptronTagger", "and", "loads", "the", "built", "-", "in", "AveragedPerceptron", "model", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tag/aptag.go#L64-L79
train
jdkato/prose
tag/aptag.go
Tag
func (pt *PerceptronTagger) Tag(words []string) []Token { var tokens []Token var clean []string var tag string var found bool p1, p2 := "-START-", "-START2-" context := []string{p1, p2} for _, w := range words { if w == "" { continue } context = append(context, normalize(w)) clean = append(clean, w) } context = append(context, []string{"-END-", "-END2-"}...) for i, word := range clean { if none.MatchString(word) { tag = "-NONE-" } else if keep.MatchString(word) { tag = word } else if tag, found = pt.model.tagMap[word]; !found { tag = pt.model.predict(featurize(i, context, word, p1, p2)) } tokens = append(tokens, Token{Tag: tag, Text: word}) p2 = p1 p1 = tag } return tokens }
go
func (pt *PerceptronTagger) Tag(words []string) []Token { var tokens []Token var clean []string var tag string var found bool p1, p2 := "-START-", "-START2-" context := []string{p1, p2} for _, w := range words { if w == "" { continue } context = append(context, normalize(w)) clean = append(clean, w) } context = append(context, []string{"-END-", "-END2-"}...) for i, word := range clean { if none.MatchString(word) { tag = "-NONE-" } else if keep.MatchString(word) { tag = word } else if tag, found = pt.model.tagMap[word]; !found { tag = pt.model.predict(featurize(i, context, word, p1, p2)) } tokens = append(tokens, Token{Tag: tag, Text: word}) p2 = p1 p1 = tag } return tokens }
[ "func", "(", "pt", "*", "PerceptronTagger", ")", "Tag", "(", "words", "[", "]", "string", ")", "[", "]", "Token", "{", "var", "tokens", "[", "]", "Token", "\n", "var", "clean", "[", "]", "string", "\n", "var", "tag", "string", "\n", "var", "found",...
// Tag takes a slice of words and returns a slice of tagged tokens.
[ "Tag", "takes", "a", "slice", "of", "words", "and", "returns", "a", "slice", "of", "tagged", "tokens", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tag/aptag.go#L120-L150
train
jdkato/prose
tag/aptag.go
Train
func (pt *PerceptronTagger) Train(sentences TupleSlice, iterations int) { var guess string var found bool pt.makeTagMap(sentences) for i := 0; i < iterations; i++ { for _, tuple := range sentences { words, tags := tuple[0], tuple[1] p1, p2 := "-START-", "-START2-" context := []string{p1, p2} for _, w := range words { if w == "" { continue } context = append(context, normalize(w)) } context = append(context, []string{"-END-", "-END2-"}...) for i, word := range words { if guess, found = pt.tagMap[word]; !found { feats := featurize(i, context, word, p1, p2) guess = pt.model.predict(feats) pt.model.update(tags[i], guess, feats) } p2 = p1 p1 = guess } } shuffle.Shuffle(sentences) } pt.model.averageWeights() }
go
func (pt *PerceptronTagger) Train(sentences TupleSlice, iterations int) { var guess string var found bool pt.makeTagMap(sentences) for i := 0; i < iterations; i++ { for _, tuple := range sentences { words, tags := tuple[0], tuple[1] p1, p2 := "-START-", "-START2-" context := []string{p1, p2} for _, w := range words { if w == "" { continue } context = append(context, normalize(w)) } context = append(context, []string{"-END-", "-END2-"}...) for i, word := range words { if guess, found = pt.tagMap[word]; !found { feats := featurize(i, context, word, p1, p2) guess = pt.model.predict(feats) pt.model.update(tags[i], guess, feats) } p2 = p1 p1 = guess } } shuffle.Shuffle(sentences) } pt.model.averageWeights() }
[ "func", "(", "pt", "*", "PerceptronTagger", ")", "Train", "(", "sentences", "TupleSlice", ",", "iterations", "int", ")", "{", "var", "guess", "string", "\n", "var", "found", "bool", "\n", "pt", ".", "makeTagMap", "(", "sentences", ")", "\n", "for", "i", ...
// Train an Averaged Perceptron model based on sentences.
[ "Train", "an", "Averaged", "Perceptron", "model", "based", "on", "sentences", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tag/aptag.go#L153-L183
train
jdkato/prose
transform/transform.go
Pascal
func Pascal(s string) string { out := "" wasSpace := false for i, c := range removeCase(s, " ", unicode.ToLower) { if i == 0 || wasSpace { c = unicode.ToUpper(c) } wasSpace = c == ' ' if !wasSpace { out += string(c) } } return out }
go
func Pascal(s string) string { out := "" wasSpace := false for i, c := range removeCase(s, " ", unicode.ToLower) { if i == 0 || wasSpace { c = unicode.ToUpper(c) } wasSpace = c == ' ' if !wasSpace { out += string(c) } } return out }
[ "func", "Pascal", "(", "s", "string", ")", "string", "{", "out", ":=", "\"\"", "\n", "wasSpace", ":=", "false", "\n", "for", "i", ",", "c", ":=", "range", "removeCase", "(", "s", ",", "\" \"", ",", "unicode", ".", "ToLower", ")", "{", "if", "i", ...
// Pascal returns a Pascal-cased copy of the string s.
[ "Pascal", "returns", "a", "Pascal", "-", "cased", "copy", "of", "the", "string", "s", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/transform/transform.go#L57-L70
train
jdkato/prose
transform/transform.go
Camel
func Camel(s string) string { first := ' ' for _, c := range s { if unicode.IsLetter(c) || unicode.IsNumber(c) { first = c break } } return strings.TrimSpace(string(unicode.ToLower(first)) + Pascal(s)[1:]) }
go
func Camel(s string) string { first := ' ' for _, c := range s { if unicode.IsLetter(c) || unicode.IsNumber(c) { first = c break } } return strings.TrimSpace(string(unicode.ToLower(first)) + Pascal(s)[1:]) }
[ "func", "Camel", "(", "s", "string", ")", "string", "{", "first", ":=", "' '", "\n", "for", "_", ",", "c", ":=", "range", "s", "{", "if", "unicode", ".", "IsLetter", "(", "c", ")", "||", "unicode", ".", "IsNumber", "(", "c", ")", "{", "first", ...
// Camel returns a Camel-cased copy of the string s.
[ "Camel", "returns", "a", "Camel", "-", "cased", "copy", "of", "the", "string", "s", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/transform/transform.go#L73-L82
train
jdkato/prose
internal/util/util.go
ReadDataFile
func ReadDataFile(path string) []byte { p, err := filepath.Abs(path) CheckError(err) data, ferr := ioutil.ReadFile(p) CheckError(ferr) return data }
go
func ReadDataFile(path string) []byte { p, err := filepath.Abs(path) CheckError(err) data, ferr := ioutil.ReadFile(p) CheckError(ferr) return data }
[ "func", "ReadDataFile", "(", "path", "string", ")", "[", "]", "byte", "{", "p", ",", "err", ":=", "filepath", ".", "Abs", "(", "path", ")", "\n", "CheckError", "(", "err", ")", "\n", "data", ",", "ferr", ":=", "ioutil", ".", "ReadFile", "(", "p", ...
// ReadDataFile reads data from a file, panicking on any errors.
[ "ReadDataFile", "reads", "data", "from", "a", "file", "panicking", "on", "any", "errors", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/util/util.go#L13-L21
train
jdkato/prose
internal/util/util.go
IsPunct
func IsPunct(c byte) bool { for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") { if c == r { return true } } return false }
go
func IsPunct(c byte) bool { for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") { if c == r { return true } } return false }
[ "func", "IsPunct", "(", "c", "byte", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "[", "]", "byte", "(", "\"!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~\"", ")", "\\\"", "\n", "\\\\", "\n", "}" ]
// IsPunct determines if a character is a punctuation symbol.
[ "IsPunct", "determines", "if", "a", "character", "is", "a", "punctuation", "symbol", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/util/util.go#L39-L46
train
jdkato/prose
internal/util/util.go
IsSpace
func IsSpace(c byte) bool { for _, r := range []byte("\t\n\r\f\v") { if c == r { return true } } return false }
go
func IsSpace(c byte) bool { for _, r := range []byte("\t\n\r\f\v") { if c == r { return true } } return false }
[ "func", "IsSpace", "(", "c", "byte", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "[", "]", "byte", "(", "\"\\t\\n\\r\\f\\v\"", ")", "\\t", "\n", "\\n", "\n", "}" ]
// IsSpace determines if a character is a whitespace character.
[ "IsSpace", "determines", "if", "a", "character", "is", "a", "whitespace", "character", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/util/util.go#L49-L56
train
jdkato/prose
internal/util/util.go
HasAnySuffix
func HasAnySuffix(a string, slice []string) bool { for _, b := range slice { if strings.HasSuffix(a, b) { return true } } return false }
go
func HasAnySuffix(a string, slice []string) bool { for _, b := range slice { if strings.HasSuffix(a, b) { return true } } return false }
[ "func", "HasAnySuffix", "(", "a", "string", ",", "slice", "[", "]", "string", ")", "bool", "{", "for", "_", ",", "b", ":=", "range", "slice", "{", "if", "strings", ".", "HasSuffix", "(", "a", ",", "b", ")", "{", "return", "true", "\n", "}", "\n",...
// HasAnySuffix determines if the string a has any suffixes contained in the // slice b.
[ "HasAnySuffix", "determines", "if", "the", "string", "a", "has", "any", "suffixes", "contained", "in", "the", "slice", "b", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/util/util.go#L80-L87
train
jdkato/prose
internal/util/util.go
ContainsAny
func ContainsAny(a string, b []string) bool { for _, s := range b { if strings.Contains(a, s) { return true } } return false }
go
func ContainsAny(a string, b []string) bool { for _, s := range b { if strings.Contains(a, s) { return true } } return false }
[ "func", "ContainsAny", "(", "a", "string", ",", "b", "[", "]", "string", ")", "bool", "{", "for", "_", ",", "s", ":=", "range", "b", "{", "if", "strings", ".", "Contains", "(", "a", ",", "s", ")", "{", "return", "true", "\n", "}", "\n", "}", ...
// ContainsAny determines if the string a contains any fo the strings contained // in the slice b.
[ "ContainsAny", "determines", "if", "the", "string", "a", "contains", "any", "fo", "the", "strings", "contained", "in", "the", "slice", "b", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/util/util.go#L91-L98
train
jdkato/prose
summarize/usage.go
WordDensity
func (d *Document) WordDensity() map[string]float64 { density := make(map[string]float64) for word, freq := range d.WordFrequency { val, _ := stats.Round(float64(freq)/d.NumWords, 3) density[word] = val } return density }
go
func (d *Document) WordDensity() map[string]float64 { density := make(map[string]float64) for word, freq := range d.WordFrequency { val, _ := stats.Round(float64(freq)/d.NumWords, 3) density[word] = val } return density }
[ "func", "(", "d", "*", "Document", ")", "WordDensity", "(", ")", "map", "[", "string", "]", "float64", "{", "density", ":=", "make", "(", "map", "[", "string", "]", "float64", ")", "\n", "for", "word", ",", "freq", ":=", "range", "d", ".", "WordFre...
// WordDensity returns a map of each word and its density.
[ "WordDensity", "returns", "a", "map", "of", "each", "word", "and", "its", "density", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/usage.go#L11-L18
train
jdkato/prose
summarize/usage.go
MeanWordLength
func (d *Document) MeanWordLength() float64 { val, _ := stats.Round(d.NumCharacters/d.NumWords, 3) return val }
go
func (d *Document) MeanWordLength() float64 { val, _ := stats.Round(d.NumCharacters/d.NumWords, 3) return val }
[ "func", "(", "d", "*", "Document", ")", "MeanWordLength", "(", ")", "float64", "{", "val", ",", "_", ":=", "stats", ".", "Round", "(", "d", ".", "NumCharacters", "/", "d", ".", "NumWords", ",", "3", ")", "\n", "return", "val", "\n", "}" ]
// MeanWordLength returns the mean number of characters per word.
[ "MeanWordLength", "returns", "the", "mean", "number", "of", "characters", "per", "word", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/usage.go#L42-L45
train
jdkato/prose
internal/model/load.go
GetAsset
func GetAsset(name string) *gob.Decoder { b, err := Asset("internal/model/" + name) util.CheckError(err) return gob.NewDecoder(bytes.NewReader(b)) }
go
func GetAsset(name string) *gob.Decoder { b, err := Asset("internal/model/" + name) util.CheckError(err) return gob.NewDecoder(bytes.NewReader(b)) }
[ "func", "GetAsset", "(", "name", "string", ")", "*", "gob", ".", "Decoder", "{", "b", ",", "err", ":=", "Asset", "(", "\"internal/model/\"", "+", "name", ")", "\n", "util", ".", "CheckError", "(", "err", ")", "\n", "return", "gob", ".", "NewDecoder", ...
// GetAsset returns the named Asset.
[ "GetAsset", "returns", "the", "named", "Asset", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/model/load.go#L14-L18
train
jdkato/prose
summarize/summarize.go
NewDocument
func NewDocument(text string) *Document { wTok := tokenize.NewWordBoundaryTokenizer() sTok := tokenize.NewPunktSentenceTokenizer() doc := Document{Content: text, WordTokenizer: wTok, SentenceTokenizer: sTok} doc.Initialize() return &doc }
go
func NewDocument(text string) *Document { wTok := tokenize.NewWordBoundaryTokenizer() sTok := tokenize.NewPunktSentenceTokenizer() doc := Document{Content: text, WordTokenizer: wTok, SentenceTokenizer: sTok} doc.Initialize() return &doc }
[ "func", "NewDocument", "(", "text", "string", ")", "*", "Document", "{", "wTok", ":=", "tokenize", ".", "NewWordBoundaryTokenizer", "(", ")", "\n", "sTok", ":=", "tokenize", ".", "NewPunktSentenceTokenizer", "(", ")", "\n", "doc", ":=", "Document", "{", "Con...
// NewDocument is a Document constructor that takes a string as an argument. It // then calculates the data necessary for computing readability and usage // statistics. // // This is a convenience wrapper around the Document initialization process // that defaults to using a WordBoundaryTokenizer and a PunktSentenceTokenizer // as its word and sentence tokenizers, respectively.
[ "NewDocument", "is", "a", "Document", "constructor", "that", "takes", "a", "string", "as", "an", "argument", ".", "It", "then", "calculates", "the", "data", "necessary", "for", "computing", "readability", "and", "usage", "statistics", ".", "This", "is", "a", ...
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/summarize.go#L88-L94
train
jdkato/prose
summarize/summarize.go
Initialize
func (d *Document) Initialize() { d.WordFrequency = make(map[string]int) for i, paragraph := range strings.Split(d.Content, "\n\n") { for _, s := range d.SentenceTokenizer.Tokenize(paragraph) { wordCount := d.NumWords d.NumSentences++ words := []Word{} for _, word := range d.WordTokenizer.Tokenize(s) { word = strings.TrimSpace(word) if len(word) == 0 { continue } d.NumCharacters += countChars(word) if _, found := d.WordFrequency[word]; found { d.WordFrequency[word]++ } else { d.WordFrequency[word] = 1 } syllables := Syllables(word) words = append(words, Word{Text: word, Syllables: syllables}) d.NumSyllables += float64(syllables) if syllables > 2 { d.NumPolysylWords++ } if isComplex(word, syllables) { d.NumComplexWords++ } d.NumWords++ } d.Sentences = append(d.Sentences, Sentence{ Text: strings.TrimSpace(s), Length: int(d.NumWords - wordCount), Words: words, Paragraph: i}) } d.NumParagraphs++ } }
go
func (d *Document) Initialize() { d.WordFrequency = make(map[string]int) for i, paragraph := range strings.Split(d.Content, "\n\n") { for _, s := range d.SentenceTokenizer.Tokenize(paragraph) { wordCount := d.NumWords d.NumSentences++ words := []Word{} for _, word := range d.WordTokenizer.Tokenize(s) { word = strings.TrimSpace(word) if len(word) == 0 { continue } d.NumCharacters += countChars(word) if _, found := d.WordFrequency[word]; found { d.WordFrequency[word]++ } else { d.WordFrequency[word] = 1 } syllables := Syllables(word) words = append(words, Word{Text: word, Syllables: syllables}) d.NumSyllables += float64(syllables) if syllables > 2 { d.NumPolysylWords++ } if isComplex(word, syllables) { d.NumComplexWords++ } d.NumWords++ } d.Sentences = append(d.Sentences, Sentence{ Text: strings.TrimSpace(s), Length: int(d.NumWords - wordCount), Words: words, Paragraph: i}) } d.NumParagraphs++ } }
[ "func", "(", "d", "*", "Document", ")", "Initialize", "(", ")", "{", "d", ".", "WordFrequency", "=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "for", "i", ",", "paragraph", ":=", "range", "strings", ".", "Split", "(", "d", ".", "C...
// Initialize calculates the data necessary for computing readability and usage // statistics.
[ "Initialize", "calculates", "the", "data", "necessary", "for", "computing", "readability", "and", "usage", "statistics", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/summarize.go#L98-L135
train
jdkato/prose
summarize/summarize.go
Assess
func (d *Document) Assess() *Assessment { a := Assessment{ FleschKincaid: d.FleschKincaid(), ReadingEase: d.FleschReadingEase(), GunningFog: d.GunningFog(), SMOG: d.SMOG(), DaleChall: d.DaleChall(), AutomatedReadability: d.AutomatedReadability(), ColemanLiau: d.ColemanLiau()} gradeScores := []float64{ a.FleschKincaid, a.AutomatedReadability, a.GunningFog, a.SMOG, a.ColemanLiau} mean, merr := stats.Mean(gradeScores) stdDev, serr := stats.StandardDeviation(gradeScores) if merr != nil || serr != nil { a.MeanGradeLevel = 0.0 a.StdDevGradeLevel = 0.0 } else { a.MeanGradeLevel = mean a.StdDevGradeLevel = stdDev } return &a }
go
func (d *Document) Assess() *Assessment { a := Assessment{ FleschKincaid: d.FleschKincaid(), ReadingEase: d.FleschReadingEase(), GunningFog: d.GunningFog(), SMOG: d.SMOG(), DaleChall: d.DaleChall(), AutomatedReadability: d.AutomatedReadability(), ColemanLiau: d.ColemanLiau()} gradeScores := []float64{ a.FleschKincaid, a.AutomatedReadability, a.GunningFog, a.SMOG, a.ColemanLiau} mean, merr := stats.Mean(gradeScores) stdDev, serr := stats.StandardDeviation(gradeScores) if merr != nil || serr != nil { a.MeanGradeLevel = 0.0 a.StdDevGradeLevel = 0.0 } else { a.MeanGradeLevel = mean a.StdDevGradeLevel = stdDev } return &a }
[ "func", "(", "d", "*", "Document", ")", "Assess", "(", ")", "*", "Assessment", "{", "a", ":=", "Assessment", "{", "FleschKincaid", ":", "d", ".", "FleschKincaid", "(", ")", ",", "ReadingEase", ":", "d", ".", "FleschReadingEase", "(", ")", ",", "Gunning...
// Assess returns an Assessment for the Document d.
[ "Assess", "returns", "an", "Assessment", "for", "the", "Document", "d", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/summarize.go#L138-L159
train
jdkato/prose
summarize/summarize.go
Summary
func (d *Document) Summary(n int) []RankedParagraph { rankings := []RankedParagraph{} scores := d.Keywords() for i := 0; i < int(d.NumParagraphs); i++ { p := RankedParagraph{Position: i} rank := 0 size := 0 for _, s := range d.Sentences { if s.Paragraph == i { size += s.Length for _, w := range s.Words { if score, found := scores[w.Text]; found { rank += score } } p.Sentences = append(p.Sentences, s) } } // Favor longer paragraphs, as they tend to be more informational. p.Rank = (rank * size) rankings = append(rankings, p) } // Sort by raking: sort.Sort(byRank(rankings)) // Take the top-n paragraphs: size := len(rankings) if size > n { rankings = rankings[size-n:] } // Sort by chronological position: sort.Sort(byIndex(rankings)) return rankings }
go
func (d *Document) Summary(n int) []RankedParagraph { rankings := []RankedParagraph{} scores := d.Keywords() for i := 0; i < int(d.NumParagraphs); i++ { p := RankedParagraph{Position: i} rank := 0 size := 0 for _, s := range d.Sentences { if s.Paragraph == i { size += s.Length for _, w := range s.Words { if score, found := scores[w.Text]; found { rank += score } } p.Sentences = append(p.Sentences, s) } } // Favor longer paragraphs, as they tend to be more informational. p.Rank = (rank * size) rankings = append(rankings, p) } // Sort by raking: sort.Sort(byRank(rankings)) // Take the top-n paragraphs: size := len(rankings) if size > n { rankings = rankings[size-n:] } // Sort by chronological position: sort.Sort(byIndex(rankings)) return rankings }
[ "func", "(", "d", "*", "Document", ")", "Summary", "(", "n", "int", ")", "[", "]", "RankedParagraph", "{", "rankings", ":=", "[", "]", "RankedParagraph", "{", "}", "\n", "scores", ":=", "d", ".", "Keywords", "(", ")", "\n", "for", "i", ":=", "0", ...
// Summary returns a Document's n highest ranked paragraphs according to // keyword frequency.
[ "Summary", "returns", "a", "Document", "s", "n", "highest", "ranked", "paragraphs", "according", "to", "keyword", "frequency", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/summarize.go#L163-L198
train
jdkato/prose
tokenize/punkt.go
NewPunktSentenceTokenizer
func NewPunktSentenceTokenizer() *PunktSentenceTokenizer { var pt PunktSentenceTokenizer var err error pt.tokenizer, err = newSentenceTokenizer(nil) util.CheckError(err) return &pt }
go
func NewPunktSentenceTokenizer() *PunktSentenceTokenizer { var pt PunktSentenceTokenizer var err error pt.tokenizer, err = newSentenceTokenizer(nil) util.CheckError(err) return &pt }
[ "func", "NewPunktSentenceTokenizer", "(", ")", "*", "PunktSentenceTokenizer", "{", "var", "pt", "PunktSentenceTokenizer", "\n", "var", "err", "error", "\n", "pt", ".", "tokenizer", ",", "err", "=", "newSentenceTokenizer", "(", "nil", ")", "\n", "util", ".", "C...
// NewPunktSentenceTokenizer creates a new PunktSentenceTokenizer and loads // its English model.
[ "NewPunktSentenceTokenizer", "creates", "a", "new", "PunktSentenceTokenizer", "and", "loads", "its", "English", "model", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/punkt.go#L41-L49
train
jdkato/prose
tokenize/punkt.go
newSentenceTokenizer
func newSentenceTokenizer(s *sentences.Storage) (*sentences.DefaultSentenceTokenizer, error) { training := s if training == nil { b, err := data.Asset("data/english.json") if err != nil { return nil, err } training, err = sentences.LoadTraining(b) if err != nil { return nil, err } } // supervisor abbreviations abbrevs := []string{"sgt", "gov", "no", "mt"} for _, abbr := range abbrevs { training.AbbrevTypes.Add(abbr) } lang := sentences.NewPunctStrings() word := newWordTokenizer(lang) annotations := sentences.NewAnnotations(training, lang, word) ortho := &sentences.OrthoContext{ Storage: training, PunctStrings: lang, TokenType: word, TokenFirst: word, } multiPunct := &multiPunctWordAnnotation{ Storage: training, TokenParser: word, TokenGrouper: &sentences.DefaultTokenGrouper{}, Ortho: ortho, } annotations = append(annotations, multiPunct) tokenizer := &sentences.DefaultSentenceTokenizer{ Storage: training, PunctStrings: lang, WordTokenizer: word, Annotations: annotations, } return tokenizer, nil }
go
func newSentenceTokenizer(s *sentences.Storage) (*sentences.DefaultSentenceTokenizer, error) { training := s if training == nil { b, err := data.Asset("data/english.json") if err != nil { return nil, err } training, err = sentences.LoadTraining(b) if err != nil { return nil, err } } // supervisor abbreviations abbrevs := []string{"sgt", "gov", "no", "mt"} for _, abbr := range abbrevs { training.AbbrevTypes.Add(abbr) } lang := sentences.NewPunctStrings() word := newWordTokenizer(lang) annotations := sentences.NewAnnotations(training, lang, word) ortho := &sentences.OrthoContext{ Storage: training, PunctStrings: lang, TokenType: word, TokenFirst: word, } multiPunct := &multiPunctWordAnnotation{ Storage: training, TokenParser: word, TokenGrouper: &sentences.DefaultTokenGrouper{}, Ortho: ortho, } annotations = append(annotations, multiPunct) tokenizer := &sentences.DefaultSentenceTokenizer{ Storage: training, PunctStrings: lang, WordTokenizer: word, Annotations: annotations, } return tokenizer, nil }
[ "func", "newSentenceTokenizer", "(", "s", "*", "sentences", ".", "Storage", ")", "(", "*", "sentences", ".", "DefaultSentenceTokenizer", ",", "error", ")", "{", "training", ":=", "s", "\n", "if", "training", "==", "nil", "{", "b", ",", "err", ":=", "data...
// English customized sentence tokenizer.
[ "English", "customized", "sentence", "tokenizer", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/punkt.go#L69-L118
train
jdkato/prose
tokenize/pragmatic.go
sub
func (r *rule) sub(text string) string { if !r.pattern.MatchString(text) { return text } orig := len(text) diff := 0 for _, submat := range r.pattern.FindAllStringSubmatchIndex(text, -1) { for idx, mat := range submat { if mat != -1 && idx > 0 && idx%2 == 0 { loc := []int{mat - diff, submat[idx+1] - diff} text = text[:loc[0]] + r.replacement + text[loc[1]:] diff = orig - len(text) } } } return text }
go
func (r *rule) sub(text string) string { if !r.pattern.MatchString(text) { return text } orig := len(text) diff := 0 for _, submat := range r.pattern.FindAllStringSubmatchIndex(text, -1) { for idx, mat := range submat { if mat != -1 && idx > 0 && idx%2 == 0 { loc := []int{mat - diff, submat[idx+1] - diff} text = text[:loc[0]] + r.replacement + text[loc[1]:] diff = orig - len(text) } } } return text }
[ "func", "(", "r", "*", "rule", ")", "sub", "(", "text", "string", ")", "string", "{", "if", "!", "r", ".", "pattern", ".", "MatchString", "(", "text", ")", "{", "return", "text", "\n", "}", "\n", "orig", ":=", "len", "(", "text", ")", "\n", "di...
// sub replaces all occurrences of Pattern with Replacement.
[ "sub", "replaces", "all", "occurrences", "of", "Pattern", "with", "Replacement", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/pragmatic.go#L72-L90
train
jdkato/prose
tokenize/pragmatic.go
subPat
func subPat(text, mtype string, pat *regexp.Regexp) string { canidates := []string{} for _, s := range pat.FindAllString(text, -1) { canidates = append(canidates, strings.TrimSpace(s)) } r := punctuationReplacer{ matches: canidates, text: text, matchType: mtype} return r.replace() }
go
func subPat(text, mtype string, pat *regexp.Regexp) string { canidates := []string{} for _, s := range pat.FindAllString(text, -1) { canidates = append(canidates, strings.TrimSpace(s)) } r := punctuationReplacer{ matches: canidates, text: text, matchType: mtype} return r.replace() }
[ "func", "subPat", "(", "text", ",", "mtype", "string", ",", "pat", "*", "regexp", ".", "Regexp", ")", "string", "{", "canidates", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "s", ":=", "range", "pat", ".", "FindAllString", "(", "text...
// subPat replaces all punctuation in the strings that match the regexp pat.
[ "subPat", "replaces", "all", "punctuation", "in", "the", "strings", "that", "match", "the", "regexp", "pat", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/pragmatic.go#L185-L193
train
jdkato/prose
tokenize/pragmatic.go
replaceBetweenQuotes
func replaceBetweenQuotes(text string) string { text = subPat(text, "single", betweenSingleQuotesRE) text = subPat(text, "double", betweenDoubleQuotesRE) text = subPat(text, "double", betweenSquareBracketsRE) text = subPat(text, "double", betweenParensRE) text = subPat(text, "double", betweenArrowQuotesRE) text = subPat(text, "double", betweenSmartQuotesRE) return text }
go
func replaceBetweenQuotes(text string) string { text = subPat(text, "single", betweenSingleQuotesRE) text = subPat(text, "double", betweenDoubleQuotesRE) text = subPat(text, "double", betweenSquareBracketsRE) text = subPat(text, "double", betweenParensRE) text = subPat(text, "double", betweenArrowQuotesRE) text = subPat(text, "double", betweenSmartQuotesRE) return text }
[ "func", "replaceBetweenQuotes", "(", "text", "string", ")", "string", "{", "text", "=", "subPat", "(", "text", ",", "\"single\"", ",", "betweenSingleQuotesRE", ")", "\n", "text", "=", "subPat", "(", "text", ",", "\"double\"", ",", "betweenDoubleQuotesRE", ")",...
// replaceBetweenQuotes replaces punctuation inside quotes.
[ "replaceBetweenQuotes", "replaces", "punctuation", "inside", "quotes", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/pragmatic.go#L196-L204
train
jdkato/prose
tokenize/pragmatic.go
substitute
func substitute(src, sub, repl string) string { idx := strings.Index(src, sub) for idx >= 0 { src = src[:idx] + repl + src[idx+len(sub):] idx = strings.Index(src, sub) } return src }
go
func substitute(src, sub, repl string) string { idx := strings.Index(src, sub) for idx >= 0 { src = src[:idx] + repl + src[idx+len(sub):] idx = strings.Index(src, sub) } return src }
[ "func", "substitute", "(", "src", ",", "sub", ",", "repl", "string", ")", "string", "{", "idx", ":=", "strings", ".", "Index", "(", "src", ",", "sub", ")", "\n", "for", "idx", ">=", "0", "{", "src", "=", "src", "[", ":", "idx", "]", "+", "repl"...
// substitute replaces the substring sub with the string repl.
[ "substitute", "replaces", "the", "substring", "sub", "with", "the", "string", "repl", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/pragmatic.go#L215-L222
train
looplab/fsm
utils.go
Visualize
func Visualize(fsm *FSM) string { var buf bytes.Buffer states := make(map[string]int) buf.WriteString(fmt.Sprintf(`digraph fsm {`)) buf.WriteString("\n") // make sure the initial state is at top for k, v := range fsm.transitions { if k.src == fsm.current { states[k.src]++ states[v]++ buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event)) buf.WriteString("\n") } } for k, v := range fsm.transitions { if k.src != fsm.current { states[k.src]++ states[v]++ buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event)) buf.WriteString("\n") } } buf.WriteString("\n") for k := range states { buf.WriteString(fmt.Sprintf(` "%s";`, k)) buf.WriteString("\n") } buf.WriteString(fmt.Sprintln("}")) return buf.String() }
go
func Visualize(fsm *FSM) string { var buf bytes.Buffer states := make(map[string]int) buf.WriteString(fmt.Sprintf(`digraph fsm {`)) buf.WriteString("\n") // make sure the initial state is at top for k, v := range fsm.transitions { if k.src == fsm.current { states[k.src]++ states[v]++ buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event)) buf.WriteString("\n") } } for k, v := range fsm.transitions { if k.src != fsm.current { states[k.src]++ states[v]++ buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event)) buf.WriteString("\n") } } buf.WriteString("\n") for k := range states { buf.WriteString(fmt.Sprintf(` "%s";`, k)) buf.WriteString("\n") } buf.WriteString(fmt.Sprintln("}")) return buf.String() }
[ "func", "Visualize", "(", "fsm", "*", "FSM", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "states", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "buf", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "`dig...
// Visualize outputs a visualization of a FSM in Graphviz format.
[ "Visualize", "outputs", "a", "visualization", "of", "a", "FSM", "in", "Graphviz", "format", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/utils.go#L9-L45
train
looplab/fsm
fsm.go
Current
func (f *FSM) Current() string { f.stateMu.RLock() defer f.stateMu.RUnlock() return f.current }
go
func (f *FSM) Current() string { f.stateMu.RLock() defer f.stateMu.RUnlock() return f.current }
[ "func", "(", "f", "*", "FSM", ")", "Current", "(", ")", "string", "{", "f", ".", "stateMu", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "stateMu", ".", "RUnlock", "(", ")", "\n", "return", "f", ".", "current", "\n", "}" ]
// Current returns the current state of the FSM.
[ "Current", "returns", "the", "current", "state", "of", "the", "FSM", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L202-L206
train
looplab/fsm
fsm.go
Is
func (f *FSM) Is(state string) bool { f.stateMu.RLock() defer f.stateMu.RUnlock() return state == f.current }
go
func (f *FSM) Is(state string) bool { f.stateMu.RLock() defer f.stateMu.RUnlock() return state == f.current }
[ "func", "(", "f", "*", "FSM", ")", "Is", "(", "state", "string", ")", "bool", "{", "f", ".", "stateMu", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "stateMu", ".", "RUnlock", "(", ")", "\n", "return", "state", "==", "f", ".", "current", "\...
// Is returns true if state is the current state.
[ "Is", "returns", "true", "if", "state", "is", "the", "current", "state", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L209-L213
train
looplab/fsm
fsm.go
SetState
func (f *FSM) SetState(state string) { f.stateMu.Lock() defer f.stateMu.Unlock() f.current = state return }
go
func (f *FSM) SetState(state string) { f.stateMu.Lock() defer f.stateMu.Unlock() f.current = state return }
[ "func", "(", "f", "*", "FSM", ")", "SetState", "(", "state", "string", ")", "{", "f", ".", "stateMu", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "stateMu", ".", "Unlock", "(", ")", "\n", "f", ".", "current", "=", "state", "\n", "return", "...
// SetState allows the user to move to the given state from current state. // The call does not trigger any callbacks, if defined.
[ "SetState", "allows", "the", "user", "to", "move", "to", "the", "given", "state", "from", "current", "state", ".", "The", "call", "does", "not", "trigger", "any", "callbacks", "if", "defined", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L217-L222
train
looplab/fsm
fsm.go
Can
func (f *FSM) Can(event string) bool { f.stateMu.RLock() defer f.stateMu.RUnlock() _, ok := f.transitions[eKey{event, f.current}] return ok && (f.transition == nil) }
go
func (f *FSM) Can(event string) bool { f.stateMu.RLock() defer f.stateMu.RUnlock() _, ok := f.transitions[eKey{event, f.current}] return ok && (f.transition == nil) }
[ "func", "(", "f", "*", "FSM", ")", "Can", "(", "event", "string", ")", "bool", "{", "f", ".", "stateMu", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "stateMu", ".", "RUnlock", "(", ")", "\n", "_", ",", "ok", ":=", "f", ".", "transitions", ...
// Can returns true if event can occur in the current state.
[ "Can", "returns", "true", "if", "event", "can", "occur", "in", "the", "current", "state", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L225-L230
train
looplab/fsm
fsm.go
AvailableTransitions
func (f *FSM) AvailableTransitions() []string { f.stateMu.RLock() defer f.stateMu.RUnlock() var transitions []string for key := range f.transitions { if key.src == f.current { transitions = append(transitions, key.event) } } return transitions }
go
func (f *FSM) AvailableTransitions() []string { f.stateMu.RLock() defer f.stateMu.RUnlock() var transitions []string for key := range f.transitions { if key.src == f.current { transitions = append(transitions, key.event) } } return transitions }
[ "func", "(", "f", "*", "FSM", ")", "AvailableTransitions", "(", ")", "[", "]", "string", "{", "f", ".", "stateMu", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "stateMu", ".", "RUnlock", "(", ")", "\n", "var", "transitions", "[", "]", "string",...
// AvailableTransitions returns a list of transitions avilable in the // current state.
[ "AvailableTransitions", "returns", "a", "list", "of", "transitions", "avilable", "in", "the", "current", "state", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L234-L244
train
looplab/fsm
fsm.go
Transition
func (f *FSM) Transition() error { f.eventMu.Lock() defer f.eventMu.Unlock() return f.doTransition() }
go
func (f *FSM) Transition() error { f.eventMu.Lock() defer f.eventMu.Unlock() return f.doTransition() }
[ "func", "(", "f", "*", "FSM", ")", "Transition", "(", ")", "error", "{", "f", ".", "eventMu", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "eventMu", ".", "Unlock", "(", ")", "\n", "return", "f", ".", "doTransition", "(", ")", "\n", "}" ]
// Transition wraps transitioner.transition.
[ "Transition", "wraps", "transitioner", ".", "transition", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L331-L335
train
looplab/fsm
fsm.go
beforeEventCallbacks
func (f *FSM) beforeEventCallbacks(e *Event) error { if fn, ok := f.callbacks[cKey{e.Event, callbackBeforeEvent}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } } if fn, ok := f.callbacks[cKey{"", callbackBeforeEvent}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } } return nil }
go
func (f *FSM) beforeEventCallbacks(e *Event) error { if fn, ok := f.callbacks[cKey{e.Event, callbackBeforeEvent}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } } if fn, ok := f.callbacks[cKey{"", callbackBeforeEvent}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } } return nil }
[ "func", "(", "f", "*", "FSM", ")", "beforeEventCallbacks", "(", "e", "*", "Event", ")", "error", "{", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "e", ".", "Event", ",", "callbackBeforeEvent", "}", "]", ";", "ok", "{", "...
// beforeEventCallbacks calls the before_ callbacks, first the named then the // general version.
[ "beforeEventCallbacks", "calls", "the", "before_", "callbacks", "first", "the", "named", "then", "the", "general", "version", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L361-L375
train
looplab/fsm
fsm.go
leaveStateCallbacks
func (f *FSM) leaveStateCallbacks(e *Event) error { if fn, ok := f.callbacks[cKey{f.current, callbackLeaveState}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } else if e.async { return AsyncError{e.Err} } } if fn, ok := f.callbacks[cKey{"", callbackLeaveState}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } else if e.async { return AsyncError{e.Err} } } return nil }
go
func (f *FSM) leaveStateCallbacks(e *Event) error { if fn, ok := f.callbacks[cKey{f.current, callbackLeaveState}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } else if e.async { return AsyncError{e.Err} } } if fn, ok := f.callbacks[cKey{"", callbackLeaveState}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } else if e.async { return AsyncError{e.Err} } } return nil }
[ "func", "(", "f", "*", "FSM", ")", "leaveStateCallbacks", "(", "e", "*", "Event", ")", "error", "{", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "f", ".", "current", ",", "callbackLeaveState", "}", "]", ";", "ok", "{", "...
// leaveStateCallbacks calls the leave_ callbacks, first the named then the // general version.
[ "leaveStateCallbacks", "calls", "the", "leave_", "callbacks", "first", "the", "named", "then", "the", "general", "version", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L379-L397
train
looplab/fsm
fsm.go
enterStateCallbacks
func (f *FSM) enterStateCallbacks(e *Event) { if fn, ok := f.callbacks[cKey{f.current, callbackEnterState}]; ok { fn(e) } if fn, ok := f.callbacks[cKey{"", callbackEnterState}]; ok { fn(e) } }
go
func (f *FSM) enterStateCallbacks(e *Event) { if fn, ok := f.callbacks[cKey{f.current, callbackEnterState}]; ok { fn(e) } if fn, ok := f.callbacks[cKey{"", callbackEnterState}]; ok { fn(e) } }
[ "func", "(", "f", "*", "FSM", ")", "enterStateCallbacks", "(", "e", "*", "Event", ")", "{", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "f", ".", "current", ",", "callbackEnterState", "}", "]", ";", "ok", "{", "fn", "(",...
// enterStateCallbacks calls the enter_ callbacks, first the named then the // general version.
[ "enterStateCallbacks", "calls", "the", "enter_", "callbacks", "first", "the", "named", "then", "the", "general", "version", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L401-L408
train
looplab/fsm
fsm.go
afterEventCallbacks
func (f *FSM) afterEventCallbacks(e *Event) { if fn, ok := f.callbacks[cKey{e.Event, callbackAfterEvent}]; ok { fn(e) } if fn, ok := f.callbacks[cKey{"", callbackAfterEvent}]; ok { fn(e) } }
go
func (f *FSM) afterEventCallbacks(e *Event) { if fn, ok := f.callbacks[cKey{e.Event, callbackAfterEvent}]; ok { fn(e) } if fn, ok := f.callbacks[cKey{"", callbackAfterEvent}]; ok { fn(e) } }
[ "func", "(", "f", "*", "FSM", ")", "afterEventCallbacks", "(", "e", "*", "Event", ")", "{", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "e", ".", "Event", ",", "callbackAfterEvent", "}", "]", ";", "ok", "{", "fn", "(", ...
// afterEventCallbacks calls the after_ callbacks, first the named then the // general version.
[ "afterEventCallbacks", "calls", "the", "after_", "callbacks", "first", "the", "named", "then", "the", "general", "version", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L412-L419
train
armon/go-socks5
request.go
Address
func (a AddrSpec) Address() string { if 0 != len(a.IP) { return net.JoinHostPort(a.IP.String(), strconv.Itoa(a.Port)) } return net.JoinHostPort(a.FQDN, strconv.Itoa(a.Port)) }
go
func (a AddrSpec) Address() string { if 0 != len(a.IP) { return net.JoinHostPort(a.IP.String(), strconv.Itoa(a.Port)) } return net.JoinHostPort(a.FQDN, strconv.Itoa(a.Port)) }
[ "func", "(", "a", "AddrSpec", ")", "Address", "(", ")", "string", "{", "if", "0", "!=", "len", "(", "a", ".", "IP", ")", "{", "return", "net", ".", "JoinHostPort", "(", "a", ".", "IP", ".", "String", "(", ")", ",", "strconv", ".", "Itoa", "(", ...
// Address returns a string suitable to dial; prefer returning IP-based // address, fallback to FQDN
[ "Address", "returns", "a", "string", "suitable", "to", "dial", ";", "prefer", "returning", "IP", "-", "based", "address", "fallback", "to", "FQDN" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L60-L65
train
armon/go-socks5
request.go
NewRequest
func NewRequest(bufConn io.Reader) (*Request, error) { // Read the version byte header := []byte{0, 0, 0} if _, err := io.ReadAtLeast(bufConn, header, 3); err != nil { return nil, fmt.Errorf("Failed to get command version: %v", err) } // Ensure we are compatible if header[0] != socks5Version { return nil, fmt.Errorf("Unsupported command version: %v", header[0]) } // Read in the destination address dest, err := readAddrSpec(bufConn) if err != nil { return nil, err } request := &Request{ Version: socks5Version, Command: header[1], DestAddr: dest, bufConn: bufConn, } return request, nil }
go
func NewRequest(bufConn io.Reader) (*Request, error) { // Read the version byte header := []byte{0, 0, 0} if _, err := io.ReadAtLeast(bufConn, header, 3); err != nil { return nil, fmt.Errorf("Failed to get command version: %v", err) } // Ensure we are compatible if header[0] != socks5Version { return nil, fmt.Errorf("Unsupported command version: %v", header[0]) } // Read in the destination address dest, err := readAddrSpec(bufConn) if err != nil { return nil, err } request := &Request{ Version: socks5Version, Command: header[1], DestAddr: dest, bufConn: bufConn, } return request, nil }
[ "func", "NewRequest", "(", "bufConn", "io", ".", "Reader", ")", "(", "*", "Request", ",", "error", ")", "{", "header", ":=", "[", "]", "byte", "{", "0", ",", "0", ",", "0", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadAtLeast", "(", ...
// NewRequest creates a new Request from the tcp connection
[ "NewRequest", "creates", "a", "new", "Request", "from", "the", "tcp", "connection" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L90-L116
train
armon/go-socks5
request.go
handleRequest
func (s *Server) handleRequest(req *Request, conn conn) error { ctx := context.Background() // Resolve the address if we have a FQDN dest := req.DestAddr if dest.FQDN != "" { ctx_, addr, err := s.config.Resolver.Resolve(ctx, dest.FQDN) if err != nil { if err := sendReply(conn, hostUnreachable, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Failed to resolve destination '%v': %v", dest.FQDN, err) } ctx = ctx_ dest.IP = addr } // Apply any address rewrites req.realDestAddr = req.DestAddr if s.config.Rewriter != nil { ctx, req.realDestAddr = s.config.Rewriter.Rewrite(ctx, req) } // Switch on the command switch req.Command { case ConnectCommand: return s.handleConnect(ctx, conn, req) case BindCommand: return s.handleBind(ctx, conn, req) case AssociateCommand: return s.handleAssociate(ctx, conn, req) default: if err := sendReply(conn, commandNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Unsupported command: %v", req.Command) } }
go
func (s *Server) handleRequest(req *Request, conn conn) error { ctx := context.Background() // Resolve the address if we have a FQDN dest := req.DestAddr if dest.FQDN != "" { ctx_, addr, err := s.config.Resolver.Resolve(ctx, dest.FQDN) if err != nil { if err := sendReply(conn, hostUnreachable, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Failed to resolve destination '%v': %v", dest.FQDN, err) } ctx = ctx_ dest.IP = addr } // Apply any address rewrites req.realDestAddr = req.DestAddr if s.config.Rewriter != nil { ctx, req.realDestAddr = s.config.Rewriter.Rewrite(ctx, req) } // Switch on the command switch req.Command { case ConnectCommand: return s.handleConnect(ctx, conn, req) case BindCommand: return s.handleBind(ctx, conn, req) case AssociateCommand: return s.handleAssociate(ctx, conn, req) default: if err := sendReply(conn, commandNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Unsupported command: %v", req.Command) } }
[ "func", "(", "s", "*", "Server", ")", "handleRequest", "(", "req", "*", "Request", ",", "conn", "conn", ")", "error", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "dest", ":=", "req", ".", "DestAddr", "\n", "if", "dest", ".", "FQ...
// handleRequest is used for request processing after authentication
[ "handleRequest", "is", "used", "for", "request", "processing", "after", "authentication" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L119-L156
train
armon/go-socks5
request.go
handleConnect
func (s *Server) handleConnect(ctx context.Context, conn conn, req *Request) error { // Check if this is allowed if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok { if err := sendReply(conn, ruleFailure, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Connect to %v blocked by rules", req.DestAddr) } else { ctx = ctx_ } // Attempt to connect dial := s.config.Dial if dial == nil { dial = func(ctx context.Context, net_, addr string) (net.Conn, error) { return net.Dial(net_, addr) } } target, err := dial(ctx, "tcp", req.realDestAddr.Address()) if err != nil { msg := err.Error() resp := hostUnreachable if strings.Contains(msg, "refused") { resp = connectionRefused } else if strings.Contains(msg, "network is unreachable") { resp = networkUnreachable } if err := sendReply(conn, resp, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Connect to %v failed: %v", req.DestAddr, err) } defer target.Close() // Send success local := target.LocalAddr().(*net.TCPAddr) bind := AddrSpec{IP: local.IP, Port: local.Port} if err := sendReply(conn, successReply, &bind); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } // Start proxying errCh := make(chan error, 2) go proxy(target, req.bufConn, errCh) go proxy(conn, target, errCh) // Wait for i := 0; i < 2; i++ { e := <-errCh if e != nil { // return from this function closes target (and conn). return e } } return nil }
go
func (s *Server) handleConnect(ctx context.Context, conn conn, req *Request) error { // Check if this is allowed if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok { if err := sendReply(conn, ruleFailure, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Connect to %v blocked by rules", req.DestAddr) } else { ctx = ctx_ } // Attempt to connect dial := s.config.Dial if dial == nil { dial = func(ctx context.Context, net_, addr string) (net.Conn, error) { return net.Dial(net_, addr) } } target, err := dial(ctx, "tcp", req.realDestAddr.Address()) if err != nil { msg := err.Error() resp := hostUnreachable if strings.Contains(msg, "refused") { resp = connectionRefused } else if strings.Contains(msg, "network is unreachable") { resp = networkUnreachable } if err := sendReply(conn, resp, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Connect to %v failed: %v", req.DestAddr, err) } defer target.Close() // Send success local := target.LocalAddr().(*net.TCPAddr) bind := AddrSpec{IP: local.IP, Port: local.Port} if err := sendReply(conn, successReply, &bind); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } // Start proxying errCh := make(chan error, 2) go proxy(target, req.bufConn, errCh) go proxy(conn, target, errCh) // Wait for i := 0; i < 2; i++ { e := <-errCh if e != nil { // return from this function closes target (and conn). return e } } return nil }
[ "func", "(", "s", "*", "Server", ")", "handleConnect", "(", "ctx", "context", ".", "Context", ",", "conn", "conn", ",", "req", "*", "Request", ")", "error", "{", "if", "ctx_", ",", "ok", ":=", "s", ".", "config", ".", "Rules", ".", "Allow", "(", ...
// handleConnect is used to handle a connect command
[ "handleConnect", "is", "used", "to", "handle", "a", "connect", "command" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L159-L214
train
armon/go-socks5
request.go
handleBind
func (s *Server) handleBind(ctx context.Context, conn conn, req *Request) error { // Check if this is allowed if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok { if err := sendReply(conn, ruleFailure, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Bind to %v blocked by rules", req.DestAddr) } else { ctx = ctx_ } // TODO: Support bind if err := sendReply(conn, commandNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return nil }
go
func (s *Server) handleBind(ctx context.Context, conn conn, req *Request) error { // Check if this is allowed if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok { if err := sendReply(conn, ruleFailure, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Bind to %v blocked by rules", req.DestAddr) } else { ctx = ctx_ } // TODO: Support bind if err := sendReply(conn, commandNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return nil }
[ "func", "(", "s", "*", "Server", ")", "handleBind", "(", "ctx", "context", ".", "Context", ",", "conn", "conn", ",", "req", "*", "Request", ")", "error", "{", "if", "ctx_", ",", "ok", ":=", "s", ".", "config", ".", "Rules", ".", "Allow", "(", "ct...
// handleBind is used to handle a connect command
[ "handleBind", "is", "used", "to", "handle", "a", "connect", "command" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L217-L233
train
armon/go-socks5
request.go
readAddrSpec
func readAddrSpec(r io.Reader) (*AddrSpec, error) { d := &AddrSpec{} // Get the address type addrType := []byte{0} if _, err := r.Read(addrType); err != nil { return nil, err } // Handle on a per type basis switch addrType[0] { case ipv4Address: addr := make([]byte, 4) if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil { return nil, err } d.IP = net.IP(addr) case ipv6Address: addr := make([]byte, 16) if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil { return nil, err } d.IP = net.IP(addr) case fqdnAddress: if _, err := r.Read(addrType); err != nil { return nil, err } addrLen := int(addrType[0]) fqdn := make([]byte, addrLen) if _, err := io.ReadAtLeast(r, fqdn, addrLen); err != nil { return nil, err } d.FQDN = string(fqdn) default: return nil, unrecognizedAddrType } // Read the port port := []byte{0, 0} if _, err := io.ReadAtLeast(r, port, 2); err != nil { return nil, err } d.Port = (int(port[0]) << 8) | int(port[1]) return d, nil }
go
func readAddrSpec(r io.Reader) (*AddrSpec, error) { d := &AddrSpec{} // Get the address type addrType := []byte{0} if _, err := r.Read(addrType); err != nil { return nil, err } // Handle on a per type basis switch addrType[0] { case ipv4Address: addr := make([]byte, 4) if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil { return nil, err } d.IP = net.IP(addr) case ipv6Address: addr := make([]byte, 16) if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil { return nil, err } d.IP = net.IP(addr) case fqdnAddress: if _, err := r.Read(addrType); err != nil { return nil, err } addrLen := int(addrType[0]) fqdn := make([]byte, addrLen) if _, err := io.ReadAtLeast(r, fqdn, addrLen); err != nil { return nil, err } d.FQDN = string(fqdn) default: return nil, unrecognizedAddrType } // Read the port port := []byte{0, 0} if _, err := io.ReadAtLeast(r, port, 2); err != nil { return nil, err } d.Port = (int(port[0]) << 8) | int(port[1]) return d, nil }
[ "func", "readAddrSpec", "(", "r", "io", ".", "Reader", ")", "(", "*", "AddrSpec", ",", "error", ")", "{", "d", ":=", "&", "AddrSpec", "{", "}", "\n", "addrType", ":=", "[", "]", "byte", "{", "0", "}", "\n", "if", "_", ",", "err", ":=", "r", "...
// readAddrSpec is used to read AddrSpec. // Expects an address type byte, follwed by the address and port
[ "readAddrSpec", "is", "used", "to", "read", "AddrSpec", ".", "Expects", "an", "address", "type", "byte", "follwed", "by", "the", "address", "and", "port" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L256-L304
train
armon/go-socks5
request.go
sendReply
func sendReply(w io.Writer, resp uint8, addr *AddrSpec) error { // Format the address var addrType uint8 var addrBody []byte var addrPort uint16 switch { case addr == nil: addrType = ipv4Address addrBody = []byte{0, 0, 0, 0} addrPort = 0 case addr.FQDN != "": addrType = fqdnAddress addrBody = append([]byte{byte(len(addr.FQDN))}, addr.FQDN...) addrPort = uint16(addr.Port) case addr.IP.To4() != nil: addrType = ipv4Address addrBody = []byte(addr.IP.To4()) addrPort = uint16(addr.Port) case addr.IP.To16() != nil: addrType = ipv6Address addrBody = []byte(addr.IP.To16()) addrPort = uint16(addr.Port) default: return fmt.Errorf("Failed to format address: %v", addr) } // Format the message msg := make([]byte, 6+len(addrBody)) msg[0] = socks5Version msg[1] = resp msg[2] = 0 // Reserved msg[3] = addrType copy(msg[4:], addrBody) msg[4+len(addrBody)] = byte(addrPort >> 8) msg[4+len(addrBody)+1] = byte(addrPort & 0xff) // Send the message _, err := w.Write(msg) return err }
go
func sendReply(w io.Writer, resp uint8, addr *AddrSpec) error { // Format the address var addrType uint8 var addrBody []byte var addrPort uint16 switch { case addr == nil: addrType = ipv4Address addrBody = []byte{0, 0, 0, 0} addrPort = 0 case addr.FQDN != "": addrType = fqdnAddress addrBody = append([]byte{byte(len(addr.FQDN))}, addr.FQDN...) addrPort = uint16(addr.Port) case addr.IP.To4() != nil: addrType = ipv4Address addrBody = []byte(addr.IP.To4()) addrPort = uint16(addr.Port) case addr.IP.To16() != nil: addrType = ipv6Address addrBody = []byte(addr.IP.To16()) addrPort = uint16(addr.Port) default: return fmt.Errorf("Failed to format address: %v", addr) } // Format the message msg := make([]byte, 6+len(addrBody)) msg[0] = socks5Version msg[1] = resp msg[2] = 0 // Reserved msg[3] = addrType copy(msg[4:], addrBody) msg[4+len(addrBody)] = byte(addrPort >> 8) msg[4+len(addrBody)+1] = byte(addrPort & 0xff) // Send the message _, err := w.Write(msg) return err }
[ "func", "sendReply", "(", "w", "io", ".", "Writer", ",", "resp", "uint8", ",", "addr", "*", "AddrSpec", ")", "error", "{", "var", "addrType", "uint8", "\n", "var", "addrBody", "[", "]", "byte", "\n", "var", "addrPort", "uint16", "\n", "switch", "{", ...
// sendReply is used to send a reply message
[ "sendReply", "is", "used", "to", "send", "a", "reply", "message" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L307-L350
train
armon/go-socks5
request.go
proxy
func proxy(dst io.Writer, src io.Reader, errCh chan error) { _, err := io.Copy(dst, src) if tcpConn, ok := dst.(closeWriter); ok { tcpConn.CloseWrite() } errCh <- err }
go
func proxy(dst io.Writer, src io.Reader, errCh chan error) { _, err := io.Copy(dst, src) if tcpConn, ok := dst.(closeWriter); ok { tcpConn.CloseWrite() } errCh <- err }
[ "func", "proxy", "(", "dst", "io", ".", "Writer", ",", "src", "io", ".", "Reader", ",", "errCh", "chan", "error", ")", "{", "_", ",", "err", ":=", "io", ".", "Copy", "(", "dst", ",", "src", ")", "\n", "if", "tcpConn", ",", "ok", ":=", "dst", ...
// proxy is used to suffle data from src to destination, and sends errors // down a dedicated channel
[ "proxy", "is", "used", "to", "suffle", "data", "from", "src", "to", "destination", "and", "sends", "errors", "down", "a", "dedicated", "channel" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L358-L364
train
armon/go-socks5
socks5.go
New
func New(conf *Config) (*Server, error) { // Ensure we have at least one authentication method enabled if len(conf.AuthMethods) == 0 { if conf.Credentials != nil { conf.AuthMethods = []Authenticator{&UserPassAuthenticator{conf.Credentials}} } else { conf.AuthMethods = []Authenticator{&NoAuthAuthenticator{}} } } // Ensure we have a DNS resolver if conf.Resolver == nil { conf.Resolver = DNSResolver{} } // Ensure we have a rule set if conf.Rules == nil { conf.Rules = PermitAll() } // Ensure we have a log target if conf.Logger == nil { conf.Logger = log.New(os.Stdout, "", log.LstdFlags) } server := &Server{ config: conf, } server.authMethods = make(map[uint8]Authenticator) for _, a := range conf.AuthMethods { server.authMethods[a.GetCode()] = a } return server, nil }
go
func New(conf *Config) (*Server, error) { // Ensure we have at least one authentication method enabled if len(conf.AuthMethods) == 0 { if conf.Credentials != nil { conf.AuthMethods = []Authenticator{&UserPassAuthenticator{conf.Credentials}} } else { conf.AuthMethods = []Authenticator{&NoAuthAuthenticator{}} } } // Ensure we have a DNS resolver if conf.Resolver == nil { conf.Resolver = DNSResolver{} } // Ensure we have a rule set if conf.Rules == nil { conf.Rules = PermitAll() } // Ensure we have a log target if conf.Logger == nil { conf.Logger = log.New(os.Stdout, "", log.LstdFlags) } server := &Server{ config: conf, } server.authMethods = make(map[uint8]Authenticator) for _, a := range conf.AuthMethods { server.authMethods[a.GetCode()] = a } return server, nil }
[ "func", "New", "(", "conf", "*", "Config", ")", "(", "*", "Server", ",", "error", ")", "{", "if", "len", "(", "conf", ".", "AuthMethods", ")", "==", "0", "{", "if", "conf", ".", "Credentials", "!=", "nil", "{", "conf", ".", "AuthMethods", "=", "[...
// New creates a new Server and potentially returns an error
[ "New", "creates", "a", "new", "Server", "and", "potentially", "returns", "an", "error" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/socks5.go#L61-L97
train
armon/go-socks5
socks5.go
ListenAndServe
func (s *Server) ListenAndServe(network, addr string) error { l, err := net.Listen(network, addr) if err != nil { return err } return s.Serve(l) }
go
func (s *Server) ListenAndServe(network, addr string) error { l, err := net.Listen(network, addr) if err != nil { return err } return s.Serve(l) }
[ "func", "(", "s", "*", "Server", ")", "ListenAndServe", "(", "network", ",", "addr", "string", ")", "error", "{", "l", ",", "err", ":=", "net", ".", "Listen", "(", "network", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ...
// ListenAndServe is used to create a listener and serve on it
[ "ListenAndServe", "is", "used", "to", "create", "a", "listener", "and", "serve", "on", "it" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/socks5.go#L100-L106
train
armon/go-socks5
socks5.go
Serve
func (s *Server) Serve(l net.Listener) error { for { conn, err := l.Accept() if err != nil { return err } go s.ServeConn(conn) } return nil }
go
func (s *Server) Serve(l net.Listener) error { for { conn, err := l.Accept() if err != nil { return err } go s.ServeConn(conn) } return nil }
[ "func", "(", "s", "*", "Server", ")", "Serve", "(", "l", "net", ".", "Listener", ")", "error", "{", "for", "{", "conn", ",", "err", ":=", "l", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "go...
// Serve is used to serve connections from a listener
[ "Serve", "is", "used", "to", "serve", "connections", "from", "a", "listener" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/socks5.go#L109-L118
train
armon/go-socks5
socks5.go
ServeConn
func (s *Server) ServeConn(conn net.Conn) error { defer conn.Close() bufConn := bufio.NewReader(conn) // Read the version byte version := []byte{0} if _, err := bufConn.Read(version); err != nil { s.config.Logger.Printf("[ERR] socks: Failed to get version byte: %v", err) return err } // Ensure we are compatible if version[0] != socks5Version { err := fmt.Errorf("Unsupported SOCKS version: %v", version) s.config.Logger.Printf("[ERR] socks: %v", err) return err } // Authenticate the connection authContext, err := s.authenticate(conn, bufConn) if err != nil { err = fmt.Errorf("Failed to authenticate: %v", err) s.config.Logger.Printf("[ERR] socks: %v", err) return err } request, err := NewRequest(bufConn) if err != nil { if err == unrecognizedAddrType { if err := sendReply(conn, addrTypeNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } } return fmt.Errorf("Failed to read destination address: %v", err) } request.AuthContext = authContext if client, ok := conn.RemoteAddr().(*net.TCPAddr); ok { request.RemoteAddr = &AddrSpec{IP: client.IP, Port: client.Port} } // Process the client request if err := s.handleRequest(request, conn); err != nil { err = fmt.Errorf("Failed to handle request: %v", err) s.config.Logger.Printf("[ERR] socks: %v", err) return err } return nil }
go
func (s *Server) ServeConn(conn net.Conn) error { defer conn.Close() bufConn := bufio.NewReader(conn) // Read the version byte version := []byte{0} if _, err := bufConn.Read(version); err != nil { s.config.Logger.Printf("[ERR] socks: Failed to get version byte: %v", err) return err } // Ensure we are compatible if version[0] != socks5Version { err := fmt.Errorf("Unsupported SOCKS version: %v", version) s.config.Logger.Printf("[ERR] socks: %v", err) return err } // Authenticate the connection authContext, err := s.authenticate(conn, bufConn) if err != nil { err = fmt.Errorf("Failed to authenticate: %v", err) s.config.Logger.Printf("[ERR] socks: %v", err) return err } request, err := NewRequest(bufConn) if err != nil { if err == unrecognizedAddrType { if err := sendReply(conn, addrTypeNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } } return fmt.Errorf("Failed to read destination address: %v", err) } request.AuthContext = authContext if client, ok := conn.RemoteAddr().(*net.TCPAddr); ok { request.RemoteAddr = &AddrSpec{IP: client.IP, Port: client.Port} } // Process the client request if err := s.handleRequest(request, conn); err != nil { err = fmt.Errorf("Failed to handle request: %v", err) s.config.Logger.Printf("[ERR] socks: %v", err) return err } return nil }
[ "func", "(", "s", "*", "Server", ")", "ServeConn", "(", "conn", "net", ".", "Conn", ")", "error", "{", "defer", "conn", ".", "Close", "(", ")", "\n", "bufConn", ":=", "bufio", ".", "NewReader", "(", "conn", ")", "\n", "version", ":=", "[", "]", "...
// ServeConn is used to serve a single connection.
[ "ServeConn", "is", "used", "to", "serve", "a", "single", "connection", "." ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/socks5.go#L121-L169
train
armon/go-socks5
auth.go
authenticate
func (s *Server) authenticate(conn io.Writer, bufConn io.Reader) (*AuthContext, error) { // Get the methods methods, err := readMethods(bufConn) if err != nil { return nil, fmt.Errorf("Failed to get auth methods: %v", err) } // Select a usable method for _, method := range methods { cator, found := s.authMethods[method] if found { return cator.Authenticate(bufConn, conn) } } // No usable method found return nil, noAcceptableAuth(conn) }
go
func (s *Server) authenticate(conn io.Writer, bufConn io.Reader) (*AuthContext, error) { // Get the methods methods, err := readMethods(bufConn) if err != nil { return nil, fmt.Errorf("Failed to get auth methods: %v", err) } // Select a usable method for _, method := range methods { cator, found := s.authMethods[method] if found { return cator.Authenticate(bufConn, conn) } } // No usable method found return nil, noAcceptableAuth(conn) }
[ "func", "(", "s", "*", "Server", ")", "authenticate", "(", "conn", "io", ".", "Writer", ",", "bufConn", "io", ".", "Reader", ")", "(", "*", "AuthContext", ",", "error", ")", "{", "methods", ",", "err", ":=", "readMethods", "(", "bufConn", ")", "\n", ...
// authenticate is used to handle connection authentication
[ "authenticate", "is", "used", "to", "handle", "connection", "authentication" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/auth.go#L113-L130
train
armon/go-socks5
auth.go
noAcceptableAuth
func noAcceptableAuth(conn io.Writer) error { conn.Write([]byte{socks5Version, noAcceptable}) return NoSupportedAuth }
go
func noAcceptableAuth(conn io.Writer) error { conn.Write([]byte{socks5Version, noAcceptable}) return NoSupportedAuth }
[ "func", "noAcceptableAuth", "(", "conn", "io", ".", "Writer", ")", "error", "{", "conn", ".", "Write", "(", "[", "]", "byte", "{", "socks5Version", ",", "noAcceptable", "}", ")", "\n", "return", "NoSupportedAuth", "\n", "}" ]
// noAcceptableAuth is used to handle when we have no eligible // authentication mechanism
[ "noAcceptableAuth", "is", "used", "to", "handle", "when", "we", "have", "no", "eligible", "authentication", "mechanism" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/auth.go#L134-L137
train
armon/go-socks5
auth.go
readMethods
func readMethods(r io.Reader) ([]byte, error) { header := []byte{0} if _, err := r.Read(header); err != nil { return nil, err } numMethods := int(header[0]) methods := make([]byte, numMethods) _, err := io.ReadAtLeast(r, methods, numMethods) return methods, err }
go
func readMethods(r io.Reader) ([]byte, error) { header := []byte{0} if _, err := r.Read(header); err != nil { return nil, err } numMethods := int(header[0]) methods := make([]byte, numMethods) _, err := io.ReadAtLeast(r, methods, numMethods) return methods, err }
[ "func", "readMethods", "(", "r", "io", ".", "Reader", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "header", ":=", "[", "]", "byte", "{", "0", "}", "\n", "if", "_", ",", "err", ":=", "r", ".", "Read", "(", "header", ")", ";", "err", ...
// readMethods is used to read the number of methods // and proceeding auth methods
[ "readMethods", "is", "used", "to", "read", "the", "number", "of", "methods", "and", "proceeding", "auth", "methods" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/auth.go#L141-L151
train
qor/qor-example
models/orders/order_item.go
ProductImageURL
func (item *OrderItem) ProductImageURL() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.MainImageURL() }
go
func (item *OrderItem) ProductImageURL() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.MainImageURL() }
[ "func", "(", "item", "*", "OrderItem", ")", "ProductImageURL", "(", ")", "string", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "ColorVariation", ".", "MainImageURL", "(", ")", "\n", "}" ]
// ProductImageURL get product image
[ "ProductImageURL", "get", "product", "image" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L34-L37
train
qor/qor-example
models/orders/order_item.go
SellingPrice
func (item *OrderItem) SellingPrice() float32 { if item.IsCart() { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Product.Price } return item.Price }
go
func (item *OrderItem) SellingPrice() float32 { if item.IsCart() { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Product.Price } return item.Price }
[ "func", "(", "item", "*", "OrderItem", ")", "SellingPrice", "(", ")", "float32", "{", "if", "item", ".", "IsCart", "(", ")", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "ColorVariation", ".", "Produ...
// SellingPrice order item's selling price
[ "SellingPrice", "order", "item", "s", "selling", "price" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L40-L46
train
qor/qor-example
models/orders/order_item.go
ProductName
func (item *OrderItem) ProductName() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Product.Name }
go
func (item *OrderItem) ProductName() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Product.Name }
[ "func", "(", "item", "*", "OrderItem", ")", "ProductName", "(", ")", "string", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "ColorVariation", ".", "Product", ".", "Name", "\n", "}" ]
// ProductName order item's color name
[ "ProductName", "order", "item", "s", "color", "name" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L49-L52
train
qor/qor-example
models/orders/order_item.go
ColorName
func (item *OrderItem) ColorName() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Color.Name }
go
func (item *OrderItem) ColorName() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Color.Name }
[ "func", "(", "item", "*", "OrderItem", ")", "ColorName", "(", ")", "string", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "ColorVariation", ".", "Color", ".", "Name", "\n", "}" ]
// ColorName order item's color name
[ "ColorName", "order", "item", "s", "color", "name" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L55-L58
train
qor/qor-example
models/orders/order_item.go
SizeName
func (item *OrderItem) SizeName() string { item.loadSizeVariation() return item.SizeVariation.Size.Name }
go
func (item *OrderItem) SizeName() string { item.loadSizeVariation() return item.SizeVariation.Size.Name }
[ "func", "(", "item", "*", "OrderItem", ")", "SizeName", "(", ")", "string", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "Size", ".", "Name", "\n", "}" ]
// SizeName order item's size name
[ "SizeName", "order", "item", "s", "size", "name" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L61-L64
train
qor/qor-example
models/orders/order_item.go
ProductPath
func (item *OrderItem) ProductPath() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.ViewPath() }
go
func (item *OrderItem) ProductPath() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.ViewPath() }
[ "func", "(", "item", "*", "OrderItem", ")", "ProductPath", "(", ")", "string", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "ColorVariation", ".", "ViewPath", "(", ")", "\n", "}" ]
// ProductPath order item's product name
[ "ProductPath", "order", "item", "s", "product", "name" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L67-L70
train
qor/qor-example
models/orders/order_item.go
Amount
func (item OrderItem) Amount() float32 { amount := item.SellingPrice() * float32(item.Quantity) if item.DiscountRate > 0 && item.DiscountRate <= 100 { amount = amount * float32(100-item.DiscountRate) / 100 } return amount }
go
func (item OrderItem) Amount() float32 { amount := item.SellingPrice() * float32(item.Quantity) if item.DiscountRate > 0 && item.DiscountRate <= 100 { amount = amount * float32(100-item.DiscountRate) / 100 } return amount }
[ "func", "(", "item", "OrderItem", ")", "Amount", "(", ")", "float32", "{", "amount", ":=", "item", ".", "SellingPrice", "(", ")", "*", "float32", "(", "item", ".", "Quantity", ")", "\n", "if", "item", ".", "DiscountRate", ">", "0", "&&", "item", ".",...
// Amount order item's amount
[ "Amount", "order", "item", "s", "amount" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L73-L79
train
qor/qor-example
app/admin/dashboard.go
SetupDashboard
func SetupDashboard(Admin *admin.Admin) { // Add Dashboard Admin.AddMenu(&admin.Menu{Name: "Dashboard", Link: "/admin", Priority: 1}) Admin.GetRouter().Get("/reports", ReportsDataHandler) initFuncMap(Admin) }
go
func SetupDashboard(Admin *admin.Admin) { // Add Dashboard Admin.AddMenu(&admin.Menu{Name: "Dashboard", Link: "/admin", Priority: 1}) Admin.GetRouter().Get("/reports", ReportsDataHandler) initFuncMap(Admin) }
[ "func", "SetupDashboard", "(", "Admin", "*", "admin", ".", "Admin", ")", "{", "Admin", ".", "AddMenu", "(", "&", "admin", ".", "Menu", "{", "Name", ":", "\"Dashboard\"", ",", "Link", ":", "\"/admin\"", ",", "Priority", ":", "1", "}", ")", "\n", "Admi...
// SetupDashboard setup dashboard
[ "SetupDashboard", "setup", "dashboard" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/admin/dashboard.go#L61-L67
train
qor/qor-example
app/api/api.go
New
func New(config *Config) *App { if config.Prefix == "" { config.Prefix = "/api" } return &App{Config: config} }
go
func New(config *Config) *App { if config.Prefix == "" { config.Prefix = "/api" } return &App{Config: config} }
[ "func", "New", "(", "config", "*", "Config", ")", "*", "App", "{", "if", "config", ".", "Prefix", "==", "\"\"", "{", "config", ".", "Prefix", "=", "\"/api\"", "\n", "}", "\n", "return", "&", "App", "{", "Config", ":", "config", "}", "\n", "}" ]
// New new home app
[ "New", "new", "home", "app" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/api/api.go#L14-L19
train
qor/qor-example
app/admin/seo.go
SetupSEO
func SetupSEO(Admin *admin.Admin) { seo.SEOCollection = qor_seo.New("Common SEO") seo.SEOCollection.RegisterGlobalVaribles(&seo.SEOGlobalSetting{SiteName: "Qor Shop"}) seo.SEOCollection.SettingResource = Admin.AddResource(&seo.MySEOSetting{}, &admin.Config{Invisible: true}) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Default Page", }) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Product Page", Varibles: []string{"Name", "Code", "CategoryName"}, Context: func(objects ...interface{}) map[string]string { product := objects[0].(products.Product) context := make(map[string]string) context["Name"] = product.Name context["Code"] = product.Code context["CategoryName"] = product.Category.Name return context }, }) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Category Page", Varibles: []string{"Name", "Code"}, Context: func(objects ...interface{}) map[string]string { category := objects[0].(products.Category) context := make(map[string]string) context["Name"] = category.Name context["Code"] = category.Code return context }, }) Admin.AddResource(seo.SEOCollection, &admin.Config{Name: "SEO Setting", Menu: []string{"Site Management"}, Singleton: true, Priority: 2}) }
go
func SetupSEO(Admin *admin.Admin) { seo.SEOCollection = qor_seo.New("Common SEO") seo.SEOCollection.RegisterGlobalVaribles(&seo.SEOGlobalSetting{SiteName: "Qor Shop"}) seo.SEOCollection.SettingResource = Admin.AddResource(&seo.MySEOSetting{}, &admin.Config{Invisible: true}) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Default Page", }) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Product Page", Varibles: []string{"Name", "Code", "CategoryName"}, Context: func(objects ...interface{}) map[string]string { product := objects[0].(products.Product) context := make(map[string]string) context["Name"] = product.Name context["Code"] = product.Code context["CategoryName"] = product.Category.Name return context }, }) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Category Page", Varibles: []string{"Name", "Code"}, Context: func(objects ...interface{}) map[string]string { category := objects[0].(products.Category) context := make(map[string]string) context["Name"] = category.Name context["Code"] = category.Code return context }, }) Admin.AddResource(seo.SEOCollection, &admin.Config{Name: "SEO Setting", Menu: []string{"Site Management"}, Singleton: true, Priority: 2}) }
[ "func", "SetupSEO", "(", "Admin", "*", "admin", ".", "Admin", ")", "{", "seo", ".", "SEOCollection", "=", "qor_seo", ".", "New", "(", "\"Common SEO\"", ")", "\n", "seo", ".", "SEOCollection", ".", "RegisterGlobalVaribles", "(", "&", "seo", ".", "SEOGlobalS...
// SetupSEO add seo
[ "SetupSEO", "add", "seo" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/admin/seo.go#L11-L42
train
qor/qor-example
app/home/handlers.go
Index
func (ctrl Controller) Index(w http.ResponseWriter, req *http.Request) { ctrl.View.Execute("index", map[string]interface{}{}, req, w) }
go
func (ctrl Controller) Index(w http.ResponseWriter, req *http.Request) { ctrl.View.Execute("index", map[string]interface{}{}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Index", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "ctrl", ".", "View", ".", "Execute", "(", "\"index\"", ",", "map", "[", "string", "]", "interface", "{", "}",...
// Index home index page
[ "Index", "home", "index", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/home/handlers.go#L17-L19
train
qor/qor-example
app/home/handlers.go
SwitchLocale
func (ctrl Controller) SwitchLocale(w http.ResponseWriter, req *http.Request) { utils.SetCookie(http.Cookie{Name: "locale", Value: req.URL.Query().Get("locale")}, &qor.Context{Request: req, Writer: w}) http.Redirect(w, req, req.Referer(), http.StatusSeeOther) }
go
func (ctrl Controller) SwitchLocale(w http.ResponseWriter, req *http.Request) { utils.SetCookie(http.Cookie{Name: "locale", Value: req.URL.Query().Get("locale")}, &qor.Context{Request: req, Writer: w}) http.Redirect(w, req, req.Referer(), http.StatusSeeOther) }
[ "func", "(", "ctrl", "Controller", ")", "SwitchLocale", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "utils", ".", "SetCookie", "(", "http", ".", "Cookie", "{", "Name", ":", "\"locale\"", ",", "Value", ":"...
// SwitchLocale switch locale
[ "SwitchLocale", "switch", "locale" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/home/handlers.go#L22-L25
train
qor/qor-example
config/application/application.go
New
func New(cfg *Config) *Application { if cfg == nil { cfg = &Config{} } if cfg.Router == nil { cfg.Router = chi.NewRouter() } if cfg.AssetFS == nil { cfg.AssetFS = assetfs.AssetFS() } return &Application{ Config: cfg, } }
go
func New(cfg *Config) *Application { if cfg == nil { cfg = &Config{} } if cfg.Router == nil { cfg.Router = chi.NewRouter() } if cfg.AssetFS == nil { cfg.AssetFS = assetfs.AssetFS() } return &Application{ Config: cfg, } }
[ "func", "New", "(", "cfg", "*", "Config", ")", "*", "Application", "{", "if", "cfg", "==", "nil", "{", "cfg", "=", "&", "Config", "{", "}", "\n", "}", "\n", "if", "cfg", ".", "Router", "==", "nil", "{", "cfg", ".", "Router", "=", "chi", ".", ...
// New new application
[ "New", "new", "application" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/config/application/application.go#L34-L50
train