id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
12,300
mattetti/audio
dsp/filters/sinc.go
LowPassCoefs
func (s *Sinc) LowPassCoefs() []float64 { if s == nil { return nil } if s._lowPassCoefs != nil && len(s._lowPassCoefs) > 0 { return s._lowPassCoefs } size := s.Taps + 1 // sample rate is 2 pi radians per second. // we get the cutt off frequency in radians per second b := (2 * math.Pi) * s.TransitionFreq() s._lowPassCoefs = make([]float64, size) // we use a window of size taps + 1 winData := s.Window(size) // we only do half the taps because the coefs are symmetric // but we fill up all the coefs for i := 0; i < (s.Taps / 2); i++ { c := float64(i) - float64(s.Taps)/2 y := math.Sin(c*b) / (math.Pi * c) s._lowPassCoefs[i] = y * winData[i] s._lowPassCoefs[size-1-i] = s._lowPassCoefs[i] } // then we do the ones we missed in case we have an odd number of taps s._lowPassCoefs[s.Taps/2] = 2 * s.TransitionFreq() * winData[s.Taps/2] return s._lowPassCoefs }
go
func (s *Sinc) LowPassCoefs() []float64 { if s == nil { return nil } if s._lowPassCoefs != nil && len(s._lowPassCoefs) > 0 { return s._lowPassCoefs } size := s.Taps + 1 // sample rate is 2 pi radians per second. // we get the cutt off frequency in radians per second b := (2 * math.Pi) * s.TransitionFreq() s._lowPassCoefs = make([]float64, size) // we use a window of size taps + 1 winData := s.Window(size) // we only do half the taps because the coefs are symmetric // but we fill up all the coefs for i := 0; i < (s.Taps / 2); i++ { c := float64(i) - float64(s.Taps)/2 y := math.Sin(c*b) / (math.Pi * c) s._lowPassCoefs[i] = y * winData[i] s._lowPassCoefs[size-1-i] = s._lowPassCoefs[i] } // then we do the ones we missed in case we have an odd number of taps s._lowPassCoefs[s.Taps/2] = 2 * s.TransitionFreq() * winData[s.Taps/2] return s._lowPassCoefs }
[ "func", "(", "s", "*", "Sinc", ")", "LowPassCoefs", "(", ")", "[", "]", "float64", "{", "if", "s", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "s", ".", "_lowPassCoefs", "!=", "nil", "&&", "len", "(", "s", ".", "_lowPassCoefs", ")", ">", "0", "{", "return", "s", ".", "_lowPassCoefs", "\n", "}", "\n", "size", ":=", "s", ".", "Taps", "+", "1", "\n", "// sample rate is 2 pi radians per second.", "// we get the cutt off frequency in radians per second", "b", ":=", "(", "2", "*", "math", ".", "Pi", ")", "*", "s", ".", "TransitionFreq", "(", ")", "\n", "s", ".", "_lowPassCoefs", "=", "make", "(", "[", "]", "float64", ",", "size", ")", "\n", "// we use a window of size taps + 1", "winData", ":=", "s", ".", "Window", "(", "size", ")", "\n\n", "// we only do half the taps because the coefs are symmetric", "// but we fill up all the coefs", "for", "i", ":=", "0", ";", "i", "<", "(", "s", ".", "Taps", "/", "2", ")", ";", "i", "++", "{", "c", ":=", "float64", "(", "i", ")", "-", "float64", "(", "s", ".", "Taps", ")", "/", "2", "\n", "y", ":=", "math", ".", "Sin", "(", "c", "*", "b", ")", "/", "(", "math", ".", "Pi", "*", "c", ")", "\n", "s", ".", "_lowPassCoefs", "[", "i", "]", "=", "y", "*", "winData", "[", "i", "]", "\n", "s", ".", "_lowPassCoefs", "[", "size", "-", "1", "-", "i", "]", "=", "s", ".", "_lowPassCoefs", "[", "i", "]", "\n", "}", "\n\n", "// then we do the ones we missed in case we have an odd number of taps", "s", ".", "_lowPassCoefs", "[", "s", ".", "Taps", "/", "2", "]", "=", "2", "*", "s", ".", "TransitionFreq", "(", ")", "*", "winData", "[", "s", ".", "Taps", "/", "2", "]", "\n", "return", "s", ".", "_lowPassCoefs", "\n", "}" ]
// LowPassCoefs returns the coeficients to create a low pass filter
[ "LowPassCoefs", "returns", "the", "coeficients", "to", "create", "a", "low", "pass", "filter" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/dsp/filters/sinc.go#L28-L55
12,301
mattetti/audio
dsp/filters/sinc.go
HighPassCoefs
func (s *Sinc) HighPassCoefs() []float64 { if s == nil { return nil } if s._highPassCoefs != nil && len(s._highPassCoefs) > 0 { return s._highPassCoefs } // we take the low pass coesf and invert them size := s.Taps + 1 s._highPassCoefs = make([]float64, size) lowPassCoefs := s.LowPassCoefs() winData := s.Window(size) for i := 0; i < (s.Taps / 2); i++ { s._highPassCoefs[i] = -lowPassCoefs[i] s._highPassCoefs[size-1-i] = s._highPassCoefs[i] } s._highPassCoefs[s.Taps/2] = (1 - 2*s.TransitionFreq()) * winData[s.Taps/2] return s._highPassCoefs }
go
func (s *Sinc) HighPassCoefs() []float64 { if s == nil { return nil } if s._highPassCoefs != nil && len(s._highPassCoefs) > 0 { return s._highPassCoefs } // we take the low pass coesf and invert them size := s.Taps + 1 s._highPassCoefs = make([]float64, size) lowPassCoefs := s.LowPassCoefs() winData := s.Window(size) for i := 0; i < (s.Taps / 2); i++ { s._highPassCoefs[i] = -lowPassCoefs[i] s._highPassCoefs[size-1-i] = s._highPassCoefs[i] } s._highPassCoefs[s.Taps/2] = (1 - 2*s.TransitionFreq()) * winData[s.Taps/2] return s._highPassCoefs }
[ "func", "(", "s", "*", "Sinc", ")", "HighPassCoefs", "(", ")", "[", "]", "float64", "{", "if", "s", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "s", ".", "_highPassCoefs", "!=", "nil", "&&", "len", "(", "s", ".", "_highPassCoefs", ")", ">", "0", "{", "return", "s", ".", "_highPassCoefs", "\n", "}", "\n\n", "// we take the low pass coesf and invert them", "size", ":=", "s", ".", "Taps", "+", "1", "\n", "s", ".", "_highPassCoefs", "=", "make", "(", "[", "]", "float64", ",", "size", ")", "\n", "lowPassCoefs", ":=", "s", ".", "LowPassCoefs", "(", ")", "\n", "winData", ":=", "s", ".", "Window", "(", "size", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "(", "s", ".", "Taps", "/", "2", ")", ";", "i", "++", "{", "s", ".", "_highPassCoefs", "[", "i", "]", "=", "-", "lowPassCoefs", "[", "i", "]", "\n", "s", ".", "_highPassCoefs", "[", "size", "-", "1", "-", "i", "]", "=", "s", ".", "_highPassCoefs", "[", "i", "]", "\n", "}", "\n", "s", ".", "_highPassCoefs", "[", "s", ".", "Taps", "/", "2", "]", "=", "(", "1", "-", "2", "*", "s", ".", "TransitionFreq", "(", ")", ")", "*", "winData", "[", "s", ".", "Taps", "/", "2", "]", "\n", "return", "s", ".", "_highPassCoefs", "\n", "}" ]
// HighPassCoefs returns the coeficients to create a high pass filter
[ "HighPassCoefs", "returns", "the", "coeficients", "to", "create", "a", "high", "pass", "filter" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/dsp/filters/sinc.go#L58-L78
12,302
mattetti/audio
dsp/filters/sinc.go
TransitionFreq
func (s *Sinc) TransitionFreq() float64 { if s == nil { return 0 } return s.CutOffFreq / float64(s.SamplingFreq) }
go
func (s *Sinc) TransitionFreq() float64 { if s == nil { return 0 } return s.CutOffFreq / float64(s.SamplingFreq) }
[ "func", "(", "s", "*", "Sinc", ")", "TransitionFreq", "(", ")", "float64", "{", "if", "s", "==", "nil", "{", "return", "0", "\n", "}", "\n", "return", "s", ".", "CutOffFreq", "/", "float64", "(", "s", ".", "SamplingFreq", ")", "\n", "}" ]
// TransitionFreq returns a ratio of the cutoff frequency and the sample rate.
[ "TransitionFreq", "returns", "a", "ratio", "of", "the", "cutoff", "frequency", "and", "the", "sample", "rate", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/dsp/filters/sinc.go#L81-L86
12,303
mattetti/audio
midi/event.go
EndOfTrack
func EndOfTrack() *Event { return &Event{ MsgType: uint8(EventByteMap["Meta"]), MsgChan: uint8(15), Cmd: MetaByteMap["End of Track"], } }
go
func EndOfTrack() *Event { return &Event{ MsgType: uint8(EventByteMap["Meta"]), MsgChan: uint8(15), Cmd: MetaByteMap["End of Track"], } }
[ "func", "EndOfTrack", "(", ")", "*", "Event", "{", "return", "&", "Event", "{", "MsgType", ":", "uint8", "(", "EventByteMap", "[", "\"", "\"", "]", ")", ",", "MsgChan", ":", "uint8", "(", "15", ")", ",", "Cmd", ":", "MetaByteMap", "[", "\"", "\"", "]", ",", "}", "\n", "}" ]
// EndOfTrack indicates the end of the midi track. Note that this event is // automatically added when encoding a normal track.
[ "EndOfTrack", "indicates", "the", "end", "of", "the", "midi", "track", ".", "Note", "that", "this", "event", "is", "automatically", "added", "when", "encoding", "a", "normal", "track", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/event.go#L33-L39
12,304
mattetti/audio
midi/event.go
Aftertouch
func Aftertouch(channel, key, vel int) *Event { return &Event{ MsgChan: uint8(channel), MsgType: uint8(EventByteMap["AfterTouch"]), Note: uint8(key), Velocity: uint8(vel), } }
go
func Aftertouch(channel, key, vel int) *Event { return &Event{ MsgChan: uint8(channel), MsgType: uint8(EventByteMap["AfterTouch"]), Note: uint8(key), Velocity: uint8(vel), } }
[ "func", "Aftertouch", "(", "channel", ",", "key", ",", "vel", "int", ")", "*", "Event", "{", "return", "&", "Event", "{", "MsgChan", ":", "uint8", "(", "channel", ")", ",", "MsgType", ":", "uint8", "(", "EventByteMap", "[", "\"", "\"", "]", ")", ",", "Note", ":", "uint8", "(", "key", ")", ",", "Velocity", ":", "uint8", "(", "vel", ")", ",", "}", "\n", "}" ]
// AfterTouch returns a pointer to a new aftertouch event
[ "AfterTouch", "returns", "a", "pointer", "to", "a", "new", "aftertouch", "event" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/event.go#L42-L49
12,305
mattetti/audio
midi/event.go
ControlChange
func ControlChange(channel, controller, newVal int) *Event { return &Event{ MsgChan: uint8(channel), MsgType: uint8(EventByteMap["ControlChange"]), Controller: uint8(controller), NewValue: uint8(newVal), } }
go
func ControlChange(channel, controller, newVal int) *Event { return &Event{ MsgChan: uint8(channel), MsgType: uint8(EventByteMap["ControlChange"]), Controller: uint8(controller), NewValue: uint8(newVal), } }
[ "func", "ControlChange", "(", "channel", ",", "controller", ",", "newVal", "int", ")", "*", "Event", "{", "return", "&", "Event", "{", "MsgChan", ":", "uint8", "(", "channel", ")", ",", "MsgType", ":", "uint8", "(", "EventByteMap", "[", "\"", "\"", "]", ")", ",", "Controller", ":", "uint8", "(", "controller", ")", ",", "NewValue", ":", "uint8", "(", "newVal", ")", ",", "}", "\n", "}" ]
// ControlChange sets a new value for a given controller // The controller number is between 0-119. // The new controller value is between 0-127.
[ "ControlChange", "sets", "a", "new", "value", "for", "a", "given", "controller", "The", "controller", "number", "is", "between", "0", "-", "119", ".", "The", "new", "controller", "value", "is", "between", "0", "-", "127", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/event.go#L54-L61
12,306
mattetti/audio
midi/event.go
ChannelAfterTouch
func ChannelAfterTouch(channel, vel int) *Event { return &Event{ MsgChan: uint8(channel), MsgType: uint8(EventByteMap["ChannelAfterTouch"]), Pressure: uint8(vel), } }
go
func ChannelAfterTouch(channel, vel int) *Event { return &Event{ MsgChan: uint8(channel), MsgType: uint8(EventByteMap["ChannelAfterTouch"]), Pressure: uint8(vel), } }
[ "func", "ChannelAfterTouch", "(", "channel", ",", "vel", "int", ")", "*", "Event", "{", "return", "&", "Event", "{", "MsgChan", ":", "uint8", "(", "channel", ")", ",", "MsgType", ":", "uint8", "(", "EventByteMap", "[", "\"", "\"", "]", ")", ",", "Pressure", ":", "uint8", "(", "vel", ")", ",", "}", "\n", "}" ]
// ChannelAfterTouch is a global aftertouch with a value from 0 to 127
[ "ChannelAfterTouch", "is", "a", "global", "aftertouch", "with", "a", "value", "from", "0", "to", "127" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/event.go#L75-L81
12,307
mattetti/audio
midi/event.go
PitchWheelChange
func PitchWheelChange(channel, int, val int) *Event { return &Event{ MsgChan: uint8(channel), MsgType: uint8(EventByteMap["PitchWheelChange"]), AbsPitchBend: uint16(val), } }
go
func PitchWheelChange(channel, int, val int) *Event { return &Event{ MsgChan: uint8(channel), MsgType: uint8(EventByteMap["PitchWheelChange"]), AbsPitchBend: uint16(val), } }
[ "func", "PitchWheelChange", "(", "channel", ",", "int", ",", "val", "int", ")", "*", "Event", "{", "return", "&", "Event", "{", "MsgChan", ":", "uint8", "(", "channel", ")", ",", "MsgType", ":", "uint8", "(", "EventByteMap", "[", "\"", "\"", "]", ")", ",", "AbsPitchBend", ":", "uint16", "(", "val", ")", ",", "}", "\n", "}" ]
// PitchWheelChange is sent to indicate a change in the pitch bender. // The possible value goes between 0 and 16383 where 8192 is the center.
[ "PitchWheelChange", "is", "sent", "to", "indicate", "a", "change", "in", "the", "pitch", "bender", ".", "The", "possible", "value", "goes", "between", "0", "and", "16383", "where", "8192", "is", "the", "center", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/event.go#L85-L91
12,308
mattetti/audio
midi/event.go
CopyrightEvent
func CopyrightEvent(txt string) *Event { return &Event{ MsgType: uint8(EventByteMap["Meta"]), Cmd: uint8(MetaByteMap["Copyright"]), Copyright: txt, } }
go
func CopyrightEvent(txt string) *Event { return &Event{ MsgType: uint8(EventByteMap["Meta"]), Cmd: uint8(MetaByteMap["Copyright"]), Copyright: txt, } }
[ "func", "CopyrightEvent", "(", "txt", "string", ")", "*", "Event", "{", "return", "&", "Event", "{", "MsgType", ":", "uint8", "(", "EventByteMap", "[", "\"", "\"", "]", ")", ",", "Cmd", ":", "uint8", "(", "MetaByteMap", "[", "\"", "\"", "]", ")", ",", "Copyright", ":", "txt", ",", "}", "\n", "}" ]
// CopyrightEvent returns a copyright event with the passed string in it.
[ "CopyrightEvent", "returns", "a", "copyright", "event", "with", "the", "passed", "string", "in", "it", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/event.go#L94-L100
12,309
mattetti/audio
midi/event.go
TempoEvent
func TempoEvent(bpmF float64) *Event { ms := uint32(60000000 / bpmF) // bpm is expressed in in microseconds per MIDI quarter-note // This event indicates a tempo change. Another way of putting // "microseconds per quarter-note" is "24ths of a microsecond per MIDI // clock". Representing tempos as time per beat instead of beat per time // allows absolutely exact dword-term synchronization with a time-based sync // protocol such as SMPTE time code or MIDI time code. This amount of // accuracy provided by this tempo resolution allows a four-minute piece at // 120 beats per minute to be accurate within 500 usec at the end of the // piece. Ideally, these events should only occur where MIDI clocks would // be located Q this convention is intended to guarantee, or at least // increase the likelihood, of compatibility with other synchronization // devices so that a time signature/tempo map stored in this format may // easily be transferred to another device. return &Event{ MsgType: uint8(EventByteMap["Meta"]), Cmd: uint8(MetaByteMap["Tempo"]), MsPerQuartNote: ms, } }
go
func TempoEvent(bpmF float64) *Event { ms := uint32(60000000 / bpmF) // bpm is expressed in in microseconds per MIDI quarter-note // This event indicates a tempo change. Another way of putting // "microseconds per quarter-note" is "24ths of a microsecond per MIDI // clock". Representing tempos as time per beat instead of beat per time // allows absolutely exact dword-term synchronization with a time-based sync // protocol such as SMPTE time code or MIDI time code. This amount of // accuracy provided by this tempo resolution allows a four-minute piece at // 120 beats per minute to be accurate within 500 usec at the end of the // piece. Ideally, these events should only occur where MIDI clocks would // be located Q this convention is intended to guarantee, or at least // increase the likelihood, of compatibility with other synchronization // devices so that a time signature/tempo map stored in this format may // easily be transferred to another device. return &Event{ MsgType: uint8(EventByteMap["Meta"]), Cmd: uint8(MetaByteMap["Tempo"]), MsPerQuartNote: ms, } }
[ "func", "TempoEvent", "(", "bpmF", "float64", ")", "*", "Event", "{", "ms", ":=", "uint32", "(", "60000000", "/", "bpmF", ")", "\n\n", "// bpm is expressed in in microseconds per MIDI quarter-note", "// This event indicates a tempo change. Another way of putting", "// \"microseconds per quarter-note\" is \"24ths of a microsecond per MIDI", "// clock\". Representing tempos as time per beat instead of beat per time", "// allows absolutely exact dword-term synchronization with a time-based sync", "// protocol such as SMPTE time code or MIDI time code. This amount of", "// accuracy provided by this tempo resolution allows a four-minute piece at", "// 120 beats per minute to be accurate within 500 usec at the end of the", "// piece. Ideally, these events should only occur where MIDI clocks would", "// be located Q this convention is intended to guarantee, or at least", "// increase the likelihood, of compatibility with other synchronization", "// devices so that a time signature/tempo map stored in this format may", "// easily be transferred to another device.", "return", "&", "Event", "{", "MsgType", ":", "uint8", "(", "EventByteMap", "[", "\"", "\"", "]", ")", ",", "Cmd", ":", "uint8", "(", "MetaByteMap", "[", "\"", "\"", "]", ")", ",", "MsPerQuartNote", ":", "ms", ",", "}", "\n", "}" ]
// TempoEvent returns a new tempo event of the passed value.
[ "TempoEvent", "returns", "a", "new", "tempo", "event", "of", "the", "passed", "value", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/event.go#L103-L124
12,310
mattetti/audio
midi/event.go
Copy
func (e *Event) Copy() *Event { newEv := &Event{ TimeDelta: e.TimeDelta, MsgType: e.MsgType, MsgChan: e.MsgChan, Note: e.Note, Velocity: e.Velocity, Pressure: e.Pressure, Controller: e.Controller, NewValue: e.NewValue, NewProgram: e.NewProgram, Channel: e.Channel, AbsPitchBend: e.AbsPitchBend, RelPitchBend: e.RelPitchBend, // Meta Cmd: e.Cmd, SeqNum: e.SeqNum, Text: e.Text, Copyright: e.Copyright, SeqTrackName: e.SeqTrackName, InstrumentName: e.InstrumentName, Lyric: e.Lyric, Marker: e.Marker, CuePoint: e.CuePoint, MsPerQuartNote: e.MsPerQuartNote, Bpm: e.Bpm, Key: e.Key, Scale: e.Scale, } if e.TimeSignature != nil { newEv.TimeSignature = &TimeSignature{ Numerator: e.TimeSignature.Numerator, Denominator: e.TimeSignature.Denominator, ClocksPerTick: e.TimeSignature.ClocksPerTick, ThirtySecondNotesPerQuarter: e.TimeSignature.ThirtySecondNotesPerQuarter, } } if e.SmpteOffset != nil { newEv.SmpteOffset = &SmpteOffset{ Hour: e.SmpteOffset.Hour, Min: e.SmpteOffset.Min, Sec: e.SmpteOffset.Sec, Fr: e.SmpteOffset.Fr, SubFr: e.SmpteOffset.SubFr, } } return newEv }
go
func (e *Event) Copy() *Event { newEv := &Event{ TimeDelta: e.TimeDelta, MsgType: e.MsgType, MsgChan: e.MsgChan, Note: e.Note, Velocity: e.Velocity, Pressure: e.Pressure, Controller: e.Controller, NewValue: e.NewValue, NewProgram: e.NewProgram, Channel: e.Channel, AbsPitchBend: e.AbsPitchBend, RelPitchBend: e.RelPitchBend, // Meta Cmd: e.Cmd, SeqNum: e.SeqNum, Text: e.Text, Copyright: e.Copyright, SeqTrackName: e.SeqTrackName, InstrumentName: e.InstrumentName, Lyric: e.Lyric, Marker: e.Marker, CuePoint: e.CuePoint, MsPerQuartNote: e.MsPerQuartNote, Bpm: e.Bpm, Key: e.Key, Scale: e.Scale, } if e.TimeSignature != nil { newEv.TimeSignature = &TimeSignature{ Numerator: e.TimeSignature.Numerator, Denominator: e.TimeSignature.Denominator, ClocksPerTick: e.TimeSignature.ClocksPerTick, ThirtySecondNotesPerQuarter: e.TimeSignature.ThirtySecondNotesPerQuarter, } } if e.SmpteOffset != nil { newEv.SmpteOffset = &SmpteOffset{ Hour: e.SmpteOffset.Hour, Min: e.SmpteOffset.Min, Sec: e.SmpteOffset.Sec, Fr: e.SmpteOffset.Fr, SubFr: e.SmpteOffset.SubFr, } } return newEv }
[ "func", "(", "e", "*", "Event", ")", "Copy", "(", ")", "*", "Event", "{", "newEv", ":=", "&", "Event", "{", "TimeDelta", ":", "e", ".", "TimeDelta", ",", "MsgType", ":", "e", ".", "MsgType", ",", "MsgChan", ":", "e", ".", "MsgChan", ",", "Note", ":", "e", ".", "Note", ",", "Velocity", ":", "e", ".", "Velocity", ",", "Pressure", ":", "e", ".", "Pressure", ",", "Controller", ":", "e", ".", "Controller", ",", "NewValue", ":", "e", ".", "NewValue", ",", "NewProgram", ":", "e", ".", "NewProgram", ",", "Channel", ":", "e", ".", "Channel", ",", "AbsPitchBend", ":", "e", ".", "AbsPitchBend", ",", "RelPitchBend", ":", "e", ".", "RelPitchBend", ",", "// Meta", "Cmd", ":", "e", ".", "Cmd", ",", "SeqNum", ":", "e", ".", "SeqNum", ",", "Text", ":", "e", ".", "Text", ",", "Copyright", ":", "e", ".", "Copyright", ",", "SeqTrackName", ":", "e", ".", "SeqTrackName", ",", "InstrumentName", ":", "e", ".", "InstrumentName", ",", "Lyric", ":", "e", ".", "Lyric", ",", "Marker", ":", "e", ".", "Marker", ",", "CuePoint", ":", "e", ".", "CuePoint", ",", "MsPerQuartNote", ":", "e", ".", "MsPerQuartNote", ",", "Bpm", ":", "e", ".", "Bpm", ",", "Key", ":", "e", ".", "Key", ",", "Scale", ":", "e", ".", "Scale", ",", "}", "\n", "if", "e", ".", "TimeSignature", "!=", "nil", "{", "newEv", ".", "TimeSignature", "=", "&", "TimeSignature", "{", "Numerator", ":", "e", ".", "TimeSignature", ".", "Numerator", ",", "Denominator", ":", "e", ".", "TimeSignature", ".", "Denominator", ",", "ClocksPerTick", ":", "e", ".", "TimeSignature", ".", "ClocksPerTick", ",", "ThirtySecondNotesPerQuarter", ":", "e", ".", "TimeSignature", ".", "ThirtySecondNotesPerQuarter", ",", "}", "\n", "}", "\n", "if", "e", ".", "SmpteOffset", "!=", "nil", "{", "newEv", ".", "SmpteOffset", "=", "&", "SmpteOffset", "{", "Hour", ":", "e", ".", "SmpteOffset", ".", "Hour", ",", "Min", ":", "e", ".", "SmpteOffset", ".", "Min", ",", "Sec", ":", "e", ".", "SmpteOffset", ".", "Sec", ",", "Fr", ":", "e", ".", "SmpteOffset", ".", "Fr", ",", "SubFr", ":", "e", ".", "SmpteOffset", ".", "SubFr", ",", "}", "\n", "}", "\n", "return", "newEv", "\n", "}" ]
// Copy returns an exact copy of the event
[ "Copy", "returns", "an", "exact", "copy", "of", "the", "event" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/event.go#L176-L223
12,311
mattetti/audio
midi/event.go
Encode
func (e *Event) Encode() []byte { buff := bytes.NewBuffer(nil) buff.Write(EncodeVarint(e.TimeDelta)) // msg type and chan are stored together msgData := []byte{(e.MsgType << 4) | e.MsgChan} if e.MsgType == EventByteMap["Meta"] { msgData = []byte{0xFF} } buff.Write(msgData) switch e.MsgType { // unknown but found in the wild (seems to come with 1 data bytes) case 0x2, 0x3, 0x4, 0x5, 0x6: buff.Write([]byte{0x0}) // Note Off/On case 0x8, 0x9, 0xA: // note binary.Write(buff, binary.BigEndian, e.Note) // velocity binary.Write(buff, binary.BigEndian, e.Velocity) // Control Change / Channel Mode // This message is sent when a controller value changes. // Controllers include devices such as pedals and levers. // Controller numbers 120-127 are reserved as "Channel Mode Messages". // The controller number is between 0-119. // The new controller value is between 0-127. case 0xB: binary.Write(buff, binary.BigEndian, e.Controller) binary.Write(buff, binary.BigEndian, e.NewValue) /* channel mode messages Documented, not technically exposed This the same code as the Control Change, but implements Mode control and special message by using reserved controller numbers 120-127. The commands are: All Sound Off c = 120, v = 0 When All Sound Off is received all oscillators will turn off, and their volume envelopes are set to zero as soon as possible. Reset All Controllers c = 121, v = x When Reset All Controllers is received, all controller values are reset to their default values. Value must only be zero unless otherwise allowed in a specific Recommended Practice. Local Control. c = 122, v = 0: Local Control Off c = 122, v = 127: Local Control On When Local Control is Off, all devices on a given channel will respond only to data received over MIDI. Played data, etc. will be ignored. Local Control On restores the functions of the normal controllers. All Notes Off. c = 123, v = 0: All Notes Off (See text for description of actual mode commands.) c = 124, v = 0: Omni Mode Off c = 125, v = 0: Omni Mode On c = 126, v = M: Mono Mode On (Poly Off) where M is the number of channels (Omni Off) or 0 (Omni On) c = 127, v = 0: Poly Mode On (Mono Off) (Note: These four messages also cause All Notes Off) When an All Notes Off is received, all oscillators will turn off. Program Change This message sent when the patch number changes. Value is the new program number. */ case 0xC: binary.Write(buff, binary.BigEndian, e.NewProgram) binary.Write(buff, binary.BigEndian, e.NewValue) // Channel Pressure (Aftertouch) // This message is most often sent by pressing down on the key after it "bottoms out". // This message is different from polyphonic after-touch. // Use this message to send the single greatest pressure value (of all the current depressed keys). // Value is the pressure value. // Most MIDI controllers don't generate Polyphonic Key AfterTouch because that requires a pressure sensor for each individual key // on a MIDI keyboard, and this is an expensive feature to implement. // For this reason, many cheaper units implement Channel Pressure instead of Aftertouch, as the former only requires // one sensor for the entire keyboard's pressure. case 0xD: binary.Write(buff, binary.BigEndian, e.Pressure) // Pitch Bend Change. // This message is sent to indicate a change in the pitch bender (wheel or lever, typically). // The pitch bender is measured by a fourteen bit value. Center (no pitch change) is 2000H. // Sensitivity is a function of the transmitter. // Last 7 bits of the first byte are the least significant 7 bits. // Last 7 bits of the second byte are the most significant 7 bits. case 0xE: // pitchbend lsb := byte(e.AbsPitchBend & 0x7F) msb := byte((e.AbsPitchBend & (0x7F << 7)) >> 7) binary.Write(buff, binary.BigEndian, []byte{lsb, msb}) // Meta // All meta-events start with FF followed by the command (xx), the length, // or number of bytes that will contain data (nn), and the actual data (dd). // meta_event = 0xFF + <meta_type> + <v_length> + <event_data_bytes> case 0xF: binary.Write(buff, binary.BigEndian, e.Cmd) switch e.Cmd { // Copyright Notice case 0x02: copyright := []byte(e.Copyright) binary.Write(buff, binary.BigEndian, EncodeVarint(uint32(len(copyright)))) binary.Write(buff, binary.BigEndian, copyright) // BPM / tempo event case 0x51: binary.Write(buff, binary.BigEndian, EncodeVarint(3)) binary.Write(buff, binary.BigEndian, Uint24(e.MsPerQuartNote)) case 0x2f: // end of track buff.WriteByte(0x0) } default: fmt.Printf("didn't encode %#v because didn't know how to\n", e) } return buff.Bytes() }
go
func (e *Event) Encode() []byte { buff := bytes.NewBuffer(nil) buff.Write(EncodeVarint(e.TimeDelta)) // msg type and chan are stored together msgData := []byte{(e.MsgType << 4) | e.MsgChan} if e.MsgType == EventByteMap["Meta"] { msgData = []byte{0xFF} } buff.Write(msgData) switch e.MsgType { // unknown but found in the wild (seems to come with 1 data bytes) case 0x2, 0x3, 0x4, 0x5, 0x6: buff.Write([]byte{0x0}) // Note Off/On case 0x8, 0x9, 0xA: // note binary.Write(buff, binary.BigEndian, e.Note) // velocity binary.Write(buff, binary.BigEndian, e.Velocity) // Control Change / Channel Mode // This message is sent when a controller value changes. // Controllers include devices such as pedals and levers. // Controller numbers 120-127 are reserved as "Channel Mode Messages". // The controller number is between 0-119. // The new controller value is between 0-127. case 0xB: binary.Write(buff, binary.BigEndian, e.Controller) binary.Write(buff, binary.BigEndian, e.NewValue) /* channel mode messages Documented, not technically exposed This the same code as the Control Change, but implements Mode control and special message by using reserved controller numbers 120-127. The commands are: All Sound Off c = 120, v = 0 When All Sound Off is received all oscillators will turn off, and their volume envelopes are set to zero as soon as possible. Reset All Controllers c = 121, v = x When Reset All Controllers is received, all controller values are reset to their default values. Value must only be zero unless otherwise allowed in a specific Recommended Practice. Local Control. c = 122, v = 0: Local Control Off c = 122, v = 127: Local Control On When Local Control is Off, all devices on a given channel will respond only to data received over MIDI. Played data, etc. will be ignored. Local Control On restores the functions of the normal controllers. All Notes Off. c = 123, v = 0: All Notes Off (See text for description of actual mode commands.) c = 124, v = 0: Omni Mode Off c = 125, v = 0: Omni Mode On c = 126, v = M: Mono Mode On (Poly Off) where M is the number of channels (Omni Off) or 0 (Omni On) c = 127, v = 0: Poly Mode On (Mono Off) (Note: These four messages also cause All Notes Off) When an All Notes Off is received, all oscillators will turn off. Program Change This message sent when the patch number changes. Value is the new program number. */ case 0xC: binary.Write(buff, binary.BigEndian, e.NewProgram) binary.Write(buff, binary.BigEndian, e.NewValue) // Channel Pressure (Aftertouch) // This message is most often sent by pressing down on the key after it "bottoms out". // This message is different from polyphonic after-touch. // Use this message to send the single greatest pressure value (of all the current depressed keys). // Value is the pressure value. // Most MIDI controllers don't generate Polyphonic Key AfterTouch because that requires a pressure sensor for each individual key // on a MIDI keyboard, and this is an expensive feature to implement. // For this reason, many cheaper units implement Channel Pressure instead of Aftertouch, as the former only requires // one sensor for the entire keyboard's pressure. case 0xD: binary.Write(buff, binary.BigEndian, e.Pressure) // Pitch Bend Change. // This message is sent to indicate a change in the pitch bender (wheel or lever, typically). // The pitch bender is measured by a fourteen bit value. Center (no pitch change) is 2000H. // Sensitivity is a function of the transmitter. // Last 7 bits of the first byte are the least significant 7 bits. // Last 7 bits of the second byte are the most significant 7 bits. case 0xE: // pitchbend lsb := byte(e.AbsPitchBend & 0x7F) msb := byte((e.AbsPitchBend & (0x7F << 7)) >> 7) binary.Write(buff, binary.BigEndian, []byte{lsb, msb}) // Meta // All meta-events start with FF followed by the command (xx), the length, // or number of bytes that will contain data (nn), and the actual data (dd). // meta_event = 0xFF + <meta_type> + <v_length> + <event_data_bytes> case 0xF: binary.Write(buff, binary.BigEndian, e.Cmd) switch e.Cmd { // Copyright Notice case 0x02: copyright := []byte(e.Copyright) binary.Write(buff, binary.BigEndian, EncodeVarint(uint32(len(copyright)))) binary.Write(buff, binary.BigEndian, copyright) // BPM / tempo event case 0x51: binary.Write(buff, binary.BigEndian, EncodeVarint(3)) binary.Write(buff, binary.BigEndian, Uint24(e.MsPerQuartNote)) case 0x2f: // end of track buff.WriteByte(0x0) } default: fmt.Printf("didn't encode %#v because didn't know how to\n", e) } return buff.Bytes() }
[ "func", "(", "e", "*", "Event", ")", "Encode", "(", ")", "[", "]", "byte", "{", "buff", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "buff", ".", "Write", "(", "EncodeVarint", "(", "e", ".", "TimeDelta", ")", ")", "\n\n", "// msg type and chan are stored together", "msgData", ":=", "[", "]", "byte", "{", "(", "e", ".", "MsgType", "<<", "4", ")", "|", "e", ".", "MsgChan", "}", "\n", "if", "e", ".", "MsgType", "==", "EventByteMap", "[", "\"", "\"", "]", "{", "msgData", "=", "[", "]", "byte", "{", "0xFF", "}", "\n", "}", "\n", "buff", ".", "Write", "(", "msgData", ")", "\n", "switch", "e", ".", "MsgType", "{", "// unknown but found in the wild (seems to come with 1 data bytes)", "case", "0x2", ",", "0x3", ",", "0x4", ",", "0x5", ",", "0x6", ":", "buff", ".", "Write", "(", "[", "]", "byte", "{", "0x0", "}", ")", "\n", "// Note Off/On", "case", "0x8", ",", "0x9", ",", "0xA", ":", "// note", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "e", ".", "Note", ")", "\n", "// velocity", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "e", ".", "Velocity", ")", "\n", "// Control Change / Channel Mode", "// This message is sent when a controller value changes.", "// Controllers include devices such as pedals and levers.", "// Controller numbers 120-127 are reserved as \"Channel Mode Messages\".", "// The controller number is between 0-119.", "// The new controller value is between 0-127.", "case", "0xB", ":", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "e", ".", "Controller", ")", "\n", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "e", ".", "NewValue", ")", "\n", "/*\n\t\t\tchannel mode messages\n\t\t\tDocumented, not technically exposed\n\n\t\t\tThis the same code as the Control Change, but implements Mode control and\n\t\t\tspecial message by using reserved controller numbers 120-127. The commands are:\n\n\t\t\tAll Sound Off\n\t\t\tc = 120, v = 0\n\t\t\tWhen All Sound Off is received all oscillators will turn off,\n\t\t\tand their volume envelopes are set to zero as soon as possible.\n\n\t\t\tReset All Controllers\n\t\t\tc = 121, v = x\n\t\t\tWhen Reset All Controllers is received, all controller values are reset to their default values.\n\t\t\tValue must only be zero unless otherwise allowed in a specific Recommended Practice.\n\n\t\t\tLocal Control.\n\t\t\tc = 122, v = 0: Local Control Off\n\t\t\tc = 122, v = 127: Local Control On\n\t\t\tWhen Local Control is Off, all devices on a given channel will respond only to data received over MIDI.\n\t\t\tPlayed data, etc. will be ignored. Local Control On restores the functions of the normal controllers.\n\n\t\t\tAll Notes Off.\n\t\t\tc = 123, v = 0: All Notes Off (See text for description of actual mode commands.)\n\t\t\tc = 124, v = 0: Omni Mode Off\n\t\t\tc = 125, v = 0: Omni Mode On\n\t\t\tc = 126, v = M: Mono Mode On (Poly Off) where M is the number of channels (Omni Off) or 0 (Omni On)\n\t\t\tc = 127, v = 0: Poly Mode On (Mono Off) (Note: These four messages also cause All Notes Off)\n\t\t\tWhen an All Notes Off is received, all oscillators will turn off.\n\t\t\tProgram Change\n\t\t\t\t\tThis message sent when the patch number changes. Value is the new program number.\n\t\t*/", "case", "0xC", ":", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "e", ".", "NewProgram", ")", "\n", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "e", ".", "NewValue", ")", "\n", "// Channel Pressure (Aftertouch)", "// This message is most often sent by pressing down on the key after it \"bottoms out\".", "// This message is different from polyphonic after-touch.", "// Use this message to send the single greatest pressure value (of all the current depressed keys).", "// Value is the pressure value.", "// Most MIDI controllers don't generate Polyphonic Key AfterTouch because that requires a pressure sensor for each individual key", "// on a MIDI keyboard, and this is an expensive feature to implement.", "// For this reason, many cheaper units implement Channel Pressure instead of Aftertouch, as the former only requires", "// one sensor for the entire keyboard's pressure.", "case", "0xD", ":", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "e", ".", "Pressure", ")", "\n", "// Pitch Bend Change.", "// This message is sent to indicate a change in the pitch bender (wheel or lever, typically).", "// The pitch bender is measured by a fourteen bit value. Center (no pitch change) is 2000H.", "// Sensitivity is a function of the transmitter.", "// Last 7 bits of the first byte are the least significant 7 bits.", "// Last 7 bits of the second byte are the most significant 7 bits.", "case", "0xE", ":", "// pitchbend", "lsb", ":=", "byte", "(", "e", ".", "AbsPitchBend", "&", "0x7F", ")", "\n", "msb", ":=", "byte", "(", "(", "e", ".", "AbsPitchBend", "&", "(", "0x7F", "<<", "7", ")", ")", ">>", "7", ")", "\n", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "[", "]", "byte", "{", "lsb", ",", "msb", "}", ")", "\n", "// Meta", "// All meta-events start with FF followed by the command (xx), the length,", "// or number of bytes that will contain data (nn), and the actual data (dd).", "// meta_event = 0xFF + <meta_type> + <v_length> + <event_data_bytes>", "case", "0xF", ":", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "e", ".", "Cmd", ")", "\n", "switch", "e", ".", "Cmd", "{", "// Copyright Notice", "case", "0x02", ":", "copyright", ":=", "[", "]", "byte", "(", "e", ".", "Copyright", ")", "\n", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "EncodeVarint", "(", "uint32", "(", "len", "(", "copyright", ")", ")", ")", ")", "\n", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "copyright", ")", "\n", "// BPM / tempo event", "case", "0x51", ":", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "EncodeVarint", "(", "3", ")", ")", "\n", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "Uint24", "(", "e", ".", "MsPerQuartNote", ")", ")", "\n", "case", "0x2f", ":", "// end of track", "buff", ".", "WriteByte", "(", "0x0", ")", "\n", "}", "\n", "default", ":", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "e", ")", "\n", "}", "\n\n", "return", "buff", ".", "Bytes", "(", ")", "\n", "}" ]
// Encode converts an Event into a slice of bytes ready to be written to a file.
[ "Encode", "converts", "an", "Event", "into", "a", "slice", "of", "bytes", "ready", "to", "be", "written", "to", "a", "file", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/event.go#L260-L371
12,312
mattetti/audio
midi/event.go
Size
func (e *Event) Size() uint32 { switch e.MsgType { case 0x2, 0x3, 0x4, 0x5, 0x6, 0xC, 0xD: return 1 // Note Off, On, aftertouch, control change case 0x8, 0x9, 0xA, 0xB, 0xE: return 2 case 0xF: // meta event switch e.Cmd { // Copyright Notice case 0x02: copyright := []byte(e.Copyright) varintBytes := EncodeVarint(uint32(len(copyright))) return uint32(len(copyright) + len(varintBytes)) // BPM (size + encoded in uint24) case 0x51: // tempo return 4 case 0x2f: // end of track return 1 default: // NOT currently support, blowing up on purpose log.Fatal(errors.New("Can't encode this meta event, it is not supported yet")) } } return 0 }
go
func (e *Event) Size() uint32 { switch e.MsgType { case 0x2, 0x3, 0x4, 0x5, 0x6, 0xC, 0xD: return 1 // Note Off, On, aftertouch, control change case 0x8, 0x9, 0xA, 0xB, 0xE: return 2 case 0xF: // meta event switch e.Cmd { // Copyright Notice case 0x02: copyright := []byte(e.Copyright) varintBytes := EncodeVarint(uint32(len(copyright))) return uint32(len(copyright) + len(varintBytes)) // BPM (size + encoded in uint24) case 0x51: // tempo return 4 case 0x2f: // end of track return 1 default: // NOT currently support, blowing up on purpose log.Fatal(errors.New("Can't encode this meta event, it is not supported yet")) } } return 0 }
[ "func", "(", "e", "*", "Event", ")", "Size", "(", ")", "uint32", "{", "switch", "e", ".", "MsgType", "{", "case", "0x2", ",", "0x3", ",", "0x4", ",", "0x5", ",", "0x6", ",", "0xC", ",", "0xD", ":", "return", "1", "\n", "// Note Off, On, aftertouch, control change", "case", "0x8", ",", "0x9", ",", "0xA", ",", "0xB", ",", "0xE", ":", "return", "2", "\n", "case", "0xF", ":", "// meta event", "switch", "e", ".", "Cmd", "{", "// Copyright Notice", "case", "0x02", ":", "copyright", ":=", "[", "]", "byte", "(", "e", ".", "Copyright", ")", "\n", "varintBytes", ":=", "EncodeVarint", "(", "uint32", "(", "len", "(", "copyright", ")", ")", ")", "\n", "return", "uint32", "(", "len", "(", "copyright", ")", "+", "len", "(", "varintBytes", ")", ")", "\n", "// BPM (size + encoded in uint24)", "case", "0x51", ":", "// tempo", "return", "4", "\n", "case", "0x2f", ":", "// end of track", "return", "1", "\n", "default", ":", "// NOT currently support, blowing up on purpose", "log", ".", "Fatal", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "\n", "return", "0", "\n", "}" ]
// Size represents the byte size to encode the event
[ "Size", "represents", "the", "byte", "size", "to", "encode", "the", "event" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/event.go#L374-L400
12,313
mattetti/audio
mp3/id3v2/id3v2.go
ReadHeader
func (t *Tag) ReadHeader(th TagHeader) error { // id3 tag ID if !th.IsValidID() { return ErrInvalidTagHeader } // version t.Header = &Header{ Version: th.ReadVersion(), Flags: th.ReadFlags(), } size, err := th.ReadSize() if err != nil { return err } t.Header.Size = size return nil }
go
func (t *Tag) ReadHeader(th TagHeader) error { // id3 tag ID if !th.IsValidID() { return ErrInvalidTagHeader } // version t.Header = &Header{ Version: th.ReadVersion(), Flags: th.ReadFlags(), } size, err := th.ReadSize() if err != nil { return err } t.Header.Size = size return nil }
[ "func", "(", "t", "*", "Tag", ")", "ReadHeader", "(", "th", "TagHeader", ")", "error", "{", "// id3 tag ID", "if", "!", "th", ".", "IsValidID", "(", ")", "{", "return", "ErrInvalidTagHeader", "\n", "}", "\n", "// version", "t", ".", "Header", "=", "&", "Header", "{", "Version", ":", "th", ".", "ReadVersion", "(", ")", ",", "Flags", ":", "th", ".", "ReadFlags", "(", ")", ",", "}", "\n", "size", ",", "err", ":=", "th", ".", "ReadSize", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "t", ".", "Header", ".", "Size", "=", "size", "\n\n", "return", "nil", "\n", "}" ]
// ReadHeader reads the 10 bytes header and parses the data which gets stored in // the tag header.
[ "ReadHeader", "reads", "the", "10", "bytes", "header", "and", "parses", "the", "data", "which", "gets", "stored", "in", "the", "tag", "header", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/id3v2/id3v2.go#L47-L64
12,314
mattetti/audio
aiff/encoder.go
Close
func (e *Encoder) Close() error { // go back and write total size if _, err := e.w.Seek(4, 0); err != nil { return err } if err := e.AddBE(uint32(e.WrittenBytes) - 8); err != nil { return fmt.Errorf("%v when writing the total written bytes", err) } if _, err := e.w.Seek(22, 0); err != nil { return err } if err := e.AddBE(uint32(e.frames)); err != nil { return fmt.Errorf("%v when writing the total of frames", err) } // rewrite the audio chunk length header if e.pcmChunkSizePos > 0 { if _, err := e.w.Seek(int64(e.pcmChunkSizePos), 0); err != nil { return err } chunksize := uint32((int(e.BitDepth)/8)*int(e.NumChans)*e.frames + 8) if err := e.AddBE(uint32(chunksize)); err != nil { return fmt.Errorf("%v when writing wav data chunk size header", err) } } // jump to the end of the file. e.w.Seek(0, 2) switch e.w.(type) { case *os.File: e.w.(*os.File).Sync() } return nil }
go
func (e *Encoder) Close() error { // go back and write total size if _, err := e.w.Seek(4, 0); err != nil { return err } if err := e.AddBE(uint32(e.WrittenBytes) - 8); err != nil { return fmt.Errorf("%v when writing the total written bytes", err) } if _, err := e.w.Seek(22, 0); err != nil { return err } if err := e.AddBE(uint32(e.frames)); err != nil { return fmt.Errorf("%v when writing the total of frames", err) } // rewrite the audio chunk length header if e.pcmChunkSizePos > 0 { if _, err := e.w.Seek(int64(e.pcmChunkSizePos), 0); err != nil { return err } chunksize := uint32((int(e.BitDepth)/8)*int(e.NumChans)*e.frames + 8) if err := e.AddBE(uint32(chunksize)); err != nil { return fmt.Errorf("%v when writing wav data chunk size header", err) } } // jump to the end of the file. e.w.Seek(0, 2) switch e.w.(type) { case *os.File: e.w.(*os.File).Sync() } return nil }
[ "func", "(", "e", "*", "Encoder", ")", "Close", "(", ")", "error", "{", "// go back and write total size", "if", "_", ",", "err", ":=", "e", ".", "w", ".", "Seek", "(", "4", ",", "0", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "e", ".", "AddBE", "(", "uint32", "(", "e", ".", "WrittenBytes", ")", "-", "8", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "e", ".", "w", ".", "Seek", "(", "22", ",", "0", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "e", ".", "AddBE", "(", "uint32", "(", "e", ".", "frames", ")", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// rewrite the audio chunk length header", "if", "e", ".", "pcmChunkSizePos", ">", "0", "{", "if", "_", ",", "err", ":=", "e", ".", "w", ".", "Seek", "(", "int64", "(", "e", ".", "pcmChunkSizePos", ")", ",", "0", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "chunksize", ":=", "uint32", "(", "(", "int", "(", "e", ".", "BitDepth", ")", "/", "8", ")", "*", "int", "(", "e", ".", "NumChans", ")", "*", "e", ".", "frames", "+", "8", ")", "\n", "if", "err", ":=", "e", ".", "AddBE", "(", "uint32", "(", "chunksize", ")", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "// jump to the end of the file.", "e", ".", "w", ".", "Seek", "(", "0", ",", "2", ")", "\n", "switch", "e", ".", "w", ".", "(", "type", ")", "{", "case", "*", "os", ".", "File", ":", "e", ".", "w", ".", "(", "*", "os", ".", "File", ")", ".", "Sync", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close flushes the content to disk, make sure the headers are up to date // Note that the underlying writter is NOT being closed.
[ "Close", "flushes", "the", "content", "to", "disk", "make", "sure", "the", "headers", "are", "up", "to", "date", "Note", "that", "the", "underlying", "writter", "is", "NOT", "being", "closed", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/aiff/encoder.go#L170-L201
12,315
mattetti/audio
transforms/bit_crush.go
BitCrush
func BitCrush(buf *audio.PCMBuffer, factor float64) { buf.SwitchPrimaryType(audio.Float) stepSize := crusherStepSize * factor for i := 0; i < len(buf.Floats); i++ { frac, exp := math.Frexp(buf.Floats[i]) frac = signum(frac) * math.Floor(math.Abs(frac)/stepSize+0.5) * stepSize buf.Floats[i] = math.Ldexp(frac, exp) } }
go
func BitCrush(buf *audio.PCMBuffer, factor float64) { buf.SwitchPrimaryType(audio.Float) stepSize := crusherStepSize * factor for i := 0; i < len(buf.Floats); i++ { frac, exp := math.Frexp(buf.Floats[i]) frac = signum(frac) * math.Floor(math.Abs(frac)/stepSize+0.5) * stepSize buf.Floats[i] = math.Ldexp(frac, exp) } }
[ "func", "BitCrush", "(", "buf", "*", "audio", ".", "PCMBuffer", ",", "factor", "float64", ")", "{", "buf", ".", "SwitchPrimaryType", "(", "audio", ".", "Float", ")", "\n", "stepSize", ":=", "crusherStepSize", "*", "factor", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "buf", ".", "Floats", ")", ";", "i", "++", "{", "frac", ",", "exp", ":=", "math", ".", "Frexp", "(", "buf", ".", "Floats", "[", "i", "]", ")", "\n", "frac", "=", "signum", "(", "frac", ")", "*", "math", ".", "Floor", "(", "math", ".", "Abs", "(", "frac", ")", "/", "stepSize", "+", "0.5", ")", "*", "stepSize", "\n", "buf", ".", "Floats", "[", "i", "]", "=", "math", ".", "Ldexp", "(", "frac", ",", "exp", ")", "\n", "}", "\n", "}" ]
// BitCrush reduces the resolution of the sample to the target bit depth // Note that bit crusher effects are usually made of this feature + a decimator
[ "BitCrush", "reduces", "the", "resolution", "of", "the", "sample", "to", "the", "target", "bit", "depth", "Note", "that", "bit", "crusher", "effects", "are", "usually", "made", "of", "this", "feature", "+", "a", "decimator" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/transforms/bit_crush.go#L17-L25
12,316
mattetti/audio
mp3/frame_header.go
IsValid
func (h FrameHeader) IsValid() bool { if len(h) < 4 { return false } return h[0] == 0xff && h[1]&0xE0 == 0xE0 && h.Version() <= MPEG1 && h.Layer() <= Layer1 }
go
func (h FrameHeader) IsValid() bool { if len(h) < 4 { return false } return h[0] == 0xff && h[1]&0xE0 == 0xE0 && h.Version() <= MPEG1 && h.Layer() <= Layer1 }
[ "func", "(", "h", "FrameHeader", ")", "IsValid", "(", ")", "bool", "{", "if", "len", "(", "h", ")", "<", "4", "{", "return", "false", "\n", "}", "\n", "return", "h", "[", "0", "]", "==", "0xff", "&&", "h", "[", "1", "]", "&", "0xE0", "==", "0xE0", "&&", "h", ".", "Version", "(", ")", "<=", "MPEG1", "&&", "h", ".", "Layer", "(", ")", "<=", "Layer1", "\n", "}" ]
// IsValid tests the basic validity of the frame header by checking the sync word
[ "IsValid", "tests", "the", "basic", "validity", "of", "the", "frame", "header", "by", "checking", "the", "sync", "word" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/frame_header.go#L11-L16
12,317
mattetti/audio
mp3/frame_header.go
BitRate
func (h FrameHeader) BitRate() FrameBitRate { if len(h) < 4 { return 0 } bitrateIdx := (h[2] >> 4) & 0x0F if bitrateIdx == 0x0F { return ErrInvalidBitrate } br := bitrates[h.Version()][h.Layer()][bitrateIdx] * 1000 if br == 0 { return ErrInvalidBitrate } return FrameBitRate(br) }
go
func (h FrameHeader) BitRate() FrameBitRate { if len(h) < 4 { return 0 } bitrateIdx := (h[2] >> 4) & 0x0F if bitrateIdx == 0x0F { return ErrInvalidBitrate } br := bitrates[h.Version()][h.Layer()][bitrateIdx] * 1000 if br == 0 { return ErrInvalidBitrate } return FrameBitRate(br) }
[ "func", "(", "h", "FrameHeader", ")", "BitRate", "(", ")", "FrameBitRate", "{", "if", "len", "(", "h", ")", "<", "4", "{", "return", "0", "\n", "}", "\n", "bitrateIdx", ":=", "(", "h", "[", "2", "]", ">>", "4", ")", "&", "0x0F", "\n", "if", "bitrateIdx", "==", "0x0F", "{", "return", "ErrInvalidBitrate", "\n", "}", "\n", "br", ":=", "bitrates", "[", "h", ".", "Version", "(", ")", "]", "[", "h", ".", "Layer", "(", ")", "]", "[", "bitrateIdx", "]", "*", "1000", "\n", "if", "br", "==", "0", "{", "return", "ErrInvalidBitrate", "\n", "}", "\n", "return", "FrameBitRate", "(", "br", ")", "\n", "}" ]
// BitRate returns the calculated bit rate from the header
[ "BitRate", "returns", "the", "calculated", "bit", "rate", "from", "the", "header" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/frame_header.go#L43-L56
12,318
mattetti/audio
mp3/frame_header.go
SampleRate
func (h FrameHeader) SampleRate() FrameSampleRate { if len(h) < 4 { return 0 } sri := (h[2] >> 2) & 0x03 if sri == 0x03 { return ErrInvalidSampleRate } return FrameSampleRate(sampleRates[h.Version()][sri]) }
go
func (h FrameHeader) SampleRate() FrameSampleRate { if len(h) < 4 { return 0 } sri := (h[2] >> 2) & 0x03 if sri == 0x03 { return ErrInvalidSampleRate } return FrameSampleRate(sampleRates[h.Version()][sri]) }
[ "func", "(", "h", "FrameHeader", ")", "SampleRate", "(", ")", "FrameSampleRate", "{", "if", "len", "(", "h", ")", "<", "4", "{", "return", "0", "\n", "}", "\n", "sri", ":=", "(", "h", "[", "2", "]", ">>", "2", ")", "&", "0x03", "\n", "if", "sri", "==", "0x03", "{", "return", "ErrInvalidSampleRate", "\n", "}", "\n", "return", "FrameSampleRate", "(", "sampleRates", "[", "h", ".", "Version", "(", ")", "]", "[", "sri", "]", ")", "\n", "}" ]
// SampleRate returns the samplerate from the header
[ "SampleRate", "returns", "the", "samplerate", "from", "the", "header" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/frame_header.go#L59-L68
12,319
mattetti/audio
mp3/frame_header.go
String
func (h FrameHeader) String() string { str := "" str += fmt.Sprintf(" Layer: %v\n", h.Layer()) str += fmt.Sprintf(" Version: %v\n", h.Version()) str += fmt.Sprintf(" Protection: %v\n", h.Protection()) str += fmt.Sprintf(" BitRate: %v\n", h.BitRate()) str += fmt.Sprintf(" SampleRate: %v\n", h.SampleRate()) str += fmt.Sprintf(" Pad: %v\n", h.Pad()) str += fmt.Sprintf(" Private: %v\n", h.Private()) str += fmt.Sprintf(" ChannelMode: %v\n", h.ChannelMode()) str += fmt.Sprintf(" CopyRight: %v\n", h.CopyRight()) str += fmt.Sprintf(" Original: %v\n", h.Original()) str += fmt.Sprintf(" Emphasis: %v\n", h.Emphasis()) str += fmt.Sprintf(" Number Samples: %v\n", h.Samples()) str += fmt.Sprintf(" Size: %v\n", h.Size()) return str }
go
func (h FrameHeader) String() string { str := "" str += fmt.Sprintf(" Layer: %v\n", h.Layer()) str += fmt.Sprintf(" Version: %v\n", h.Version()) str += fmt.Sprintf(" Protection: %v\n", h.Protection()) str += fmt.Sprintf(" BitRate: %v\n", h.BitRate()) str += fmt.Sprintf(" SampleRate: %v\n", h.SampleRate()) str += fmt.Sprintf(" Pad: %v\n", h.Pad()) str += fmt.Sprintf(" Private: %v\n", h.Private()) str += fmt.Sprintf(" ChannelMode: %v\n", h.ChannelMode()) str += fmt.Sprintf(" CopyRight: %v\n", h.CopyRight()) str += fmt.Sprintf(" Original: %v\n", h.Original()) str += fmt.Sprintf(" Emphasis: %v\n", h.Emphasis()) str += fmt.Sprintf(" Number Samples: %v\n", h.Samples()) str += fmt.Sprintf(" Size: %v\n", h.Size()) return str }
[ "func", "(", "h", "FrameHeader", ")", "String", "(", ")", "string", "{", "str", ":=", "\"", "\"", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "Layer", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "Version", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "Protection", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "BitRate", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "SampleRate", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "Pad", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "Private", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "ChannelMode", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "CopyRight", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "Original", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "Emphasis", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "Samples", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "h", ".", "Size", "(", ")", ")", "\n", "return", "str", "\n", "}" ]
// String dumps the frame header as a string for display purposes
[ "String", "dumps", "the", "frame", "header", "as", "a", "string", "for", "display", "purposes" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/frame_header.go#L120-L136
12,320
mattetti/audio
mp3/frame_header.go
Samples
func (h FrameHeader) Samples() int { if len(h) < 4 { return 0 } ftype, ok := samplesPerFrame[h.Version()] if !ok { return 0 } return ftype[h.Layer()] }
go
func (h FrameHeader) Samples() int { if len(h) < 4 { return 0 } ftype, ok := samplesPerFrame[h.Version()] if !ok { return 0 } return ftype[h.Layer()] }
[ "func", "(", "h", "FrameHeader", ")", "Samples", "(", ")", "int", "{", "if", "len", "(", "h", ")", "<", "4", "{", "return", "0", "\n", "}", "\n", "ftype", ",", "ok", ":=", "samplesPerFrame", "[", "h", ".", "Version", "(", ")", "]", "\n", "if", "!", "ok", "{", "return", "0", "\n", "}", "\n", "return", "ftype", "[", "h", ".", "Layer", "(", ")", "]", "\n", "}" ]
// Samples is the number of samples contained in this frame
[ "Samples", "is", "the", "number", "of", "samples", "contained", "in", "this", "frame" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/frame_header.go#L139-L148
12,321
templexxx/xor
nosimd.go
bytesNoSIMD
func bytesNoSIMD(dst, a, b []byte, size int) { if supportsUnaligned { fastXORBytes(dst, a, b, size) } else { // TODO(hanwen): if (dst, a, b) have common alignment // we could still try fastXORBytes. It is not clear // how often this happens, and it's only worth it if // the block encryption itself is hardware // accelerated. safeXORBytes(dst, a, b, size) } }
go
func bytesNoSIMD(dst, a, b []byte, size int) { if supportsUnaligned { fastXORBytes(dst, a, b, size) } else { // TODO(hanwen): if (dst, a, b) have common alignment // we could still try fastXORBytes. It is not clear // how often this happens, and it's only worth it if // the block encryption itself is hardware // accelerated. safeXORBytes(dst, a, b, size) } }
[ "func", "bytesNoSIMD", "(", "dst", ",", "a", ",", "b", "[", "]", "byte", ",", "size", "int", ")", "{", "if", "supportsUnaligned", "{", "fastXORBytes", "(", "dst", ",", "a", ",", "b", ",", "size", ")", "\n", "}", "else", "{", "// TODO(hanwen): if (dst, a, b) have common alignment", "// we could still try fastXORBytes. It is not clear", "// how often this happens, and it's only worth it if", "// the block encryption itself is hardware", "// accelerated.", "safeXORBytes", "(", "dst", ",", "a", ",", "b", ",", "size", ")", "\n", "}", "\n", "}" ]
// xor the bytes in a and b. The destination is assumed to have enough space.
[ "xor", "the", "bytes", "in", "a", "and", "b", ".", "The", "destination", "is", "assumed", "to", "have", "enough", "space", "." ]
4e92f724b73b7aaf61869bb1ae5817822e738430
https://github.com/templexxx/xor/blob/4e92f724b73b7aaf61869bb1ae5817822e738430/nosimd.go#L16-L27
12,322
templexxx/xor
nosimd.go
partNoSIMD
func partNoSIMD(start, end int, dst []byte, src [][]byte) { bytesNoSIMD(dst[start:end], src[0][start:end], src[1][start:end], end-start) for i := 2; i < len(src); i++ { bytesNoSIMD(dst[start:end], dst[start:end], src[i][start:end], end-start) } }
go
func partNoSIMD(start, end int, dst []byte, src [][]byte) { bytesNoSIMD(dst[start:end], src[0][start:end], src[1][start:end], end-start) for i := 2; i < len(src); i++ { bytesNoSIMD(dst[start:end], dst[start:end], src[i][start:end], end-start) } }
[ "func", "partNoSIMD", "(", "start", ",", "end", "int", ",", "dst", "[", "]", "byte", ",", "src", "[", "]", "[", "]", "byte", ")", "{", "bytesNoSIMD", "(", "dst", "[", "start", ":", "end", "]", ",", "src", "[", "0", "]", "[", "start", ":", "end", "]", ",", "src", "[", "1", "]", "[", "start", ":", "end", "]", ",", "end", "-", "start", ")", "\n", "for", "i", ":=", "2", ";", "i", "<", "len", "(", "src", ")", ";", "i", "++", "{", "bytesNoSIMD", "(", "dst", "[", "start", ":", "end", "]", ",", "dst", "[", "start", ":", "end", "]", ",", "src", "[", "i", "]", "[", "start", ":", "end", "]", ",", "end", "-", "start", ")", "\n", "}", "\n", "}" ]
// split vect will improve performance with big data by reducing cache pollution
[ "split", "vect", "will", "improve", "performance", "with", "big", "data", "by", "reducing", "cache", "pollution" ]
4e92f724b73b7aaf61869bb1ae5817822e738430
https://github.com/templexxx/xor/blob/4e92f724b73b7aaf61869bb1ae5817822e738430/nosimd.go#L49-L54
12,323
smotes/purse
purse.go
New
func New(dir string) (*MemoryPurse, error) { dir = filepath.Clean(dir) + string(os.PathSeparator) f, err := os.Open(dir) if err != nil { return nil, err } defer f.Close() fis, err := f.Readdir(-1) if err != nil { return nil, err } p := &MemoryPurse{files: make(map[string]string, 0)} for _, fi := range fis { if !fi.IsDir() { if filepath.Ext(fi.Name()) == ext { err = addToPurse(p, fi.Name(), filepath.Join(dir, fi.Name())) } } else { err = filepath.Walk(filepath.Join(dir, fi.Name()), func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() || filepath.Ext(info.Name()) != ext { return nil } return addToPurse(p, strings.TrimPrefix(path, dir), path) }) } if err != nil { return nil, err } } return p, nil }
go
func New(dir string) (*MemoryPurse, error) { dir = filepath.Clean(dir) + string(os.PathSeparator) f, err := os.Open(dir) if err != nil { return nil, err } defer f.Close() fis, err := f.Readdir(-1) if err != nil { return nil, err } p := &MemoryPurse{files: make(map[string]string, 0)} for _, fi := range fis { if !fi.IsDir() { if filepath.Ext(fi.Name()) == ext { err = addToPurse(p, fi.Name(), filepath.Join(dir, fi.Name())) } } else { err = filepath.Walk(filepath.Join(dir, fi.Name()), func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() || filepath.Ext(info.Name()) != ext { return nil } return addToPurse(p, strings.TrimPrefix(path, dir), path) }) } if err != nil { return nil, err } } return p, nil }
[ "func", "New", "(", "dir", "string", ")", "(", "*", "MemoryPurse", ",", "error", ")", "{", "dir", "=", "filepath", ".", "Clean", "(", "dir", ")", "+", "string", "(", "os", ".", "PathSeparator", ")", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "fis", ",", "err", ":=", "f", ".", "Readdir", "(", "-", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "p", ":=", "&", "MemoryPurse", "{", "files", ":", "make", "(", "map", "[", "string", "]", "string", ",", "0", ")", "}", "\n\n", "for", "_", ",", "fi", ":=", "range", "fis", "{", "if", "!", "fi", ".", "IsDir", "(", ")", "{", "if", "filepath", ".", "Ext", "(", "fi", ".", "Name", "(", ")", ")", "==", "ext", "{", "err", "=", "addToPurse", "(", "p", ",", "fi", ".", "Name", "(", ")", ",", "filepath", ".", "Join", "(", "dir", ",", "fi", ".", "Name", "(", ")", ")", ")", "\n", "}", "\n", "}", "else", "{", "err", "=", "filepath", ".", "Walk", "(", "filepath", ".", "Join", "(", "dir", ",", "fi", ".", "Name", "(", ")", ")", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "info", ".", "IsDir", "(", ")", "||", "filepath", ".", "Ext", "(", "info", ".", "Name", "(", ")", ")", "!=", "ext", "{", "return", "nil", "\n", "}", "\n", "return", "addToPurse", "(", "p", ",", "strings", ".", "TrimPrefix", "(", "path", ",", "dir", ")", ",", "path", ")", "\n", "}", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "p", ",", "nil", "\n", "}" ]
// New loads SQL files' contents in the specified directory dir into memory. // A file's contents can be accessed with the Get method. // // New returns an error if the directory does not exist or is not a directory.
[ "New", "loads", "SQL", "files", "contents", "in", "the", "specified", "directory", "dir", "into", "memory", ".", "A", "file", "s", "contents", "can", "be", "accessed", "with", "the", "Get", "method", ".", "New", "returns", "an", "error", "if", "the", "directory", "does", "not", "exist", "or", "is", "not", "a", "directory", "." ]
9ce9ed34191cbabb61a4dd1d5623e69a3b95cdda
https://github.com/smotes/purse/blob/9ce9ed34191cbabb61a4dd1d5623e69a3b95cdda/purse.go#L36-L72
12,324
smotes/purse
purse.go
Get
func (p *MemoryPurse) Get(filename string) (v string, ok bool) { p.mu.RLock() v, ok = p.files[filename] p.mu.RUnlock() return }
go
func (p *MemoryPurse) Get(filename string) (v string, ok bool) { p.mu.RLock() v, ok = p.files[filename] p.mu.RUnlock() return }
[ "func", "(", "p", "*", "MemoryPurse", ")", "Get", "(", "filename", "string", ")", "(", "v", "string", ",", "ok", "bool", ")", "{", "p", ".", "mu", ".", "RLock", "(", ")", "\n", "v", ",", "ok", "=", "p", ".", "files", "[", "filename", "]", "\n", "p", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "\n", "}" ]
// Get returns a SQL file's contents as a string. // If the file does not exist or does exists but had a read error, // then v == "" and ok == false.
[ "Get", "returns", "a", "SQL", "file", "s", "contents", "as", "a", "string", ".", "If", "the", "file", "does", "not", "exist", "or", "does", "exists", "but", "had", "a", "read", "error", "then", "v", "==", "and", "ok", "==", "false", "." ]
9ce9ed34191cbabb61a4dd1d5623e69a3b95cdda
https://github.com/smotes/purse/blob/9ce9ed34191cbabb61a4dd1d5623e69a3b95cdda/purse.go#L77-L82
12,325
smotes/purse
purse.go
Files
func (p *MemoryPurse) Files() []string { fs := make([]string, len(p.files)) i := 0 for k, _ := range p.files { fs[i] = k i++ } return fs }
go
func (p *MemoryPurse) Files() []string { fs := make([]string, len(p.files)) i := 0 for k, _ := range p.files { fs[i] = k i++ } return fs }
[ "func", "(", "p", "*", "MemoryPurse", ")", "Files", "(", ")", "[", "]", "string", "{", "fs", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "p", ".", "files", ")", ")", "\n", "i", ":=", "0", "\n", "for", "k", ",", "_", ":=", "range", "p", ".", "files", "{", "fs", "[", "i", "]", "=", "k", "\n", "i", "++", "\n", "}", "\n", "return", "fs", "\n", "}" ]
// Files returns a slice of filenames for all loaded SQL files.
[ "Files", "returns", "a", "slice", "of", "filenames", "for", "all", "loaded", "SQL", "files", "." ]
9ce9ed34191cbabb61a4dd1d5623e69a3b95cdda
https://github.com/smotes/purse/blob/9ce9ed34191cbabb61a4dd1d5623e69a3b95cdda/purse.go#L85-L93
12,326
smotes/purse
purse.go
addToPurse
func addToPurse(purse *MemoryPurse, name, path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() b, err := ioutil.ReadAll(f) if err != nil { return err } purse.files[name] = string(b) return nil }
go
func addToPurse(purse *MemoryPurse, name, path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() b, err := ioutil.ReadAll(f) if err != nil { return err } purse.files[name] = string(b) return nil }
[ "func", "addToPurse", "(", "purse", "*", "MemoryPurse", ",", "name", ",", "path", "string", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "purse", ".", "files", "[", "name", "]", "=", "string", "(", "b", ")", "\n", "return", "nil", "\n", "}" ]
// addToPurse adds a file to the specified purse with the given name.
[ "addToPurse", "adds", "a", "file", "to", "the", "specified", "purse", "with", "the", "given", "name", "." ]
9ce9ed34191cbabb61a4dd1d5623e69a3b95cdda
https://github.com/smotes/purse/blob/9ce9ed34191cbabb61a4dd1d5623e69a3b95cdda/purse.go#L96-L108
12,327
myesui/uuid
saver.go
String
func (o Store) String() string { return fmt.Sprintf("Timestamp[%s]-Sequence[%d]-Node[%x]", o.Timestamp, o.Sequence, o.Node) }
go
func (o Store) String() string { return fmt.Sprintf("Timestamp[%s]-Sequence[%d]-Node[%x]", o.Timestamp, o.Sequence, o.Node) }
[ "func", "(", "o", "Store", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "o", ".", "Timestamp", ",", "o", ".", "Sequence", ",", "o", ".", "Node", ")", "\n", "}" ]
// String returns a string representation of the Store.
[ "String", "returns", "a", "string", "representation", "of", "the", "Store", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/saver.go#L24-L26
12,328
myesui/uuid
types.go
MarshalText
func (o UUID) MarshalText() ([]byte, error) { f := FormatCanonical if defaultFormats[printFormat] { f = printFormat } return []byte(formatUuid(o.Bytes(), f)), nil }
go
func (o UUID) MarshalText() ([]byte, error) { f := FormatCanonical if defaultFormats[printFormat] { f = printFormat } return []byte(formatUuid(o.Bytes(), f)), nil }
[ "func", "(", "o", "UUID", ")", "MarshalText", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "f", ":=", "FormatCanonical", "\n", "if", "defaultFormats", "[", "printFormat", "]", "{", "f", "=", "printFormat", "\n", "}", "\n", "return", "[", "]", "byte", "(", "formatUuid", "(", "o", ".", "Bytes", "(", ")", ",", "f", ")", ")", ",", "nil", "\n", "}" ]
// MarshalText implements the encoding.TextMarshaler interface. It will marshal // text into one of the known formats, if you have changed to a custom Format // the text be output in canonical format.
[ "MarshalText", "implements", "the", "encoding", ".", "TextMarshaler", "interface", ".", "It", "will", "marshal", "text", "into", "one", "of", "the", "known", "formats", "if", "you", "have", "changed", "to", "a", "custom", "Format", "the", "text", "be", "output", "in", "canonical", "format", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/types.go#L83-L89
12,329
myesui/uuid
types.go
UnmarshalText
func (o *UUID) UnmarshalText(uuid []byte) error { id, err := parse(string(uuid)) if err == nil { o.UnmarshalBinary(id) } return err }
go
func (o *UUID) UnmarshalText(uuid []byte) error { id, err := parse(string(uuid)) if err == nil { o.UnmarshalBinary(id) } return err }
[ "func", "(", "o", "*", "UUID", ")", "UnmarshalText", "(", "uuid", "[", "]", "byte", ")", "error", "{", "id", ",", "err", ":=", "parse", "(", "string", "(", "uuid", ")", ")", "\n", "if", "err", "==", "nil", "{", "o", ".", "UnmarshalBinary", "(", "id", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// UnmarshalText implements the encoding.TextUnmarshaler interface. It will // support any text that MarshalText can produce.
[ "UnmarshalText", "implements", "the", "encoding", ".", "TextUnmarshaler", "interface", ".", "It", "will", "support", "any", "text", "that", "MarshalText", "can", "produce", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/types.go#L93-L99
12,330
myesui/uuid
types.go
Value
func (o UUID) Value() (value driver.Value, err error) { if IsNil(o) { value, err = nil, nil return } value, err = o.MarshalText() return }
go
func (o UUID) Value() (value driver.Value, err error) { if IsNil(o) { value, err = nil, nil return } value, err = o.MarshalText() return }
[ "func", "(", "o", "UUID", ")", "Value", "(", ")", "(", "value", "driver", ".", "Value", ",", "err", "error", ")", "{", "if", "IsNil", "(", "o", ")", "{", "value", ",", "err", "=", "nil", ",", "nil", "\n", "return", "\n", "}", "\n", "value", ",", "err", "=", "o", ".", "MarshalText", "(", ")", "\n", "return", "\n", "}" ]
// Value implements the driver.Valuer interface
[ "Value", "implements", "the", "driver", ".", "Valuer", "interface" ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/types.go#L102-L109
12,331
myesui/uuid
types.go
Scan
func (o *UUID) Scan(src interface{}) error { if src == nil { return nil } if src == "" { return nil } switch src := src.(type) { case string: return o.UnmarshalText([]byte(src)) case []byte: if len(src) == length { return o.UnmarshalBinary(src) } else { return o.UnmarshalText(src) } default: return fmt.Errorf("uuid: cannot scan type [%T] into UUID", src) } }
go
func (o *UUID) Scan(src interface{}) error { if src == nil { return nil } if src == "" { return nil } switch src := src.(type) { case string: return o.UnmarshalText([]byte(src)) case []byte: if len(src) == length { return o.UnmarshalBinary(src) } else { return o.UnmarshalText(src) } default: return fmt.Errorf("uuid: cannot scan type [%T] into UUID", src) } }
[ "func", "(", "o", "*", "UUID", ")", "Scan", "(", "src", "interface", "{", "}", ")", "error", "{", "if", "src", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "src", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "switch", "src", ":=", "src", ".", "(", "type", ")", "{", "case", "string", ":", "return", "o", ".", "UnmarshalText", "(", "[", "]", "byte", "(", "src", ")", ")", "\n\n", "case", "[", "]", "byte", ":", "if", "len", "(", "src", ")", "==", "length", "{", "return", "o", ".", "UnmarshalBinary", "(", "src", ")", "\n", "}", "else", "{", "return", "o", ".", "UnmarshalText", "(", "src", ")", "\n", "}", "\n\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "src", ")", "\n", "}", "\n", "}" ]
// Scan implements the sql.Scanner interface
[ "Scan", "implements", "the", "sql", ".", "Scanner", "interface" ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/types.go#L112-L134
12,332
myesui/uuid
types.go
UUID
func (o Immutable) UUID() UUID { id := UUID{} id.unmarshal(o.Bytes()) return id }
go
func (o Immutable) UUID() UUID { id := UUID{} id.unmarshal(o.Bytes()) return id }
[ "func", "(", "o", "Immutable", ")", "UUID", "(", ")", "UUID", "{", "id", ":=", "UUID", "{", "}", "\n", "id", ".", "unmarshal", "(", "o", ".", "Bytes", "(", ")", ")", "\n", "return", "id", "\n", "}" ]
// UUID converts this implementation to the default type uuid.UUID
[ "UUID", "converts", "this", "implementation", "to", "the", "default", "type", "uuid", ".", "UUID" ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/types.go#L171-L175
12,333
myesui/uuid
savers/filesystem.go
Save
func (o *FileSystemSaver) Save(store uuid.Store) { if store.Timestamp >= o.Timestamp { err := o.openAndDo(o.encode, &store) if err == nil { if o.Report { o.Println("file system saver saved", store) } } o.Timestamp = store.Add(o.Duration) } }
go
func (o *FileSystemSaver) Save(store uuid.Store) { if store.Timestamp >= o.Timestamp { err := o.openAndDo(o.encode, &store) if err == nil { if o.Report { o.Println("file system saver saved", store) } } o.Timestamp = store.Add(o.Duration) } }
[ "func", "(", "o", "*", "FileSystemSaver", ")", "Save", "(", "store", "uuid", ".", "Store", ")", "{", "if", "store", ".", "Timestamp", ">=", "o", ".", "Timestamp", "{", "err", ":=", "o", ".", "openAndDo", "(", "o", ".", "encode", ",", "&", "store", ")", "\n", "if", "err", "==", "nil", "{", "if", "o", ".", "Report", "{", "o", ".", "Println", "(", "\"", "\"", ",", "store", ")", "\n", "}", "\n", "}", "\n", "o", ".", "Timestamp", "=", "store", ".", "Add", "(", "o", ".", "Duration", ")", "\n", "}", "\n", "}" ]
// Save saves the given store to the filesystem.
[ "Save", "saves", "the", "given", "store", "to", "the", "filesystem", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/savers/filesystem.go#L49-L60
12,334
myesui/uuid
savers/filesystem.go
Read
func (o *FileSystemSaver) Read() (store uuid.Store, err error) { store = uuid.Store{} _, err = os.Stat(o.Path); if err != nil { if os.IsNotExist(err) { dir, file := path.Split(o.Path) if dir == "" || dir == "/" { dir = os.TempDir() } o.Path = path.Join(dir, file) err = os.MkdirAll(dir, os.ModeDir|0700) if err == nil { // If new encode blank store goto open } } goto failed } open: err = o.openAndDo(o.decode, &store) if err == nil { o.Println("file system saver created", o.Path) return } failed: o.Println("file system saver read error - will autogenerate", err) return }
go
func (o *FileSystemSaver) Read() (store uuid.Store, err error) { store = uuid.Store{} _, err = os.Stat(o.Path); if err != nil { if os.IsNotExist(err) { dir, file := path.Split(o.Path) if dir == "" || dir == "/" { dir = os.TempDir() } o.Path = path.Join(dir, file) err = os.MkdirAll(dir, os.ModeDir|0700) if err == nil { // If new encode blank store goto open } } goto failed } open: err = o.openAndDo(o.decode, &store) if err == nil { o.Println("file system saver created", o.Path) return } failed: o.Println("file system saver read error - will autogenerate", err) return }
[ "func", "(", "o", "*", "FileSystemSaver", ")", "Read", "(", ")", "(", "store", "uuid", ".", "Store", ",", "err", "error", ")", "{", "store", "=", "uuid", ".", "Store", "{", "}", "\n", "_", ",", "err", "=", "os", ".", "Stat", "(", "o", ".", "Path", ")", ";", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "dir", ",", "file", ":=", "path", ".", "Split", "(", "o", ".", "Path", ")", "\n", "if", "dir", "==", "\"", "\"", "||", "dir", "==", "\"", "\"", "{", "dir", "=", "os", ".", "TempDir", "(", ")", "\n", "}", "\n", "o", ".", "Path", "=", "path", ".", "Join", "(", "dir", ",", "file", ")", "\n\n", "err", "=", "os", ".", "MkdirAll", "(", "dir", ",", "os", ".", "ModeDir", "|", "0700", ")", "\n", "if", "err", "==", "nil", "{", "// If new encode blank store", "goto", "open", "\n", "}", "\n", "}", "\n", "goto", "failed", "\n", "}", "\n\n", "open", ":", "err", "=", "o", ".", "openAndDo", "(", "o", ".", "decode", ",", "&", "store", ")", "\n", "if", "err", "==", "nil", "{", "o", ".", "Println", "(", "\"", "\"", ",", "o", ".", "Path", ")", "\n", "return", "\n", "}", "\n\n", "failed", ":", "o", ".", "Println", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}" ]
// Read reads and loads the Store from the filesystem.
[ "Read", "reads", "and", "loads", "the", "Store", "from", "the", "filesystem", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/savers/filesystem.go#L63-L93
12,335
myesui/uuid
generator.go
RegisterGenerator
func RegisterGenerator(config *GeneratorConfig) (err error) { notOnce := true once.Do(func() { generator, err = NewGenerator(config) notOnce = false return }) if notOnce { panic("uuid: Register* methods cannot be called more than once.") } return }
go
func RegisterGenerator(config *GeneratorConfig) (err error) { notOnce := true once.Do(func() { generator, err = NewGenerator(config) notOnce = false return }) if notOnce { panic("uuid: Register* methods cannot be called more than once.") } return }
[ "func", "RegisterGenerator", "(", "config", "*", "GeneratorConfig", ")", "(", "err", "error", ")", "{", "notOnce", ":=", "true", "\n", "once", ".", "Do", "(", "func", "(", ")", "{", "generator", ",", "err", "=", "NewGenerator", "(", "config", ")", "\n", "notOnce", "=", "false", "\n", "return", "\n", "}", ")", "\n", "if", "notOnce", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "\n", "}" ]
// RegisterGenerator will set the package generator with the given configuration // Like uuid.Init this can only be called once. Any subsequent calls will have no // effect. If you call this you do not need to call uuid.Init.
[ "RegisterGenerator", "will", "set", "the", "package", "generator", "with", "the", "given", "configuration", "Like", "uuid", ".", "Init", "this", "can", "only", "be", "called", "once", ".", "Any", "subsequent", "calls", "will", "have", "no", "effect", ".", "If", "you", "call", "this", "you", "do", "not", "need", "to", "call", "uuid", ".", "Init", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/generator.go#L191-L202
12,336
myesui/uuid
generator.go
NewV1
func (o *Generator) NewV1() UUID { o.read() id := UUID{} makeUuid(&id, uint32(o.Timestamp), uint16(o.Timestamp>>32), uint16(o.Timestamp>>48), uint16(o.Sequence), o.Node) id.setRFC4122Version(VersionOne) return id }
go
func (o *Generator) NewV1() UUID { o.read() id := UUID{} makeUuid(&id, uint32(o.Timestamp), uint16(o.Timestamp>>32), uint16(o.Timestamp>>48), uint16(o.Sequence), o.Node) id.setRFC4122Version(VersionOne) return id }
[ "func", "(", "o", "*", "Generator", ")", "NewV1", "(", ")", "UUID", "{", "o", ".", "read", "(", ")", "\n", "id", ":=", "UUID", "{", "}", "\n\n", "makeUuid", "(", "&", "id", ",", "uint32", "(", "o", ".", "Timestamp", ")", ",", "uint16", "(", "o", ".", "Timestamp", ">>", "32", ")", ",", "uint16", "(", "o", ".", "Timestamp", ">>", "48", ")", ",", "uint16", "(", "o", ".", "Sequence", ")", ",", "o", ".", "Node", ")", "\n\n", "id", ".", "setRFC4122Version", "(", "VersionOne", ")", "\n", "return", "id", "\n", "}" ]
// NewV1 generates a new RFC4122 version 1 UUID based on a 60 bit timestamp and // node id.
[ "NewV1", "generates", "a", "new", "RFC4122", "version", "1", "UUID", "based", "on", "a", "60", "bit", "timestamp", "and", "node", "id", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/generator.go#L329-L342
12,337
myesui/uuid
generator.go
ReadV1
func (o *Generator) ReadV1(ids []UUID) { for i := range ids { ids[i] = o.NewV1() } }
go
func (o *Generator) ReadV1(ids []UUID) { for i := range ids { ids[i] = o.NewV1() } }
[ "func", "(", "o", "*", "Generator", ")", "ReadV1", "(", "ids", "[", "]", "UUID", ")", "{", "for", "i", ":=", "range", "ids", "{", "ids", "[", "i", "]", "=", "o", ".", "NewV1", "(", ")", "\n", "}", "\n", "}" ]
// ReadV1 will read a slice of UUIDs. Be careful with the set amount.
[ "ReadV1", "will", "read", "a", "slice", "of", "UUIDs", ".", "Be", "careful", "with", "the", "set", "amount", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/generator.go#L345-L349
12,338
myesui/uuid
generator.go
BulkV1
func (o *Generator) BulkV1(amount int) []UUID { ids := make([]UUID, amount) o.ReadV1(ids) return ids }
go
func (o *Generator) BulkV1(amount int) []UUID { ids := make([]UUID, amount) o.ReadV1(ids) return ids }
[ "func", "(", "o", "*", "Generator", ")", "BulkV1", "(", "amount", "int", ")", "[", "]", "UUID", "{", "ids", ":=", "make", "(", "[", "]", "UUID", ",", "amount", ")", "\n", "o", ".", "ReadV1", "(", "ids", ")", "\n", "return", "ids", "\n", "}" ]
// BulkV1 will return a slice of V1 UUIDs. Be careful with the set amount.
[ "BulkV1", "will", "return", "a", "slice", "of", "V1", "UUIDs", ".", "Be", "careful", "with", "the", "set", "amount", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/generator.go#L352-L356
12,339
myesui/uuid
generator.go
NewV2
func (o *Generator) NewV2(idType SystemId) UUID { o.read() id := UUID{} var osId uint32 switch idType { case SystemIdUser: osId = uint32(os.Getuid()) case SystemIdGroup: osId = uint32(os.Getgid()) case SystemIdEffectiveUser: osId = uint32(os.Geteuid()) case SystemIdEffectiveGroup: osId = uint32(os.Getegid()) case SystemIdCallerProcess: osId = uint32(os.Getpid()) case SystemIdCallerProcessParent: osId = uint32(os.Getppid()) } makeUuid(&id, osId, uint16(o.Timestamp>>32), uint16(o.Timestamp>>48), uint16(o.Sequence), o.Node) id[9] = byte(idType) id.setRFC4122Version(VersionTwo) return id }
go
func (o *Generator) NewV2(idType SystemId) UUID { o.read() id := UUID{} var osId uint32 switch idType { case SystemIdUser: osId = uint32(os.Getuid()) case SystemIdGroup: osId = uint32(os.Getgid()) case SystemIdEffectiveUser: osId = uint32(os.Geteuid()) case SystemIdEffectiveGroup: osId = uint32(os.Getegid()) case SystemIdCallerProcess: osId = uint32(os.Getpid()) case SystemIdCallerProcessParent: osId = uint32(os.Getppid()) } makeUuid(&id, osId, uint16(o.Timestamp>>32), uint16(o.Timestamp>>48), uint16(o.Sequence), o.Node) id[9] = byte(idType) id.setRFC4122Version(VersionTwo) return id }
[ "func", "(", "o", "*", "Generator", ")", "NewV2", "(", "idType", "SystemId", ")", "UUID", "{", "o", ".", "read", "(", ")", "\n\n", "id", ":=", "UUID", "{", "}", "\n\n", "var", "osId", "uint32", "\n\n", "switch", "idType", "{", "case", "SystemIdUser", ":", "osId", "=", "uint32", "(", "os", ".", "Getuid", "(", ")", ")", "\n", "case", "SystemIdGroup", ":", "osId", "=", "uint32", "(", "os", ".", "Getgid", "(", ")", ")", "\n", "case", "SystemIdEffectiveUser", ":", "osId", "=", "uint32", "(", "os", ".", "Geteuid", "(", ")", ")", "\n", "case", "SystemIdEffectiveGroup", ":", "osId", "=", "uint32", "(", "os", ".", "Getegid", "(", ")", ")", "\n", "case", "SystemIdCallerProcess", ":", "osId", "=", "uint32", "(", "os", ".", "Getpid", "(", ")", ")", "\n", "case", "SystemIdCallerProcessParent", ":", "osId", "=", "uint32", "(", "os", ".", "Getppid", "(", ")", ")", "\n", "}", "\n\n", "makeUuid", "(", "&", "id", ",", "osId", ",", "uint16", "(", "o", ".", "Timestamp", ">>", "32", ")", ",", "uint16", "(", "o", ".", "Timestamp", ">>", "48", ")", ",", "uint16", "(", "o", ".", "Sequence", ")", ",", "o", ".", "Node", ")", "\n\n", "id", "[", "9", "]", "=", "byte", "(", "idType", ")", "\n", "id", ".", "setRFC4122Version", "(", "VersionTwo", ")", "\n", "return", "id", "\n", "}" ]
// NewV2 generates a new DCE version 2 UUID based on a 60 bit timestamp, node id // and the id of the given Id type.
[ "NewV2", "generates", "a", "new", "DCE", "version", "2", "UUID", "based", "on", "a", "60", "bit", "timestamp", "node", "id", "and", "the", "id", "of", "the", "given", "Id", "type", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/generator.go#L360-L392
12,340
myesui/uuid
generator.go
NewV3
func (o *Generator) NewV3(namespace Implementation, names ...interface{}) UUID { id := UUID{} id.unmarshal(digest(md5.New(), namespace.Bytes(), names...)) id.setRFC4122Version(VersionThree) return id }
go
func (o *Generator) NewV3(namespace Implementation, names ...interface{}) UUID { id := UUID{} id.unmarshal(digest(md5.New(), namespace.Bytes(), names...)) id.setRFC4122Version(VersionThree) return id }
[ "func", "(", "o", "*", "Generator", ")", "NewV3", "(", "namespace", "Implementation", ",", "names", "...", "interface", "{", "}", ")", "UUID", "{", "id", ":=", "UUID", "{", "}", "\n", "id", ".", "unmarshal", "(", "digest", "(", "md5", ".", "New", "(", ")", ",", "namespace", ".", "Bytes", "(", ")", ",", "names", "...", ")", ")", "\n", "id", ".", "setRFC4122Version", "(", "VersionThree", ")", "\n", "return", "id", "\n", "}" ]
// NewV3 generates a new RFC4122 version 3 UUID based on the MD5 hash of a // namespace UUID namespace Implementation UUID and one or more unique names.
[ "NewV3", "generates", "a", "new", "RFC4122", "version", "3", "UUID", "based", "on", "the", "MD5", "hash", "of", "a", "namespace", "UUID", "namespace", "Implementation", "UUID", "and", "one", "or", "more", "unique", "names", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/generator.go#L396-L401
12,341
myesui/uuid
generator.go
NewV5
func (o *Generator) NewV5(namespace Implementation, names ...interface{}) UUID { id := UUID{} id.unmarshal(digest(sha1.New(), namespace.Bytes(), names...)) id.setRFC4122Version(VersionFive) return id }
go
func (o *Generator) NewV5(namespace Implementation, names ...interface{}) UUID { id := UUID{} id.unmarshal(digest(sha1.New(), namespace.Bytes(), names...)) id.setRFC4122Version(VersionFive) return id }
[ "func", "(", "o", "*", "Generator", ")", "NewV5", "(", "namespace", "Implementation", ",", "names", "...", "interface", "{", "}", ")", "UUID", "{", "id", ":=", "UUID", "{", "}", "\n", "id", ".", "unmarshal", "(", "digest", "(", "sha1", ".", "New", "(", ")", ",", "namespace", ".", "Bytes", "(", ")", ",", "names", "...", ")", ")", "\n", "id", ".", "setRFC4122Version", "(", "VersionFive", ")", "\n", "return", "id", "\n", "}" ]
// NewV5 generates an RFC4122 version 5 UUID based on the SHA-1 hash of a // namespace Implementation UUID and one or more unique names.
[ "NewV5", "generates", "an", "RFC4122", "version", "5", "UUID", "based", "on", "the", "SHA", "-", "1", "hash", "of", "a", "namespace", "Implementation", "UUID", "and", "one", "or", "more", "unique", "names", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/generator.go#L469-L474
12,342
myesui/uuid
timestamp.go
Time
func (o Timestamp) Time() time.Time { return time.Unix(0, int64((o-gregorianToUNIXOffset)*100)).UTC() }
go
func (o Timestamp) Time() time.Time { return time.Unix(0, int64((o-gregorianToUNIXOffset)*100)).UTC() }
[ "func", "(", "o", "Timestamp", ")", "Time", "(", ")", "time", ".", "Time", "{", "return", "time", ".", "Unix", "(", "0", ",", "int64", "(", "(", "o", "-", "gregorianToUNIXOffset", ")", "*", "100", ")", ")", ".", "UTC", "(", ")", "\n", "}" ]
// Time converts UUID Timestamp to UTC time.Time // Note some higher clock resolutions will lose accuracy if above 100 ns ticks
[ "Time", "converts", "UUID", "Timestamp", "to", "UTC", "time", ".", "Time", "Note", "some", "higher", "clock", "resolutions", "will", "lose", "accuracy", "if", "above", "100", "ns", "ticks" ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/timestamp.go#L46-L48
12,343
myesui/uuid
timestamp.go
Add
func (o Timestamp) Add(duration time.Duration) Timestamp { return o + Timestamp(duration/100) }
go
func (o Timestamp) Add(duration time.Duration) Timestamp { return o + Timestamp(duration/100) }
[ "func", "(", "o", "Timestamp", ")", "Add", "(", "duration", "time", ".", "Duration", ")", "Timestamp", "{", "return", "o", "+", "Timestamp", "(", "duration", "/", "100", ")", "\n", "}" ]
// Add returns the timestamp as modified by the duration
[ "Add", "returns", "the", "timestamp", "as", "modified", "by", "the", "duration" ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/timestamp.go#L51-L53
12,344
myesui/uuid
timestamp.go
Sub
func (o Timestamp) Sub(duration time.Duration) Timestamp { return o - Timestamp(duration/100) }
go
func (o Timestamp) Sub(duration time.Duration) Timestamp { return o - Timestamp(duration/100) }
[ "func", "(", "o", "Timestamp", ")", "Sub", "(", "duration", "time", ".", "Duration", ")", "Timestamp", "{", "return", "o", "-", "Timestamp", "(", "duration", "/", "100", ")", "\n", "}" ]
// Sub returns the timestamp as modified by the duration
[ "Sub", "returns", "the", "timestamp", "as", "modified", "by", "the", "duration" ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/timestamp.go#L56-L58
12,345
myesui/uuid
uuid.go
New
func New(data []byte) UUID { o := UUID{} o.unmarshal(data) return o }
go
func New(data []byte) UUID { o := UUID{} o.unmarshal(data) return o }
[ "func", "New", "(", "data", "[", "]", "byte", ")", "UUID", "{", "o", ":=", "UUID", "{", "}", "\n", "o", ".", "unmarshal", "(", "data", ")", "\n", "return", "o", "\n", "}" ]
// New creates a UUID from a slice of bytes.
[ "New", "creates", "a", "UUID", "from", "a", "slice", "of", "bytes", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/uuid.go#L75-L79
12,346
myesui/uuid
uuid.go
NewHex
func NewHex(uuid string) UUID { o := UUID{} o.unmarshal(fromHex(uuid)) return o }
go
func NewHex(uuid string) UUID { o := UUID{} o.unmarshal(fromHex(uuid)) return o }
[ "func", "NewHex", "(", "uuid", "string", ")", "UUID", "{", "o", ":=", "UUID", "{", "}", "\n", "o", ".", "unmarshal", "(", "fromHex", "(", "uuid", ")", ")", "\n", "return", "o", "\n", "}" ]
// NewHex creates a UUID from a hex string. // Will panic if hex string is invalid use Parse otherwise.
[ "NewHex", "creates", "a", "UUID", "from", "a", "hex", "string", ".", "Will", "panic", "if", "hex", "string", "is", "invalid", "use", "Parse", "otherwise", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/uuid.go#L83-L87
12,347
myesui/uuid
uuid.go
Equal
func Equal(p1, p2 Implementation) bool { return bytes.Equal(p1.Bytes(), p2.Bytes()) }
go
func Equal(p1, p2 Implementation) bool { return bytes.Equal(p1.Bytes(), p2.Bytes()) }
[ "func", "Equal", "(", "p1", ",", "p2", "Implementation", ")", "bool", "{", "return", "bytes", ".", "Equal", "(", "p1", ".", "Bytes", "(", ")", ",", "p2", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// Equal compares whether each Implementation UUID is the same
[ "Equal", "compares", "whether", "each", "Implementation", "UUID", "is", "the", "same" ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/uuid.go#L252-L254
12,348
myesui/uuid
uuid.go
IsNil
func IsNil(uuid Implementation) bool { if uuid == nil { return true } for _, v := range uuid.Bytes() { if v != 0 { return false } } return true }
go
func IsNil(uuid Implementation) bool { if uuid == nil { return true } for _, v := range uuid.Bytes() { if v != 0 { return false } } return true }
[ "func", "IsNil", "(", "uuid", "Implementation", ")", "bool", "{", "if", "uuid", "==", "nil", "{", "return", "true", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "uuid", ".", "Bytes", "(", ")", "{", "if", "v", "!=", "0", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsNil returns true if Implementation UUID is all zeros?
[ "IsNil", "returns", "true", "if", "Implementation", "UUID", "is", "all", "zeros?" ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/uuid.go#L257-L267
12,349
myesui/uuid
version.go
String
func (o Version) String() string { switch o { case VersionOne: return "Version 1: Based on a 60 Bit Timestamp." case VersionTwo: return "Version 2: Based on DCE security domain and 60 bit timestamp." case VersionThree: return "Version 3: Namespace UUID and unique names hashed by MD5." case VersionFour: return "Version 4: Crypto-random generated." case VersionFive: return "Version 5: Namespace UUID and unique names hashed by SHA-1." default: return "Unknown: Not supported" } }
go
func (o Version) String() string { switch o { case VersionOne: return "Version 1: Based on a 60 Bit Timestamp." case VersionTwo: return "Version 2: Based on DCE security domain and 60 bit timestamp." case VersionThree: return "Version 3: Namespace UUID and unique names hashed by MD5." case VersionFour: return "Version 4: Crypto-random generated." case VersionFive: return "Version 5: Namespace UUID and unique names hashed by SHA-1." default: return "Unknown: Not supported" } }
[ "func", "(", "o", "Version", ")", "String", "(", ")", "string", "{", "switch", "o", "{", "case", "VersionOne", ":", "return", "\"", "\"", "\n", "case", "VersionTwo", ":", "return", "\"", "\"", "\n", "case", "VersionThree", ":", "return", "\"", "\"", "\n", "case", "VersionFour", ":", "return", "\"", "\"", "\n", "case", "VersionFive", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// String returns English description of version.
[ "String", "returns", "English", "description", "of", "version", "." ]
835a10bbd6bce40820349a68b1368a62c3c5617c
https://github.com/myesui/uuid/blob/835a10bbd6bce40820349a68b1368a62c3c5617c/version.go#L35-L50
12,350
bluele/mecab-golang
node.go
Next
func (node *Node) Next() error { node.current = node.current.next if node.current == nil { return StopIteration } return nil }
go
func (node *Node) Next() error { node.current = node.current.next if node.current == nil { return StopIteration } return nil }
[ "func", "(", "node", "*", "Node", ")", "Next", "(", ")", "error", "{", "node", ".", "current", "=", "node", ".", "current", ".", "next", "\n", "if", "node", ".", "current", "==", "nil", "{", "return", "StopIteration", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// proceed to the next node. // if current node is last, this method returns StopIteration error.
[ "proceed", "to", "the", "next", "node", ".", "if", "current", "node", "is", "last", "this", "method", "returns", "StopIteration", "error", "." ]
c8cfe04e87f99006004f2bb27f101a96b2f7f28b
https://github.com/bluele/mecab-golang/blob/c8cfe04e87f99006004f2bb27f101a96b2f7f28b/node.go#L24-L30
12,351
bluele/mecab-golang
node.go
StartPos
func (node *Node) StartPos() int { pFirstNode, _ := strconv.Atoi(fmt.Sprintf("%d", node.head.surface)) pCurrentNode, _ := strconv.Atoi(fmt.Sprintf("%d", node.current.surface)) return utf8.RuneCountInString(C.GoStringN(node.head.surface, C.int(pCurrentNode-pFirstNode))) }
go
func (node *Node) StartPos() int { pFirstNode, _ := strconv.Atoi(fmt.Sprintf("%d", node.head.surface)) pCurrentNode, _ := strconv.Atoi(fmt.Sprintf("%d", node.current.surface)) return utf8.RuneCountInString(C.GoStringN(node.head.surface, C.int(pCurrentNode-pFirstNode))) }
[ "func", "(", "node", "*", "Node", ")", "StartPos", "(", ")", "int", "{", "pFirstNode", ",", "_", ":=", "strconv", ".", "Atoi", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ".", "head", ".", "surface", ")", ")", "\n", "pCurrentNode", ",", "_", ":=", "strconv", ".", "Atoi", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ".", "current", ".", "surface", ")", ")", "\n", "return", "utf8", ".", "RuneCountInString", "(", "C", ".", "GoStringN", "(", "node", ".", "head", ".", "surface", ",", "C", ".", "int", "(", "pCurrentNode", "-", "pFirstNode", ")", ")", ")", "\n", "}" ]
// start pos in the text.
[ "start", "pos", "in", "the", "text", "." ]
c8cfe04e87f99006004f2bb27f101a96b2f7f28b
https://github.com/bluele/mecab-golang/blob/c8cfe04e87f99006004f2bb27f101a96b2f7f28b/node.go#L114-L118
12,352
aclements/go-moremath
scale/linear.go
ebase
func (s Linear) ebase() int { if s.Base == 0 { return 10 } else if s.Base == 1 { panic("scale.Linear cannot have a base of 1") } else if s.Base < 0 { panic("scale.Linear cannot have a negative base") } return s.Base }
go
func (s Linear) ebase() int { if s.Base == 0 { return 10 } else if s.Base == 1 { panic("scale.Linear cannot have a base of 1") } else if s.Base < 0 { panic("scale.Linear cannot have a negative base") } return s.Base }
[ "func", "(", "s", "Linear", ")", "ebase", "(", ")", "int", "{", "if", "s", ".", "Base", "==", "0", "{", "return", "10", "\n", "}", "else", "if", "s", ".", "Base", "==", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "else", "if", "s", ".", "Base", "<", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "s", ".", "Base", "\n", "}" ]
// ebase sanity checks and returns the "effective base" of this scale. // If s.Base is 0, it returns 10. If s.Base is 1 or negative, it // panics.
[ "ebase", "sanity", "checks", "and", "returns", "the", "effective", "base", "of", "this", "scale", ".", "If", "s", ".", "Base", "is", "0", "it", "returns", "10", ".", "If", "s", ".", "Base", "is", "1", "or", "negative", "it", "panics", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/scale/linear.go#L55-L64
12,353
aclements/go-moremath
scale/interface.go
Map
func (q QQ) Map(x float64) float64 { return q.Dest.Unmap(q.Src.Map(x)) }
go
func (q QQ) Map(x float64) float64 { return q.Dest.Unmap(q.Src.Map(x)) }
[ "func", "(", "q", "QQ", ")", "Map", "(", "x", "float64", ")", "float64", "{", "return", "q", ".", "Dest", ".", "Unmap", "(", "q", ".", "Src", ".", "Map", "(", "x", ")", ")", "\n", "}" ]
// Map maps from a value x in the source scale's input domain to a // value y in the destination scale's input domain.
[ "Map", "maps", "from", "a", "value", "x", "in", "the", "source", "scale", "s", "input", "domain", "to", "a", "value", "y", "in", "the", "destination", "scale", "s", "input", "domain", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/scale/interface.go#L49-L51
12,354
aclements/go-moremath
stats/stream.go
Add
func (s *StreamStats) Add(x float64) { s.Total += x if s.Count == 0 { s.Min, s.Max = x, x } else { if x < s.Min { s.Min = x } if x > s.Max { s.Max = x } } s.Count++ // Update online mean, mean of squares, and variance. Online // variance based on Wikipedia's presentation ("Algorithms for // calculating variance") of Knuth's formulation of Welford // 1962. delta := x - s.mean s.mean += delta / float64(s.Count) s.meanOfSquares += (x*x - s.meanOfSquares) / float64(s.Count) s.vM2 += delta * (x - s.mean) }
go
func (s *StreamStats) Add(x float64) { s.Total += x if s.Count == 0 { s.Min, s.Max = x, x } else { if x < s.Min { s.Min = x } if x > s.Max { s.Max = x } } s.Count++ // Update online mean, mean of squares, and variance. Online // variance based on Wikipedia's presentation ("Algorithms for // calculating variance") of Knuth's formulation of Welford // 1962. delta := x - s.mean s.mean += delta / float64(s.Count) s.meanOfSquares += (x*x - s.meanOfSquares) / float64(s.Count) s.vM2 += delta * (x - s.mean) }
[ "func", "(", "s", "*", "StreamStats", ")", "Add", "(", "x", "float64", ")", "{", "s", ".", "Total", "+=", "x", "\n", "if", "s", ".", "Count", "==", "0", "{", "s", ".", "Min", ",", "s", ".", "Max", "=", "x", ",", "x", "\n", "}", "else", "{", "if", "x", "<", "s", ".", "Min", "{", "s", ".", "Min", "=", "x", "\n", "}", "\n", "if", "x", ">", "s", ".", "Max", "{", "s", ".", "Max", "=", "x", "\n", "}", "\n", "}", "\n", "s", ".", "Count", "++", "\n\n", "// Update online mean, mean of squares, and variance. Online", "// variance based on Wikipedia's presentation (\"Algorithms for", "// calculating variance\") of Knuth's formulation of Welford", "// 1962.", "delta", ":=", "x", "-", "s", ".", "mean", "\n", "s", ".", "mean", "+=", "delta", "/", "float64", "(", "s", ".", "Count", ")", "\n", "s", ".", "meanOfSquares", "+=", "(", "x", "*", "x", "-", "s", ".", "meanOfSquares", ")", "/", "float64", "(", "s", ".", "Count", ")", "\n", "s", ".", "vM2", "+=", "delta", "*", "(", "x", "-", "s", ".", "mean", ")", "\n", "}" ]
// Add updates s's statistics with sample value x.
[ "Add", "updates", "s", "s", "statistics", "with", "sample", "value", "x", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/stream.go#L31-L53
12,355
aclements/go-moremath
stats/stream.go
Combine
func (s *StreamStats) Combine(o *StreamStats) { count := s.Count + o.Count // Compute combined online variance statistics delta := o.mean - s.mean mean := s.mean + delta*float64(o.Count)/float64(count) vM2 := s.vM2 + o.vM2 + delta*delta*float64(s.Count)*float64(o.Count)/float64(count) s.Count = count s.Total += o.Total if o.Min < s.Min { s.Min = o.Min } if o.Max > s.Max { s.Max = o.Max } s.mean = mean s.meanOfSquares += (o.meanOfSquares - s.meanOfSquares) * float64(o.Count) / float64(count) s.vM2 = vM2 }
go
func (s *StreamStats) Combine(o *StreamStats) { count := s.Count + o.Count // Compute combined online variance statistics delta := o.mean - s.mean mean := s.mean + delta*float64(o.Count)/float64(count) vM2 := s.vM2 + o.vM2 + delta*delta*float64(s.Count)*float64(o.Count)/float64(count) s.Count = count s.Total += o.Total if o.Min < s.Min { s.Min = o.Min } if o.Max > s.Max { s.Max = o.Max } s.mean = mean s.meanOfSquares += (o.meanOfSquares - s.meanOfSquares) * float64(o.Count) / float64(count) s.vM2 = vM2 }
[ "func", "(", "s", "*", "StreamStats", ")", "Combine", "(", "o", "*", "StreamStats", ")", "{", "count", ":=", "s", ".", "Count", "+", "o", ".", "Count", "\n\n", "// Compute combined online variance statistics", "delta", ":=", "o", ".", "mean", "-", "s", ".", "mean", "\n", "mean", ":=", "s", ".", "mean", "+", "delta", "*", "float64", "(", "o", ".", "Count", ")", "/", "float64", "(", "count", ")", "\n", "vM2", ":=", "s", ".", "vM2", "+", "o", ".", "vM2", "+", "delta", "*", "delta", "*", "float64", "(", "s", ".", "Count", ")", "*", "float64", "(", "o", ".", "Count", ")", "/", "float64", "(", "count", ")", "\n\n", "s", ".", "Count", "=", "count", "\n", "s", ".", "Total", "+=", "o", ".", "Total", "\n", "if", "o", ".", "Min", "<", "s", ".", "Min", "{", "s", ".", "Min", "=", "o", ".", "Min", "\n", "}", "\n", "if", "o", ".", "Max", ">", "s", ".", "Max", "{", "s", ".", "Max", "=", "o", ".", "Max", "\n", "}", "\n", "s", ".", "mean", "=", "mean", "\n", "s", ".", "meanOfSquares", "+=", "(", "o", ".", "meanOfSquares", "-", "s", ".", "meanOfSquares", ")", "*", "float64", "(", "o", ".", "Count", ")", "/", "float64", "(", "count", ")", "\n", "s", ".", "vM2", "=", "vM2", "\n", "}" ]
// Combine updates s's statistics as if all samples added to o were // added to s.
[ "Combine", "updates", "s", "s", "statistics", "as", "if", "all", "samples", "added", "to", "o", "were", "added", "to", "s", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/stream.go#L77-L96
12,356
aclements/go-moremath
stats/udist.go
hasTies
func (d UDist) hasTies() bool { for _, t := range d.T { if t > 1 { return true } } return false }
go
func (d UDist) hasTies() bool { for _, t := range d.T { if t > 1 { return true } } return false }
[ "func", "(", "d", "UDist", ")", "hasTies", "(", ")", "bool", "{", "for", "_", ",", "t", ":=", "range", "d", ".", "T", "{", "if", "t", ">", "1", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// hasTies returns true if d has any tied samples.
[ "hasTies", "returns", "true", "if", "d", "has", "any", "tied", "samples", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/udist.go#L40-L47
12,357
aclements/go-moremath
mathx/choose.go
Choose
func Choose(n, k int) float64 { if k == 0 || k == n { return 1 } if k < 0 || n < k { return 0 } if n <= smallFactLimit { // Implies k <= smallFactLimit // It's faster to do several integer multiplications // than it is to do an extra integer division. // Remarkably, this is also faster than pre-computing // Pascal's triangle (presumably because this is very // cache efficient). numer := int64(1) for n1 := int64(n - (k - 1)); n1 <= int64(n); n1++ { numer *= n1 } denom := smallFact[k] return float64(numer / denom) } return math.Exp(lchoose(n, k)) }
go
func Choose(n, k int) float64 { if k == 0 || k == n { return 1 } if k < 0 || n < k { return 0 } if n <= smallFactLimit { // Implies k <= smallFactLimit // It's faster to do several integer multiplications // than it is to do an extra integer division. // Remarkably, this is also faster than pre-computing // Pascal's triangle (presumably because this is very // cache efficient). numer := int64(1) for n1 := int64(n - (k - 1)); n1 <= int64(n); n1++ { numer *= n1 } denom := smallFact[k] return float64(numer / denom) } return math.Exp(lchoose(n, k)) }
[ "func", "Choose", "(", "n", ",", "k", "int", ")", "float64", "{", "if", "k", "==", "0", "||", "k", "==", "n", "{", "return", "1", "\n", "}", "\n", "if", "k", "<", "0", "||", "n", "<", "k", "{", "return", "0", "\n", "}", "\n", "if", "n", "<=", "smallFactLimit", "{", "// Implies k <= smallFactLimit", "// It's faster to do several integer multiplications", "// than it is to do an extra integer division.", "// Remarkably, this is also faster than pre-computing", "// Pascal's triangle (presumably because this is very", "// cache efficient).", "numer", ":=", "int64", "(", "1", ")", "\n", "for", "n1", ":=", "int64", "(", "n", "-", "(", "k", "-", "1", ")", ")", ";", "n1", "<=", "int64", "(", "n", ")", ";", "n1", "++", "{", "numer", "*=", "n1", "\n", "}", "\n", "denom", ":=", "smallFact", "[", "k", "]", "\n", "return", "float64", "(", "numer", "/", "denom", ")", "\n", "}", "\n\n", "return", "math", ".", "Exp", "(", "lchoose", "(", "n", ",", "k", ")", ")", "\n", "}" ]
// Choose returns the binomial coefficient of n and k.
[ "Choose", "returns", "the", "binomial", "coefficient", "of", "n", "and", "k", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/mathx/choose.go#L22-L44
12,358
aclements/go-moremath
stats/sample.go
Bounds
func Bounds(xs []float64) (min float64, max float64) { if len(xs) == 0 { return math.NaN(), math.NaN() } min, max = xs[0], xs[0] for _, x := range xs { if x < min { min = x } if x > max { max = x } } return }
go
func Bounds(xs []float64) (min float64, max float64) { if len(xs) == 0 { return math.NaN(), math.NaN() } min, max = xs[0], xs[0] for _, x := range xs { if x < min { min = x } if x > max { max = x } } return }
[ "func", "Bounds", "(", "xs", "[", "]", "float64", ")", "(", "min", "float64", ",", "max", "float64", ")", "{", "if", "len", "(", "xs", ")", "==", "0", "{", "return", "math", ".", "NaN", "(", ")", ",", "math", ".", "NaN", "(", ")", "\n", "}", "\n", "min", ",", "max", "=", "xs", "[", "0", "]", ",", "xs", "[", "0", "]", "\n", "for", "_", ",", "x", ":=", "range", "xs", "{", "if", "x", "<", "min", "{", "min", "=", "x", "\n", "}", "\n", "if", "x", ">", "max", "{", "max", "=", "x", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Bounds returns the minimum and maximum values of xs.
[ "Bounds", "returns", "the", "minimum", "and", "maximum", "values", "of", "xs", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/sample.go#L29-L43
12,359
aclements/go-moremath
stats/sample.go
Bounds
func (s Sample) Bounds() (min float64, max float64) { if len(s.Xs) == 0 || (!s.Sorted && s.Weights == nil) { return Bounds(s.Xs) } if s.Sorted { if s.Weights == nil { return s.Xs[0], s.Xs[len(s.Xs)-1] } min, max = math.NaN(), math.NaN() for i, w := range s.Weights { if w != 0 { min = s.Xs[i] break } } if math.IsNaN(min) { return } for i := range s.Weights { if s.Weights[len(s.Weights)-i-1] != 0 { max = s.Xs[len(s.Weights)-i-1] break } } } else { min, max = math.Inf(1), math.Inf(-1) for i, x := range s.Xs { w := s.Weights[i] if x < min && w != 0 { min = x } if x > max && w != 0 { max = x } } if math.IsInf(min, 0) { min, max = math.NaN(), math.NaN() } } return }
go
func (s Sample) Bounds() (min float64, max float64) { if len(s.Xs) == 0 || (!s.Sorted && s.Weights == nil) { return Bounds(s.Xs) } if s.Sorted { if s.Weights == nil { return s.Xs[0], s.Xs[len(s.Xs)-1] } min, max = math.NaN(), math.NaN() for i, w := range s.Weights { if w != 0 { min = s.Xs[i] break } } if math.IsNaN(min) { return } for i := range s.Weights { if s.Weights[len(s.Weights)-i-1] != 0 { max = s.Xs[len(s.Weights)-i-1] break } } } else { min, max = math.Inf(1), math.Inf(-1) for i, x := range s.Xs { w := s.Weights[i] if x < min && w != 0 { min = x } if x > max && w != 0 { max = x } } if math.IsInf(min, 0) { min, max = math.NaN(), math.NaN() } } return }
[ "func", "(", "s", "Sample", ")", "Bounds", "(", ")", "(", "min", "float64", ",", "max", "float64", ")", "{", "if", "len", "(", "s", ".", "Xs", ")", "==", "0", "||", "(", "!", "s", ".", "Sorted", "&&", "s", ".", "Weights", "==", "nil", ")", "{", "return", "Bounds", "(", "s", ".", "Xs", ")", "\n", "}", "\n\n", "if", "s", ".", "Sorted", "{", "if", "s", ".", "Weights", "==", "nil", "{", "return", "s", ".", "Xs", "[", "0", "]", ",", "s", ".", "Xs", "[", "len", "(", "s", ".", "Xs", ")", "-", "1", "]", "\n", "}", "\n", "min", ",", "max", "=", "math", ".", "NaN", "(", ")", ",", "math", ".", "NaN", "(", ")", "\n", "for", "i", ",", "w", ":=", "range", "s", ".", "Weights", "{", "if", "w", "!=", "0", "{", "min", "=", "s", ".", "Xs", "[", "i", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "math", ".", "IsNaN", "(", "min", ")", "{", "return", "\n", "}", "\n", "for", "i", ":=", "range", "s", ".", "Weights", "{", "if", "s", ".", "Weights", "[", "len", "(", "s", ".", "Weights", ")", "-", "i", "-", "1", "]", "!=", "0", "{", "max", "=", "s", ".", "Xs", "[", "len", "(", "s", ".", "Weights", ")", "-", "i", "-", "1", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "else", "{", "min", ",", "max", "=", "math", ".", "Inf", "(", "1", ")", ",", "math", ".", "Inf", "(", "-", "1", ")", "\n", "for", "i", ",", "x", ":=", "range", "s", ".", "Xs", "{", "w", ":=", "s", ".", "Weights", "[", "i", "]", "\n", "if", "x", "<", "min", "&&", "w", "!=", "0", "{", "min", "=", "x", "\n", "}", "\n", "if", "x", ">", "max", "&&", "w", "!=", "0", "{", "max", "=", "x", "\n", "}", "\n", "}", "\n", "if", "math", ".", "IsInf", "(", "min", ",", "0", ")", "{", "min", ",", "max", "=", "math", ".", "NaN", "(", ")", ",", "math", ".", "NaN", "(", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Bounds returns the minimum and maximum values of the Sample. // // If the Sample is weighted, this ignores samples with zero weight. // // This is constant time if s.Sorted and there are no zero-weighted // values.
[ "Bounds", "returns", "the", "minimum", "and", "maximum", "values", "of", "the", "Sample", ".", "If", "the", "Sample", "is", "weighted", "this", "ignores", "samples", "with", "zero", "weight", ".", "This", "is", "constant", "time", "if", "s", ".", "Sorted", "and", "there", "are", "no", "zero", "-", "weighted", "values", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/sample.go#L51-L92
12,360
aclements/go-moremath
stats/sample.go
Weight
func (s Sample) Weight() float64 { if s.Weights == nil { return float64(len(s.Xs)) } return vec.Sum(s.Weights) }
go
func (s Sample) Weight() float64 { if s.Weights == nil { return float64(len(s.Xs)) } return vec.Sum(s.Weights) }
[ "func", "(", "s", "Sample", ")", "Weight", "(", ")", "float64", "{", "if", "s", ".", "Weights", "==", "nil", "{", "return", "float64", "(", "len", "(", "s", ".", "Xs", ")", ")", "\n", "}", "\n", "return", "vec", ".", "Sum", "(", "s", ".", "Weights", ")", "\n", "}" ]
// Weight returns the total weight of the Sasmple.
[ "Weight", "returns", "the", "total", "weight", "of", "the", "Sasmple", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/sample.go#L107-L112
12,361
aclements/go-moremath
stats/sample.go
Mean
func Mean(xs []float64) float64 { if len(xs) == 0 { return math.NaN() } m := 0.0 for i, x := range xs { m += (x - m) / float64(i+1) } return m }
go
func Mean(xs []float64) float64 { if len(xs) == 0 { return math.NaN() } m := 0.0 for i, x := range xs { m += (x - m) / float64(i+1) } return m }
[ "func", "Mean", "(", "xs", "[", "]", "float64", ")", "float64", "{", "if", "len", "(", "xs", ")", "==", "0", "{", "return", "math", ".", "NaN", "(", ")", "\n", "}", "\n", "m", ":=", "0.0", "\n", "for", "i", ",", "x", ":=", "range", "xs", "{", "m", "+=", "(", "x", "-", "m", ")", "/", "float64", "(", "i", "+", "1", ")", "\n", "}", "\n", "return", "m", "\n", "}" ]
// Mean returns the arithmetic mean of xs.
[ "Mean", "returns", "the", "arithmetic", "mean", "of", "xs", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/sample.go#L115-L124
12,362
aclements/go-moremath
stats/sample.go
Mean
func (s Sample) Mean() float64 { if len(s.Xs) == 0 || s.Weights == nil { return Mean(s.Xs) } m, wsum := 0.0, 0.0 for i, x := range s.Xs { // Use weighted incremental mean: // m_i = (1 - w_i/wsum_i) * m_(i-1) + (w_i/wsum_i) * x_i // = m_(i-1) + (x_i - m_(i-1)) * (w_i/wsum_i) w := s.Weights[i] wsum += w m += (x - m) * w / wsum } return m }
go
func (s Sample) Mean() float64 { if len(s.Xs) == 0 || s.Weights == nil { return Mean(s.Xs) } m, wsum := 0.0, 0.0 for i, x := range s.Xs { // Use weighted incremental mean: // m_i = (1 - w_i/wsum_i) * m_(i-1) + (w_i/wsum_i) * x_i // = m_(i-1) + (x_i - m_(i-1)) * (w_i/wsum_i) w := s.Weights[i] wsum += w m += (x - m) * w / wsum } return m }
[ "func", "(", "s", "Sample", ")", "Mean", "(", ")", "float64", "{", "if", "len", "(", "s", ".", "Xs", ")", "==", "0", "||", "s", ".", "Weights", "==", "nil", "{", "return", "Mean", "(", "s", ".", "Xs", ")", "\n", "}", "\n\n", "m", ",", "wsum", ":=", "0.0", ",", "0.0", "\n", "for", "i", ",", "x", ":=", "range", "s", ".", "Xs", "{", "// Use weighted incremental mean:", "// m_i = (1 - w_i/wsum_i) * m_(i-1) + (w_i/wsum_i) * x_i", "// = m_(i-1) + (x_i - m_(i-1)) * (w_i/wsum_i)", "w", ":=", "s", ".", "Weights", "[", "i", "]", "\n", "wsum", "+=", "w", "\n", "m", "+=", "(", "x", "-", "m", ")", "*", "w", "/", "wsum", "\n", "}", "\n", "return", "m", "\n", "}" ]
// Mean returns the arithmetic mean of the Sample.
[ "Mean", "returns", "the", "arithmetic", "mean", "of", "the", "Sample", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/sample.go#L127-L142
12,363
aclements/go-moremath
stats/sample.go
GeoMean
func GeoMean(xs []float64) float64 { if len(xs) == 0 { return math.NaN() } m := 0.0 for i, x := range xs { if x <= 0 { return math.NaN() } lx := math.Log(x) m += (lx - m) / float64(i+1) } return math.Exp(m) }
go
func GeoMean(xs []float64) float64 { if len(xs) == 0 { return math.NaN() } m := 0.0 for i, x := range xs { if x <= 0 { return math.NaN() } lx := math.Log(x) m += (lx - m) / float64(i+1) } return math.Exp(m) }
[ "func", "GeoMean", "(", "xs", "[", "]", "float64", ")", "float64", "{", "if", "len", "(", "xs", ")", "==", "0", "{", "return", "math", ".", "NaN", "(", ")", "\n", "}", "\n", "m", ":=", "0.0", "\n", "for", "i", ",", "x", ":=", "range", "xs", "{", "if", "x", "<=", "0", "{", "return", "math", ".", "NaN", "(", ")", "\n", "}", "\n", "lx", ":=", "math", ".", "Log", "(", "x", ")", "\n", "m", "+=", "(", "lx", "-", "m", ")", "/", "float64", "(", "i", "+", "1", ")", "\n", "}", "\n", "return", "math", ".", "Exp", "(", "m", ")", "\n", "}" ]
// GeoMean returns the geometric mean of xs. xs must be positive.
[ "GeoMean", "returns", "the", "geometric", "mean", "of", "xs", ".", "xs", "must", "be", "positive", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/sample.go#L145-L158
12,364
aclements/go-moremath
stats/sample.go
GeoMean
func (s Sample) GeoMean() float64 { if len(s.Xs) == 0 || s.Weights == nil { return GeoMean(s.Xs) } m, wsum := 0.0, 0.0 for i, x := range s.Xs { w := s.Weights[i] wsum += w lx := math.Log(x) m += (lx - m) * w / wsum } return math.Exp(m) }
go
func (s Sample) GeoMean() float64 { if len(s.Xs) == 0 || s.Weights == nil { return GeoMean(s.Xs) } m, wsum := 0.0, 0.0 for i, x := range s.Xs { w := s.Weights[i] wsum += w lx := math.Log(x) m += (lx - m) * w / wsum } return math.Exp(m) }
[ "func", "(", "s", "Sample", ")", "GeoMean", "(", ")", "float64", "{", "if", "len", "(", "s", ".", "Xs", ")", "==", "0", "||", "s", ".", "Weights", "==", "nil", "{", "return", "GeoMean", "(", "s", ".", "Xs", ")", "\n", "}", "\n\n", "m", ",", "wsum", ":=", "0.0", ",", "0.0", "\n", "for", "i", ",", "x", ":=", "range", "s", ".", "Xs", "{", "w", ":=", "s", ".", "Weights", "[", "i", "]", "\n", "wsum", "+=", "w", "\n", "lx", ":=", "math", ".", "Log", "(", "x", ")", "\n", "m", "+=", "(", "lx", "-", "m", ")", "*", "w", "/", "wsum", "\n", "}", "\n", "return", "math", ".", "Exp", "(", "m", ")", "\n", "}" ]
// GeoMean returns the geometric mean of the Sample. All samples // values must be positive.
[ "GeoMean", "returns", "the", "geometric", "mean", "of", "the", "Sample", ".", "All", "samples", "values", "must", "be", "positive", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/sample.go#L162-L175
12,365
aclements/go-moremath
stats/sample.go
Variance
func Variance(xs []float64) float64 { if len(xs) == 0 { return math.NaN() } else if len(xs) <= 1 { return 0 } // Based on Wikipedia's presentation of Welford 1962 // (http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm). // This is more numerically stable than the standard two-pass // formula and not prone to massive cancellation. mean, M2 := 0.0, 0.0 for n, x := range xs { delta := x - mean mean += delta / float64(n+1) M2 += delta * (x - mean) } return M2 / float64(len(xs)-1) }
go
func Variance(xs []float64) float64 { if len(xs) == 0 { return math.NaN() } else if len(xs) <= 1 { return 0 } // Based on Wikipedia's presentation of Welford 1962 // (http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm). // This is more numerically stable than the standard two-pass // formula and not prone to massive cancellation. mean, M2 := 0.0, 0.0 for n, x := range xs { delta := x - mean mean += delta / float64(n+1) M2 += delta * (x - mean) } return M2 / float64(len(xs)-1) }
[ "func", "Variance", "(", "xs", "[", "]", "float64", ")", "float64", "{", "if", "len", "(", "xs", ")", "==", "0", "{", "return", "math", ".", "NaN", "(", ")", "\n", "}", "else", "if", "len", "(", "xs", ")", "<=", "1", "{", "return", "0", "\n", "}", "\n\n", "// Based on Wikipedia's presentation of Welford 1962", "// (http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm).", "// This is more numerically stable than the standard two-pass", "// formula and not prone to massive cancellation.", "mean", ",", "M2", ":=", "0.0", ",", "0.0", "\n", "for", "n", ",", "x", ":=", "range", "xs", "{", "delta", ":=", "x", "-", "mean", "\n", "mean", "+=", "delta", "/", "float64", "(", "n", "+", "1", ")", "\n", "M2", "+=", "delta", "*", "(", "x", "-", "mean", ")", "\n", "}", "\n", "return", "M2", "/", "float64", "(", "len", "(", "xs", ")", "-", "1", ")", "\n", "}" ]
// Variance returns the sample variance of xs.
[ "Variance", "returns", "the", "sample", "variance", "of", "xs", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/sample.go#L178-L196
12,366
aclements/go-moremath
stats/sample.go
StdDev
func (s Sample) StdDev() float64 { if len(s.Xs) == 0 || s.Weights == nil { return StdDev(s.Xs) } // TODO(austin) panic("Weighted StdDev not implemented") }
go
func (s Sample) StdDev() float64 { if len(s.Xs) == 0 || s.Weights == nil { return StdDev(s.Xs) } // TODO(austin) panic("Weighted StdDev not implemented") }
[ "func", "(", "s", "Sample", ")", "StdDev", "(", ")", "float64", "{", "if", "len", "(", "s", ".", "Xs", ")", "==", "0", "||", "s", ".", "Weights", "==", "nil", "{", "return", "StdDev", "(", "s", ".", "Xs", ")", "\n", "}", "\n", "// TODO(austin)", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// StdDev returns the sample standard deviation of the Sample.
[ "StdDev", "returns", "the", "sample", "standard", "deviation", "of", "the", "Sample", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/sample.go#L212-L218
12,367
aclements/go-moremath
stats/sample.go
IQR
func (s Sample) IQR() float64 { if !s.Sorted { s = *s.Copy().Sort() } return s.Quantile(0.75) - s.Quantile(0.25) }
go
func (s Sample) IQR() float64 { if !s.Sorted { s = *s.Copy().Sort() } return s.Quantile(0.75) - s.Quantile(0.25) }
[ "func", "(", "s", "Sample", ")", "IQR", "(", ")", "float64", "{", "if", "!", "s", ".", "Sorted", "{", "s", "=", "*", "s", ".", "Copy", "(", ")", ".", "Sort", "(", ")", "\n", "}", "\n", "return", "s", ".", "Quantile", "(", "0.75", ")", "-", "s", ".", "Quantile", "(", "0.25", ")", "\n", "}" ]
// IQR returns the interquartile range of the Sample. // // This is constant time if s.Sorted and s.Weights == nil.
[ "IQR", "returns", "the", "interquartile", "range", "of", "the", "Sample", ".", "This", "is", "constant", "time", "if", "s", ".", "Sorted", "and", "s", ".", "Weights", "==", "nil", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/sample.go#L280-L285
12,368
aclements/go-moremath
stats/sample.go
Sort
func (s *Sample) Sort() *Sample { if s.Sorted || sort.Float64sAreSorted(s.Xs) { // All set } else if s.Weights == nil { sort.Float64s(s.Xs) } else { sort.Sort(&sampleSorter{s.Xs, s.Weights}) } s.Sorted = true return s }
go
func (s *Sample) Sort() *Sample { if s.Sorted || sort.Float64sAreSorted(s.Xs) { // All set } else if s.Weights == nil { sort.Float64s(s.Xs) } else { sort.Sort(&sampleSorter{s.Xs, s.Weights}) } s.Sorted = true return s }
[ "func", "(", "s", "*", "Sample", ")", "Sort", "(", ")", "*", "Sample", "{", "if", "s", ".", "Sorted", "||", "sort", ".", "Float64sAreSorted", "(", "s", ".", "Xs", ")", "{", "// All set", "}", "else", "if", "s", ".", "Weights", "==", "nil", "{", "sort", ".", "Float64s", "(", "s", ".", "Xs", ")", "\n", "}", "else", "{", "sort", ".", "Sort", "(", "&", "sampleSorter", "{", "s", ".", "Xs", ",", "s", ".", "Weights", "}", ")", "\n", "}", "\n", "s", ".", "Sorted", "=", "true", "\n", "return", "s", "\n", "}" ]
// Sort sorts the samples in place in s and returns s. // // A sorted sample improves the performance of some algorithms.
[ "Sort", "sorts", "the", "samples", "in", "place", "in", "s", "and", "returns", "s", ".", "A", "sorted", "sample", "improves", "the", "performance", "of", "some", "algorithms", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/stats/sample.go#L308-L318
12,369
aclements/go-moremath
scale/log.go
NewLog
func NewLog(min, max float64, base int) (Log, error) { if min > max { min, max = max, min } if base <= 1 { return Log{}, RangeErr("Log scale base must be 2 or more") } if min <= 0 && max >= 0 { return Log{}, RangeErr("Log scale range cannot include 0") } return Log{Min: min, Max: max, Base: base}, nil }
go
func NewLog(min, max float64, base int) (Log, error) { if min > max { min, max = max, min } if base <= 1 { return Log{}, RangeErr("Log scale base must be 2 or more") } if min <= 0 && max >= 0 { return Log{}, RangeErr("Log scale range cannot include 0") } return Log{Min: min, Max: max, Base: base}, nil }
[ "func", "NewLog", "(", "min", ",", "max", "float64", ",", "base", "int", ")", "(", "Log", ",", "error", ")", "{", "if", "min", ">", "max", "{", "min", ",", "max", "=", "max", ",", "min", "\n", "}", "\n\n", "if", "base", "<=", "1", "{", "return", "Log", "{", "}", ",", "RangeErr", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "min", "<=", "0", "&&", "max", ">=", "0", "{", "return", "Log", "{", "}", ",", "RangeErr", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "Log", "{", "Min", ":", "min", ",", "Max", ":", "max", ",", "Base", ":", "base", "}", ",", "nil", "\n", "}" ]
// NewLog constructs a Log scale. If the arguments are out of range, // it returns a RangeErr.
[ "NewLog", "constructs", "a", "Log", "scale", ".", "If", "the", "arguments", "are", "out", "of", "range", "it", "returns", "a", "RangeErr", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/scale/log.go#L36-L49
12,370
aclements/go-moremath
fit/lsquares.go
PolynomialRegression
func PolynomialRegression(xs, ys, weights []float64, degree int) PolynomialRegressionResult { terms := make([]func(xs, termOut []float64), degree+1) terms[0] = func(xs, termsOut []float64) { for i := range termsOut { termsOut[i] = 1 } } if degree >= 1 { terms[1] = func(xs, termOut []float64) { copy(termOut, xs) } } if degree >= 2 { terms[2] = func(xs, termOut []float64) { for i, x := range xs { termOut[i] = x * x } } } for d := 3; d < len(terms); d++ { d := d terms[d] = func(xs, termOut []float64) { for i, x := range xs { termOut[i] = math.Pow(x, float64(d+1)) } } } coeffs := LinearLeastSquares(xs, ys, weights, terms...) f := func(x float64) float64 { y := coeffs[0] xp := x for _, c := range coeffs[1:] { y += xp * c xp *= x } return y } return PolynomialRegressionResult{coeffs, f} }
go
func PolynomialRegression(xs, ys, weights []float64, degree int) PolynomialRegressionResult { terms := make([]func(xs, termOut []float64), degree+1) terms[0] = func(xs, termsOut []float64) { for i := range termsOut { termsOut[i] = 1 } } if degree >= 1 { terms[1] = func(xs, termOut []float64) { copy(termOut, xs) } } if degree >= 2 { terms[2] = func(xs, termOut []float64) { for i, x := range xs { termOut[i] = x * x } } } for d := 3; d < len(terms); d++ { d := d terms[d] = func(xs, termOut []float64) { for i, x := range xs { termOut[i] = math.Pow(x, float64(d+1)) } } } coeffs := LinearLeastSquares(xs, ys, weights, terms...) f := func(x float64) float64 { y := coeffs[0] xp := x for _, c := range coeffs[1:] { y += xp * c xp *= x } return y } return PolynomialRegressionResult{coeffs, f} }
[ "func", "PolynomialRegression", "(", "xs", ",", "ys", ",", "weights", "[", "]", "float64", ",", "degree", "int", ")", "PolynomialRegressionResult", "{", "terms", ":=", "make", "(", "[", "]", "func", "(", "xs", ",", "termOut", "[", "]", "float64", ")", ",", "degree", "+", "1", ")", "\n", "terms", "[", "0", "]", "=", "func", "(", "xs", ",", "termsOut", "[", "]", "float64", ")", "{", "for", "i", ":=", "range", "termsOut", "{", "termsOut", "[", "i", "]", "=", "1", "\n", "}", "\n", "}", "\n", "if", "degree", ">=", "1", "{", "terms", "[", "1", "]", "=", "func", "(", "xs", ",", "termOut", "[", "]", "float64", ")", "{", "copy", "(", "termOut", ",", "xs", ")", "\n", "}", "\n", "}", "\n", "if", "degree", ">=", "2", "{", "terms", "[", "2", "]", "=", "func", "(", "xs", ",", "termOut", "[", "]", "float64", ")", "{", "for", "i", ",", "x", ":=", "range", "xs", "{", "termOut", "[", "i", "]", "=", "x", "*", "x", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "d", ":=", "3", ";", "d", "<", "len", "(", "terms", ")", ";", "d", "++", "{", "d", ":=", "d", "\n", "terms", "[", "d", "]", "=", "func", "(", "xs", ",", "termOut", "[", "]", "float64", ")", "{", "for", "i", ",", "x", ":=", "range", "xs", "{", "termOut", "[", "i", "]", "=", "math", ".", "Pow", "(", "x", ",", "float64", "(", "d", "+", "1", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "coeffs", ":=", "LinearLeastSquares", "(", "xs", ",", "ys", ",", "weights", ",", "terms", "...", ")", "\n", "f", ":=", "func", "(", "x", "float64", ")", "float64", "{", "y", ":=", "coeffs", "[", "0", "]", "\n", "xp", ":=", "x", "\n", "for", "_", ",", "c", ":=", "range", "coeffs", "[", "1", ":", "]", "{", "y", "+=", "xp", "*", "c", "\n", "xp", "*=", "x", "\n", "}", "\n", "return", "y", "\n", "}", "\n", "return", "PolynomialRegressionResult", "{", "coeffs", ",", "f", "}", "\n", "}" ]
// PolynomialRegression performs a least squares regression with a // polynomial of the given degree. If weights is non-nil, it is used // to weight the residuals.
[ "PolynomialRegression", "performs", "a", "least", "squares", "regression", "with", "a", "polynomial", "of", "the", "given", "degree", ".", "If", "weights", "is", "non", "-", "nil", "it", "is", "used", "to", "weight", "the", "residuals", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/fit/lsquares.go#L135-L174
12,371
aclements/go-moremath
vec/vec.go
Linspace
func Linspace(lo, hi float64, num int) []float64 { res := make([]float64, num) if num == 1 { res[0] = lo return res } for i := 0; i < num; i++ { res[i] = lo + float64(i)*(hi-lo)/float64(num-1) } return res }
go
func Linspace(lo, hi float64, num int) []float64 { res := make([]float64, num) if num == 1 { res[0] = lo return res } for i := 0; i < num; i++ { res[i] = lo + float64(i)*(hi-lo)/float64(num-1) } return res }
[ "func", "Linspace", "(", "lo", ",", "hi", "float64", ",", "num", "int", ")", "[", "]", "float64", "{", "res", ":=", "make", "(", "[", "]", "float64", ",", "num", ")", "\n", "if", "num", "==", "1", "{", "res", "[", "0", "]", "=", "lo", "\n", "return", "res", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "num", ";", "i", "++", "{", "res", "[", "i", "]", "=", "lo", "+", "float64", "(", "i", ")", "*", "(", "hi", "-", "lo", ")", "/", "float64", "(", "num", "-", "1", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// Linspace returns num values spaced evenly between lo and hi, // inclusive. If num is 1, this returns an array consisting of lo.
[ "Linspace", "returns", "num", "values", "spaced", "evenly", "between", "lo", "and", "hi", "inclusive", ".", "If", "num", "is", "1", "this", "returns", "an", "array", "consisting", "of", "lo", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/vec/vec.go#L32-L42
12,372
aclements/go-moremath
vec/vec.go
Sum
func Sum(xs []float64) float64 { sum := 0.0 for _, x := range xs { sum += x } return sum }
go
func Sum(xs []float64) float64 { sum := 0.0 for _, x := range xs { sum += x } return sum }
[ "func", "Sum", "(", "xs", "[", "]", "float64", ")", "float64", "{", "sum", ":=", "0.0", "\n", "for", "_", ",", "x", ":=", "range", "xs", "{", "sum", "+=", "x", "\n", "}", "\n", "return", "sum", "\n", "}" ]
// Sum returns the sum of xs.
[ "Sum", "returns", "the", "sum", "of", "xs", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/vec/vec.go#L55-L61
12,373
aclements/go-moremath
vec/vec.go
Concat
func Concat(xss ...[]float64) []float64 { total := 0 for _, xs := range xss { total += len(xs) } out := make([]float64, total) pos := 0 for _, xs := range xss { pos += copy(out[pos:], xs) } return out }
go
func Concat(xss ...[]float64) []float64 { total := 0 for _, xs := range xss { total += len(xs) } out := make([]float64, total) pos := 0 for _, xs := range xss { pos += copy(out[pos:], xs) } return out }
[ "func", "Concat", "(", "xss", "...", "[", "]", "float64", ")", "[", "]", "float64", "{", "total", ":=", "0", "\n", "for", "_", ",", "xs", ":=", "range", "xss", "{", "total", "+=", "len", "(", "xs", ")", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "float64", ",", "total", ")", "\n", "pos", ":=", "0", "\n", "for", "_", ",", "xs", ":=", "range", "xss", "{", "pos", "+=", "copy", "(", "out", "[", "pos", ":", "]", ",", "xs", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// Concat returns the concatenation of its arguments. It does not // modify its inputs.
[ "Concat", "returns", "the", "concatenation", "of", "its", "arguments", ".", "It", "does", "not", "modify", "its", "inputs", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/vec/vec.go#L65-L76
12,374
aclements/go-moremath
cmd/dist/plot.go
FprintCDF
func FprintCDF(w io.Writer, dists ...stats.Dist) error { xscale, xs := commonScale(dists...) for _, d := range dists { if err := fprintFn(w, d.CDF, xscale, xs); err != nil { return err } } return fprintScale(w, xscale) }
go
func FprintCDF(w io.Writer, dists ...stats.Dist) error { xscale, xs := commonScale(dists...) for _, d := range dists { if err := fprintFn(w, d.CDF, xscale, xs); err != nil { return err } } return fprintScale(w, xscale) }
[ "func", "FprintCDF", "(", "w", "io", ".", "Writer", ",", "dists", "...", "stats", ".", "Dist", ")", "error", "{", "xscale", ",", "xs", ":=", "commonScale", "(", "dists", "...", ")", "\n", "for", "_", ",", "d", ":=", "range", "dists", "{", "if", "err", ":=", "fprintFn", "(", "w", ",", "d", ".", "CDF", ",", "xscale", ",", "xs", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "fprintScale", "(", "w", ",", "xscale", ")", "\n", "}" ]
// FprintCDF is equivalent to FprintPDF, but prints the CDF of each // distribution.
[ "FprintCDF", "is", "equivalent", "to", "FprintPDF", "but", "prints", "the", "CDF", "of", "each", "distribution", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/cmd/dist/plot.go#L48-L56
12,375
aclements/go-moremath
cmd/dist/plot.go
makeScale
func makeScale(x1, x2 float64, y1, y2 int) scale.QQ { return scale.QQ{ Src: &scale.Linear{Min: x1, Max: x2, Clamp: true}, Dest: &scale.Linear{Min: float64(y1), Max: float64(y2) - 1e-10}, } }
go
func makeScale(x1, x2 float64, y1, y2 int) scale.QQ { return scale.QQ{ Src: &scale.Linear{Min: x1, Max: x2, Clamp: true}, Dest: &scale.Linear{Min: float64(y1), Max: float64(y2) - 1e-10}, } }
[ "func", "makeScale", "(", "x1", ",", "x2", "float64", ",", "y1", ",", "y2", "int", ")", "scale", ".", "QQ", "{", "return", "scale", ".", "QQ", "{", "Src", ":", "&", "scale", ".", "Linear", "{", "Min", ":", "x1", ",", "Max", ":", "x2", ",", "Clamp", ":", "true", "}", ",", "Dest", ":", "&", "scale", ".", "Linear", "{", "Min", ":", "float64", "(", "y1", ")", ",", "Max", ":", "float64", "(", "y2", ")", "-", "1e-10", "}", ",", "}", "\n", "}" ]
// makeScale creates a linear scale from [x1, x2) to [y1, y2).
[ "makeScale", "creates", "a", "linear", "scale", "from", "[", "x1", "x2", ")", "to", "[", "y1", "y2", ")", "." ]
b1aff36309c727972dd8b46fcc93f88763a62348
https://github.com/aclements/go-moremath/blob/b1aff36309c727972dd8b46fcc93f88763a62348/cmd/dist/plot.go#L59-L64
12,376
mikioh/ipaddr
prefix.go
Contains
func (p *Prefix) Contains(q *Prefix) bool { if p.IP.To4() != nil { return p.containsIPv4(q) } if p.IP.To16() != nil && p.IP.To4() == nil { return p.containsIPv6(q) } return false }
go
func (p *Prefix) Contains(q *Prefix) bool { if p.IP.To4() != nil { return p.containsIPv4(q) } if p.IP.To16() != nil && p.IP.To4() == nil { return p.containsIPv6(q) } return false }
[ "func", "(", "p", "*", "Prefix", ")", "Contains", "(", "q", "*", "Prefix", ")", "bool", "{", "if", "p", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "return", "p", ".", "containsIPv4", "(", "q", ")", "\n", "}", "\n", "if", "p", ".", "IP", ".", "To16", "(", ")", "!=", "nil", "&&", "p", ".", "IP", ".", "To4", "(", ")", "==", "nil", "{", "return", "p", ".", "containsIPv6", "(", "q", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Contains reports whether q is a subnetwork of p.
[ "Contains", "reports", "whether", "q", "is", "a", "subnetwork", "of", "p", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L56-L64
12,377
mikioh/ipaddr
prefix.go
Exclude
func (p *Prefix) Exclude(q *Prefix) []Prefix { if !p.IPNet.Contains(q.IP) { return nil } if p.Equal(q) { return []Prefix{*q} } subsFn := subnetsIPv6 if p.IP.To4() != nil { subsFn = subnetsIPv4 } var ps []Prefix l, r := subsFn(p, false) for !l.Equal(q) && !r.Equal(q) { if l.IPNet.Contains(q.IP) { ps = append(ps, *r) l, r = subsFn(l, true) } else if r.IPNet.Contains(q.IP) { ps = append(ps, *l) l, r = subsFn(r, true) } } if l.Equal(q) { ps = append(ps, *r) } else if r.Equal(q) { ps = append(ps, *l) } return ps }
go
func (p *Prefix) Exclude(q *Prefix) []Prefix { if !p.IPNet.Contains(q.IP) { return nil } if p.Equal(q) { return []Prefix{*q} } subsFn := subnetsIPv6 if p.IP.To4() != nil { subsFn = subnetsIPv4 } var ps []Prefix l, r := subsFn(p, false) for !l.Equal(q) && !r.Equal(q) { if l.IPNet.Contains(q.IP) { ps = append(ps, *r) l, r = subsFn(l, true) } else if r.IPNet.Contains(q.IP) { ps = append(ps, *l) l, r = subsFn(r, true) } } if l.Equal(q) { ps = append(ps, *r) } else if r.Equal(q) { ps = append(ps, *l) } return ps }
[ "func", "(", "p", "*", "Prefix", ")", "Exclude", "(", "q", "*", "Prefix", ")", "[", "]", "Prefix", "{", "if", "!", "p", ".", "IPNet", ".", "Contains", "(", "q", ".", "IP", ")", "{", "return", "nil", "\n", "}", "\n", "if", "p", ".", "Equal", "(", "q", ")", "{", "return", "[", "]", "Prefix", "{", "*", "q", "}", "\n", "}", "\n", "subsFn", ":=", "subnetsIPv6", "\n", "if", "p", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "subsFn", "=", "subnetsIPv4", "\n", "}", "\n", "var", "ps", "[", "]", "Prefix", "\n", "l", ",", "r", ":=", "subsFn", "(", "p", ",", "false", ")", "\n", "for", "!", "l", ".", "Equal", "(", "q", ")", "&&", "!", "r", ".", "Equal", "(", "q", ")", "{", "if", "l", ".", "IPNet", ".", "Contains", "(", "q", ".", "IP", ")", "{", "ps", "=", "append", "(", "ps", ",", "*", "r", ")", "\n", "l", ",", "r", "=", "subsFn", "(", "l", ",", "true", ")", "\n", "}", "else", "if", "r", ".", "IPNet", ".", "Contains", "(", "q", ".", "IP", ")", "{", "ps", "=", "append", "(", "ps", ",", "*", "l", ")", "\n", "l", ",", "r", "=", "subsFn", "(", "r", ",", "true", ")", "\n", "}", "\n", "}", "\n", "if", "l", ".", "Equal", "(", "q", ")", "{", "ps", "=", "append", "(", "ps", ",", "*", "r", ")", "\n", "}", "else", "if", "r", ".", "Equal", "(", "q", ")", "{", "ps", "=", "append", "(", "ps", ",", "*", "l", ")", "\n", "}", "\n", "return", "ps", "\n", "}" ]
// Exclude returns a list of prefixes that do not contain q.
[ "Exclude", "returns", "a", "list", "of", "prefixes", "that", "do", "not", "contain", "q", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L111-L139
12,378
mikioh/ipaddr
prefix.go
Last
func (p *Prefix) Last() net.IP { if p.IP.To4() != nil { i := p.lastIPv4Int() return i.ip() } if p.IP.To16() != nil && p.IP.To4() == nil { i := p.lastIPv6Int() return i.ip() } return nil }
go
func (p *Prefix) Last() net.IP { if p.IP.To4() != nil { i := p.lastIPv4Int() return i.ip() } if p.IP.To16() != nil && p.IP.To4() == nil { i := p.lastIPv6Int() return i.ip() } return nil }
[ "func", "(", "p", "*", "Prefix", ")", "Last", "(", ")", "net", ".", "IP", "{", "if", "p", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "i", ":=", "p", ".", "lastIPv4Int", "(", ")", "\n", "return", "i", ".", "ip", "(", ")", "\n", "}", "\n", "if", "p", ".", "IP", ".", "To16", "(", ")", "!=", "nil", "&&", "p", ".", "IP", ".", "To4", "(", ")", "==", "nil", "{", "i", ":=", "p", ".", "lastIPv6Int", "(", ")", "\n", "return", "i", ".", "ip", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Last returns the last IP in the address range of p. // It returns the address of p when p contains only one address.
[ "Last", "returns", "the", "last", "IP", "in", "the", "address", "range", "of", "p", ".", "It", "returns", "the", "address", "of", "p", "when", "p", "contains", "only", "one", "address", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L178-L188
12,379
mikioh/ipaddr
prefix.go
Len
func (p *Prefix) Len() int { l, _ := p.Mask.Size() return l }
go
func (p *Prefix) Len() int { l, _ := p.Mask.Size() return l }
[ "func", "(", "p", "*", "Prefix", ")", "Len", "(", ")", "int", "{", "l", ",", "_", ":=", "p", ".", "Mask", ".", "Size", "(", ")", "\n", "return", "l", "\n", "}" ]
// Len returns the length of p in bits.
[ "Len", "returns", "the", "length", "of", "p", "in", "bits", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L191-L194
12,380
mikioh/ipaddr
prefix.go
MarshalBinary
func (p *Prefix) MarshalBinary() ([]byte, error) { ip := p.IP if p.IP.To4() != nil { ip = p.IP.To4() } var b [1 + net.IPv6len]byte n := p.Len() l := ((n + 8 - 1) &^ (8 - 1)) / 8 b[0] = byte(n) l++ copy(b[1:l], ip) return b[:l], nil }
go
func (p *Prefix) MarshalBinary() ([]byte, error) { ip := p.IP if p.IP.To4() != nil { ip = p.IP.To4() } var b [1 + net.IPv6len]byte n := p.Len() l := ((n + 8 - 1) &^ (8 - 1)) / 8 b[0] = byte(n) l++ copy(b[1:l], ip) return b[:l], nil }
[ "func", "(", "p", "*", "Prefix", ")", "MarshalBinary", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "ip", ":=", "p", ".", "IP", "\n", "if", "p", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "ip", "=", "p", ".", "IP", ".", "To4", "(", ")", "\n", "}", "\n", "var", "b", "[", "1", "+", "net", ".", "IPv6len", "]", "byte", "\n", "n", ":=", "p", ".", "Len", "(", ")", "\n", "l", ":=", "(", "(", "n", "+", "8", "-", "1", ")", "&^", "(", "8", "-", "1", ")", ")", "/", "8", "\n", "b", "[", "0", "]", "=", "byte", "(", "n", ")", "\n", "l", "++", "\n", "copy", "(", "b", "[", "1", ":", "l", "]", ",", "ip", ")", "\n", "return", "b", "[", ":", "l", "]", ",", "nil", "\n", "}" ]
// MarshalBinary returns a BGP NLRI binary form of p.
[ "MarshalBinary", "returns", "a", "BGP", "NLRI", "binary", "form", "of", "p", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L197-L209
12,381
mikioh/ipaddr
prefix.go
NumNodes
func (p *Prefix) NumNodes() *big.Int { i := new(big.Int).SetBytes(invert(p.Mask)) return i.Add(i, big.NewInt(1)) }
go
func (p *Prefix) NumNodes() *big.Int { i := new(big.Int).SetBytes(invert(p.Mask)) return i.Add(i, big.NewInt(1)) }
[ "func", "(", "p", "*", "Prefix", ")", "NumNodes", "(", ")", "*", "big", ".", "Int", "{", "i", ":=", "new", "(", "big", ".", "Int", ")", ".", "SetBytes", "(", "invert", "(", "p", ".", "Mask", ")", ")", "\n", "return", "i", ".", "Add", "(", "i", ",", "big", ".", "NewInt", "(", "1", ")", ")", "\n", "}" ]
// NumNodes returns the number of IP node addresses in p.
[ "NumNodes", "returns", "the", "number", "of", "IP", "node", "addresses", "in", "p", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L217-L220
12,382
mikioh/ipaddr
prefix.go
Overlaps
func (p *Prefix) Overlaps(q *Prefix) bool { return p.Contains(q) || q.Contains(p) || p.Equal(q) }
go
func (p *Prefix) Overlaps(q *Prefix) bool { return p.Contains(q) || q.Contains(p) || p.Equal(q) }
[ "func", "(", "p", "*", "Prefix", ")", "Overlaps", "(", "q", "*", "Prefix", ")", "bool", "{", "return", "p", ".", "Contains", "(", "q", ")", "||", "q", ".", "Contains", "(", "p", ")", "||", "p", ".", "Equal", "(", "q", ")", "\n", "}" ]
// Overlaps reports whether p overlaps with q.
[ "Overlaps", "reports", "whether", "p", "overlaps", "with", "q", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L223-L225
12,383
mikioh/ipaddr
prefix.go
Subnets
func (p *Prefix) Subnets(n int) []Prefix { if 0 > n || n > 17 { // don't bother runtime.makeslice by big numbers return nil } ps := make([]Prefix, 1<<uint(n)) if p.IP.To4() != nil { x := ipToIPv4Int(p.IP) off := uint(IPv4PrefixLen - p.Len() - n) for i := range ps { ii := x | ipv4Int(i<<off) ps[i] = *ii.prefix(p.Len()+n, IPv4PrefixLen) } return ps } x := ipToIPv6Int(p.IP) off := IPv6PrefixLen - p.Len() - n for i := range ps { id := ipv6Int{0, uint64(i)} id.lsh(off) ii := ipv6Int{x[0] | id[0], x[1] | id[1]} ps[i] = *ii.prefix(p.Len()+n, IPv6PrefixLen) } return ps }
go
func (p *Prefix) Subnets(n int) []Prefix { if 0 > n || n > 17 { // don't bother runtime.makeslice by big numbers return nil } ps := make([]Prefix, 1<<uint(n)) if p.IP.To4() != nil { x := ipToIPv4Int(p.IP) off := uint(IPv4PrefixLen - p.Len() - n) for i := range ps { ii := x | ipv4Int(i<<off) ps[i] = *ii.prefix(p.Len()+n, IPv4PrefixLen) } return ps } x := ipToIPv6Int(p.IP) off := IPv6PrefixLen - p.Len() - n for i := range ps { id := ipv6Int{0, uint64(i)} id.lsh(off) ii := ipv6Int{x[0] | id[0], x[1] | id[1]} ps[i] = *ii.prefix(p.Len()+n, IPv6PrefixLen) } return ps }
[ "func", "(", "p", "*", "Prefix", ")", "Subnets", "(", "n", "int", ")", "[", "]", "Prefix", "{", "if", "0", ">", "n", "||", "n", ">", "17", "{", "// don't bother runtime.makeslice by big numbers", "return", "nil", "\n", "}", "\n", "ps", ":=", "make", "(", "[", "]", "Prefix", ",", "1", "<<", "uint", "(", "n", ")", ")", "\n", "if", "p", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "x", ":=", "ipToIPv4Int", "(", "p", ".", "IP", ")", "\n", "off", ":=", "uint", "(", "IPv4PrefixLen", "-", "p", ".", "Len", "(", ")", "-", "n", ")", "\n", "for", "i", ":=", "range", "ps", "{", "ii", ":=", "x", "|", "ipv4Int", "(", "i", "<<", "off", ")", "\n", "ps", "[", "i", "]", "=", "*", "ii", ".", "prefix", "(", "p", ".", "Len", "(", ")", "+", "n", ",", "IPv4PrefixLen", ")", "\n", "}", "\n", "return", "ps", "\n", "}", "\n", "x", ":=", "ipToIPv6Int", "(", "p", ".", "IP", ")", "\n", "off", ":=", "IPv6PrefixLen", "-", "p", ".", "Len", "(", ")", "-", "n", "\n", "for", "i", ":=", "range", "ps", "{", "id", ":=", "ipv6Int", "{", "0", ",", "uint64", "(", "i", ")", "}", "\n", "id", ".", "lsh", "(", "off", ")", "\n", "ii", ":=", "ipv6Int", "{", "x", "[", "0", "]", "|", "id", "[", "0", "]", ",", "x", "[", "1", "]", "|", "id", "[", "1", "]", "}", "\n", "ps", "[", "i", "]", "=", "*", "ii", ".", "prefix", "(", "p", ".", "Len", "(", ")", "+", "n", ",", "IPv6PrefixLen", ")", "\n", "}", "\n", "return", "ps", "\n", "}" ]
// Subnets returns a list of prefixes that are split from p, into // small address blocks by n which represents a number of subnetworks // in the power of 2 notation.
[ "Subnets", "returns", "a", "list", "of", "prefixes", "that", "are", "split", "from", "p", "into", "small", "address", "blocks", "by", "n", "which", "represents", "a", "number", "of", "subnetworks", "in", "the", "power", "of", "2", "notation", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L234-L257
12,384
mikioh/ipaddr
prefix.go
UnmarshalBinary
func (p *Prefix) UnmarshalBinary(b []byte) error { if p.IP.To4() != nil { binary.BigEndian.PutUint32(p.Mask, mask32(int(b[0]))) copy(p.IP, net.IPv4zero) copy(p.IP.To4(), b[1:]) } if p.IP.To16() != nil && p.IP.To4() == nil { var m ipv6Int m.mask(int(b[0])) binary.BigEndian.PutUint64(p.Mask[:8], m[0]) binary.BigEndian.PutUint64(p.Mask[8:16], m[1]) copy(p.IP, net.IPv6unspecified) copy(p.IP, b[1:]) } return nil }
go
func (p *Prefix) UnmarshalBinary(b []byte) error { if p.IP.To4() != nil { binary.BigEndian.PutUint32(p.Mask, mask32(int(b[0]))) copy(p.IP, net.IPv4zero) copy(p.IP.To4(), b[1:]) } if p.IP.To16() != nil && p.IP.To4() == nil { var m ipv6Int m.mask(int(b[0])) binary.BigEndian.PutUint64(p.Mask[:8], m[0]) binary.BigEndian.PutUint64(p.Mask[8:16], m[1]) copy(p.IP, net.IPv6unspecified) copy(p.IP, b[1:]) } return nil }
[ "func", "(", "p", "*", "Prefix", ")", "UnmarshalBinary", "(", "b", "[", "]", "byte", ")", "error", "{", "if", "p", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "binary", ".", "BigEndian", ".", "PutUint32", "(", "p", ".", "Mask", ",", "mask32", "(", "int", "(", "b", "[", "0", "]", ")", ")", ")", "\n", "copy", "(", "p", ".", "IP", ",", "net", ".", "IPv4zero", ")", "\n", "copy", "(", "p", ".", "IP", ".", "To4", "(", ")", ",", "b", "[", "1", ":", "]", ")", "\n", "}", "\n", "if", "p", ".", "IP", ".", "To16", "(", ")", "!=", "nil", "&&", "p", ".", "IP", ".", "To4", "(", ")", "==", "nil", "{", "var", "m", "ipv6Int", "\n", "m", ".", "mask", "(", "int", "(", "b", "[", "0", "]", ")", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "p", ".", "Mask", "[", ":", "8", "]", ",", "m", "[", "0", "]", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "p", ".", "Mask", "[", "8", ":", "16", "]", ",", "m", "[", "1", "]", ")", "\n", "copy", "(", "p", ".", "IP", ",", "net", ".", "IPv6unspecified", ")", "\n", "copy", "(", "p", ".", "IP", ",", "b", "[", "1", ":", "]", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UnmarshalBinary replaces p with the BGP NLRI binary form b.
[ "UnmarshalBinary", "replaces", "p", "with", "the", "BGP", "NLRI", "binary", "form", "b", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L260-L275
12,385
mikioh/ipaddr
prefix.go
UnmarshalText
func (p *Prefix) UnmarshalText(txt []byte) error { _, n, err := net.ParseCIDR(string(txt)) if err != nil { return err } copy(p.IP.To16(), n.IP.To16()) copy(p.Mask, n.Mask) return nil }
go
func (p *Prefix) UnmarshalText(txt []byte) error { _, n, err := net.ParseCIDR(string(txt)) if err != nil { return err } copy(p.IP.To16(), n.IP.To16()) copy(p.Mask, n.Mask) return nil }
[ "func", "(", "p", "*", "Prefix", ")", "UnmarshalText", "(", "txt", "[", "]", "byte", ")", "error", "{", "_", ",", "n", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "string", "(", "txt", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "copy", "(", "p", ".", "IP", ".", "To16", "(", ")", ",", "n", ".", "IP", ".", "To16", "(", ")", ")", "\n", "copy", "(", "p", ".", "Mask", ",", "n", ".", "Mask", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalText replaces p with txt.
[ "UnmarshalText", "replaces", "p", "with", "txt", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L278-L286
12,386
mikioh/ipaddr
prefix.go
Aggregate
func Aggregate(ps []Prefix) []Prefix { ps = newSortedPrefixes(ps, sortAscending, true) sortByDescending(ps) switch len(ps) { case 0: return nil case 1: return ps[:1] } bfFn, superFn := branchingFactorIPv6, supernetIPv6 if ps[0].IP.To4() != nil { bfFn, superFn = branchingFactorIPv4, supernetIPv4 } ps = aggregate(aggregateByBF(ps, bfFn, superFn)) sortByAscending(ps) return ps }
go
func Aggregate(ps []Prefix) []Prefix { ps = newSortedPrefixes(ps, sortAscending, true) sortByDescending(ps) switch len(ps) { case 0: return nil case 1: return ps[:1] } bfFn, superFn := branchingFactorIPv6, supernetIPv6 if ps[0].IP.To4() != nil { bfFn, superFn = branchingFactorIPv4, supernetIPv4 } ps = aggregate(aggregateByBF(ps, bfFn, superFn)) sortByAscending(ps) return ps }
[ "func", "Aggregate", "(", "ps", "[", "]", "Prefix", ")", "[", "]", "Prefix", "{", "ps", "=", "newSortedPrefixes", "(", "ps", ",", "sortAscending", ",", "true", ")", "\n", "sortByDescending", "(", "ps", ")", "\n", "switch", "len", "(", "ps", ")", "{", "case", "0", ":", "return", "nil", "\n", "case", "1", ":", "return", "ps", "[", ":", "1", "]", "\n", "}", "\n", "bfFn", ",", "superFn", ":=", "branchingFactorIPv6", ",", "supernetIPv6", "\n", "if", "ps", "[", "0", "]", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "bfFn", ",", "superFn", "=", "branchingFactorIPv4", ",", "supernetIPv4", "\n", "}", "\n", "ps", "=", "aggregate", "(", "aggregateByBF", "(", "ps", ",", "bfFn", ",", "superFn", ")", ")", "\n", "sortByAscending", "(", "ps", ")", "\n", "return", "ps", "\n", "}" ]
// Aggregate aggregates ps and returns a list of aggregated prefixes.
[ "Aggregate", "aggregates", "ps", "and", "returns", "a", "list", "of", "aggregated", "prefixes", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L289-L305
12,387
mikioh/ipaddr
prefix.go
NewPrefix
func NewPrefix(n *net.IPNet) *Prefix { n.IP = n.IP.To16() return &Prefix{IPNet: *n} }
go
func NewPrefix(n *net.IPNet) *Prefix { n.IP = n.IP.To16() return &Prefix{IPNet: *n} }
[ "func", "NewPrefix", "(", "n", "*", "net", ".", "IPNet", ")", "*", "Prefix", "{", "n", ".", "IP", "=", "n", ".", "IP", ".", "To16", "(", ")", "\n", "return", "&", "Prefix", "{", "IPNet", ":", "*", "n", "}", "\n", "}" ]
// NewPrefix returns a new prefix.
[ "NewPrefix", "returns", "a", "new", "prefix", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L430-L433
12,388
mikioh/ipaddr
prefix.go
Summarize
func Summarize(first, last net.IP) []Prefix { if fip := first.To4(); fip != nil { lip := last.To4() if lip == nil { return nil } return summarizeIPv4(fip, lip) } if fip := first.To16(); fip != nil && fip.To4() == nil { lip := last.To16() if lip == nil || last.To4() != nil { return nil } return summarizeIPv6(fip, lip) } return nil }
go
func Summarize(first, last net.IP) []Prefix { if fip := first.To4(); fip != nil { lip := last.To4() if lip == nil { return nil } return summarizeIPv4(fip, lip) } if fip := first.To16(); fip != nil && fip.To4() == nil { lip := last.To16() if lip == nil || last.To4() != nil { return nil } return summarizeIPv6(fip, lip) } return nil }
[ "func", "Summarize", "(", "first", ",", "last", "net", ".", "IP", ")", "[", "]", "Prefix", "{", "if", "fip", ":=", "first", ".", "To4", "(", ")", ";", "fip", "!=", "nil", "{", "lip", ":=", "last", ".", "To4", "(", ")", "\n", "if", "lip", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "summarizeIPv4", "(", "fip", ",", "lip", ")", "\n", "}", "\n", "if", "fip", ":=", "first", ".", "To16", "(", ")", ";", "fip", "!=", "nil", "&&", "fip", ".", "To4", "(", ")", "==", "nil", "{", "lip", ":=", "last", ".", "To16", "(", ")", "\n", "if", "lip", "==", "nil", "||", "last", ".", "To4", "(", ")", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "summarizeIPv6", "(", "fip", ",", "lip", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Summarize summarizes the address range from first to last and // returns a list of prefixes.
[ "Summarize", "summarizes", "the", "address", "range", "from", "first", "to", "last", "and", "returns", "a", "list", "of", "prefixes", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L437-L453
12,389
mikioh/ipaddr
prefix.go
Supernet
func Supernet(ps []Prefix) *Prefix { if len(ps) == 0 { return nil } if ps[0].IP.To4() != nil { ps = byAddrFamily(ps).newIPv4Prefixes() } if ps[0].IP.To16() != nil && ps[0].IP.To4() == nil { ps = byAddrFamily(ps).newIPv6Prefixes() } switch len(ps) { case 0: return nil case 1: return &ps[0] } if ps[0].IP.To4() != nil { return supernetIPv4(ps) } if ps[0].IP.To16() != nil && ps[0].IP.To4() == nil { return supernetIPv6(ps) } return nil }
go
func Supernet(ps []Prefix) *Prefix { if len(ps) == 0 { return nil } if ps[0].IP.To4() != nil { ps = byAddrFamily(ps).newIPv4Prefixes() } if ps[0].IP.To16() != nil && ps[0].IP.To4() == nil { ps = byAddrFamily(ps).newIPv6Prefixes() } switch len(ps) { case 0: return nil case 1: return &ps[0] } if ps[0].IP.To4() != nil { return supernetIPv4(ps) } if ps[0].IP.To16() != nil && ps[0].IP.To4() == nil { return supernetIPv6(ps) } return nil }
[ "func", "Supernet", "(", "ps", "[", "]", "Prefix", ")", "*", "Prefix", "{", "if", "len", "(", "ps", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "if", "ps", "[", "0", "]", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "ps", "=", "byAddrFamily", "(", "ps", ")", ".", "newIPv4Prefixes", "(", ")", "\n", "}", "\n", "if", "ps", "[", "0", "]", ".", "IP", ".", "To16", "(", ")", "!=", "nil", "&&", "ps", "[", "0", "]", ".", "IP", ".", "To4", "(", ")", "==", "nil", "{", "ps", "=", "byAddrFamily", "(", "ps", ")", ".", "newIPv6Prefixes", "(", ")", "\n", "}", "\n", "switch", "len", "(", "ps", ")", "{", "case", "0", ":", "return", "nil", "\n", "case", "1", ":", "return", "&", "ps", "[", "0", "]", "\n", "}", "\n", "if", "ps", "[", "0", "]", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "return", "supernetIPv4", "(", "ps", ")", "\n", "}", "\n", "if", "ps", "[", "0", "]", ".", "IP", ".", "To16", "(", ")", "!=", "nil", "&&", "ps", "[", "0", "]", ".", "IP", ".", "To4", "(", ")", "==", "nil", "{", "return", "supernetIPv6", "(", "ps", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Supernet finds out a shortest common prefix for ps. // It returns nil when no suitable prefix is found.
[ "Supernet", "finds", "out", "a", "shortest", "common", "prefix", "for", "ps", ".", "It", "returns", "nil", "when", "no", "suitable", "prefix", "is", "found", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/prefix.go#L513-L536
12,390
mikioh/ipaddr
cursor.go
First
func (c *Cursor) First() *Position { return &Position{IP: c.ps[0].IP, Prefix: c.ps[0]} }
go
func (c *Cursor) First() *Position { return &Position{IP: c.ps[0].IP, Prefix: c.ps[0]} }
[ "func", "(", "c", "*", "Cursor", ")", "First", "(", ")", "*", "Position", "{", "return", "&", "Position", "{", "IP", ":", "c", ".", "ps", "[", "0", "]", ".", "IP", ",", "Prefix", ":", "c", ".", "ps", "[", "0", "]", "}", "\n", "}" ]
// First returns the start position on c.
[ "First", "returns", "the", "start", "position", "on", "c", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/cursor.go#L33-L35
12,391
mikioh/ipaddr
cursor.go
Last
func (c *Cursor) Last() *Position { return &Position{IP: c.ps[len(c.ps)-1].Last(), Prefix: c.ps[len(c.ps)-1]} }
go
func (c *Cursor) Last() *Position { return &Position{IP: c.ps[len(c.ps)-1].Last(), Prefix: c.ps[len(c.ps)-1]} }
[ "func", "(", "c", "*", "Cursor", ")", "Last", "(", ")", "*", "Position", "{", "return", "&", "Position", "{", "IP", ":", "c", ".", "ps", "[", "len", "(", "c", ".", "ps", ")", "-", "1", "]", ".", "Last", "(", ")", ",", "Prefix", ":", "c", ".", "ps", "[", "len", "(", "c", ".", "ps", ")", "-", "1", "]", "}", "\n", "}" ]
// Last returns the end position on c.
[ "Last", "returns", "the", "end", "position", "on", "c", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/cursor.go#L38-L40
12,392
mikioh/ipaddr
cursor.go
Next
func (c *Cursor) Next() *Position { n := c.curr.cmp(&c.end) if n == 0 { if c.pi == len(c.ps)-1 { return nil } c.pi++ c.curr = ipToIPv6Int(c.ps[c.pi].IP.To16()) c.start = c.curr if c.ps[c.pi].IP.To4() != nil { c.end = c.ps[c.pi].lastIPv4MappedIPv6Int() } if c.ps[c.pi].IP.To16() != nil && c.ps[c.pi].IP.To4() == nil { c.end = c.ps[c.pi].lastIPv6Int() } } else { c.curr.incr() } return c.Pos() }
go
func (c *Cursor) Next() *Position { n := c.curr.cmp(&c.end) if n == 0 { if c.pi == len(c.ps)-1 { return nil } c.pi++ c.curr = ipToIPv6Int(c.ps[c.pi].IP.To16()) c.start = c.curr if c.ps[c.pi].IP.To4() != nil { c.end = c.ps[c.pi].lastIPv4MappedIPv6Int() } if c.ps[c.pi].IP.To16() != nil && c.ps[c.pi].IP.To4() == nil { c.end = c.ps[c.pi].lastIPv6Int() } } else { c.curr.incr() } return c.Pos() }
[ "func", "(", "c", "*", "Cursor", ")", "Next", "(", ")", "*", "Position", "{", "n", ":=", "c", ".", "curr", ".", "cmp", "(", "&", "c", ".", "end", ")", "\n", "if", "n", "==", "0", "{", "if", "c", ".", "pi", "==", "len", "(", "c", ".", "ps", ")", "-", "1", "{", "return", "nil", "\n", "}", "\n", "c", ".", "pi", "++", "\n", "c", ".", "curr", "=", "ipToIPv6Int", "(", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "IP", ".", "To16", "(", ")", ")", "\n", "c", ".", "start", "=", "c", ".", "curr", "\n", "if", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "c", ".", "end", "=", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "lastIPv4MappedIPv6Int", "(", ")", "\n", "}", "\n", "if", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "IP", ".", "To16", "(", ")", "!=", "nil", "&&", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "IP", ".", "To4", "(", ")", "==", "nil", "{", "c", ".", "end", "=", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "lastIPv6Int", "(", ")", "\n", "}", "\n", "}", "else", "{", "c", ".", "curr", ".", "incr", "(", ")", "\n", "}", "\n", "return", "c", ".", "Pos", "(", ")", "\n", "}" ]
// Next turns to the next position on c. // It returns nil at the end on c.
[ "Next", "turns", "to", "the", "next", "position", "on", "c", ".", "It", "returns", "nil", "at", "the", "end", "on", "c", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/cursor.go#L49-L68
12,393
mikioh/ipaddr
cursor.go
Pos
func (c *Cursor) Pos() *Position { return &Position{IP: c.curr.ip(), Prefix: c.ps[c.pi]} }
go
func (c *Cursor) Pos() *Position { return &Position{IP: c.curr.ip(), Prefix: c.ps[c.pi]} }
[ "func", "(", "c", "*", "Cursor", ")", "Pos", "(", ")", "*", "Position", "{", "return", "&", "Position", "{", "IP", ":", "c", ".", "curr", ".", "ip", "(", ")", ",", "Prefix", ":", "c", ".", "ps", "[", "c", ".", "pi", "]", "}", "\n", "}" ]
// Pos returns the current position on c.
[ "Pos", "returns", "the", "current", "position", "on", "c", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/cursor.go#L71-L73
12,394
mikioh/ipaddr
cursor.go
Prev
func (c *Cursor) Prev() *Position { n := c.curr.cmp(&c.start) if n == 0 { if c.pi == 0 { return nil } c.pi-- if c.ps[c.pi].IP.To4() != nil { c.curr = c.ps[c.pi].lastIPv4MappedIPv6Int() c.end = c.curr } if c.ps[c.pi].IP.To16() != nil && c.ps[c.pi].IP.To4() == nil { c.curr = c.ps[c.pi].lastIPv6Int() c.end = c.curr } c.start = ipToIPv6Int(c.ps[c.pi].IP.To16()) } else { c.curr.decr() } return c.Pos() }
go
func (c *Cursor) Prev() *Position { n := c.curr.cmp(&c.start) if n == 0 { if c.pi == 0 { return nil } c.pi-- if c.ps[c.pi].IP.To4() != nil { c.curr = c.ps[c.pi].lastIPv4MappedIPv6Int() c.end = c.curr } if c.ps[c.pi].IP.To16() != nil && c.ps[c.pi].IP.To4() == nil { c.curr = c.ps[c.pi].lastIPv6Int() c.end = c.curr } c.start = ipToIPv6Int(c.ps[c.pi].IP.To16()) } else { c.curr.decr() } return c.Pos() }
[ "func", "(", "c", "*", "Cursor", ")", "Prev", "(", ")", "*", "Position", "{", "n", ":=", "c", ".", "curr", ".", "cmp", "(", "&", "c", ".", "start", ")", "\n", "if", "n", "==", "0", "{", "if", "c", ".", "pi", "==", "0", "{", "return", "nil", "\n", "}", "\n", "c", ".", "pi", "--", "\n", "if", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "c", ".", "curr", "=", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "lastIPv4MappedIPv6Int", "(", ")", "\n", "c", ".", "end", "=", "c", ".", "curr", "\n", "}", "\n", "if", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "IP", ".", "To16", "(", ")", "!=", "nil", "&&", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "IP", ".", "To4", "(", ")", "==", "nil", "{", "c", ".", "curr", "=", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "lastIPv6Int", "(", ")", "\n", "c", ".", "end", "=", "c", ".", "curr", "\n", "}", "\n", "c", ".", "start", "=", "ipToIPv6Int", "(", "c", ".", "ps", "[", "c", ".", "pi", "]", ".", "IP", ".", "To16", "(", ")", ")", "\n", "}", "else", "{", "c", ".", "curr", ".", "decr", "(", ")", "\n", "}", "\n", "return", "c", ".", "Pos", "(", ")", "\n", "}" ]
// Prev turns to the previous position on c. // It returns nil at the start on c.
[ "Prev", "turns", "to", "the", "previous", "position", "on", "c", ".", "It", "returns", "nil", "at", "the", "start", "on", "c", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/cursor.go#L77-L97
12,395
mikioh/ipaddr
cursor.go
Reset
func (c *Cursor) Reset(ps []Prefix) { ps = newSortedPrefixes(ps, sortAscending, false) if len(ps) > 0 { c.ps = ps } c.set(0, c.ps[0].IP.To16()) }
go
func (c *Cursor) Reset(ps []Prefix) { ps = newSortedPrefixes(ps, sortAscending, false) if len(ps) > 0 { c.ps = ps } c.set(0, c.ps[0].IP.To16()) }
[ "func", "(", "c", "*", "Cursor", ")", "Reset", "(", "ps", "[", "]", "Prefix", ")", "{", "ps", "=", "newSortedPrefixes", "(", "ps", ",", "sortAscending", ",", "false", ")", "\n", "if", "len", "(", "ps", ")", ">", "0", "{", "c", ".", "ps", "=", "ps", "\n", "}", "\n", "c", ".", "set", "(", "0", ",", "c", ".", "ps", "[", "0", "]", ".", "IP", ".", "To16", "(", ")", ")", "\n", "}" ]
// Reset resets all state and switches to ps. // It uses the existing prefixes when ps is nil.
[ "Reset", "resets", "all", "state", "and", "switches", "to", "ps", ".", "It", "uses", "the", "existing", "prefixes", "when", "ps", "is", "nil", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/cursor.go#L101-L107
12,396
mikioh/ipaddr
cursor.go
Set
func (c *Cursor) Set(pos *Position) error { if pos == nil { return errors.New("invalid position") } pi := -1 for i, p := range c.ps { if p.Equal(&pos.Prefix) { pi = i break } } if pi == -1 || !c.ps[pi].IPNet.Contains(pos.IP) { return errors.New("position out of range") } c.set(pi, pos.IP.To16()) return nil }
go
func (c *Cursor) Set(pos *Position) error { if pos == nil { return errors.New("invalid position") } pi := -1 for i, p := range c.ps { if p.Equal(&pos.Prefix) { pi = i break } } if pi == -1 || !c.ps[pi].IPNet.Contains(pos.IP) { return errors.New("position out of range") } c.set(pi, pos.IP.To16()) return nil }
[ "func", "(", "c", "*", "Cursor", ")", "Set", "(", "pos", "*", "Position", ")", "error", "{", "if", "pos", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "pi", ":=", "-", "1", "\n", "for", "i", ",", "p", ":=", "range", "c", ".", "ps", "{", "if", "p", ".", "Equal", "(", "&", "pos", ".", "Prefix", ")", "{", "pi", "=", "i", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "pi", "==", "-", "1", "||", "!", "c", ".", "ps", "[", "pi", "]", ".", "IPNet", ".", "Contains", "(", "pos", ".", "IP", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "set", "(", "pi", ",", "pos", ".", "IP", ".", "To16", "(", ")", ")", "\n", "return", "nil", "\n", "}" ]
// Set sets the current position on c to pos.
[ "Set", "sets", "the", "current", "position", "on", "c", "to", "pos", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/cursor.go#L110-L126
12,397
mikioh/ipaddr
cursor.go
NewCursor
func NewCursor(ps []Prefix) *Cursor { ps = newSortedPrefixes(ps, sortAscending, false) if len(ps) == 0 { return nil } c := &Cursor{ps: ps} c.set(0, c.ps[0].IP.To16()) return c }
go
func NewCursor(ps []Prefix) *Cursor { ps = newSortedPrefixes(ps, sortAscending, false) if len(ps) == 0 { return nil } c := &Cursor{ps: ps} c.set(0, c.ps[0].IP.To16()) return c }
[ "func", "NewCursor", "(", "ps", "[", "]", "Prefix", ")", "*", "Cursor", "{", "ps", "=", "newSortedPrefixes", "(", "ps", ",", "sortAscending", ",", "false", ")", "\n", "if", "len", "(", "ps", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "c", ":=", "&", "Cursor", "{", "ps", ":", "ps", "}", "\n", "c", ".", "set", "(", "0", ",", "c", ".", "ps", "[", "0", "]", ".", "IP", ".", "To16", "(", ")", ")", "\n", "return", "c", "\n", "}" ]
// NewCursor returns a new cursor.
[ "NewCursor", "returns", "a", "new", "cursor", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/cursor.go#L129-L137
12,398
mikioh/ipaddr
position.go
IsBroadcast
func (p *Position) IsBroadcast() bool { return !p.IP.IsUnspecified() && !p.IP.IsMulticast() && p.IP.To4() != nil && (p.IP.Equal(net.IPv4bcast) || p.IP.Equal(p.Prefix.Last())) }
go
func (p *Position) IsBroadcast() bool { return !p.IP.IsUnspecified() && !p.IP.IsMulticast() && p.IP.To4() != nil && (p.IP.Equal(net.IPv4bcast) || p.IP.Equal(p.Prefix.Last())) }
[ "func", "(", "p", "*", "Position", ")", "IsBroadcast", "(", ")", "bool", "{", "return", "!", "p", ".", "IP", ".", "IsUnspecified", "(", ")", "&&", "!", "p", ".", "IP", ".", "IsMulticast", "(", ")", "&&", "p", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "&&", "(", "p", ".", "IP", ".", "Equal", "(", "net", ".", "IPv4bcast", ")", "||", "p", ".", "IP", ".", "Equal", "(", "p", ".", "Prefix", ".", "Last", "(", ")", ")", ")", "\n", "}" ]
// IsBroadcast reports whether p is an IPv4 directed or limited // broadcast address.
[ "IsBroadcast", "reports", "whether", "p", "is", "an", "IPv4", "directed", "or", "limited", "broadcast", "address", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/position.go#L17-L19
12,399
mikioh/ipaddr
position.go
IsSubnetRouterAnycast
func (p *Position) IsSubnetRouterAnycast() bool { return !p.IP.IsUnspecified() && !p.IP.IsLoopback() && !p.IP.IsMulticast() && p.IP.To16() != nil && p.IP.To4() == nil && p.IP.Equal(p.Prefix.IP) }
go
func (p *Position) IsSubnetRouterAnycast() bool { return !p.IP.IsUnspecified() && !p.IP.IsLoopback() && !p.IP.IsMulticast() && p.IP.To16() != nil && p.IP.To4() == nil && p.IP.Equal(p.Prefix.IP) }
[ "func", "(", "p", "*", "Position", ")", "IsSubnetRouterAnycast", "(", ")", "bool", "{", "return", "!", "p", ".", "IP", ".", "IsUnspecified", "(", ")", "&&", "!", "p", ".", "IP", ".", "IsLoopback", "(", ")", "&&", "!", "p", ".", "IP", ".", "IsMulticast", "(", ")", "&&", "p", ".", "IP", ".", "To16", "(", ")", "!=", "nil", "&&", "p", ".", "IP", ".", "To4", "(", ")", "==", "nil", "&&", "p", ".", "IP", ".", "Equal", "(", "p", ".", "Prefix", ".", "IP", ")", "\n", "}" ]
// IsSubnetRouterAnycast reports whether p is an IPv6 subnet router // anycast address.
[ "IsSubnetRouterAnycast", "reports", "whether", "p", "is", "an", "IPv6", "subnet", "router", "anycast", "address", "." ]
d465c8ab672111787b24b8f03326449059a4aa33
https://github.com/mikioh/ipaddr/blob/d465c8ab672111787b24b8f03326449059a4aa33/position.go#L23-L25