repo
stringclasses 6
values | id
int64 0
371
| target_function_prompt
stringlengths 258
11.6k
| function_signature
stringlengths 258
11.6k
| focal_code
stringlengths 258
11.6k
| function_name
stringlengths 2
36
| start_line
int64 3
1.61k
| end_line
int64 23
1.64k
| file_path
stringlengths 7
56
| context
stringlengths 3.33k
9.15k
|
|---|---|---|---|---|---|---|---|---|---|
Go-master
| 0
|
func IsSubsequence(s string, t string) bool {
if len(s) > len(t) {
return false
}
if s == t {
return true
}
if len(s) == 0 {
return true
}
sIndex := 0
for tIndex := 0; tIndex < len(t); tIndex++ {
if s[sIndex] == t[tIndex] {
sIndex++
}
if sIndex == len(s) {
return true
}
}
return false
}
|
func IsSubsequence(s string, t string) bool {
if len(s) > len(t) {
return false
}
if s == t {
return true
}
if len(s) == 0 {
return true
}
sIndex := 0
for tIndex := 0; tIndex < len(t); tIndex++ {
if s[sIndex] == t[tIndex] {
sIndex++
}
if sIndex == len(s) {
return true
}
}
return false
}
|
func IsSubsequence(s string, t string) bool {
if len(s) > len(t) {
return false
}
if s == t {
return true
}
if len(s) == 0 {
return true
}
sIndex := 0
for tIndex := 0; tIndex < len(t); tIndex++ {
if s[sIndex] == t[tIndex] {
sIndex++
}
if sIndex == len(s) {
return true
}
}
return false
}
|
IsSubsequence
| 9
| 34
|
strings/issubsequence.go
|
#FILE: Go-master/structure/trie/trie.go
##CHUNK 1
}
return r
}
// remove lazily a word from the Trie node, no node is actually removed.
func (n *Node) remove(s string) {
if len(s) == 0 {
return
}
next, ok := n, false
for _, c := range s {
next, ok = next.children[c]
if !ok {
// word cannot be found - we're done !
return
}
}
next.isLeaf = false
}
#FILE: Go-master/structure/set/set.go
##CHUNK 1
return false
}
func (st *set[T]) IsSubsetOf(superSet Set[T]) bool {
if st.Len() > superSet.Len() {
return false
}
for _, item := range st.GetItems() {
if !superSet.In(item) {
return false
}
}
return true
}
func (st *set[T]) IsProperSubsetOf(superSet Set[T]) bool {
if st.Len() == superSet.Len() {
return false
}
#FILE: Go-master/strings/ahocorasick/shared.go
##CHUNK 1
stateIsTerminal[current] = true
f[current] = []int{i} // F(Current) <- {i}
}
}
return trie, stateIsTerminal, f
}
// Contains Returns 'true' if array of int's 's' contains int 'e', 'false' otherwise.
func Contains(s []int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
// GetWord Function that returns word found in text 't' at position range 'begin' to 'end'.
func GetWord(begin, end int, t string) string {
for end >= len(t) {
#FILE: Go-master/structure/tree/btree.go
##CHUNK 1
}
}
func (node *BTreeNode[T]) IsFull(maxKeys int) bool {
return node.numKeys == maxKeys
}
func (node *BTreeNode[T]) Search(key T) bool {
i := 0
for ; i < node.numKeys; i++ {
if key == node.keys[i] {
return true
}
if key < node.keys[i] {
break
}
}
if node.isLeaf {
return false
}
##CHUNK 2
if key == node.keys[i] {
return true
}
if key < node.keys[i] {
break
}
}
if node.isLeaf {
return false
}
return node.children[i].Search(key)
}
func (tree *BTree[T]) Search(key T) bool {
if tree.root == nil {
return false
}
return tree.root.Search(key)
}
#FILE: Go-master/project_euler/problem_19/problem19.go
##CHUNK 1
return count
}
func IsLeapYear(year int) bool {
if year%4 == 0 {
if year%100 == 0 {
return year%400 == 0
}
return true
}
return false
}
#FILE: Go-master/graph/dijkstra.go
##CHUNK 1
pq.Update(*item)
}
}
}
for pq.Size() > 0 {
curr := pq.Pop().(Item)
if curr.node == end {
break
}
visit(curr)
}
item := nodes[end]
if item == nil {
return -1, false
}
return item.dist, true
}
#FILE: Go-master/math/prime/primecheck.go
##CHUNK 1
return false
}
// 2 and 3 are prime
if n < 4 {
return true
}
// all numbers divisible by 2 except 2 are not prime
if n%2 == 0 {
return false
}
for i := int64(3); i*i <= n; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
#FILE: Go-master/graph/floydwarshall_test.go
##CHUNK 1
for i := range *a {
if len((*a)[i]) != len(b[i]) {
return false
}
for j := range (*a)[i] {
if (*a)[i][j] == Inf && b[i][j] == Inf {
continue
}
if !almostEqual((*a)[i][j], b[i][j]) {
return false
}
}
}
return true
}
#CURRENT FILE: Go-master/strings/issubsequence.go
|
Go-master
| 1
|
func IsIsogram(text string, order IsogramOrder) (bool, error) {
if order < First || order > Third {
return false, errors.New("Invalid isogram order provided")
}
text = strings.ToLower(text)
text = strings.Join(strings.Fields(text), "")
if hasDigit(text) || hasSymbol(text) {
return false, errors.New("Cannot contain numbers or symbols")
}
letters := make(map[string]int)
for _, c := range text {
l := string(c)
if _, ok := letters[l]; ok {
letters[l] += 1
if letters[l] > 3 {
return false, nil
}
continue
}
letters[l] = 1
}
mapVals := make(map[int]bool)
for _, v := range letters {
mapVals[v] = true
}
if _, ok := mapVals[int(order)]; ok && len(mapVals) == 1 {
return true, nil
}
return false, nil
}
|
func IsIsogram(text string, order IsogramOrder) (bool, error) {
if order < First || order > Third {
return false, errors.New("Invalid isogram order provided")
}
text = strings.ToLower(text)
text = strings.Join(strings.Fields(text), "")
if hasDigit(text) || hasSymbol(text) {
return false, errors.New("Cannot contain numbers or symbols")
}
letters := make(map[string]int)
for _, c := range text {
l := string(c)
if _, ok := letters[l]; ok {
letters[l] += 1
if letters[l] > 3 {
return false, nil
}
continue
}
letters[l] = 1
}
mapVals := make(map[int]bool)
for _, v := range letters {
mapVals[v] = true
}
if _, ok := mapVals[int(order)]; ok && len(mapVals) == 1 {
return true, nil
}
return false, nil
}
|
func IsIsogram(text string, order IsogramOrder) (bool, error) {
if order < First || order > Third {
return false, errors.New("Invalid isogram order provided")
}
text = strings.ToLower(text)
text = strings.Join(strings.Fields(text), "")
if hasDigit(text) || hasSymbol(text) {
return false, errors.New("Cannot contain numbers or symbols")
}
letters := make(map[string]int)
for _, c := range text {
l := string(c)
if _, ok := letters[l]; ok {
letters[l] += 1
if letters[l] > 3 {
return false, nil
}
continue
}
letters[l] = 1
}
mapVals := make(map[int]bool)
for _, v := range letters {
mapVals[v] = true
}
if _, ok := mapVals[int(order)]; ok && len(mapVals) == 1 {
return true, nil
}
return false, nil
}
|
IsIsogram
| 33
| 70
|
strings/isisogram.go
|
#FILE: Go-master/graph/cycle.go
##CHUNK 1
}
}
return allCycles
}
func (g Graph) findAllCyclesHelper(current int, all, visiting, visited map[int]struct{}) (bool, [][]int) {
parents := [][]int{}
delete(all, current)
visiting[current] = struct{}{}
neighbors := g.edges[current]
for v := range neighbors {
if _, ok := visited[v]; ok {
continue
} else if _, ok := visiting[v]; ok {
##CHUNK 2
if g.hasCycleHelper(current, all, visiting, visited) {
return true
}
}
return false
}
func (g Graph) hasCycleHelper(v int, all, visiting, visited map[int]struct{}) bool {
delete(all, v)
visiting[v] = struct{}{}
neighbors := g.edges[v]
for v := range neighbors {
if _, ok := visited[v]; ok {
continue
} else if _, ok := visiting[v]; ok {
return true
} else if g.hasCycleHelper(v, all, visiting, visited) {
##CHUNK 3
delete(all, v)
visiting[v] = struct{}{}
neighbors := g.edges[v]
for v := range neighbors {
if _, ok := visited[v]; ok {
continue
} else if _, ok := visiting[v]; ok {
return true
} else if g.hasCycleHelper(v, all, visiting, visited) {
return true
}
}
delete(visiting, v)
visited[v] = struct{}{}
return false
}
// this function can do HasCycle() job but it is slower
func (g *Graph) FindAllCycles() []Graph {
##CHUNK 4
parents := [][]int{}
delete(all, current)
visiting[current] = struct{}{}
neighbors := g.edges[current]
for v := range neighbors {
if _, ok := visited[v]; ok {
continue
} else if _, ok := visiting[v]; ok {
parents = append(parents, []int{v, current})
return true, parents
} else if ok, savedParents := g.findAllCyclesHelper(v, all, visiting, visited); ok {
parents = append(parents, savedParents...)
parents = append(parents, []int{v, current})
return true, parents
}
}
delete(visiting, current)
visited[current] = struct{}{}
#FILE: Go-master/cipher/transposition/transposition_test.go
##CHUNK 1
return string(b)
}
func TestEncrypt(t *testing.T) {
fn := func(text string, keyWord string) (bool, error) {
encrypt, err := Encrypt([]rune(text), keyWord)
if err != nil && !errors.Is(err, ErrNoTextToEncrypt) && !errors.Is(err, ErrKeyMissing) {
t.Error("Unexpected error ", err)
}
return text == string(encrypt), err
}
for _, s := range texts {
if check, err := fn(s, getRandomString()); check || err != nil {
t.Error("String ", s, " not encrypted")
}
}
if _, err := fn(getRandomString(), ""); err == nil {
t.Error("Error! empty string encryption")
}
}
#FILE: Go-master/math/prime/millerrabintest.go
##CHUNK 1
}
// MillerTestMultiple is like MillerTest but runs the test for multiple
// witnesses.
func MillerTestMultiple(num int64, witnesses ...int64) (bool, error) {
for _, witness := range witnesses {
prime, err := MillerTest(num, witness)
if err != nil {
return false, err
}
if !prime {
return false, nil
}
}
return true, nil
}
// MillerRabinProbabilistic is a probabilistic test for primality
##CHUNK 2
d, _ := formatNum(num)
res, err := modular.Exponentiation(witness, d, num)
if err != nil {
return false, err
}
// miller conditions checks
if res == 1 || res == num-1 {
return true, nil
}
for d != num-1 {
res = (res * res) % num
d *= 2
if res == 1 {
return false, nil
}
if res == num-1 {
return true, nil
}
#FILE: Go-master/strings/isisogram_test.go
##CHUNK 1
{
"Not an isogram",
"Randomstring",
4,
false,
errors.New("Invalid isogram order provided"),
},
{
"Third order isogram checked as first order",
"Deeded",
1,
false,
nil,
},
}
func TestIsIsogram(t *testing.T) {
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
actualVal, actualErr := strings.IsIsogram(test.input, test.order)
#FILE: Go-master/structure/tree/tree_test.go
##CHUNK 1
if _, ok := tree.Min(); ok {
t.Errorf("Error with Min method.")
}
if _, ok := tree.Max(); ok {
t.Errorf("Error with Max method.")
}
tree.Push(nums...)
if min, ok := tree.Min(); !ok || min != nums[0] {
t.Errorf("Error with Min method.")
}
if max, ok := tree.Max(); !ok || max != nums[ll-1] {
t.Errorf("Error with Max method.")
}
}
lens := []int{500, 1_000, 10_000}
for _, ll := range lens {
nums := rand.Perm(ll)
sort.Ints(nums)
#FILE: Go-master/strings/charoccurrence.go
##CHUNK 1
// returns a map with `rune` as keys and the count as value.
func CountChars(text string) map[rune]int {
charMap := make(map[rune]int, 0)
for _, c := range text {
if _, ok := charMap[c]; !ok {
charMap[c] = 0
}
charMap[c]++
}
return charMap
}
#CURRENT FILE: Go-master/strings/isisogram.go
|
Go-master
| 2
|
func GeneticString(target string, charmap []rune, conf *Conf) (*Result, error) {
populationNum := conf.PopulationNum
if populationNum == 0 {
populationNum = 200
}
selectionNum := conf.SelectionNum
if selectionNum == 0 {
selectionNum = 50
}
// Verify if 'populationNum' s bigger than 'selectionNum'
if populationNum < selectionNum {
return nil, errors.New("populationNum must be bigger than selectionNum")
}
mutationProb := conf.MutationProb
if mutationProb == .0 {
mutationProb = .4
}
debug := conf.Debug
// Just a seed to improve randomness required by the algorithm
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
// Verify that the target contains no genes besides the ones inside genes variable.
for position, r := range target {
invalid := true
for _, n := range charmap {
if n == r {
invalid = false
}
}
if invalid {
message := fmt.Sprintf("character not available in charmap at position: %v", position)
return nil, errors.New(message)
}
}
// Generate random starting population
pop := make([]PopulationItem, populationNum)
for i := 0; i < populationNum; i++ {
key := ""
for x := 0; x < utf8.RuneCountInString(target); x++ {
choice := rnd.Intn(len(charmap))
key += string(charmap[choice])
}
pop[i] = PopulationItem{key, 0}
}
// Just some logs to know what the algorithms is doing
gen, generatedPop := 0, 0
// This loop will end when we will find a perfect match for our target
for {
gen++
generatedPop += len(pop)
// Random population created now it's time to evaluate
for i, item := range pop {
pop[i].Value = 0
itemKey, targetRune := []rune(item.Key), []rune(target)
for x := 0; x < len(target); x++ {
if itemKey[x] == targetRune[x] {
pop[i].Value++
}
}
pop[i].Value = pop[i].Value / float64(len(targetRune))
}
sort.SliceStable(pop, func(i, j int) bool { return pop[i].Value > pop[j].Value })
// Check if there is a matching evolution
if pop[0].Key == target {
break
}
// Print the best resultPrint the Best result every 10 generations
// just to know that the algorithm is working
if debug && gen%10 == 0 {
fmt.Println("Generation:", strconv.Itoa(gen), "Analyzed:", generatedPop, "Best:", pop[0])
}
// Generate a new population vector keeping some of the best evolutions
// Keeping this avoid regression of evolution
var popChildren []PopulationItem
popChildren = append(popChildren, pop[0:int(selectionNum/3)]...)
// This is Selection
for i := 0; i < int(selectionNum); i++ {
parent1 := pop[i]
// Generate more child proportionally to the fitness score
nChild := (parent1.Value * 100) + 1
if nChild >= 10 {
nChild = 10
}
for x := 0.0; x < nChild; x++ {
parent2 := pop[rnd.Intn(selectionNum)]
// Crossover
split := rnd.Intn(utf8.RuneCountInString(target))
child1 := append([]rune(parent1.Key)[:split], []rune(parent2.Key)[split:]...)
child2 := append([]rune(parent2.Key)[:split], []rune(parent1.Key)[split:]...)
// Clean fitness value
// Mutate
if rnd.Float64() < mutationProb {
child1[rnd.Intn(len(child1))] = charmap[rnd.Intn(len(charmap))]
}
if rnd.Float64() < mutationProb {
child2[rnd.Intn(len(child2))] = charmap[rnd.Intn(len(charmap))]
}
// Push into 'popChildren'
popChildren = append(popChildren, PopulationItem{string(child1), 0})
popChildren = append(popChildren, PopulationItem{string(child2), 0})
// Check if the population has already reached the maximum value and if so,
// break the cycle. If this check is disabled the algorithm will take
// forever to compute large strings but will also calculate small string in
// a lot fewer generationsù
if len(popChildren) >= selectionNum {
break
}
}
}
pop = popChildren
}
return &Result{gen, generatedPop, pop[0]}, nil
}
|
func GeneticString(target string, charmap []rune, conf *Conf) (*Result, error) {
populationNum := conf.PopulationNum
if populationNum == 0 {
populationNum = 200
}
selectionNum := conf.SelectionNum
if selectionNum == 0 {
selectionNum = 50
}
// Verify if 'populationNum' s bigger than 'selectionNum'
if populationNum < selectionNum {
return nil, errors.New("populationNum must be bigger than selectionNum")
}
mutationProb := conf.MutationProb
if mutationProb == .0 {
mutationProb = .4
}
debug := conf.Debug
// Just a seed to improve randomness required by the algorithm
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
// Verify that the target contains no genes besides the ones inside genes variable.
for position, r := range target {
invalid := true
for _, n := range charmap {
if n == r {
invalid = false
}
}
if invalid {
message := fmt.Sprintf("character not available in charmap at position: %v", position)
return nil, errors.New(message)
}
}
// Generate random starting population
pop := make([]PopulationItem, populationNum)
for i := 0; i < populationNum; i++ {
key := ""
for x := 0; x < utf8.RuneCountInString(target); x++ {
choice := rnd.Intn(len(charmap))
key += string(charmap[choice])
}
pop[i] = PopulationItem{key, 0}
}
// Just some logs to know what the algorithms is doing
gen, generatedPop := 0, 0
// This loop will end when we will find a perfect match for our target
for {
gen++
generatedPop += len(pop)
// Random population created now it's time to evaluate
for i, item := range pop {
pop[i].Value = 0
itemKey, targetRune := []rune(item.Key), []rune(target)
for x := 0; x < len(target); x++ {
if itemKey[x] == targetRune[x] {
pop[i].Value++
}
}
pop[i].Value = pop[i].Value / float64(len(targetRune))
}
sort.SliceStable(pop, func(i, j int) bool { return pop[i].Value > pop[j].Value })
// Check if there is a matching evolution
if pop[0].Key == target {
break
}
// Print the best resultPrint the Best result every 10 generations
// just to know that the algorithm is working
if debug && gen%10 == 0 {
fmt.Println("Generation:", strconv.Itoa(gen), "Analyzed:", generatedPop, "Best:", pop[0])
}
// Generate a new population vector keeping some of the best evolutions
// Keeping this avoid regression of evolution
var popChildren []PopulationItem
popChildren = append(popChildren, pop[0:int(selectionNum/3)]...)
// This is Selection
for i := 0; i < int(selectionNum); i++ {
parent1 := pop[i]
// Generate more child proportionally to the fitness score
nChild := (parent1.Value * 100) + 1
if nChild >= 10 {
nChild = 10
}
for x := 0.0; x < nChild; x++ {
parent2 := pop[rnd.Intn(selectionNum)]
// Crossover
split := rnd.Intn(utf8.RuneCountInString(target))
child1 := append([]rune(parent1.Key)[:split], []rune(parent2.Key)[split:]...)
child2 := append([]rune(parent2.Key)[:split], []rune(parent1.Key)[split:]...)
// Clean fitness value
// Mutate
if rnd.Float64() < mutationProb {
child1[rnd.Intn(len(child1))] = charmap[rnd.Intn(len(charmap))]
}
if rnd.Float64() < mutationProb {
child2[rnd.Intn(len(child2))] = charmap[rnd.Intn(len(charmap))]
}
// Push into 'popChildren'
popChildren = append(popChildren, PopulationItem{string(child1), 0})
popChildren = append(popChildren, PopulationItem{string(child2), 0})
// Check if the population has already reached the maximum value and if so,
// break the cycle. If this check is disabled the algorithm will take
// forever to compute large strings but will also calculate small string in
// a lot fewer generationsù
if len(popChildren) >= selectionNum {
break
}
}
}
pop = popChildren
}
return &Result{gen, generatedPop, pop[0]}, nil
}
|
func GeneticString(target string, charmap []rune, conf *Conf) (*Result, error) {
populationNum := conf.PopulationNum
if populationNum == 0 {
populationNum = 200
}
selectionNum := conf.SelectionNum
if selectionNum == 0 {
selectionNum = 50
}
// Verify if 'populationNum' s bigger than 'selectionNum'
if populationNum < selectionNum {
return nil, errors.New("populationNum must be bigger than selectionNum")
}
mutationProb := conf.MutationProb
if mutationProb == .0 {
mutationProb = .4
}
debug := conf.Debug
// Just a seed to improve randomness required by the algorithm
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
// Verify that the target contains no genes besides the ones inside genes variable.
for position, r := range target {
invalid := true
for _, n := range charmap {
if n == r {
invalid = false
}
}
if invalid {
message := fmt.Sprintf("character not available in charmap at position: %v", position)
return nil, errors.New(message)
}
}
// Generate random starting population
pop := make([]PopulationItem, populationNum)
for i := 0; i < populationNum; i++ {
key := ""
for x := 0; x < utf8.RuneCountInString(target); x++ {
choice := rnd.Intn(len(charmap))
key += string(charmap[choice])
}
pop[i] = PopulationItem{key, 0}
}
// Just some logs to know what the algorithms is doing
gen, generatedPop := 0, 0
// This loop will end when we will find a perfect match for our target
for {
gen++
generatedPop += len(pop)
// Random population created now it's time to evaluate
for i, item := range pop {
pop[i].Value = 0
itemKey, targetRune := []rune(item.Key), []rune(target)
for x := 0; x < len(target); x++ {
if itemKey[x] == targetRune[x] {
pop[i].Value++
}
}
pop[i].Value = pop[i].Value / float64(len(targetRune))
}
sort.SliceStable(pop, func(i, j int) bool { return pop[i].Value > pop[j].Value })
// Check if there is a matching evolution
if pop[0].Key == target {
break
}
// Print the best resultPrint the Best result every 10 generations
// just to know that the algorithm is working
if debug && gen%10 == 0 {
fmt.Println("Generation:", strconv.Itoa(gen), "Analyzed:", generatedPop, "Best:", pop[0])
}
// Generate a new population vector keeping some of the best evolutions
// Keeping this avoid regression of evolution
var popChildren []PopulationItem
popChildren = append(popChildren, pop[0:int(selectionNum/3)]...)
// This is Selection
for i := 0; i < int(selectionNum); i++ {
parent1 := pop[i]
// Generate more child proportionally to the fitness score
nChild := (parent1.Value * 100) + 1
if nChild >= 10 {
nChild = 10
}
for x := 0.0; x < nChild; x++ {
parent2 := pop[rnd.Intn(selectionNum)]
// Crossover
split := rnd.Intn(utf8.RuneCountInString(target))
child1 := append([]rune(parent1.Key)[:split], []rune(parent2.Key)[split:]...)
child2 := append([]rune(parent2.Key)[:split], []rune(parent1.Key)[split:]...)
// Clean fitness value
// Mutate
if rnd.Float64() < mutationProb {
child1[rnd.Intn(len(child1))] = charmap[rnd.Intn(len(charmap))]
}
if rnd.Float64() < mutationProb {
child2[rnd.Intn(len(child2))] = charmap[rnd.Intn(len(charmap))]
}
// Push into 'popChildren'
popChildren = append(popChildren, PopulationItem{string(child1), 0})
popChildren = append(popChildren, PopulationItem{string(child2), 0})
// Check if the population has already reached the maximum value and if so,
// break the cycle. If this check is disabled the algorithm will take
// forever to compute large strings but will also calculate small string in
// a lot fewer generationsù
if len(popChildren) >= selectionNum {
break
}
}
}
pop = popChildren
}
return &Result{gen, generatedPop, pop[0]}, nil
}
|
GeneticString
| 70
| 196
|
strings/genetic/genetic.go
|
#FILE: Go-master/math/pi/montecarlopi.go
##CHUNK 1
}
// splitInt takes an integer x and splits it within an integer slice of length n in the most uniform
// way possible.
// For example, splitInt(10, 3) will return []int{4, 3, 3}, nil
func splitInt(x int, n int) ([]int, error) {
if x < n {
return nil, fmt.Errorf("x must be < n - given values are x=%d, n=%d", x, n)
}
split := make([]int, n)
if x%n == 0 {
for i := 0; i < n; i++ {
split[i] = x / n
}
} else {
limit := x % n
for i := 0; i < limit; i++ {
split[i] = x/n + 1
}
for i := limit; i < n; i++ {
##CHUNK 2
func drawPoints(n int, c chan<- int) {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
inside := 0
for i := 0; i < n; i++ {
x, y := rnd.Float64(), rnd.Float64()
if x*x+y*y <= 1 {
inside++
}
}
c <- inside
}
// splitInt takes an integer x and splits it within an integer slice of length n in the most uniform
// way possible.
// For example, splitInt(10, 3) will return []int{4, 3, 3}, nil
func splitInt(x int, n int) ([]int, error) {
if x < n {
return nil, fmt.Errorf("x must be < n - given values are x=%d, n=%d", x, n)
}
split := make([]int, n)
##CHUNK 3
import (
"fmt" // Used for error formatting
"math/rand" // Used for random number generation in Monte Carlo method
"runtime" // Used to get information on available CPUs
"time" // Used for seeding the random number generation
)
func MonteCarloPi(randomPoints int) float64 {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
inside := 0
for i := 0; i < randomPoints; i++ {
x := rnd.Float64()
y := rnd.Float64()
if x*x+y*y <= 1 {
inside += 1
}
}
pi := float64(inside) / float64(randomPoints) * 4
return pi
##CHUNK 4
inside := 0
for i := 0; i < randomPoints; i++ {
x := rnd.Float64()
y := rnd.Float64()
if x*x+y*y <= 1 {
inside += 1
}
}
pi := float64(inside) / float64(randomPoints) * 4
return pi
}
// MonteCarloPiConcurrent approximates the value of pi using the Monte Carlo method.
// Unlike the MonteCarloPi function (first version), this implementation uses
// goroutines and channels to parallelize the computation.
// More details on the Monte Carlo method available at https://en.wikipedia.org/wiki/Monte_Carlo_method.
// More details on goroutines parallelization available at https://go.dev/doc/effective_go#parallel.
func MonteCarloPiConcurrent(n int) (float64, error) {
numCPU := runtime.GOMAXPROCS(0)
c := make(chan int, numCPU)
#FILE: Go-master/sort/countingsort.go
##CHUNK 1
import "github.com/TheAlgorithms/Go/constraints"
func Count[T constraints.Integer](data []T) []T {
if len(data) == 0 {
return data
}
var aMin, aMax = data[0], data[0]
for _, x := range data {
if x < aMin {
aMin = x
}
if x > aMax {
aMax = x
}
}
count := make([]int, aMax-aMin+1)
for _, x := range data {
count[x-aMin]++ // this is the reason for having only Integer constraint instead of Ordered.
}
#FILE: Go-master/strings/search/boyermoore.go
##CHUNK 1
// using booyer moore horspool modification
// O(n) space instead of O(n**2)
bcr := make(map[byte]int)
for i := 0; i < n-1; i++ {
bcr[pattern[i]] = n - i - 1
}
// Apostolico–Giancarlo modification
// allow to skip patterns that we know matches
// let us do O(l) instead of O(ln)
skips := make(map[int]int)
for _, s := range bcr {
i := 0
for ; i < n-s; i++ {
if pattern[n-1-i] != pattern[n-1-s-i] {
break
}
}
skips[s] = i
}
#FILE: Go-master/graph/floydwarshall.go
##CHUNK 1
// Running over the result matrix and following the algorithm
for k := 0; k < numVertices; k++ {
for i := 0; i < numVertices; i++ {
for j := 0; j < numVertices; j++ {
// If there is a less costly path from i to j node, remembering it
if result[i][j] > result[i][k]+result[k][j] {
result[i][j] = result[i][k] + result[k][j]
}
}
}
}
return result
}
#FILE: Go-master/cipher/railfence/railfence.go
##CHUNK 1
for _, char := range line {
if char != 0 {
result.WriteRune(char)
}
}
}
return result.String()
}
func Decrypt(cipherText string, rails int) string {
if rails == 1 || rails >= len(cipherText) {
return cipherText
}
// Placeholder for the decrypted message
decrypted := make([]rune, len(cipherText))
// Calculate the zigzag pattern and place characters accordingly
index := 0
for rail := 0; rail < rails; rail++ {
#FILE: Go-master/structure/tree/btree.go
##CHUNK 1
return node.children[node.numKeys].Max()
}
func (node *BTreeNode[T]) Delete(tree *BTree[T], key T) {
node.Verify(tree)
if node.isLeaf {
// Case 1: Node is a leaf. Directly delete the key.
for i := 0; i < node.numKeys; i++ {
if key == node.keys[i] {
node.DeleteIthKey(i)
return
}
}
return
}
minKeys := minKeys(tree.maxKeys)
i := 0
for ; i < node.numKeys; i++ {
if key == node.keys[i] {
#FILE: Go-master/graph/edmondkarp.go
##CHUNK 1
parent := make(map[int]int)
// BFS loop with saving the path found
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(rGraph[v]); i++ {
if !marked[i] && rGraph[v][i] > 0 {
parent[i] = v
// Terminate the BFS, if we reach to sink
if i == sink {
return parent
}
marked[i] = true
queue = append(queue, i)
}
}
}
// source and sink are not in the same connected component
return nil
#CURRENT FILE: Go-master/strings/genetic/genetic.go
|
Go-master
| 3
|
func Distance(str1, str2 string, icost, scost, dcost int) int {
row1 := make([]int, len(str2)+1)
row2 := make([]int, len(str2)+1)
for i := 1; i <= len(str2); i++ {
row1[i] = i * icost
}
for i := 1; i <= len(str1); i++ {
row2[0] = i * dcost
for j := 1; j <= len(str2); j++ {
if str1[i-1] == str2[j-1] {
row2[j] = row1[j-1]
} else {
ins := row2[j-1] + icost
del := row1[j] + dcost
sub := row1[j-1] + scost
if ins < del && ins < sub {
row2[j] = ins
} else if del < sub {
row2[j] = del
} else {
row2[j] = sub
}
}
}
row1, row2 = row2, row1
}
return row1[len(row1)-1]
}
|
func Distance(str1, str2 string, icost, scost, dcost int) int {
row1 := make([]int, len(str2)+1)
row2 := make([]int, len(str2)+1)
for i := 1; i <= len(str2); i++ {
row1[i] = i * icost
}
for i := 1; i <= len(str1); i++ {
row2[0] = i * dcost
for j := 1; j <= len(str2); j++ {
if str1[i-1] == str2[j-1] {
row2[j] = row1[j-1]
} else {
ins := row2[j-1] + icost
del := row1[j] + dcost
sub := row1[j-1] + scost
if ins < del && ins < sub {
row2[j] = ins
} else if del < sub {
row2[j] = del
} else {
row2[j] = sub
}
}
}
row1, row2 = row2, row1
}
return row1[len(row1)-1]
}
|
func Distance(str1, str2 string, icost, scost, dcost int) int {
row1 := make([]int, len(str2)+1)
row2 := make([]int, len(str2)+1)
for i := 1; i <= len(str2); i++ {
row1[i] = i * icost
}
for i := 1; i <= len(str1); i++ {
row2[0] = i * dcost
for j := 1; j <= len(str2); j++ {
if str1[i-1] == str2[j-1] {
row2[j] = row1[j-1]
} else {
ins := row2[j-1] + icost
del := row1[j] + dcost
sub := row1[j-1] + scost
if ins < del && ins < sub {
row2[j] = ins
} else if del < sub {
row2[j] = del
} else {
row2[j] = sub
}
}
}
row1, row2 = row2, row1
}
return row1[len(row1)-1]
}
|
Distance
| 9
| 41
|
strings/levenshtein/levenshteindistance.go
|
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
##CHUNK 2
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
return dp[m][sum]
}
#FILE: Go-master/dynamic/wildcardmatching.go
##CHUNK 1
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
##CHUNK 2
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
}
return dp[len(s)][len(p)]
}
#FILE: Go-master/dynamic/interleavingstrings.go
##CHUNK 1
if len(s1)+len(s2) != len(s3) {
return false
}
dp := make([][]bool, len(s1)+1)
for i := range dp {
dp[i] = make([]bool, len(s2)+1)
}
dp[0][0] = true
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
##CHUNK 2
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1])
}
}
return dp[len(s1)][len(s2)]
}
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
#FILE: Go-master/dynamic/uniquepaths.go
##CHUNK 1
}
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
for i := 0; i < m; i++ {
grid[i][0] = 1
}
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}
#FILE: Go-master/dynamic/longestcommonsubsequence.go
##CHUNK 1
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i := 0; i <= aLen; i++ {
for j := 0; j <= bLen; j++ {
if i == 0 || j == 0 {
lcs[i][j] = 0
} else if aRunes[i-1] == bRunes[j-1] {
lcs[i][j] = lcs[i-1][j-1] + 1
} else {
lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])
}
}
}
// returning the length of longest common subsequence
return lcs[aLen][bLen]
}
#FILE: Go-master/dynamic/binomialcoefficient.go
##CHUNK 1
// }
// }
// Bin2 function
func Bin2(n int, k int) int {
var i, j int
B := make([][]int, (n + 1))
for i := range B {
B[i] = make([]int, k+1)
}
for i = 0; i <= n; i++ {
for j = 0; j <= min.Int(i, k); j++ {
if j == 0 || j == i {
B[i][j] = 1
} else {
B[i][j] = B[i-1][j-1] + B[i-1][j]
}
}
#CURRENT FILE: Go-master/strings/levenshtein/levenshteindistance.go
|
Go-master
| 4
|
func LongestPalindrome(s string) string {
boundaries := makeBoundaries(s)
b := make([]int, len(boundaries))
k := 0
index := 0
maxLen := 0
maxCenterSize := 0
for i := range b {
if i < k {
b[i] = min.Int(b[2*index-i], k-i)
} else {
b[i] = 1
}
for i-b[i] >= 0 && i+b[i] < len(boundaries) && boundaries[i-b[i]] == boundaries[i+b[i]] {
b[i] += 1
}
if maxLen < b[i]-1 {
maxLen = b[i] - 1
maxCenterSize = i
}
if b[i]+i-1 > k {
k = b[i] + i - 1
index = i
}
}
return nextBoundary(boundaries[maxCenterSize-maxLen : maxCenterSize+maxLen])
}
|
func LongestPalindrome(s string) string {
boundaries := makeBoundaries(s)
b := make([]int, len(boundaries))
k := 0
index := 0
maxLen := 0
maxCenterSize := 0
for i := range b {
if i < k {
b[i] = min.Int(b[2*index-i], k-i)
} else {
b[i] = 1
}
for i-b[i] >= 0 && i+b[i] < len(boundaries) && boundaries[i-b[i]] == boundaries[i+b[i]] {
b[i] += 1
}
if maxLen < b[i]-1 {
maxLen = b[i] - 1
maxCenterSize = i
}
if b[i]+i-1 > k {
k = b[i] + i - 1
index = i
}
}
return nextBoundary(boundaries[maxCenterSize-maxLen : maxCenterSize+maxLen])
}
|
func LongestPalindrome(s string) string {
boundaries := makeBoundaries(s)
b := make([]int, len(boundaries))
k := 0
index := 0
maxLen := 0
maxCenterSize := 0
for i := range b {
if i < k {
b[i] = min.Int(b[2*index-i], k-i)
} else {
b[i] = 1
}
for i-b[i] >= 0 && i+b[i] < len(boundaries) && boundaries[i-b[i]] == boundaries[i+b[i]] {
b[i] += 1
}
if maxLen < b[i]-1 {
maxLen = b[i] - 1
maxCenterSize = i
}
if b[i]+i-1 > k {
k = b[i] + i - 1
index = i
}
}
return nextBoundary(boundaries[maxCenterSize-maxLen : maxCenterSize+maxLen])
}
|
LongestPalindrome
| 36
| 62
|
strings/manacher/longestpalindrome.go
|
#FILE: Go-master/strings/search/boyermoore.go
##CHUNK 1
skip := 0
jump := n
for i := 0; i < l-n+1; {
skip = skips[jump]
for k := n - 1; k > -1; k-- {
if text[i+k] != pattern[k] {
jump, ok := bcr[text[i+k]]
if !ok {
jump = n
}
i += jump
break
}
if k == n-jump {
k -= skip
}
if k == 0 {
positions = append(positions, i)
jump = 1
##CHUNK 2
skips := make(map[int]int)
for _, s := range bcr {
i := 0
for ; i < n-s; i++ {
if pattern[n-1-i] != pattern[n-1-s-i] {
break
}
}
skips[s] = i
}
skip := 0
jump := n
for i := 0; i < l-n+1; {
skip = skips[jump]
for k := n - 1; k > -1; k-- {
if text[i+k] != pattern[k] {
jump, ok := bcr[text[i+k]]
if !ok {
jump = n
#FILE: Go-master/math/binomialcoefficient.go
##CHUNK 1
// This function returns C(n, k) for given n and k
func Combinations(n int, k int) (int, error) {
if n < 0 || k < 0 {
return -1, ErrPosArgsOnly
}
if k > (n - k) {
k = n - k
}
res := 1
for i := 0; i < k; i++ {
res *= (n - i)
res /= (i + 1)
}
return res, nil
}
##CHUNK 2
package math
import (
"errors"
)
var ErrPosArgsOnly error = errors.New("arguments must be positive")
// C is Binomial Coefficient function
// This function returns C(n, k) for given n and k
func Combinations(n int, k int) (int, error) {
if n < 0 || k < 0 {
return -1, ErrPosArgsOnly
}
if k > (n - k) {
k = n - k
}
res := 1
for i := 0; i < k; i++ {
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/matrixmultiplication.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
prod := dp[i][k] + dp[k+1][j] + D[i-1]*D[k]*D[j]
dp[i][j] = min.Int(prod, dp[i][j])
}
}
}
return dp[1][N-1]
}
/*
##CHUNK 2
}
return q
}
// MatrixChainDp function
func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
#FILE: Go-master/math/kthnumber.go
##CHUNK 1
return kthNumber(nums, index)
}
// kthNumber use the selection algorithm (based on the partition method - the same one as used in quicksort).
func kthNumber(nums []int, k int) (int, error) {
if k < 0 || k >= len(nums) {
return -1, search.ErrNotFound
}
start := 0
end := len(nums) - 1
for start <= end {
pivot := sort.Partition(nums, start, end)
if k == pivot {
return nums[pivot], nil
}
if k > pivot {
start = pivot + 1
continue
}
end = pivot - 1
#FILE: Go-master/dynamic/optimalbst.go
##CHUNK 1
j := i + length - 1
dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value
sum := sum(freq, i, j)
// Try every key as root and compute cost
for k := i; k <= j; k++ {
// Left cost: dp[i][k-1] is valid only if k > i
var leftCost int
if k > i {
leftCost = dp[i][k-1]
} else {
leftCost = 0
}
// Right cost: dp[k+1][j] is valid only if k < j
var rightCost int
if k < j {
rightCost = dp[k+1][j]
} else {
rightCost = 0
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
#CURRENT FILE: Go-master/strings/manacher/longestpalindrome.go
|
Go-master
| 5
|
func horspool(t, p []rune) (int, error) {
shiftMap := computeShiftMap(t, p)
pos := 0
for pos <= len(t)-len(p) {
if isMatch(pos, t, p) {
return pos, nil
}
if pos+len(p) >= len(t) {
// because the remaining length of the input string
// is the same as the length of the pattern
// and it does not match the pattern
// it is impossible to find the pattern
break
}
// because of the check above
// t[pos+len(p)] is defined
pos += shiftMap[t[pos+len(p)]]
}
return -1, ErrNotFound
}
|
func horspool(t, p []rune) (int, error) {
shiftMap := computeShiftMap(t, p)
pos := 0
for pos <= len(t)-len(p) {
if isMatch(pos, t, p) {
return pos, nil
}
if pos+len(p) >= len(t) {
// because the remaining length of the input string
// is the same as the length of the pattern
// and it does not match the pattern
// it is impossible to find the pattern
break
}
// because of the check above
// t[pos+len(p)] is defined
pos += shiftMap[t[pos+len(p)]]
}
return -1, ErrNotFound
}
|
func horspool(t, p []rune) (int, error) {
shiftMap := computeShiftMap(t, p)
pos := 0
for pos <= len(t)-len(p) {
if isMatch(pos, t, p) {
return pos, nil
}
if pos+len(p) >= len(t) {
// because the remaining length of the input string
// is the same as the length of the pattern
// and it does not match the pattern
// it is impossible to find the pattern
break
}
// because of the check above
// t[pos+len(p)] is defined
pos += shiftMap[t[pos+len(p)]]
}
return -1, ErrNotFound
}
|
horspool
| 15
| 36
|
strings/horspool/horspool.go
|
#FILE: Go-master/strings/bom/bom.go
##CHUNK 1
// currentOcc := 0
// pos = 0
// if debugMode == true {
// fmt.Printf("\n\nWe are reading backwards in %q, searching for %q\n\nat position %d:\n", t, p, pos+m-1)
// }
// for pos <= n-m {
// current = 0 //initial state of the oracle
// j = m
// for j > 0 && stateExists(current, oracle) {
// if debugMode == true {
// prettyPrint(current, j, n, pos, t, oracle)
// }
// current = getTransition(current, t[pos+j-1], oracle)
// j--
// }
// if stateExists(current, oracle) {
// if debugMode == true {
// fmt.Printf(" We got an occurrence!")
// }
// occurrences[currentOcc] = pos
##CHUNK 2
// prettyPrint(current, j, n, pos, t, oracle)
// }
// current = getTransition(current, t[pos+j-1], oracle)
// j--
// }
// if stateExists(current, oracle) {
// if debugMode == true {
// fmt.Printf(" We got an occurrence!")
// }
// occurrences[currentOcc] = pos
// currentOcc++
// }
// pos = pos + j + 1
// if pos+m-1 < len(t) {
// if debugMode == true {
// fmt.Printf("\n\nposition %d:\n", pos+m-1)
// }
// }
// }
// elapsed := time.Since(startTime)
##CHUNK 3
// // Function bom performing the Backward Oracle Matching algorithm.
// // Prints whether the word/pattern was found + positions of possible multiple occurrences
// // or that the word was not found.
// func bom(t, p string) {
// startTime := time.Now()
// n, m := len(t), len(p)
// var current, j, pos int
// oracle := oracleOnLine(reverse(p))
// occurrences := make([]int, len(t))
// currentOcc := 0
// pos = 0
// if debugMode == true {
// fmt.Printf("\n\nWe are reading backwards in %q, searching for %q\n\nat position %d:\n", t, p, pos+m-1)
// }
// for pos <= n-m {
// current = 0 //initial state of the oracle
// j = m
// for j > 0 && stateExists(current, oracle) {
// if debugMode == true {
#FILE: Go-master/structure/queue/queuelinklistwithlist.go
##CHUNK 1
// Back it will return the back value
func (lq *LQueue) Back() (any, error) {
if !lq.Empty() {
val := lq.queue.Back().Value
return val, nil
}
return "", fmt.Errorf("error queue is empty")
}
// Len it will return the length of list
func (lq *LQueue) Len() int {
return lq.queue.Len()
}
// Empty is check our list is empty or not
func (lq *LQueue) Empty() bool {
return lq.queue.Len() == 0
}
#FILE: Go-master/search/jump.go
##CHUNK 1
package search
import "math"
// Jump search works by jumping multiple steps ahead in sorted list until it find an item larger than target,
// then create a sublist of item from the last searched item up to the current item and perform a linear search.
func Jump(array []int, target int) (int, error) {
n := len(array)
if n == 0 {
return -1, ErrNotFound
}
// the optimal value of step is square root of the length of list
step := int(math.Round(math.Sqrt(float64(n))))
prev := 0 // previous index
curr := step // current index
for array[curr-1] < target {
prev = curr
if prev >= len(array) {
##CHUNK 2
}
// the optimal value of step is square root of the length of list
step := int(math.Round(math.Sqrt(float64(n))))
prev := 0 // previous index
curr := step // current index
for array[curr-1] < target {
prev = curr
if prev >= len(array) {
return -1, ErrNotFound
}
curr += step
// prevent jumping over list range
if curr > n {
curr = n
}
}
#FILE: Go-master/sort/cyclesort.go
##CHUNK 1
counter, cycle, len := 0, 0, len(arr)
// Early return if the array too small
if len <= 1 {
return arr
}
for cycle = 0; cycle < len-1; cycle++ {
elem := arr[cycle]
// Find total smaller elements to right
pos := cycle
for counter = cycle + 1; counter < len; counter++ {
if arr[counter] < elem {
pos++
}
}
// In case this element is already in correct position, let's skip processing
if pos == cycle {
continue
}
// In case we have same elements, we want to skip to the end of that list as well, ignoring order
#FILE: Go-master/structure/queue/queuelinkedlist.go
##CHUNK 1
if ll.head == nil {
ll.tail = nil
}
ll.length--
return data
}
// isEmpty it will check our list is empty or not
func (ll *Queue) isEmpty() bool {
return ll.length == 0
}
// len is return the length of queue
func (ll *Queue) len() int {
return ll.length
}
// frontQueue it will return the front data
func (ll *Queue) frontQueue() any {
#FILE: Go-master/strings/search/naive.go
##CHUNK 1
package search
// Implementation of naive string search
// O(n*m) where n=len(txt) and m=len(pattern)
func Naive(text string, pattern string) []int {
var positions []int
for i := 0; i <= len(text)-len(pattern); i++ {
var match bool = true
for j := 0; j < len(pattern); j++ {
if text[i+j] != pattern[j] {
match = false
break
}
}
if match {
positions = append(positions, i)
}
}
return positions
#CURRENT FILE: Go-master/strings/horspool/horspool.go
##CHUNK 1
// in order to handle multy-byte character properly
// the input is converted into rune arrays
return horspool([]rune(t), []rune(p))
}
}
// Checks if the array p matches the subarray of t starting at pos.
// Note that backward iteration.
// There are [other](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm#Tuning_the_comparison_loop)
// approaches possible.
func isMatch(pos int, t, p []rune) bool {
j := len(p)
for j > 0 && t[pos+j-1] == p[j-1] {
j--
}
return j == 0
}
func computeShiftMap(t, p []rune) (res map[rune]int) {
res = make(map[rune]int)
|
Go-master
| 6
|
func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) {
trie = make(map[int]map[uint8]int)
stateIsTerminal = make([]bool, 1)
f = make(map[int][]int)
state := 1
CreateNewState(0, trie)
for i := 0; i < len(p); i++ {
current := 0
j := 0
for j < len(p[i]) && GetTransition(current, p[i][j], trie) != -1 {
current = GetTransition(current, p[i][j], trie)
j++
}
for j < len(p[i]) {
stateIsTerminal = BoolArrayCapUp(stateIsTerminal)
CreateNewState(state, trie)
stateIsTerminal[state] = false
CreateTransition(current, p[i][j], state, trie)
current = state
j++
state++
}
if stateIsTerminal[current] {
newArray := IntArrayCapUp(f[current])
newArray[len(newArray)-1] = i
f[current] = newArray // F(Current) <- F(Current) union {i}
} else {
stateIsTerminal[current] = true
f[current] = []int{i} // F(Current) <- {i}
}
}
return trie, stateIsTerminal, f
}
|
func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) {
trie = make(map[int]map[uint8]int)
stateIsTerminal = make([]bool, 1)
f = make(map[int][]int)
state := 1
CreateNewState(0, trie)
for i := 0; i < len(p); i++ {
current := 0
j := 0
for j < len(p[i]) && GetTransition(current, p[i][j], trie) != -1 {
current = GetTransition(current, p[i][j], trie)
j++
}
for j < len(p[i]) {
stateIsTerminal = BoolArrayCapUp(stateIsTerminal)
CreateNewState(state, trie)
stateIsTerminal[state] = false
CreateTransition(current, p[i][j], state, trie)
current = state
j++
state++
}
if stateIsTerminal[current] {
newArray := IntArrayCapUp(f[current])
newArray[len(newArray)-1] = i
f[current] = newArray // F(Current) <- F(Current) union {i}
} else {
stateIsTerminal[current] = true
f[current] = []int{i} // F(Current) <- {i}
}
}
return trie, stateIsTerminal, f
}
|
func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) {
trie = make(map[int]map[uint8]int)
stateIsTerminal = make([]bool, 1)
f = make(map[int][]int)
state := 1
CreateNewState(0, trie)
for i := 0; i < len(p); i++ {
current := 0
j := 0
for j < len(p[i]) && GetTransition(current, p[i][j], trie) != -1 {
current = GetTransition(current, p[i][j], trie)
j++
}
for j < len(p[i]) {
stateIsTerminal = BoolArrayCapUp(stateIsTerminal)
CreateNewState(state, trie)
stateIsTerminal[state] = false
CreateTransition(current, p[i][j], state, trie)
current = state
j++
state++
}
if stateIsTerminal[current] {
newArray := IntArrayCapUp(f[current])
newArray[len(newArray)-1] = i
f[current] = newArray // F(Current) <- F(Current) union {i}
} else {
stateIsTerminal[current] = true
f[current] = []int{i} // F(Current) <- {i}
}
}
return trie, stateIsTerminal, f
}
|
ConstructTrie
| 3
| 35
|
strings/ahocorasick/shared.go
|
#FILE: Go-master/strings/ahocorasick/advancedahocorasick.go
##CHUNK 1
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
CreateTransition(i, a[j], i, acToReturn)
}
}
for current := 1; current < len(stateIsTerminal); current++ {
for j := range a {
if GetTransition(current, a[j], acToReturn) == -1 {
CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn)
}
}
}
##CHUNK 2
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
##CHUNK 3
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
##CHUNK 4
CreateTransition(i, a[j], i, acToReturn)
}
}
for current := 1; current < len(stateIsTerminal); current++ {
for j := range a {
if GetTransition(current, a[j], acToReturn) == -1 {
CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn)
}
}
}
return acToReturn, f
}
##CHUNK 5
package ahocorasick
import (
"fmt"
"time"
)
// Advanced Function performing the Advanced Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func Advanced(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
current = 0
}
##CHUNK 6
resultOccurrences,
}
}
// BuildExtendedAc Functions that builds extended Aho Corasick automaton.
func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s := make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
#FILE: Go-master/strings/ahocorasick/ahocorasick.go
##CHUNK 1
}
// Functions that builds Aho Corasick automaton.
func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s = make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
##CHUNK 2
}
// AhoCorasick Function performing the Basic Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func AhoCorasick(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f, s := BuildAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
fmt.Printf(" (Continue) \n")
} else {
current = 0
}
_, ok := f[current]
##CHUNK 3
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
fmt.Printf(" (Continue) \n")
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
##CHUNK 4
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
return acToReturn, f, s
}
#CURRENT FILE: Go-master/strings/ahocorasick/shared.go
|
Go-master
| 7
|
func Advanced(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
resultOccurrences,
}
}
|
func Advanced(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
resultOccurrences,
}
}
|
func Advanced(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
resultOccurrences,
}
}
|
Advanced
| 9
| 42
|
strings/ahocorasick/advancedahocorasick.go
|
#FILE: Go-master/strings/ahocorasick/ahocorasick.go
##CHUNK 1
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
resultOccurrences,
}
##CHUNK 2
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
fmt.Printf(" (Continue) \n")
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
##CHUNK 3
}
// AhoCorasick Function performing the Basic Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func AhoCorasick(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f, s := BuildAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
fmt.Printf(" (Continue) \n")
} else {
current = 0
}
_, ok := f[current]
##CHUNK 4
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
resultOccurrences,
}
}
// Functions that builds Aho Corasick automaton.
func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s = make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
##CHUNK 5
package ahocorasick
import (
"fmt"
"time"
)
// Result structure to hold occurrences
type Result struct {
occurrences map[string][]int
}
// AhoCorasick Function performing the Basic Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func AhoCorasick(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f, s := BuildAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
#FILE: Go-master/strings/ahocorasick/shared.go
##CHUNK 1
current := 0
j := 0
for j < len(p[i]) && GetTransition(current, p[i][j], trie) != -1 {
current = GetTransition(current, p[i][j], trie)
j++
}
for j < len(p[i]) {
stateIsTerminal = BoolArrayCapUp(stateIsTerminal)
CreateNewState(state, trie)
stateIsTerminal[state] = false
CreateTransition(current, p[i][j], state, trie)
current = state
j++
state++
}
if stateIsTerminal[current] {
newArray := IntArrayCapUp(f[current])
newArray[len(newArray)-1] = i
f[current] = newArray // F(Current) <- F(Current) union {i}
} else {
#FILE: Go-master/strings/bom/bom.go
##CHUNK 1
// currentOcc++
// }
// pos = pos + j + 1
// if pos+m-1 < len(t) {
// if debugMode == true {
// fmt.Printf("\n\nposition %d:\n", pos+m-1)
// }
// }
// }
// elapsed := time.Since(startTime)
// fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
// fmt.Printf("\n\n")
// if currentOcc > 0 {
// fmt.Printf("Word %q was found %d times at positions: ", p, currentOcc)
// for k := 0; k < currentOcc-1; k++ {
// fmt.Printf("%d, ", occurrences[k])
// }
// fmt.Printf("%d", occurrences[currentOcc-1])
// fmt.Printf(".\n")
// }
##CHUNK 2
// // Function bom performing the Backward Oracle Matching algorithm.
// // Prints whether the word/pattern was found + positions of possible multiple occurrences
// // or that the word was not found.
// func bom(t, p string) {
// startTime := time.Now()
// n, m := len(t), len(p)
// var current, j, pos int
// oracle := oracleOnLine(reverse(p))
// occurrences := make([]int, len(t))
// currentOcc := 0
// pos = 0
// if debugMode == true {
// fmt.Printf("\n\nWe are reading backwards in %q, searching for %q\n\nat position %d:\n", t, p, pos+m-1)
// }
// for pos <= n-m {
// current = 0 //initial state of the oracle
// j = m
// for j > 0 && stateExists(current, oracle) {
// if debugMode == true {
#CURRENT FILE: Go-master/strings/ahocorasick/advancedahocorasick.go
##CHUNK 1
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
CreateTransition(i, a[j], i, acToReturn)
}
}
for current := 1; current < len(stateIsTerminal); current++ {
for j := range a {
if GetTransition(current, a[j], acToReturn) == -1 {
CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn)
}
}
}
return acToReturn, f
}
##CHUNK 2
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
CreateTransition(i, a[j], i, acToReturn)
}
}
for current := 1; current < len(stateIsTerminal); current++ {
|
Go-master
| 8
|
func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s := make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
CreateTransition(i, a[j], i, acToReturn)
}
}
for current := 1; current < len(stateIsTerminal); current++ {
for j := range a {
if GetTransition(current, a[j], acToReturn) == -1 {
CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn)
}
}
}
return acToReturn, f
}
|
func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s := make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
CreateTransition(i, a[j], i, acToReturn)
}
}
for current := 1; current < len(stateIsTerminal); current++ {
for j := range a {
if GetTransition(current, a[j], acToReturn) == -1 {
CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn)
}
}
}
return acToReturn, f
}
|
func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s := make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
CreateTransition(i, a[j], i, acToReturn)
}
}
for current := 1; current < len(stateIsTerminal); current++ {
for j := range a {
if GetTransition(current, a[j], acToReturn) == -1 {
CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn)
}
}
}
return acToReturn, f
}
|
BuildExtendedAc
| 45
| 81
|
strings/ahocorasick/advancedahocorasick.go
|
#FILE: Go-master/strings/ahocorasick/ahocorasick.go
##CHUNK 1
}
// Functions that builds Aho Corasick automaton.
func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s = make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
##CHUNK 2
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
return acToReturn, f, s
}
##CHUNK 3
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
resultOccurrences,
}
}
// Functions that builds Aho Corasick automaton.
func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s = make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
##CHUNK 4
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
fmt.Printf(" (Continue) \n")
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
##CHUNK 5
}
// AhoCorasick Function performing the Basic Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func AhoCorasick(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f, s := BuildAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
fmt.Printf(" (Continue) \n")
} else {
current = 0
}
_, ok := f[current]
#FILE: Go-master/strings/ahocorasick/shared.go
##CHUNK 1
current := 0
j := 0
for j < len(p[i]) && GetTransition(current, p[i][j], trie) != -1 {
current = GetTransition(current, p[i][j], trie)
j++
}
for j < len(p[i]) {
stateIsTerminal = BoolArrayCapUp(stateIsTerminal)
CreateNewState(state, trie)
stateIsTerminal[state] = false
CreateTransition(current, p[i][j], state, trie)
current = state
j++
state++
}
if stateIsTerminal[current] {
newArray := IntArrayCapUp(f[current])
newArray[len(newArray)-1] = i
f[current] = newArray // F(Current) <- F(Current) union {i}
} else {
##CHUNK 2
CreateTransition(current, p[i][j], state, trie)
current = state
j++
state++
}
if stateIsTerminal[current] {
newArray := IntArrayCapUp(f[current])
newArray[len(newArray)-1] = i
f[current] = newArray // F(Current) <- F(Current) union {i}
} else {
stateIsTerminal[current] = true
f[current] = []int{i} // F(Current) <- {i}
}
}
return trie, stateIsTerminal, f
}
// Contains Returns 'true' if array of int's 's' contains int 'e', 'false' otherwise.
func Contains(s []int, e int) bool {
for _, a := range s {
##CHUNK 3
package ahocorasick
// ConstructTrie Function that constructs Trie as an automaton for a set of reversed & trimmed strings.
func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) {
trie = make(map[int]map[uint8]int)
stateIsTerminal = make([]bool, 1)
f = make(map[int][]int)
state := 1
CreateNewState(0, trie)
for i := 0; i < len(p); i++ {
current := 0
j := 0
for j < len(p[i]) && GetTransition(current, p[i][j], trie) != -1 {
current = GetTransition(current, p[i][j], trie)
j++
}
for j < len(p[i]) {
stateIsTerminal = BoolArrayCapUp(stateIsTerminal)
CreateNewState(state, trie)
stateIsTerminal[state] = false
#CURRENT FILE: Go-master/strings/ahocorasick/advancedahocorasick.go
##CHUNK 1
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
##CHUNK 2
package ahocorasick
import (
"fmt"
"time"
)
// Advanced Function performing the Advanced Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func Advanced(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
current = 0
}
|
Go-master
| 9
|
func AhoCorasick(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f, s := BuildAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
fmt.Printf(" (Continue) \n")
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
resultOccurrences,
}
}
|
func AhoCorasick(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f, s := BuildAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
fmt.Printf(" (Continue) \n")
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
resultOccurrences,
}
}
|
func AhoCorasick(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f, s := BuildAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
fmt.Printf(" (Continue) \n")
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
resultOccurrences,
}
}
|
AhoCorasick
| 14
| 50
|
strings/ahocorasick/ahocorasick.go
|
#FILE: Go-master/strings/ahocorasick/advancedahocorasick.go
##CHUNK 1
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
##CHUNK 2
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
##CHUNK 3
package ahocorasick
import (
"fmt"
"time"
)
// Advanced Function performing the Advanced Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func Advanced(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
current = 0
}
##CHUNK 4
}
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
resultOccurrences,
}
}
// BuildExtendedAc Functions that builds extended Aho Corasick automaton.
func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s := make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
##CHUNK 5
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
CreateTransition(i, a[j], i, acToReturn)
}
}
for current := 1; current < len(stateIsTerminal); current++ {
for j := range a {
if GetTransition(current, a[j], acToReturn) == -1 {
CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn)
}
}
}
##CHUNK 6
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
##CHUNK 7
CreateTransition(i, a[j], i, acToReturn)
}
}
for current := 1; current < len(stateIsTerminal); current++ {
for j := range a {
if GetTransition(current, a[j], acToReturn) == -1 {
CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn)
}
}
}
return acToReturn, f
}
##CHUNK 8
resultOccurrences,
}
}
// BuildExtendedAc Functions that builds extended Aho Corasick automaton.
func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s := make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
#FILE: Go-master/strings/ahocorasick/shared.go
##CHUNK 1
current := 0
j := 0
for j < len(p[i]) && GetTransition(current, p[i][j], trie) != -1 {
current = GetTransition(current, p[i][j], trie)
j++
}
for j < len(p[i]) {
stateIsTerminal = BoolArrayCapUp(stateIsTerminal)
CreateNewState(state, trie)
stateIsTerminal[state] = false
CreateTransition(current, p[i][j], state, trie)
current = state
j++
state++
}
if stateIsTerminal[current] {
newArray := IntArrayCapUp(f[current])
newArray[len(newArray)-1] = i
f[current] = newArray // F(Current) <- F(Current) union {i}
} else {
#CURRENT FILE: Go-master/strings/ahocorasick/ahocorasick.go
##CHUNK 1
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
return acToReturn, f, s
}
|
Go-master
| 10
|
func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s = make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
return acToReturn, f, s
}
|
func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s = make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
return acToReturn, f, s
}
|
func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s = make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
return acToReturn, f, s
}
|
BuildAc
| 53
| 76
|
strings/ahocorasick/ahocorasick.go
|
#FILE: Go-master/strings/ahocorasick/advancedahocorasick.go
##CHUNK 1
resultOccurrences,
}
}
// BuildExtendedAc Functions that builds extended Aho Corasick automaton.
func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s := make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
##CHUNK 2
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
##CHUNK 3
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
CreateTransition(i, a[j], i, acToReturn)
}
}
for current := 1; current < len(stateIsTerminal); current++ {
for j := range a {
if GetTransition(current, a[j], acToReturn) == -1 {
CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn)
}
}
}
##CHUNK 4
}
elapsed := time.Since(startTime)
fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
var resultOccurrences = make(map[string][]int)
for key, value := range occurrences {
resultOccurrences[p[key]] = value
}
return Result{
resultOccurrences,
}
}
// BuildExtendedAc Functions that builds extended Aho Corasick automaton.
func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s := make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
##CHUNK 5
CreateTransition(i, a[j], i, acToReturn)
}
}
for current := 1; current < len(stateIsTerminal); current++ {
for j := range a {
if GetTransition(current, a[j], acToReturn) == -1 {
CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn)
}
}
}
return acToReturn, f
}
#FILE: Go-master/strings/ahocorasick/shared.go
##CHUNK 1
CreateTransition(current, p[i][j], state, trie)
current = state
j++
state++
}
if stateIsTerminal[current] {
newArray := IntArrayCapUp(f[current])
newArray[len(newArray)-1] = i
f[current] = newArray // F(Current) <- F(Current) union {i}
} else {
stateIsTerminal[current] = true
f[current] = []int{i} // F(Current) <- {i}
}
}
return trie, stateIsTerminal, f
}
// Contains Returns 'true' if array of int's 's' contains int 'e', 'false' otherwise.
func Contains(s []int, e int) bool {
for _, a := range s {
##CHUNK 2
current := 0
j := 0
for j < len(p[i]) && GetTransition(current, p[i][j], trie) != -1 {
current = GetTransition(current, p[i][j], trie)
j++
}
for j < len(p[i]) {
stateIsTerminal = BoolArrayCapUp(stateIsTerminal)
CreateNewState(state, trie)
stateIsTerminal[state] = false
CreateTransition(current, p[i][j], state, trie)
current = state
j++
state++
}
if stateIsTerminal[current] {
newArray := IntArrayCapUp(f[current])
newArray[len(newArray)-1] = i
f[current] = newArray // F(Current) <- F(Current) union {i}
} else {
#FILE: Go-master/strings/bom/bom.go
##CHUNK 1
// }
// // Adds one letter to the oracle.
// func oracleAddLetter(oracle map[int]map[uint8]int, supply []int, orP string, o uint8) (oracleToReturn map[int]map[uint8]int, orPToReturn string) {
// m := len(orP)
// var s int
// createNewState(m+1, oracle)
// createTransition(m, o, m+1, oracle)
// k := supply[m]
// for k > -1 && getTransition(k, o, oracle) == -1 {
// createTransition(k, o, m+1, oracle)
// k = supply[k]
// }
// if k == -1 {
// s = 0
// } else {
// s = getTransition(k, o, oracle)
// }
// supply[m+1] = s
// return oracle, orP + string(o)
#CURRENT FILE: Go-master/strings/ahocorasick/ahocorasick.go
##CHUNK 1
}
// AhoCorasick Function performing the Basic Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func AhoCorasick(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f, s := BuildAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
fmt.Printf(" (Continue) \n")
} else {
current = 0
}
_, ok := f[current]
##CHUNK 2
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
fmt.Printf(" (Continue) \n")
} else {
current = 0
}
_, ok := f[current]
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1
}
}
}
}
|
Go-master
| 11
|
func HuffTree(listfreq []SymbolFreq) (*Node, error) {
if len(listfreq) < 1 {
return nil, fmt.Errorf("huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs")
}
q1 := make([]Node, len(listfreq))
q2 := make([]Node, 0, len(listfreq))
for i, x := range listfreq { // after the loop, q1 is a slice of leaf nodes representing listfreq
q1[i] = Node{left: nil, right: nil, symbol: x.Symbol, weight: x.Freq}
}
//loop invariant: q1, q2 are ordered by increasing weights
for len(q1)+len(q2) > 1 {
var node1, node2 Node
node1, q1, q2 = least(q1, q2)
node2, q1, q2 = least(q1, q2)
node := Node{left: &node1, right: &node2,
symbol: -1, weight: node1.weight + node2.weight}
q2 = append(q2, node)
}
if len(q1) == 1 { // returns the remaining node in q1, q2
return &q1[0], nil
}
return &q2[0], nil
}
|
func HuffTree(listfreq []SymbolFreq) (*Node, error) {
if len(listfreq) < 1 {
return nil, fmt.Errorf("huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs")
}
q1 := make([]Node, len(listfreq))
q2 := make([]Node, 0, len(listfreq))
for i, x := range listfreq { // after the loop, q1 is a slice of leaf nodes representing listfreq
q1[i] = Node{left: nil, right: nil, symbol: x.Symbol, weight: x.Freq}
}
//loop invariant: q1, q2 are ordered by increasing weights
for len(q1)+len(q2) > 1 {
var node1, node2 Node
node1, q1, q2 = least(q1, q2)
node2, q1, q2 = least(q1, q2)
node := Node{left: &node1, right: &node2,
symbol: -1, weight: node1.weight + node2.weight}
q2 = append(q2, node)
}
if len(q1) == 1 { // returns the remaining node in q1, q2
return &q1[0], nil
}
return &q2[0], nil
}
|
func HuffTree(listfreq []SymbolFreq) (*Node, error) {
if len(listfreq) < 1 {
return nil, fmt.Errorf("huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs")
}
q1 := make([]Node, len(listfreq))
q2 := make([]Node, 0, len(listfreq))
for i, x := range listfreq { // after the loop, q1 is a slice of leaf nodes representing listfreq
q1[i] = Node{left: nil, right: nil, symbol: x.Symbol, weight: x.Freq}
}
//loop invariant: q1, q2 are ordered by increasing weights
for len(q1)+len(q2) > 1 {
var node1, node2 Node
node1, q1, q2 = least(q1, q2)
node2, q1, q2 = least(q1, q2)
node := Node{left: &node1, right: &node2,
symbol: -1, weight: node1.weight + node2.weight}
q2 = append(q2, node)
}
if len(q1) == 1 { // returns the remaining node in q1, q2
return &q1[0], nil
}
return &q2[0], nil
}
|
HuffTree
| 34
| 56
|
compression/huffmancoding.go
|
#FILE: Go-master/sqrt/sqrtdecomposition_test.go
##CHUNK 1
func(q1, q2 int) int { return q1 + q2 },
func(q, a, b int) int { return q - a + b },
)
for i := 0; i < len(test.updates); i++ {
s.Update(test.updates[i].index, test.updates[i].value)
}
for i := 0; i < len(test.queries); i++ {
result := s.Query(test.queries[i].firstIndex, test.queries[i].lastIndex)
if result != test.expected[i] {
t.Logf("FAIL: %s", test.description)
t.Fatalf("Expected result: %d\nFound: %d\n", test.expected[i], result)
}
}
})
}
}
##CHUNK 2
{index: 3, value: 3},
{index: 6, value: 6}},
queries: []query{{3, 5}, {7, 8}, {3, 7}, {0, 10}},
expected: []int{4, 1, 11, 18},
},
}
for _, test := range sqrtDecompositionTestData {
t.Run(test.description, func(t *testing.T) {
s := sqrt.NewSqrtDecomposition(test.array,
func(e int) int { return e },
func(q1, q2 int) int { return q1 + q2 },
func(q, a, b int) int { return q - a + b },
)
for i := 0; i < len(test.updates); i++ {
s.Update(test.updates[i].index, test.updates[i].value)
}
for i := 0; i < len(test.queries); i++ {
result := s.Query(test.queries[i].firstIndex, test.queries[i].lastIndex)
#FILE: Go-master/project_euler/problem_18/tree.go
##CHUNK 1
if pivot.LeftIsNil() {
pivotEnded = true
}
}
return maxPathValue
}
// PrintReport is a method that prints a report of the tree
// Node by node
func (t *Tree) PrintReport() {
t.Nodes = make(map[int]struct{})
if t.Root == nil {
return
}
queue := make([]Node, 0)
queue = append(queue, t.Root)
head := 0
#FILE: Go-master/math/pi/montecarlopi.go
##CHUNK 1
}
// splitInt takes an integer x and splits it within an integer slice of length n in the most uniform
// way possible.
// For example, splitInt(10, 3) will return []int{4, 3, 3}, nil
func splitInt(x int, n int) ([]int, error) {
if x < n {
return nil, fmt.Errorf("x must be < n - given values are x=%d, n=%d", x, n)
}
split := make([]int, n)
if x%n == 0 {
for i := 0; i < n; i++ {
split[i] = x / n
}
} else {
limit := x % n
for i := 0; i < limit; i++ {
split[i] = x/n + 1
}
for i := limit; i < n; i++ {
#FILE: Go-master/dynamic/longestincreasingsubsequence.go
##CHUNK 1
)
// LongestIncreasingSubsequence returns the longest increasing subsequence
// where all elements of the subsequence are sorted in increasing order
func LongestIncreasingSubsequence(elements []int) int {
n := len(elements)
lis := make([]int, n)
for i := range lis {
lis[i] = 1
}
for i := range lis {
for j := 0; j < i; j++ {
if elements[i] > elements[j] && lis[i] < lis[j]+1 {
lis[i] = lis[j] + 1
}
}
}
res := 0
for _, value := range lis {
res = max.Int(res, value)
#FILE: Go-master/structure/tree/rbtree.go
##CHUNK 1
type RB[T constraints.Ordered] struct {
Root *RBNode[T]
_NIL *RBNode[T] // a sentinel value for nil
}
// NewRB creates a new Red-Black Tree
func NewRB[T constraints.Ordered]() *RB[T] {
leaf := &RBNode[T]{color: Black, left: nil, right: nil}
leaf.parent = leaf
return &RB[T]{
Root: leaf,
_NIL: leaf,
}
}
// Empty determines the Red-Black tree is empty
func (t *RB[T]) Empty() bool {
return t.Root == t._NIL
}
#FILE: Go-master/graph/coloring/graph_test.go
##CHUNK 1
func getTestGraphsForNegativeTests() (list []*testGraph) {
list = getTestGraphs()
list[0].VertexColors = nil
list[1].VertexColors = map[int]coloring.Color{}
for v := range list[2].VertexColors {
in := len(list[2].VertexColors) - v - 1
list[2].VertexColors[v] = list[2].VertexColors[in]
}
for v := range list[3].VertexColors {
list[3].VertexColors[v] = 1
}
return list[:4]
}
func TestGraphValidateColorsOfVertex_Negative(t *testing.T) {
for i, tt := range getTestGraphsForNegativeTests() {
t.Run(strconv.Itoa(i), func(t *testing.T) {
if err := tt.Graph.ValidateColorsOfVertex(tt.VertexColors); err == nil {
t.Errorf("ValidateColorsOfVertex() error = nil, want some err")
}
#CURRENT FILE: Go-master/compression/huffmancoding.go
##CHUNK 1
// HuffTree returns the root Node of the Huffman tree by compressing listfreq.
// The compression produces the most optimal code lengths, provided listfreq is ordered,
}
// least removes the node with lowest weight from q1, q2.
// It returns the node with lowest weight and the slices q1, q2 after the update.
func least(q1 []Node, q2 []Node) (Node, []Node, []Node) {
if len(q1) == 0 {
return q2[0], q1, q2[1:]
}
if len(q2) == 0 {
return q1[0], q1[1:], q2
}
if q1[0].weight <= q2[0].weight {
return q1[0], q1[1:], q2
}
return q2[0], q1, q2[1:]
}
##CHUNK 2
right *Node
symbol rune
weight int
}
// A SymbolFreq is a pair of a symbol and its associated frequency.
type SymbolFreq struct {
Symbol rune
Freq int
}
// HuffTree returns the root Node of the Huffman tree by compressing listfreq.
// The compression produces the most optimal code lengths, provided listfreq is ordered,
}
// least removes the node with lowest weight from q1, q2.
// It returns the node with lowest weight and the slices q1, q2 after the update.
func least(q1 []Node, q2 []Node) (Node, []Node, []Node) {
if len(q1) == 0 {
return q2[0], q1, q2[1:]
##CHUNK 3
}
if len(q2) == 0 {
return q1[0], q1[1:], q2
}
if q1[0].weight <= q2[0].weight {
return q1[0], q1[1:], q2
}
return q2[0], q1, q2[1:]
}
// HuffEncoding recursively traverses the Huffman tree pointed by node to obtain
// the map codes, that associates a rune with a slice of booleans.
// Each code is prefixed by prefix and left and right children are labelled with
// the booleans false and true, respectively.
func HuffEncoding(node *Node, prefix []bool, codes map[rune][]bool) {
if node.symbol != -1 { //base case
codes[node.symbol] = prefix
return
}
// inductive step
|
Go-master
| 12
|
func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool) {
var route []int
var stack []int
startIdx := GetIdx(start, nodes)
stack = append(stack, startIdx)
for len(stack) > 0 {
now := stack[len(stack)-1]
route = append(route, nodes[now])
if len(stack) > 1 {
stack = stack[:len(stack)-1]
} else {
stack = stack[:len(stack)-1]
}
for i := 0; i < len(edges[now]); i++ {
if edges[now][i] && NotExist(i, stack) {
stack = append(stack, i)
}
edges[now][i] = false
edges[i][now] = false
}
if route[len(route)-1] == end {
return route, true
}
}
if showroute {
return route, false
} else {
return nil, false
}
}
|
func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool) {
var route []int
var stack []int
startIdx := GetIdx(start, nodes)
stack = append(stack, startIdx)
for len(stack) > 0 {
now := stack[len(stack)-1]
route = append(route, nodes[now])
if len(stack) > 1 {
stack = stack[:len(stack)-1]
} else {
stack = stack[:len(stack)-1]
}
for i := 0; i < len(edges[now]); i++ {
if edges[now][i] && NotExist(i, stack) {
stack = append(stack, i)
}
edges[now][i] = false
edges[i][now] = false
}
if route[len(route)-1] == end {
return route, true
}
}
if showroute {
return route, false
} else {
return nil, false
}
}
|
func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool) {
var route []int
var stack []int
startIdx := GetIdx(start, nodes)
stack = append(stack, startIdx)
for len(stack) > 0 {
now := stack[len(stack)-1]
route = append(route, nodes[now])
if len(stack) > 1 {
stack = stack[:len(stack)-1]
} else {
stack = stack[:len(stack)-1]
}
for i := 0; i < len(edges[now]); i++ {
if edges[now][i] && NotExist(i, stack) {
stack = append(stack, i)
}
edges[now][i] = false
edges[i][now] = false
}
if route[len(route)-1] == end {
return route, true
}
}
if showroute {
return route, false
} else {
return nil, false
}
}
|
DepthFirstSearchHelper
| 26
| 56
|
graph/depthfirstsearch.go
|
#FILE: Go-master/structure/tree/tree.go
##CHUNK 1
return searchTreeHelper(node.Left(), nilNode, key)
}
return searchTreeHelper(node.Right(), nilNode, key)
}
func inOrderHelper[T constraints.Ordered](node, nilNode Node[T]) []T {
var stack []Node[T]
var ret []T
for node != nilNode || len(stack) > 0 {
for node != nilNode {
stack = append(stack, node)
node = node.Left()
}
node = stack[len(stack)-1]
stack = stack[:len(stack)-1]
ret = append(ret, node.Key())
node = node.Right()
}
##CHUNK 2
func searchTreeHelper[T constraints.Ordered](node, nilNode Node[T], key T) (Node[T], bool) {
if node == nilNode {
return node, false
}
if key == node.Key() {
return node, true
}
if key < node.Key() {
return searchTreeHelper(node.Left(), nilNode, key)
}
return searchTreeHelper(node.Right(), nilNode, key)
}
func inOrderHelper[T constraints.Ordered](node, nilNode Node[T]) []T {
var stack []Node[T]
var ret []T
for node != nilNode || len(stack) > 0 {
##CHUNK 3
for node != nilNode {
stack = append(stack, node)
node = node.Left()
}
node = stack[len(stack)-1]
stack = stack[:len(stack)-1]
ret = append(ret, node.Key())
node = node.Right()
}
return ret
}
func preOrderRecursive[T constraints.Ordered](n, nilNode Node[T], traversal *[]T) {
if n == nilNode {
return
}
*traversal = append(*traversal, n.Key())
#FILE: Go-master/graph/kosaraju.go
##CHUNK 1
var sccs [][]int
for len(stack) > 0 {
// Pop vertex from stack
v := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// Perform DFS if not already visited.
if !visited[v] {
scc := []int{}
transposed.dfs(v, visited, &scc)
sccs = append(sccs, scc)
}
}
return sccs
}
// Helper function to fill the stack with vertices in the order of their finish times.
func (g *Graph) fillOrder(v int, visited []bool, stack *[]int) {
#FILE: Go-master/other/nested/nestedbrackets.go
##CHUNK 1
// Brackets such as '{', '[', '(' are valid UTF-8 characters,
// which means that only one byte is required to code them,
// so can be stored as bytes.
var stack []byte
for i := 0; i < len(input); i++ {
if input[i] == '(' || input[i] == '{' || input[i] == '[' {
stack = append(stack, input[i])
} else {
if len(stack) > 0 {
pair := string(stack[len(stack)-1]) + string(input[i])
stack = stack[:len(stack)-1]
if pair != "[]" && pair != "{}" && pair != "()" {
// This means that two types of brackets has
// been mixed together, for example "([)]",
// which makes seuqence invalid by definition.
return false
}
##CHUNK 2
if len(stack) > 0 {
pair := string(stack[len(stack)-1]) + string(input[i])
stack = stack[:len(stack)-1]
if pair != "[]" && pair != "{}" && pair != "()" {
// This means that two types of brackets has
// been mixed together, for example "([)]",
// which makes seuqence invalid by definition.
return false
}
} else {
// This means that closing bracket is encountered
// before opening one, which makes all sequence
// invalid by definition.
return false
}
}
}
// If sequence is properly nested, all elements in stack
##CHUNK 3
// space complexity: O(n)
func IsBalanced(input string) bool {
if len(input) == 0 {
return true
}
if len(input)%2 != 0 {
return false
}
// Brackets such as '{', '[', '(' are valid UTF-8 characters,
// which means that only one byte is required to code them,
// so can be stored as bytes.
var stack []byte
for i := 0; i < len(input); i++ {
if input[i] == '(' || input[i] == '{' || input[i] == '[' {
stack = append(stack, input[i])
} else {
#FILE: Go-master/project_euler/problem_18/tree.go
##CHUNK 1
for len(stack) > 0 {
current := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// If we run out of steps, we check the sum of the path,
// update the maxPathValue if necessary and continue
if current.StepsLeft == 0 {
if current.Sum > maxPathValue {
maxPathValue = current.Sum
pivot = current.Node
}
continue
}
if !current.Node.RightIsNil() {
stack = append(stack, DFSNode{
Node: current.Node.Right(),
StepsLeft: current.StepsLeft - 1,
Sum: current.Sum + int(current.Node.Right().Value()),
})
##CHUNK 2
var pivot Node = r.Root
pivotEnded := false
maxPathValue := int(pivot.Value())
stack := make([]DFSNode, 0)
for !pivotEnded {
stack = append(stack, DFSNode{Node: pivot, StepsLeft: deep, Sum: maxPathValue})
for len(stack) > 0 {
current := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// If we run out of steps, we check the sum of the path,
// update the maxPathValue if necessary and continue
if current.StepsLeft == 0 {
if current.Sum > maxPathValue {
maxPathValue = current.Sum
pivot = current.Node
#CURRENT FILE: Go-master/graph/depthfirstsearch.go
##CHUNK 1
if nodes[i] == target {
return i
}
}
return -1
}
func NotExist(target int, slice []int) bool {
for i := 0; i < len(slice); i++ {
if slice[i] == target {
return false
}
}
return true
}
}
func DepthFirstSearch(start, end int, nodes []int, edges [][]bool) ([]int, bool) {
return DepthFirstSearchHelper(start, end, nodes, edges, false)
}
|
Go-master
| 13
|
func EdmondKarp(graph WeightedGraph, source int, sink int) float64 {
// Check graph emptiness
if len(graph) == 0 {
return 0.0
}
// Check correct dimensions of the graph slice
for i := 0; i < len(graph); i++ {
if len(graph[i]) != len(graph) {
return 0.0
}
}
rGraph := make(WeightedGraph, len(graph))
for i := 0; i < len(graph); i++ {
rGraph[i] = make([]float64, len(graph))
}
// Init the residual graph with the same capacities as the original graph
copy(rGraph, graph)
maxFlow := 0.0
for {
parent := FindPath(rGraph, source, sink)
if parent == nil {
break
}
// Finding the max flow over the path returned by BFS
// i.e. finding minimum residual capacity amonth the path edges
pathFlow := math.MaxFloat64
for v := sink; v != source; v = parent[v] {
u := parent[v]
if rGraph[u][v] < pathFlow {
pathFlow = rGraph[u][v]
}
}
// update residual capacities of the edges and
// reverse edges along the path
for v := sink; v != source; v = parent[v] {
u := parent[v]
rGraph[u][v] -= pathFlow
rGraph[v][u] += pathFlow
}
// Update the total flow found so far
maxFlow += pathFlow
}
return maxFlow
}
|
func EdmondKarp(graph WeightedGraph, source int, sink int) float64 {
// Check graph emptiness
if len(graph) == 0 {
return 0.0
}
// Check correct dimensions of the graph slice
for i := 0; i < len(graph); i++ {
if len(graph[i]) != len(graph) {
return 0.0
}
}
rGraph := make(WeightedGraph, len(graph))
for i := 0; i < len(graph); i++ {
rGraph[i] = make([]float64, len(graph))
}
// Init the residual graph with the same capacities as the original graph
copy(rGraph, graph)
maxFlow := 0.0
for {
parent := FindPath(rGraph, source, sink)
if parent == nil {
break
}
// Finding the max flow over the path returned by BFS
// i.e. finding minimum residual capacity amonth the path edges
pathFlow := math.MaxFloat64
for v := sink; v != source; v = parent[v] {
u := parent[v]
if rGraph[u][v] < pathFlow {
pathFlow = rGraph[u][v]
}
}
// update residual capacities of the edges and
// reverse edges along the path
for v := sink; v != source; v = parent[v] {
u := parent[v]
rGraph[u][v] -= pathFlow
rGraph[v][u] += pathFlow
}
// Update the total flow found so far
maxFlow += pathFlow
}
return maxFlow
}
|
func EdmondKarp(graph WeightedGraph, source int, sink int) float64 {
// Check graph emptiness
if len(graph) == 0 {
return 0.0
}
// Check correct dimensions of the graph slice
for i := 0; i < len(graph); i++ {
if len(graph[i]) != len(graph) {
return 0.0
}
}
rGraph := make(WeightedGraph, len(graph))
for i := 0; i < len(graph); i++ {
rGraph[i] = make([]float64, len(graph))
}
// Init the residual graph with the same capacities as the original graph
copy(rGraph, graph)
maxFlow := 0.0
for {
parent := FindPath(rGraph, source, sink)
if parent == nil {
break
}
// Finding the max flow over the path returned by BFS
// i.e. finding minimum residual capacity amonth the path edges
pathFlow := math.MaxFloat64
for v := sink; v != source; v = parent[v] {
u := parent[v]
if rGraph[u][v] < pathFlow {
pathFlow = rGraph[u][v]
}
}
// update residual capacities of the edges and
// reverse edges along the path
for v := sink; v != source; v = parent[v] {
u := parent[v]
rGraph[u][v] -= pathFlow
rGraph[v][u] += pathFlow
}
// Update the total flow found so far
maxFlow += pathFlow
}
return maxFlow
}
|
EdmondKarp
| 42
| 92
|
graph/edmondkarp.go
|
#FILE: Go-master/graph/floydwarshall.go
##CHUNK 1
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
numVertices := len(graph)
// Initializing result matrix and filling it up with same values as given graph
result := make(WeightedGraph, numVertices)
for i := 0; i < numVertices; i++ {
result[i] = make([]float64, numVertices)
for j := 0; j < numVertices; j++ {
result[i][j] = graph[i][j]
}
}
##CHUNK 2
type WeightedGraph [][]float64
// Defining maximum value. If two vertices share this value, it means they are not connected
var Inf = math.Inf(1)
// FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm
func FloydWarshall(graph WeightedGraph) WeightedGraph {
// If graph is empty, returns nil
if len(graph) == 0 || len(graph) != len(graph[0]) {
return nil
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
numVertices := len(graph)
##CHUNK 3
// Initializing result matrix and filling it up with same values as given graph
result := make(WeightedGraph, numVertices)
for i := 0; i < numVertices; i++ {
result[i] = make([]float64, numVertices)
for j := 0; j < numVertices; j++ {
result[i][j] = graph[i][j]
}
}
// Running over the result matrix and following the algorithm
for k := 0; k < numVertices; k++ {
for i := 0; i < numVertices; i++ {
for j := 0; j < numVertices; j++ {
// If there is a less costly path from i to j node, remembering it
if result[i][j] > result[i][k]+result[k][j] {
result[i][j] = result[i][k] + result[k][j]
}
}
#FILE: Go-master/sort/bucketsort.go
##CHUNK 1
}
// find the maximum and minimum elements in arr
max := arr[0]
min := arr[0]
for _, v := range arr {
if v > max {
max = v
}
if v < min {
min = v
}
}
// create an empty bucket for each element in arr
bucket := make([][]T, len(arr))
// put each element in the appropriate bucket
for _, v := range arr {
bucketIndex := int((v - min) / (max - min) * T(len(arr)-1))
##CHUNK 2
package sort
import "github.com/TheAlgorithms/Go/constraints"
// Bucket sorts a slice. It is mainly useful
// when input is uniformly distributed over a range.
func Bucket[T constraints.Number](arr []T) []T {
// early return if the array too small
if len(arr) <= 1 {
return arr
}
// find the maximum and minimum elements in arr
max := arr[0]
min := arr[0]
for _, v := range arr {
if v > max {
max = v
}
if v < min {
#FILE: Go-master/graph/coloring/bipartite.go
##CHUNK 1
}
}
for i := range g.edges {
if colors[i] == 0 {
colors[i] = 1
colorNode(i)
}
}
return colors
}
// basically tries to color the graph in two colors if each edge
// connects 2 differently colored nodes the graph can be considered bipartite
func BipartiteCheck(N int, edges [][]int) bool {
var graph Graph
for i := 0; i < N; i++ {
graph.AddVertex(i)
}
##CHUNK 2
return colors
}
// basically tries to color the graph in two colors if each edge
// connects 2 differently colored nodes the graph can be considered bipartite
func BipartiteCheck(N int, edges [][]int) bool {
var graph Graph
for i := 0; i < N; i++ {
graph.AddVertex(i)
}
for _, e := range edges {
graph.AddEdge(e[0], e[1])
}
return graph.ValidateColorsOfVertex(graph.TryBipartiteColoring()) == nil
}
#FILE: Go-master/graph/depthfirstsearch.go
##CHUNK 1
// depthfirstsearch.go
// description: this file contains the implementation of the depth first search algorithm
// details: Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node and explores as far as possible along each branch before backtracking.
// time complexity: O(n)
// space complexity: O(n)
package graph
func GetIdx(target int, nodes []int) int {
for i := 0; i < len(nodes); i++ {
if nodes[i] == target {
return i
}
}
return -1
}
func NotExist(target int, slice []int) bool {
for i := 0; i < len(slice); i++ {
if slice[i] == target {
#CURRENT FILE: Go-master/graph/edmondkarp.go
##CHUNK 1
parent := make(map[int]int)
// BFS loop with saving the path found
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(rGraph[v]); i++ {
if !marked[i] && rGraph[v][i] > 0 {
parent[i] = v
// Terminate the BFS, if we reach to sink
if i == sink {
return parent
}
marked[i] = true
queue = append(queue, i)
}
}
}
// source and sink are not in the same connected component
return nil
##CHUNK 2
"math"
)
// Returns a mapping of vertices as path, if there is any from source to sink
// Otherwise, returns nil
func FindPath(rGraph WeightedGraph, source int, sink int) map[int]int {
queue := make([]int, 0)
marked := make([]bool, len(rGraph))
marked[source] = true
queue = append(queue, source)
parent := make(map[int]int)
// BFS loop with saving the path found
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(rGraph[v]); i++ {
if !marked[i] && rGraph[v][i] > 0 {
parent[i] = v
// Terminate the BFS, if we reach to sink
|
Go-master
| 14
|
func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int) {
queue := make([]int, 0)
discovered := make([]int, nodes)
discovered[start] = 1
queue = append(queue, start)
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(edges[v]); i++ {
if discovered[i] == 0 && edges[v][i] > 0 {
if i == end {
return true, discovered[v]
}
discovered[i] = discovered[v] + 1
queue = append(queue, i)
}
}
}
return false, 0
}
|
func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int) {
queue := make([]int, 0)
discovered := make([]int, nodes)
discovered[start] = 1
queue = append(queue, start)
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(edges[v]); i++ {
if discovered[i] == 0 && edges[v][i] > 0 {
if i == end {
return true, discovered[v]
}
discovered[i] = discovered[v] + 1
queue = append(queue, i)
}
}
}
return false, 0
}
|
func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int) {
queue := make([]int, 0)
discovered := make([]int, nodes)
discovered[start] = 1
queue = append(queue, start)
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(edges[v]); i++ {
if discovered[i] == 0 && edges[v][i] > 0 {
if i == end {
return true, discovered[v]
}
discovered[i] = discovered[v] + 1
queue = append(queue, i)
}
}
}
return false, 0
}
|
BreadthFirstSearch
| 8
| 27
|
graph/breadthfirstsearch.go
|
#FILE: Go-master/graph/edmondkarp.go
##CHUNK 1
parent := make(map[int]int)
// BFS loop with saving the path found
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(rGraph[v]); i++ {
if !marked[i] && rGraph[v][i] > 0 {
parent[i] = v
// Terminate the BFS, if we reach to sink
if i == sink {
return parent
}
marked[i] = true
queue = append(queue, i)
}
}
}
// source and sink are not in the same connected component
return nil
##CHUNK 2
"math"
)
// Returns a mapping of vertices as path, if there is any from source to sink
// Otherwise, returns nil
func FindPath(rGraph WeightedGraph, source int, sink int) map[int]int {
queue := make([]int, 0)
marked := make([]bool, len(rGraph))
marked[source] = true
queue = append(queue, source)
parent := make(map[int]int)
// BFS loop with saving the path found
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(rGraph[v]); i++ {
if !marked[i] && rGraph[v][i] > 0 {
parent[i] = v
// Terminate the BFS, if we reach to sink
##CHUNK 3
if i == sink {
return parent
}
marked[i] = true
queue = append(queue, i)
}
}
}
// source and sink are not in the same connected component
return nil
}
func EdmondKarp(graph WeightedGraph, source int, sink int) float64 {
// Check graph emptiness
if len(graph) == 0 {
return 0.0
}
// Check correct dimensions of the graph slice
for i := 0; i < len(graph); i++ {
#FILE: Go-master/graph/kahn.go
##CHUNK 1
queue := make([]int, 0, n)
for i := 0; i < n; i++ {
if inDegree[i] == 0 {
queue = append(queue, i)
}
}
// order holds a valid topological order
order := make([]int, 0, n)
// process the dependency-free vertices
// every time we process a vertex, we "remove" it from the graph
for len(queue) > 0 {
// pop the first vertex from the queue
vtx := queue[0]
queue = queue[1:]
// add the vertex to the topological order
order = append(order, vtx)
// "remove" all the edges coming out of this vertex
##CHUNK 2
for _, d := range dependencies {
// make sure we don't add the same edge twice
if _, ok := g.edges[d[0]][d[1]]; !ok {
g.AddEdge(d[0], d[1])
inDegree[d[1]]++
}
}
// queue holds all vertices with in-degree 0
// these vertices have no dependency and thus can be ordered first
queue := make([]int, 0, n)
for i := 0; i < n; i++ {
if inDegree[i] == 0 {
queue = append(queue, i)
}
}
// order holds a valid topological order
order := make([]int, 0, n)
##CHUNK 3
// process the dependency-free vertices
// every time we process a vertex, we "remove" it from the graph
for len(queue) > 0 {
// pop the first vertex from the queue
vtx := queue[0]
queue = queue[1:]
// add the vertex to the topological order
order = append(order, vtx)
// "remove" all the edges coming out of this vertex
// every time we remove an edge, the corresponding in-degree reduces by 1
// if all dependencies on a vertex is removed, enqueue the vertex
for neighbour := range g.edges[vtx] {
inDegree[neighbour]--
if inDegree[neighbour] == 0 {
queue = append(queue, neighbour)
}
}
}
#FILE: Go-master/project_euler/problem_18/tree.go
##CHUNK 1
ID int
}
func (t *Tree) BFSInsert(value NodeValue) {
t.Nodes = make(map[int]struct{}) // Reset the nodes map
if t.Root == nil {
t.Root = &Root{NodeValue: value, ID: 0}
t.ID = 1
return
}
queue := make([]Node, 0)
queue = append(queue, t.Root)
t.isInQueue(t.Root.GetID())
head := 0
for head < len(queue) {
current := queue[head]
##CHUNK 2
}
queue := make([]Node, 0)
queue = append(queue, t.Root)
t.isInQueue(t.Root.GetID())
head := 0
for head < len(queue) {
current := queue[head]
head++
childNode := current.CreateChild(value, t.ID)
if current.HasSpace() {
current.Insert(childNode)
t.ID++
return
}
if !t.isInQueue(current.Left().GetID()) { // Avoid duplicates
##CHUNK 3
func (t *Tree) PrintReport() {
t.Nodes = make(map[int]struct{})
if t.Root == nil {
return
}
queue := make([]Node, 0)
queue = append(queue, t.Root)
head := 0
for head < len(queue) {
current := queue[head]
head++
print("ID:", current.GetID())
print(", Current node:", current.Value())
if !current.LeftIsNil() {
print(", Left Child:", current.Left().Value())
#FILE: Go-master/graph/depthfirstsearch.go
##CHUNK 1
return false
}
}
return true
}
func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool) {
var route []int
var stack []int
startIdx := GetIdx(start, nodes)
stack = append(stack, startIdx)
for len(stack) > 0 {
now := stack[len(stack)-1]
route = append(route, nodes[now])
if len(stack) > 1 {
stack = stack[:len(stack)-1]
} else {
stack = stack[:len(stack)-1]
}
for i := 0; i < len(edges[now]); i++ {
#CURRENT FILE: Go-master/graph/breadthfirstsearch.go
|
Go-master
| 15
|
func FloydWarshall(graph WeightedGraph) WeightedGraph {
// If graph is empty, returns nil
if len(graph) == 0 || len(graph) != len(graph[0]) {
return nil
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
numVertices := len(graph)
// Initializing result matrix and filling it up with same values as given graph
result := make(WeightedGraph, numVertices)
for i := 0; i < numVertices; i++ {
result[i] = make([]float64, numVertices)
for j := 0; j < numVertices; j++ {
result[i][j] = graph[i][j]
}
}
// Running over the result matrix and following the algorithm
for k := 0; k < numVertices; k++ {
for i := 0; i < numVertices; i++ {
for j := 0; j < numVertices; j++ {
// If there is a less costly path from i to j node, remembering it
if result[i][j] > result[i][k]+result[k][j] {
result[i][j] = result[i][k] + result[k][j]
}
}
}
}
return result
}
|
func FloydWarshall(graph WeightedGraph) WeightedGraph {
// If graph is empty, returns nil
if len(graph) == 0 || len(graph) != len(graph[0]) {
return nil
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
numVertices := len(graph)
// Initializing result matrix and filling it up with same values as given graph
result := make(WeightedGraph, numVertices)
for i := 0; i < numVertices; i++ {
result[i] = make([]float64, numVertices)
for j := 0; j < numVertices; j++ {
result[i][j] = graph[i][j]
}
}
// Running over the result matrix and following the algorithm
for k := 0; k < numVertices; k++ {
for i := 0; i < numVertices; i++ {
for j := 0; j < numVertices; j++ {
// If there is a less costly path from i to j node, remembering it
if result[i][j] > result[i][k]+result[k][j] {
result[i][j] = result[i][k] + result[k][j]
}
}
}
}
return result
}
|
func FloydWarshall(graph WeightedGraph) WeightedGraph {
// If graph is empty, returns nil
if len(graph) == 0 || len(graph) != len(graph[0]) {
return nil
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
numVertices := len(graph)
// Initializing result matrix and filling it up with same values as given graph
result := make(WeightedGraph, numVertices)
for i := 0; i < numVertices; i++ {
result[i] = make([]float64, numVertices)
for j := 0; j < numVertices; j++ {
result[i][j] = graph[i][j]
}
}
// Running over the result matrix and following the algorithm
for k := 0; k < numVertices; k++ {
for i := 0; i < numVertices; i++ {
for j := 0; j < numVertices; j++ {
// If there is a less costly path from i to j node, remembering it
if result[i][j] > result[i][k]+result[k][j] {
result[i][j] = result[i][k] + result[k][j]
}
}
}
}
return result
}
|
FloydWarshall
| 16
| 54
|
graph/floydwarshall.go
|
#FILE: Go-master/graph/edmondkarp.go
##CHUNK 1
}
func EdmondKarp(graph WeightedGraph, source int, sink int) float64 {
// Check graph emptiness
if len(graph) == 0 {
return 0.0
}
// Check correct dimensions of the graph slice
for i := 0; i < len(graph); i++ {
if len(graph[i]) != len(graph) {
return 0.0
}
}
rGraph := make(WeightedGraph, len(graph))
for i := 0; i < len(graph); i++ {
rGraph[i] = make([]float64, len(graph))
}
// Init the residual graph with the same capacities as the original graph
##CHUNK 2
if len(graph[i]) != len(graph) {
return 0.0
}
}
rGraph := make(WeightedGraph, len(graph))
for i := 0; i < len(graph); i++ {
rGraph[i] = make([]float64, len(graph))
}
// Init the residual graph with the same capacities as the original graph
copy(rGraph, graph)
maxFlow := 0.0
for {
parent := FindPath(rGraph, source, sink)
if parent == nil {
break
}
// Finding the max flow over the path returned by BFS
##CHUNK 3
if i == sink {
return parent
}
marked[i] = true
queue = append(queue, i)
}
}
}
// source and sink are not in the same connected component
return nil
}
func EdmondKarp(graph WeightedGraph, source int, sink int) float64 {
// Check graph emptiness
if len(graph) == 0 {
return 0.0
}
// Check correct dimensions of the graph slice
for i := 0; i < len(graph); i++ {
#FILE: Go-master/math/matrix/strassenmatrixmultiply.go
##CHUNK 1
return Matrix[T]{}, err
}
C21, err := M2.Add(M4)
if err != nil {
return Matrix[T]{}, err
}
C22, err := A10.Subtract(M2)
if err != nil {
return Matrix[T]{}, err
}
// Combine subMatrices into the result matrix
var zeroVal T
C := New(n, n, zeroVal)
for i := 0; i < mid; i++ {
for j := 0; j < mid; j++ {
val, err := C11.Get(i, j)
if err != nil {
return Matrix[T]{}, err
##CHUNK 2
// Combine subMatrices into the result matrix
var zeroVal T
C := New(n, n, zeroVal)
for i := 0; i < mid; i++ {
for j := 0; j < mid; j++ {
val, err := C11.Get(i, j)
if err != nil {
return Matrix[T]{}, err
}
err = C.Set(i, j, val)
if err != nil {
return Matrix[T]{}, err
}
val, err = C12.Get(i, j)
if err != nil {
return Matrix[T]{}, err
#FILE: Go-master/math/matrix/strassenmatrixmultiply_test.go
##CHUNK 1
// Check the values in the result matrix
for i := 0; i < expectedRows; i++ {
for j := 0; j < expectedColumns; j++ {
val, err := resultMatrix.Get(i, j)
if err != nil {
t.Fatalf("Failed to copy matrix: %v", err)
}
expVal, err := expectedData.Get(i, j)
if err != nil {
t.Fatalf("Failed to copy matrix: %v", err)
}
if val != expVal {
t.Errorf("Expected value %d at (%d, %d) in result matrix, but got %d", expVal, i, j, val)
}
}
}
}
func TestMatrixMultiplication(t *testing.T) {
rand.New(rand.NewSource(time.Now().UnixNano()))
##CHUNK 2
// Generate random matrices for testing
size := 1 << (rand.Intn(8) + 1) // tests for matrix with n as power of 2
matrixA := MakeRandomMatrix[int](size, size)
matrixB := MakeRandomMatrix[int](size, size)
// Calculate the expected result using the standard multiplication
expected, err := matrixA.Multiply(matrixB)
if err != nil {
t.Error("copyMatrix.Set error: " + err.Error())
}
// Calculate the result using the Strassen algorithm
result, err := matrixA.StrassenMatrixMultiply(matrixB)
if err != nil {
t.Error("copyMatrix.Set error: " + err.Error())
}
// Check if the result matches the expected result
for i := 0; i < size; i++ {
for j := 0; j < size; j++ {
val, err := result.Get(i, j)
##CHUNK 3
columns := resultMatrix.Columns()
if rows != expectedRows {
t.Errorf("Expected %d rows in result matrix, but got %d", expectedRows, rows)
}
if columns != expectedColumns {
t.Errorf("Expected %d columns in result matrix, but got %d", expectedColumns, columns)
}
// Check the values in the result matrix
for i := 0; i < expectedRows; i++ {
for j := 0; j < expectedColumns; j++ {
val, err := resultMatrix.Get(i, j)
if err != nil {
t.Fatalf("Failed to copy matrix: %v", err)
}
expVal, err := expectedData.Get(i, j)
if err != nil {
t.Fatalf("Failed to copy matrix: %v", err)
#FILE: Go-master/math/matrix/multiply.go
##CHUNK 1
for i := 0; i < m1.Rows(); i++ {
for j := 0; j < m2.Columns(); j++ {
i, j := i, j // Capture the loop variable for the goroutine
wg.Add(1)
go func() {
defer wg.Done()
// Compute the dot product of the row from the first matrix and the column from the second matrix.
dotProduct := zeroVal
for k := 0; k < m1.Columns(); k++ {
select {
case <-ctx.Done():
return // Context canceled; return without an error
default:
}
val1, err := m1.Get(i, k)
if err != nil {
cancel()
select {
case errCh <- err:
#FILE: Go-master/cipher/transposition/transposition.go
##CHUNK 1
return nil, ErrKeyMissing
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[j] = text[i+key[j]-1]
}
result = append(result, transposition...)
}
result = []rune(strings.TrimRight(string(result), string(placeholder)))
return result, nil
}
#CURRENT FILE: Go-master/graph/floydwarshall.go
|
Go-master
| 16
|
func KruskalMST(n int, edges []Edge) ([]Edge, int) {
// Initialize variables to store the minimum spanning tree and its total cost
var mst []Edge
var cost int
// Create a new UnionFind data structure with 'n' nodes
u := NewUnionFind(n)
// Sort the edges in non-decreasing order based on their weights
sort.SliceStable(edges, func(i, j int) bool {
return edges[i].Weight < edges[j].Weight
})
// Iterate through the sorted edges
for _, edge := range edges {
// Check if adding the current edge forms a cycle or not
if u.Find(int(edge.Start)) != u.Find(int(edge.End)) {
// Add the edge to the minimum spanning tree
mst = append(mst, edge)
// Add the weight of the edge to the total cost
cost += edge.Weight
// Merge the sets containing the start and end vertices of the current edge
u.Union(int(edge.Start), int(edge.End))
}
}
// Return the minimum spanning tree and its total cost
return mst, cost
}
|
func KruskalMST(n int, edges []Edge) ([]Edge, int) {
// Initialize variables to store the minimum spanning tree and its total cost
var mst []Edge
var cost int
// Create a new UnionFind data structure with 'n' nodes
u := NewUnionFind(n)
// Sort the edges in non-decreasing order based on their weights
sort.SliceStable(edges, func(i, j int) bool {
return edges[i].Weight < edges[j].Weight
})
// Iterate through the sorted edges
for _, edge := range edges {
// Check if adding the current edge forms a cycle or not
if u.Find(int(edge.Start)) != u.Find(int(edge.End)) {
// Add the edge to the minimum spanning tree
mst = append(mst, edge)
// Add the weight of the edge to the total cost
cost += edge.Weight
// Merge the sets containing the start and end vertices of the current edge
u.Union(int(edge.Start), int(edge.End))
}
}
// Return the minimum spanning tree and its total cost
return mst, cost
}
|
func KruskalMST(n int, edges []Edge) ([]Edge, int) {
// Initialize variables to store the minimum spanning tree and its total cost
var mst []Edge
var cost int
// Create a new UnionFind data structure with 'n' nodes
u := NewUnionFind(n)
// Sort the edges in non-decreasing order based on their weights
sort.SliceStable(edges, func(i, j int) bool {
return edges[i].Weight < edges[j].Weight
})
// Iterate through the sorted edges
for _, edge := range edges {
// Check if adding the current edge forms a cycle or not
if u.Find(int(edge.Start)) != u.Find(int(edge.End)) {
// Add the edge to the minimum spanning tree
mst = append(mst, edge)
// Add the weight of the edge to the total cost
cost += edge.Weight
// Merge the sets containing the start and end vertices of the current edge
u.Union(int(edge.Start), int(edge.End))
}
}
// Return the minimum spanning tree and its total cost
return mst, cost
}
|
KruskalMST
| 22
| 50
|
graph/kruskal.go
|
#FILE: Go-master/dynamic/optimalbst.go
##CHUNK 1
}
// Total cost for root k
cost := sum + leftCost + rightCost
// Update dp[i][j] with the minimum cost
dp[i][j] = min.Int(dp[i][j], cost)
}
}
}
return dp[0][n-1]
}
// Helper function to sum the frequencies
func sum(freq []int, i, j int) int {
total := 0
for k := i; k <= j; k++ {
total += freq[k]
}
return total
##CHUNK 2
} else {
leftCost = 0
}
// Right cost: dp[k+1][j] is valid only if k < j
var rightCost int
if k < j {
rightCost = dp[k+1][j]
} else {
rightCost = 0
}
// Total cost for root k
cost := sum + leftCost + rightCost
// Update dp[i][j] with the minimum cost
dp[i][j] = min.Int(dp[i][j], cost)
}
}
}
#FILE: Go-master/graph/prim.go
##CHUNK 1
var mst []Edge
marked := make([]bool, g.vertices)
h := &minEdge{}
// Pushing neighbors of the start node to the binary heap
for neighbor, weight := range g.edges[int(start)] {
heap.Push(h, Edge{start, Vertex(neighbor), weight})
}
marked[start] = true
cost := 0
for h.Len() > 0 {
e := heap.Pop(h).(Edge)
end := int(e.End)
// To avoid cycles
if marked[end] {
continue
}
marked[end] = true
cost += e.Weight
mst = append(mst, e)
// Check for neighbors of the newly added edge's End vertex
##CHUNK 2
e := heap.Pop(h).(Edge)
end := int(e.End)
// To avoid cycles
if marked[end] {
continue
}
marked[end] = true
cost += e.Weight
mst = append(mst, e)
// Check for neighbors of the newly added edge's End vertex
for neighbor, weight := range g.edges[end] {
if !marked[neighbor] {
heap.Push(h, Edge{e.End, Vertex(neighbor), weight})
}
}
}
return mst, cost
}
##CHUNK 3
// The Prim's algorithm computes the minimum spanning tree for a weighted undirected graph
// Worst Case Time Complexity: O(E log V) using Binary heap, where V is the number of vertices and E is the number of edges
// Space Complexity: O(V + E)
// Implementation is based on the book 'Introduction to Algorithms' (CLRS)
package graph
import (
"container/heap"
)
type minEdge []Edge
func (h minEdge) Len() int { return len(h) }
func (h minEdge) Less(i, j int) bool { return h[i].Weight < h[j].Weight }
func (h minEdge) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minEdge) Push(x interface{}) {
*h = append(*h, x.(Edge))
}
#FILE: Go-master/graph/graph.go
##CHUNK 1
g.edges[v] = make(map[int]int)
}
}
// AddEdge will add a new edge between the provided vertices in the graph
func (g *Graph) AddEdge(one, two int) {
// Add an edge with 0 weight
g.AddWeightedEdge(one, two, 0)
}
// AddWeightedEdge will add a new weighted edge between the provided vertices in the graph
func (g *Graph) AddWeightedEdge(one, two, weight int) {
// Add vertices: one and two to the graph if they are not present
g.AddVertex(one)
g.AddVertex(two)
// And finally add the edges
// one->two and two->one for undirected graph
// one->two for directed graphs
g.edges[one][two] = weight
##CHUNK 2
// AddWeightedEdge will add a new weighted edge between the provided vertices in the graph
func (g *Graph) AddWeightedEdge(one, two, weight int) {
// Add vertices: one and two to the graph if they are not present
g.AddVertex(one)
g.AddVertex(two)
// And finally add the edges
// one->two and two->one for undirected graph
// one->two for directed graphs
g.edges[one][two] = weight
if !g.Directed {
g.edges[two][one] = weight
}
}
##CHUNK 3
// AddVertex will add a new vertex in the graph.
// If the vertex already exists it will do nothing.
func (g *Graph) AddVertex(v int) {
if g.edges == nil {
g.edges = make(map[int]map[int]int)
}
// Check if vertex is present or not
if _, ok := g.edges[v]; !ok {
g.edges[v] = make(map[int]int)
}
}
// AddEdge will add a new edge between the provided vertices in the graph
func (g *Graph) AddEdge(one, two int) {
// Add an edge with 0 weight
g.AddWeightedEdge(one, two, 0)
}
##CHUNK 4
// This file contains the simple structural implementation of
// directed & undirected graphs used within the graph package
// Author(s): [Shivam](https://github.com/Shivam010), [Tahmeed](https://github.com/Tahmeed156)
package graph
// Graph provides a structure to store the graph.
// It is safe to use its empty object.
type Graph struct {
vertices int
edges map[int]map[int]int // Stores weight of an edge
Directed bool // Differentiate directed/undirected graphs
}
// Constructor functions for graphs (undirected by default)
func New(v int) *Graph {
return &Graph{
vertices: v,
}
}
#FILE: Go-master/graph/topological.go
##CHUNK 1
// topological.go
// description: Topological sort
// details: Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.
// time complexity: O(V+E) where V is the number of vertices and E is the number of edges in the graph
// space complexity: O(V) where V is the number of vertices in the graph
// reference: https://en.wikipedia.org/wiki/Topological_sorting
package graph
// Topological assumes that graph given is valid and that its
// possible to get a topological ordering.
// constraints are array of []int{a, b}, representing
// an edge going from a to b
func Topological(N int, constraints [][]int) []int {
dependencies := make([]int, N)
nodes := make([]int, N)
for i := range nodes {
nodes[i] = i
}
edges := make([][]bool, N)
#CURRENT FILE: Go-master/graph/kruskal.go
|
Go-master
| 17
|
func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree) {
tree = new(Tree)
tree.numbersVertex, tree.root, tree.MAXLOG = numbersVertex, root, 0
tree.depth = make([]int, numbersVertex)
tree.dad = make([]int, numbersVertex)
for (1 << tree.MAXLOG) <= numbersVertex {
(tree.MAXLOG) += 1
}
(tree.MAXLOG) += 1
tree.jump = make([][]int, tree.MAXLOG)
for j := 0; j < tree.MAXLOG; j++ {
tree.jump[j] = make([]int, numbersVertex)
}
tree.edges = make([][]int, numbersVertex)
for _, e := range edges {
tree.addEdge(e.from, e.to)
}
return tree
}
|
func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree) {
tree = new(Tree)
tree.numbersVertex, tree.root, tree.MAXLOG = numbersVertex, root, 0
tree.depth = make([]int, numbersVertex)
tree.dad = make([]int, numbersVertex)
for (1 << tree.MAXLOG) <= numbersVertex {
(tree.MAXLOG) += 1
}
(tree.MAXLOG) += 1
tree.jump = make([][]int, tree.MAXLOG)
for j := 0; j < tree.MAXLOG; j++ {
tree.jump[j] = make([]int, numbersVertex)
}
tree.edges = make([][]int, numbersVertex)
for _, e := range edges {
tree.addEdge(e.from, e.to)
}
return tree
}
|
func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree) {
tree = new(Tree)
tree.numbersVertex, tree.root, tree.MAXLOG = numbersVertex, root, 0
tree.depth = make([]int, numbersVertex)
tree.dad = make([]int, numbersVertex)
for (1 << tree.MAXLOG) <= numbersVertex {
(tree.MAXLOG) += 1
}
(tree.MAXLOG) += 1
tree.jump = make([][]int, tree.MAXLOG)
for j := 0; j < tree.MAXLOG; j++ {
tree.jump[j] = make([]int, numbersVertex)
}
tree.edges = make([][]int, numbersVertex)
for _, e := range edges {
tree.addEdge(e.from, e.to)
}
return tree
}
|
NewTree
| 85
| 107
|
graph/lowestcommonancestor.go
|
#FILE: Go-master/graph/lowestcommonancestor_test.go
##CHUNK 1
const MAXVERTEX int = 2000
var numbersVertex int = rnd.Intn(MAXVERTEX) + 1
var root int = rnd.Intn(numbersVertex)
var edges []TreeEdge
var fullGraph []TreeEdge
for u := 0; u < numbersVertex; u++ {
for v := 0; v < numbersVertex; v++ {
fullGraph = append(fullGraph, TreeEdge{
from: u,
to: v,
})
}
}
rnd.Shuffle(len(fullGraph), func(i, j int) {
fullGraph[i], fullGraph[j] = fullGraph[j], fullGraph[i]
})
par := make([]int, numbersVertex)
##CHUNK 2
from: u,
to: v,
})
}
}
rnd.Shuffle(len(fullGraph), func(i, j int) {
fullGraph[i], fullGraph[j] = fullGraph[j], fullGraph[i]
})
par := make([]int, numbersVertex)
for u := 0; u < numbersVertex; u++ {
par[u] = u
}
var findp func(int) int
findp = func(u int) int {
if u == par[u] {
return u
} else {
par[u] = findp(par[u])
##CHUNK 3
return true
}
for _, e := range fullGraph {
if join(e.from, e.to) == true {
edges = append(edges, e)
}
}
return NewTree(numbersVertex, root, edges)
}
func generateQuery(tree *Tree) []Query {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
const MAXQUERY = 50
var queries []Query
bruteforceLCA := func(u, v int) int {
for u != v {
if tree.GetDepth(u) > tree.GetDepth(v) {
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/uniquepaths.go
##CHUNK 1
}
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
for i := 0; i < m; i++ {
grid[i][0] = 1
}
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}
#FILE: Go-master/dynamic/binomialcoefficient.go
##CHUNK 1
// }
// }
// Bin2 function
func Bin2(n int, k int) int {
var i, j int
B := make([][]int, (n + 1))
for i := range B {
B[i] = make([]int, k+1)
}
for i = 0; i <= n; i++ {
for j = 0; j <= min.Int(i, k); j++ {
if j == 0 || j == i {
B[i][j] = 1
} else {
B[i][j] = B[i-1][j-1] + B[i-1][j]
}
}
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
##CHUNK 2
)
// Max function - possible duplicate
func Max(a, b int) int {
return int(math.Max(float64(a), float64(b)))
}
// Knapsack solves knapsack problem
// return maxProfit
func Knapsack(maxWeight int, weights, values []int) int {
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
#FILE: Go-master/dynamic/longestcommonsubsequence.go
##CHUNK 1
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i := 0; i <= aLen; i++ {
for j := 0; j <= bLen; j++ {
if i == 0 || j == 0 {
lcs[i][j] = 0
} else if aRunes[i-1] == bRunes[j-1] {
lcs[i][j] = lcs[i-1][j-1] + 1
} else {
lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])
}
}
}
// returning the length of longest common subsequence
return lcs[aLen][bLen]
}
#CURRENT FILE: Go-master/graph/lowestcommonancestor.go
|
Go-master
| 18
|
func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) {
// 1. Choose a random integer k from the range [1, q-1]
k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1)))
if err != nil {
panic(err)
}
// 2. Compute r = (g^k mod p) mod q
r = new(big.Int).Exp(g, k, p)
r.Mod(r, q)
// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
s = new(big.Int).ModInverse(k, q) // k^-1 mod q
s.Mul(
s,
new(big.Int).Add( // (H(m) + x*r)
h,
new(big.Int).Mul(x, r),
),
)
s.Mod(s, q) // mod q
return r, s
}
|
func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) {
// 1. Choose a random integer k from the range [1, q-1]
k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1)))
if err != nil {
panic(err)
}
// 2. Compute r = (g^k mod p) mod q
r = new(big.Int).Exp(g, k, p)
r.Mod(r, q)
// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
s = new(big.Int).ModInverse(k, q) // k^-1 mod q
s.Mul(
s,
new(big.Int).Add( // (H(m) + x*r)
h,
new(big.Int).Mul(x, r),
),
)
s.Mod(s, q) // mod q
return r, s
}
|
func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) {
// 1. Choose a random integer k from the range [1, q-1]
k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1)))
if err != nil {
panic(err)
}
// 2. Compute r = (g^k mod p) mod q
r = new(big.Int).Exp(g, k, p)
r.Mod(r, q)
// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
s = new(big.Int).ModInverse(k, q) // k^-1 mod q
s.Mul(
s,
new(big.Int).Add( // (H(m) + x*r)
h,
new(big.Int).Mul(x, r),
),
)
s.Mod(s, q) // mod q
return r, s
}
|
Sign
| 124
| 148
|
cipher/dsa/dsa.go
|
#CURRENT FILE: Go-master/cipher/dsa/dsa.go
##CHUNK 1
// Sign is signature generation for DSA
// 1. Choose a random integer k from the range [1, q-1]
// 2. Compute r = (g^k mod p) mod q
}
// Verify is signature verification for DSA
// 1. Compute w = s^-1 mod q
// 2. Compute u1 = (H(m) * w) mod q
// 3. Compute u2 = (r * w) mod q
// 4. Compute v = ((g^u1 * y^u2) mod p) mod q
// 5. If v == r, the signature is valid
func Verify(m []byte, r, s, p, q, g, y *big.Int) bool {
// 1. Compute w = s^-1 mod q
w := new(big.Int).ModInverse(s, q)
// 2. Compute u1 = (H(m) * w) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
u1 := new(big.Int).Mul(h, w)
u1.Mod(u1, q)
##CHUNK 2
// 5. If v == r, the signature is valid
func Verify(m []byte, r, s, p, q, g, y *big.Int) bool {
// 1. Compute w = s^-1 mod q
w := new(big.Int).ModInverse(s, q)
// 2. Compute u1 = (H(m) * w) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
u1 := new(big.Int).Mul(h, w)
u1.Mod(u1, q)
// 3. Compute u2 = (r * w) mod q
u2 := new(big.Int).Mul(r, w)
u2.Mod(u2, q)
// 4. Compute v = ((g^u1 * y^u2) mod p) mod q
v := new(big.Int).Exp(g, u1, p)
v.Mul(
v,
new(big.Int).Exp(y, u2, p),
)
##CHUNK 3
if err != nil {
panic(err)
}
dsa.privKey = x
// 2. Compute y = g^x mod p
dsa.pubKey = new(big.Int).Exp(dsa.G, x, dsa.P)
}
// Sign is signature generation for DSA
// 1. Choose a random integer k from the range [1, q-1]
// 2. Compute r = (g^k mod p) mod q
}
// Verify is signature verification for DSA
// 1. Compute w = s^-1 mod q
// 2. Compute u1 = (H(m) * w) mod q
// 3. Compute u2 = (r * w) mod q
// 4. Compute v = ((g^u1 * y^u2) mod p) mod q
##CHUNK 4
// 3. Compute u2 = (r * w) mod q
u2 := new(big.Int).Mul(r, w)
u2.Mod(u2, q)
// 4. Compute v = ((g^u1 * y^u2) mod p) mod q
v := new(big.Int).Exp(g, u1, p)
v.Mul(
v,
new(big.Int).Exp(y, u2, p),
)
v.Mod(v, p)
v.Mod(v, q)
// 5. If v == r, the signature is valid
return v.Cmp(r) == 0
}
// GetPublicKey returns the public key (y)
func (dsa *dsa) GetPublicKey() *big.Int {
return dsa.pubKey
##CHUNK 5
dsa.G = g
}
// keyGen is key generation for DSA
// 1. Choose a random integer x from the range [1, q-1]
// 2. Compute y = g^x mod p
func (dsa *dsa) keyGen() {
// 1. Choose a random integer x from the range [1, q-1]
x, err := rand.Int(rand.Reader, new(big.Int).Sub(dsa.Q, big.NewInt(1)))
if err != nil {
panic(err)
}
dsa.privKey = x
// 2. Compute y = g^x mod p
dsa.pubKey = new(big.Int).Exp(dsa.G, x, dsa.P)
}
##CHUNK 6
}
// 4. Choose an integer h randomly from the range [2, p-2]. Commonly, h = 2
// 5. Compute g = h^((p-1)/q) mod p. In case g == 1, increment h until g != 1
pm1 := new(big.Int).Sub(p, one)
for g.Cmp(one) == 0 {
g.Exp(h, new(big.Int).Div(pm1, q), p)
h.Add(h, one)
}
dsa.G = g
}
// keyGen is key generation for DSA
// 1. Choose a random integer x from the range [1, q-1]
// 2. Compute y = g^x mod p
func (dsa *dsa) keyGen() {
// 1. Choose a random integer x from the range [1, q-1]
x, err := rand.Int(rand.Reader, new(big.Int).Sub(dsa.Q, big.NewInt(1)))
##CHUNK 7
}
// Parameter generation for DSA
// 1. FIPS 186-4 specifies that the L and N values must be (1024, 160), (2048, 224), or (3072, 256)
// 2. Choose a N-bit prime q
// 3. Choose a L-bit prime p such that p-1 is a multiple of q
// 4. Choose an integer h randomly from the range [2, p-2]
// 5. Compute g = h^((p-1)/q) mod p
// 6. Return (p, q, g)
func (dsa *dsa) dsaParameterGeneration() {
var err error
p, q, bigInt := new(big.Int), new(big.Int), new(big.Int)
one, g, h := big.NewInt(1), big.NewInt(1), big.NewInt(2)
pBytes := make([]byte, L/8)
// GPLoop is a label for the loop
// We use this loop to change the prime q if we don't find a prime p
GPLoop:
for {
// 2. Choose a N-bit prime q
##CHUNK 8
privKey *big.Int // private key (x)
}
)
// New creates a new DSA instance
func New() *dsa {
d := new(dsa)
d.dsaParameterGeneration()
d.keyGen()
return d
}
// Parameter generation for DSA
// 1. FIPS 186-4 specifies that the L and N values must be (1024, 160), (2048, 224), or (3072, 256)
// 2. Choose a N-bit prime q
// 3. Choose a L-bit prime p such that p-1 is a multiple of q
// 4. Choose an integer h randomly from the range [2, p-2]
// 5. Compute g = h^((p-1)/q) mod p
// 6. Return (p, q, g)
func (dsa *dsa) dsaParameterGeneration() {
##CHUNK 9
var err error
p, q, bigInt := new(big.Int), new(big.Int), new(big.Int)
one, g, h := big.NewInt(1), big.NewInt(1), big.NewInt(2)
pBytes := make([]byte, L/8)
// GPLoop is a label for the loop
// We use this loop to change the prime q if we don't find a prime p
GPLoop:
for {
// 2. Choose a N-bit prime q
q, err = rand.Prime(rand.Reader, N)
if err != nil {
panic(err)
}
for i := 0; i < 4*L; i++ {
// 3. Choose a L-bit prime p such that p-1 is a multiple of q
// In this case we generate a random number of L bits
if _, err := io.ReadFull(rand.Reader, pBytes); err != nil {
panic(err)
##CHUNK 10
bigInt.Sub(bigInt, one)
p.Sub(p, bigInt)
if p.BitLen() < L || !p.ProbablyPrime(numMRTests) { // Check if p is prime and has L bits
continue
}
dsa.P = p
dsa.Q = q
break GPLoop
}
}
// 4. Choose an integer h randomly from the range [2, p-2]. Commonly, h = 2
// 5. Compute g = h^((p-1)/q) mod p. In case g == 1, increment h until g != 1
pm1 := new(big.Int).Sub(p, one)
for g.Cmp(one) == 0 {
g.Exp(h, new(big.Int).Div(pm1, q), p)
h.Add(h, one)
}
|
Go-master
| 19
|
func Verify(m []byte, r, s, p, q, g, y *big.Int) bool {
// 1. Compute w = s^-1 mod q
w := new(big.Int).ModInverse(s, q)
// 2. Compute u1 = (H(m) * w) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
u1 := new(big.Int).Mul(h, w)
u1.Mod(u1, q)
// 3. Compute u2 = (r * w) mod q
u2 := new(big.Int).Mul(r, w)
u2.Mod(u2, q)
// 4. Compute v = ((g^u1 * y^u2) mod p) mod q
v := new(big.Int).Exp(g, u1, p)
v.Mul(
v,
new(big.Int).Exp(y, u2, p),
)
v.Mod(v, p)
v.Mod(v, q)
// 5. If v == r, the signature is valid
return v.Cmp(r) == 0
}
|
func Verify(m []byte, r, s, p, q, g, y *big.Int) bool {
// 1. Compute w = s^-1 mod q
w := new(big.Int).ModInverse(s, q)
// 2. Compute u1 = (H(m) * w) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
u1 := new(big.Int).Mul(h, w)
u1.Mod(u1, q)
// 3. Compute u2 = (r * w) mod q
u2 := new(big.Int).Mul(r, w)
u2.Mod(u2, q)
// 4. Compute v = ((g^u1 * y^u2) mod p) mod q
v := new(big.Int).Exp(g, u1, p)
v.Mul(
v,
new(big.Int).Exp(y, u2, p),
)
v.Mod(v, p)
v.Mod(v, q)
// 5. If v == r, the signature is valid
return v.Cmp(r) == 0
}
|
func Verify(m []byte, r, s, p, q, g, y *big.Int) bool {
// 1. Compute w = s^-1 mod q
w := new(big.Int).ModInverse(s, q)
// 2. Compute u1 = (H(m) * w) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
u1 := new(big.Int).Mul(h, w)
u1.Mod(u1, q)
// 3. Compute u2 = (r * w) mod q
u2 := new(big.Int).Mul(r, w)
u2.Mod(u2, q)
// 4. Compute v = ((g^u1 * y^u2) mod p) mod q
v := new(big.Int).Exp(g, u1, p)
v.Mul(
v,
new(big.Int).Exp(y, u2, p),
)
v.Mod(v, p)
v.Mod(v, q)
// 5. If v == r, the signature is valid
return v.Cmp(r) == 0
}
|
Verify
| 156
| 180
|
cipher/dsa/dsa.go
|
#FILE: Go-master/cipher/rsa/rsa2.go
##CHUNK 1
// returns the RSA object
func New() *rsa {
// The following code generates keys for RSA encryption/decryption
// 1. Choose two large prime numbers, p and q and compute n = p * q
p, q := randomPrime() // p and q stands for prime numbers
modulus := p * q // n stands for common number
// 2. Compute the totient of n, lcm(p-1, q-1)
totient := uint64(lcm.Lcm(int64(p-1), int64(q-1)))
// 3. Choose an integer e such that 1 < e < totient(n) and gcd(e, totient(n)) = 1
publicKey := uint64(2) // e stands for encryption key (public key)
for publicKey < totient {
if gcd.Recursive(int64(publicKey), int64(totient)) == 1 {
break
}
publicKey++
}
// 4. Compute d such that d * e ≡ 1 (mod totient(n))
#CURRENT FILE: Go-master/cipher/dsa/dsa.go
##CHUNK 1
new(big.Int).Add( // (H(m) + x*r)
h,
new(big.Int).Mul(x, r),
),
)
s.Mod(s, q) // mod q
return r, s
}
// Verify is signature verification for DSA
// 1. Compute w = s^-1 mod q
// 2. Compute u1 = (H(m) * w) mod q
// 3. Compute u2 = (r * w) mod q
// 4. Compute v = ((g^u1 * y^u2) mod p) mod q
}
// GetPublicKey returns the public key (y)
func (dsa *dsa) GetPublicKey() *big.Int {
return dsa.pubKey
##CHUNK 2
// Verify is signature verification for DSA
// 1. Compute w = s^-1 mod q
// 2. Compute u1 = (H(m) * w) mod q
// 3. Compute u2 = (r * w) mod q
// 4. Compute v = ((g^u1 * y^u2) mod p) mod q
}
// GetPublicKey returns the public key (y)
func (dsa *dsa) GetPublicKey() *big.Int {
return dsa.pubKey
}
// GetParameters returns the DSA parameters (p, q, g)
func (dsa *dsa) GetParameters() parameters {
return dsa.parameters
}
// GetPrivateKey returns the private Key (x)
func (dsa *dsa) GetPrivateKey() *big.Int {
return dsa.privKey
##CHUNK 3
// 2. Compute r = (g^k mod p) mod q
r = new(big.Int).Exp(g, k, p)
r.Mod(r, q)
// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
s = new(big.Int).ModInverse(k, q) // k^-1 mod q
s.Mul(
s,
new(big.Int).Add( // (H(m) + x*r)
h,
new(big.Int).Mul(x, r),
),
)
s.Mod(s, q) // mod q
return r, s
}
##CHUNK 4
// Sign is signature generation for DSA
// 1. Choose a random integer k from the range [1, q-1]
// 2. Compute r = (g^k mod p) mod q
// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q
func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) {
// 1. Choose a random integer k from the range [1, q-1]
k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1)))
if err != nil {
panic(err)
}
// 2. Compute r = (g^k mod p) mod q
r = new(big.Int).Exp(g, k, p)
r.Mod(r, q)
// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
s = new(big.Int).ModInverse(k, q) // k^-1 mod q
s.Mul(
s,
##CHUNK 5
if err != nil {
panic(err)
}
dsa.privKey = x
// 2. Compute y = g^x mod p
dsa.pubKey = new(big.Int).Exp(dsa.G, x, dsa.P)
}
// Sign is signature generation for DSA
// 1. Choose a random integer k from the range [1, q-1]
// 2. Compute r = (g^k mod p) mod q
// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q
func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) {
// 1. Choose a random integer k from the range [1, q-1]
k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1)))
if err != nil {
panic(err)
}
##CHUNK 6
}
// 4. Choose an integer h randomly from the range [2, p-2]. Commonly, h = 2
// 5. Compute g = h^((p-1)/q) mod p. In case g == 1, increment h until g != 1
pm1 := new(big.Int).Sub(p, one)
for g.Cmp(one) == 0 {
g.Exp(h, new(big.Int).Div(pm1, q), p)
h.Add(h, one)
}
dsa.G = g
}
// keyGen is key generation for DSA
// 1. Choose a random integer x from the range [1, q-1]
// 2. Compute y = g^x mod p
func (dsa *dsa) keyGen() {
// 1. Choose a random integer x from the range [1, q-1]
x, err := rand.Int(rand.Reader, new(big.Int).Sub(dsa.Q, big.NewInt(1)))
##CHUNK 7
}
// Parameter generation for DSA
// 1. FIPS 186-4 specifies that the L and N values must be (1024, 160), (2048, 224), or (3072, 256)
// 2. Choose a N-bit prime q
// 3. Choose a L-bit prime p such that p-1 is a multiple of q
// 4. Choose an integer h randomly from the range [2, p-2]
// 5. Compute g = h^((p-1)/q) mod p
// 6. Return (p, q, g)
func (dsa *dsa) dsaParameterGeneration() {
var err error
p, q, bigInt := new(big.Int), new(big.Int), new(big.Int)
one, g, h := big.NewInt(1), big.NewInt(1), big.NewInt(2)
pBytes := make([]byte, L/8)
// GPLoop is a label for the loop
// We use this loop to change the prime q if we don't find a prime p
GPLoop:
for {
// 2. Choose a N-bit prime q
##CHUNK 8
privKey *big.Int // private key (x)
}
)
// New creates a new DSA instance
func New() *dsa {
d := new(dsa)
d.dsaParameterGeneration()
d.keyGen()
return d
}
// Parameter generation for DSA
// 1. FIPS 186-4 specifies that the L and N values must be (1024, 160), (2048, 224), or (3072, 256)
// 2. Choose a N-bit prime q
// 3. Choose a L-bit prime p such that p-1 is a multiple of q
// 4. Choose an integer h randomly from the range [2, p-2]
// 5. Compute g = h^((p-1)/q) mod p
// 6. Return (p, q, g)
func (dsa *dsa) dsaParameterGeneration() {
##CHUNK 9
bigInt.Sub(bigInt, one)
p.Sub(p, bigInt)
if p.BitLen() < L || !p.ProbablyPrime(numMRTests) { // Check if p is prime and has L bits
continue
}
dsa.P = p
dsa.Q = q
break GPLoop
}
}
// 4. Choose an integer h randomly from the range [2, p-2]. Commonly, h = 2
// 5. Compute g = h^((p-1)/q) mod p. In case g == 1, increment h until g != 1
pm1 := new(big.Int).Sub(p, one)
for g.Cmp(one) == 0 {
g.Exp(h, new(big.Int).Div(pm1, q), p)
h.Add(h, one)
}
|
Go-master
| 20
|
func Encrypt(text string, rails int) string {
if rails == 1 {
return text
}
// Create a matrix for the rail fence pattern
matrix := make([][]rune, rails)
for i := range matrix {
matrix[i] = make([]rune, len(text))
}
// Fill the matrix
dirDown := false
row, col := 0, 0
for _, char := range text {
if row == 0 || row == rails-1 {
dirDown = !dirDown
}
matrix[row][col] = char
col++
if dirDown {
row++
} else {
row--
}
}
var result strings.Builder
for _, line := range matrix {
for _, char := range line {
if char != 0 {
result.WriteRune(char)
}
}
}
return result.String()
}
|
func Encrypt(text string, rails int) string {
if rails == 1 {
return text
}
// Create a matrix for the rail fence pattern
matrix := make([][]rune, rails)
for i := range matrix {
matrix[i] = make([]rune, len(text))
}
// Fill the matrix
dirDown := false
row, col := 0, 0
for _, char := range text {
if row == 0 || row == rails-1 {
dirDown = !dirDown
}
matrix[row][col] = char
col++
if dirDown {
row++
} else {
row--
}
}
var result strings.Builder
for _, line := range matrix {
for _, char := range line {
if char != 0 {
result.WriteRune(char)
}
}
}
return result.String()
}
|
func Encrypt(text string, rails int) string {
if rails == 1 {
return text
}
// Create a matrix for the rail fence pattern
matrix := make([][]rune, rails)
for i := range matrix {
matrix[i] = make([]rune, len(text))
}
// Fill the matrix
dirDown := false
row, col := 0, 0
for _, char := range text {
if row == 0 || row == rails-1 {
dirDown = !dirDown
}
matrix[row][col] = char
col++
if dirDown {
row++
} else {
row--
}
}
var result strings.Builder
for _, line := range matrix {
for _, char := range line {
if char != 0 {
result.WriteRune(char)
}
}
}
return result.String()
}
|
Encrypt
| 12
| 48
|
cipher/railfence/railfence.go
|
#FILE: Go-master/math/matrix/isvalid.go
##CHUNK 1
package matrix
import "github.com/TheAlgorithms/Go/constraints"
// IsValid checks if the input matrix has consistent row lengths.
func IsValid[T constraints.Integer](elements [][]T) bool {
if len(elements) == 0 {
return true
}
columns := len(elements[0])
for _, row := range elements {
if len(row) != columns {
return false
}
}
return true
}
#FILE: Go-master/conversion/hexadecimaltodecimal.go
##CHUNK 1
// Check if the string has a valid hexadecimal prefix
if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") {
hexStr = hexStr[2:]
}
// Validate the hexadecimal string
if !isValidHexadecimal(hexStr) {
return 0, fmt.Errorf("invalid hexadecimal string")
}
var decimalValue int64
for _, char := range hexStr {
var digit int64
if char >= '0' && char <= '9' {
digit = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
digit = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
digit = int64(char - 'a' + 10)
} else {
##CHUNK 2
var decimalValue int64
for _, char := range hexStr {
var digit int64
if char >= '0' && char <= '9' {
digit = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
digit = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
digit = int64(char - 'a' + 10)
} else {
return 0, fmt.Errorf("invalid character in hexadecimal string: %c", char)
}
decimalValue = decimalValue*16 + digit
}
return decimalValue, nil
}
#FILE: Go-master/conversion/hexadecimaltobinary.go
##CHUNK 1
char := hex[i]
var value int64
if char >= '0' && char <= '9' {
value = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
value = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
value = int64(char - 'a' + 10)
} else {
return "", errors.New("invalid character in hexadecimal string: " + string(char))
}
decimal = decimal*16 + value
}
// Convert the integer to a binary string without using predefined functions
var binaryBuilder strings.Builder
if decimal == 0 {
binaryBuilder.WriteString("0")
} else {
for decimal > 0 {
#FILE: Go-master/math/matrix/matrix.go
##CHUNK 1
columns := len(elements[0])
matrix := Matrix[T]{
elements: make([][]T, rows),
rows: rows, // Set the rows field
columns: columns, // Set the columns field
}
for i := range matrix.elements {
matrix.elements[i] = make([]T, columns)
copy(matrix.elements[i], elements[i])
}
return matrix, nil
}
func (m Matrix[T]) Get(row, col int) (T, error) {
if row < 0 || row >= m.rows || col < 0 || col >= m.columns {
var zeroVal T
return zeroVal, errors.New("index out of range")
}
#FILE: Go-master/math/matrix/isvalid_test.go
##CHUNK 1
// Test case 3: Invalid matrix with inconsistent row lengths
invalidMatrix := [][]int{
{1, 2, 3},
{4, 5},
{6, 7, 8},
}
result3 := matrix.IsValid(invalidMatrix)
if result3 {
t.Errorf("IsValid(invalidMatrix) returned true, expected false (invalid matrix with inconsistent row lengths)")
}
}
func BenchmarkIsValid(b *testing.B) {
// Create a sample matrix for benchmarking
rows := 100
columns := 100
elements := make([][]int, rows)
for i := range elements {
#FILE: Go-master/cipher/transposition/transposition.go
##CHUNK 1
}
func Encrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
keyLength := len(key)
textLength := len(text)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
if text[len(text)-1] == placeholder {
return nil, fmt.Errorf("%w: cannot encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder)
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
#FILE: Go-master/strings/manacher/longestpalindrome.go
##CHUNK 1
}
result.WriteRune('#')
}
return result.String()
}
func nextBoundary(s string) string {
var result strings.Builder
for _, ch := range s {
if ch != '#' {
result.WriteRune(ch)
}
}
return result.String()
}
func LongestPalindrome(s string) string {
boundaries := makeBoundaries(s)
b := make([]int, len(boundaries))
k := 0
#FILE: Go-master/math/matrix/determinant_test.go
##CHUNK 1
if determinant != expectedValue {
t.Errorf("Determinant of the default matrix with an initial value 0 was %d; wanted %d.", initialValue, expectedValue)
}
}
// Benchmark a 3 by 3 matrix for computational throughput
func BenchmarkSmallMatrixDeterminant(b *testing.B) {
// Create a 3 by 3 matrix for benchmarking
rows := 3
columns := 3
initialValue := 0
matrix := matrix.New(rows, columns, initialValue)
for i := 0; i < b.N; i++ {
_, _ = matrix.Determinant()
}
}
// Benchmark a 10 by 10 matrix for computational throughput.
func BenchmarkMatrixDeterminant(b *testing.B) {
#CURRENT FILE: Go-master/cipher/railfence/railfence.go
##CHUNK 1
)
}
func Decrypt(cipherText string, rails int) string {
if rails == 1 || rails >= len(cipherText) {
return cipherText
}
// Placeholder for the decrypted message
decrypted := make([]rune, len(cipherText))
// Calculate the zigzag pattern and place characters accordingly
index := 0
for rail := 0; rail < rails; rail++ {
position := rail
down := true // Direction flag
for position < len(cipherText) {
decrypted[position] = rune(cipherText[index])
index++
// Determine the next position based on the current rail and direction
|
Go-master
| 21
|
func Decrypt(cipherText string, rails int) string {
if rails == 1 || rails >= len(cipherText) {
return cipherText
}
// Placeholder for the decrypted message
decrypted := make([]rune, len(cipherText))
// Calculate the zigzag pattern and place characters accordingly
index := 0
for rail := 0; rail < rails; rail++ {
position := rail
down := true // Direction flag
for position < len(cipherText) {
decrypted[position] = rune(cipherText[index])
index++
// Determine the next position based on the current rail and direction
if rail == 0 || rail == rails-1 {
position += 2 * (rails - 1)
} else if down {
position += 2 * (rails - 1 - rail)
down = false
} else {
position += 2 * rail
down = true
}
}
}
return string(decrypted)
}
|
func Decrypt(cipherText string, rails int) string {
if rails == 1 || rails >= len(cipherText) {
return cipherText
}
// Placeholder for the decrypted message
decrypted := make([]rune, len(cipherText))
// Calculate the zigzag pattern and place characters accordingly
index := 0
for rail := 0; rail < rails; rail++ {
position := rail
down := true // Direction flag
for position < len(cipherText) {
decrypted[position] = rune(cipherText[index])
index++
// Determine the next position based on the current rail and direction
if rail == 0 || rail == rails-1 {
position += 2 * (rails - 1)
} else if down {
position += 2 * (rails - 1 - rail)
down = false
} else {
position += 2 * rail
down = true
}
}
}
return string(decrypted)
}
|
func Decrypt(cipherText string, rails int) string {
if rails == 1 || rails >= len(cipherText) {
return cipherText
}
// Placeholder for the decrypted message
decrypted := make([]rune, len(cipherText))
// Calculate the zigzag pattern and place characters accordingly
index := 0
for rail := 0; rail < rails; rail++ {
position := rail
down := true // Direction flag
for position < len(cipherText) {
decrypted[position] = rune(cipherText[index])
index++
// Determine the next position based on the current rail and direction
if rail == 0 || rail == rails-1 {
position += 2 * (rails - 1)
} else if down {
position += 2 * (rails - 1 - rail)
down = false
} else {
position += 2 * rail
down = true
}
}
}
return string(decrypted)
}
|
Decrypt
| 49
| 80
|
cipher/railfence/railfence.go
|
#FILE: Go-master/structure/linkedlist/singlylinkedlist.go
##CHUNK 1
if ll.Head.Next == nil {
return ll.DelAtBeg()
}
cur := ll.Head
for ; cur.Next.Next != nil; cur = cur.Next {
}
retval := cur.Next.Val
cur.Next = nil
ll.length--
return retval, true
}
// DelByPos deletes the node at the middle based on position in the list
// and returns its value. Returns false if the list is empty or length is not more than given position
func (ll *Singly[T]) DelByPos(pos int) (T, bool) {
switch {
#FILE: Go-master/math/prime/primecheck.go
##CHUNK 1
return false
}
// 2 and 3 are prime
if n < 4 {
return true
}
// all numbers divisible by 2 except 2 are not prime
if n%2 == 0 {
return false
}
for i := int64(3); i*i <= n; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
#FILE: Go-master/structure/linkedlist/cyclic.go
##CHUNK 1
if places < 0 {
multiple := cl.Size - 1 - places/cl.Size
places += multiple * cl.Size
}
places %= cl.Size
if places > cl.Size/2 {
places = cl.Size - places
for i := 0; i < places; i++ {
cl.Head = cl.Head.Prev
}
} else if places == 0 {
return
} else {
for i := 0; i < places; i++ {
cl.Head = cl.Head.Next
}
}
}
#FILE: Go-master/structure/linkedlist/doubly.go
##CHUNK 1
func (ll *Doubly[T]) DelAtEnd() (T, bool) {
// no item
if ll.Head.Prev == nil {
var r T
return r, false
}
n := ll.Head.Prev
val := n.Val
ll.Remove(n)
return val, true
}
// DelByPos deletes node at middle based on position in list
// and returns value. If empty or position of node is less than linked list length, returns false
func (ll *Doubly[T]) DelByPos(pos int) (T, bool) {
switch {
case ll.Head == nil:
var r T
#FILE: Go-master/structure/fenwicktree/fenwicktree.go
##CHUNK 1
newArray := []int{0} // Appending a 0 to the beginning as this implementation uses 1 based indexing
fenwickTree := &FenwickTree{
n: len(array),
array: append(newArray, array...),
bit: append(newArray, array...),
}
for i := 1; i < fenwickTree.n; i++ {
nextPos := i + (i & -i)
if nextPos <= fenwickTree.n {
fenwickTree.bit[nextPos] += fenwickTree.bit[i]
}
}
return fenwickTree
}
// PrefixSum returns the sum of the prefix ending at position pos.
func (f *FenwickTree) PrefixSum(pos int) int {
if pos > f.n {
return 0
}
##CHUNK 2
prefixSum := 0
for i := pos; i > 0; i -= (i & -i) {
prefixSum += f.bit[i]
}
return prefixSum
}
// RangeSum returns the sum of the elements in the range l to r
// both inclusive.
func (f *FenwickTree) RangeSum(l int, r int) int {
return f.PrefixSum(r) - f.PrefixSum(l-1)
}
// Add Adds value to the element at position pos of the array
// and recomputes the range sums.
func (f *FenwickTree) Add(pos int, value int) {
for i := pos; i <= f.n; i += (i & -i) {
f.bit[i] += value
}
}
#FILE: Go-master/strings/ahocorasick/advancedahocorasick.go
##CHUNK 1
s[i] = -1
for current := 1; current < len(stateIsTerminal); current++ {
o, parent := GetParent(current, acTrie)
down := s[parent]
for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {
down = s[down]
}
if StateExists(down, acToReturn) {
s[current] = GetTransition(down, o, acToReturn)
if stateIsTerminal[s[current]] {
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in p
for j := range a {
if GetTransition(i, a[j], acToReturn) == -1 {
#FILE: Go-master/sort/timsort.go
##CHUNK 1
}
Insertion(data[lower:upper])
}
}
// mergeRuns merge sorts all the data runs into a single sorted data slice.
func mergeRuns[T constraints.Ordered](data []T, runSize int) {
for size := runSize; size < len(data); size *= 2 {
for lowerBound := 0; lowerBound < len(data); lowerBound += size * 2 {
middleBound := lowerBound + size - 1
upperBound := lowerBound + 2*size - 1
if len(data)-1 < upperBound {
upperBound = len(data) - 1
}
mergeRun(data, lowerBound, middleBound, upperBound)
}
}
}
#CURRENT FILE: Go-master/cipher/railfence/railfence.go
##CHUNK 1
)
func Encrypt(text string, rails int) string {
if rails == 1 {
return text
}
// Create a matrix for the rail fence pattern
matrix := make([][]rune, rails)
for i := range matrix {
matrix[i] = make([]rune, len(text))
}
// Fill the matrix
dirDown := false
row, col := 0, 0
for _, char := range text {
if row == 0 || row == rails-1 {
dirDown = !dirDown
}
##CHUNK 2
// railfence.go
// description: Rail Fence Cipher
// details: The rail fence cipher is a an encryption algorithm that uses a rail fence pattern to encode a message. it is a type of transposition cipher that rearranges the characters of the plaintext to form the ciphertext.
// time complexity: O(n)
// space complexity: O(n)
// ref: https://en.wikipedia.org/wiki/Rail_fence_cipher
package railfence
import (
"strings"
)
func Encrypt(text string, rails int) string {
if rails == 1 {
return text
}
// Create a matrix for the rail fence pattern
matrix := make([][]rune, rails)
for i := range matrix {
|
Go-master
| 22
|
func Encrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
keyLength := len(key)
textLength := len(text)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
if text[len(text)-1] == placeholder {
return nil, fmt.Errorf("%w: cannot encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder)
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
textLength = len(text)
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[key[j]-1] = text[i+j]
}
result = append(result, transposition...)
}
return result, nil
}
|
func Encrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
keyLength := len(key)
textLength := len(text)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
if text[len(text)-1] == placeholder {
return nil, fmt.Errorf("%w: cannot encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder)
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
textLength = len(text)
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[key[j]-1] = text[i+j]
}
result = append(result, transposition...)
}
return result, nil
}
|
func Encrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
keyLength := len(key)
textLength := len(text)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
if text[len(text)-1] == placeholder {
return nil, fmt.Errorf("%w: cannot encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder)
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
textLength = len(text)
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[key[j]-1] = text[i+j]
}
result = append(result, transposition...)
}
return result, nil
}
|
Encrypt
| 52
| 80
|
cipher/transposition/transposition.go
|
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
#FILE: Go-master/dynamic/abbreviation.go
##CHUNK 1
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] = true
}
if string(a[i]) == strings.ToLower(string(a[i])) {
dp[i+1][j] = true
}
}
}
}
return dp[len(a)][len(b)]
}
#FILE: Go-master/dynamic/longestcommonsubsequence.go
##CHUNK 1
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i := 0; i <= aLen; i++ {
for j := 0; j <= bLen; j++ {
if i == 0 || j == 0 {
lcs[i][j] = 0
} else if aRunes[i-1] == bRunes[j-1] {
lcs[i][j] = lcs[i-1][j-1] + 1
} else {
lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])
}
}
}
// returning the length of longest common subsequence
return lcs[aLen][bLen]
}
#FILE: Go-master/math/factorial/factorial.go
##CHUNK 1
if n < 0 {
return 0, ErrNegativeArgument
}
result := 1
for i := 2; i <= n; i++ {
result *= i
}
return result, nil
}
// Recursive This function recursively computes the factorial of a number
func Recursive(n int) (int, error) {
if n < 0 {
return 0, ErrNegativeArgument
}
if n <= 1 {
return 1, nil
}
prev, _ := Recursive(n - 1)
return n * prev, nil
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
#FILE: Go-master/graph/floydwarshall.go
##CHUNK 1
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
numVertices := len(graph)
// Initializing result matrix and filling it up with same values as given graph
result := make(WeightedGraph, numVertices)
for i := 0; i < numVertices; i++ {
result[i] = make([]float64, numVertices)
for j := 0; j < numVertices; j++ {
result[i][j] = graph[i][j]
}
}
#CURRENT FILE: Go-master/cipher/transposition/transposition.go
##CHUNK 1
}
}
func Decrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
textLength := len(text)
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
keyLength := len(key)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
##CHUNK 2
if keyLength <= 0 {
return nil, ErrKeyMissing
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[j] = text[i+key[j]-1]
}
result = append(result, transposition...)
}
result = []rune(strings.TrimRight(string(result), string(placeholder)))
return result, nil
}
##CHUNK 3
}
func getIndex(wordSet []rune, subString rune) int {
n := len(wordSet)
for i := 0; i < n; i++ {
if wordSet[i] == subString {
return i
}
}
return 0
}
}
func Decrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
textLength := len(text)
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
keyLength := len(key)
|
Go-master
| 23
|
func Decrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
textLength := len(text)
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
keyLength := len(key)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[j] = text[i+key[j]-1]
}
result = append(result, transposition...)
}
result = []rune(strings.TrimRight(string(result), string(placeholder)))
return result, nil
}
|
func Decrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
textLength := len(text)
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
keyLength := len(key)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[j] = text[i+key[j]-1]
}
result = append(result, transposition...)
}
result = []rune(strings.TrimRight(string(result), string(placeholder)))
return result, nil
}
|
func Decrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
textLength := len(text)
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
keyLength := len(key)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[j] = text[i+key[j]-1]
}
result = append(result, transposition...)
}
result = []rune(strings.TrimRight(string(result), string(placeholder)))
return result, nil
}
|
Decrypt
| 82
| 106
|
cipher/transposition/transposition.go
|
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/math/factorial/factorial.go
##CHUNK 1
if n < 0 {
return 0, ErrNegativeArgument
}
result := 1
for i := 2; i <= n; i++ {
result *= i
}
return result, nil
}
// Recursive This function recursively computes the factorial of a number
func Recursive(n int) (int, error) {
if n < 0 {
return 0, ErrNegativeArgument
}
if n <= 1 {
return 1, nil
}
prev, _ := Recursive(n - 1)
return n * prev, nil
#FILE: Go-master/graph/floydwarshall.go
##CHUNK 1
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
numVertices := len(graph)
// Initializing result matrix and filling it up with same values as given graph
result := make(WeightedGraph, numVertices)
for i := 0; i < numVertices; i++ {
result[i] = make([]float64, numVertices)
for j := 0; j < numVertices; j++ {
result[i][j] = graph[i][j]
}
}
##CHUNK 2
// Initializing result matrix and filling it up with same values as given graph
result := make(WeightedGraph, numVertices)
for i := 0; i < numVertices; i++ {
result[i] = make([]float64, numVertices)
for j := 0; j < numVertices; j++ {
result[i][j] = graph[i][j]
}
}
// Running over the result matrix and following the algorithm
for k := 0; k < numVertices; k++ {
for i := 0; i < numVertices; i++ {
for j := 0; j < numVertices; j++ {
// If there is a less costly path from i to j node, remembering it
if result[i][j] > result[i][k]+result[k][j] {
result[i][j] = result[i][k] + result[k][j]
}
}
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
#CURRENT FILE: Go-master/cipher/transposition/transposition.go
##CHUNK 1
return nil, ErrNoTextToEncrypt
}
if text[len(text)-1] == placeholder {
return nil, fmt.Errorf("%w: cannot encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder)
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
textLength = len(text)
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[key[j]-1] = text[i+j]
}
result = append(result, transposition...)
}
return result, nil
##CHUNK 2
}
func Encrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
keyLength := len(key)
textLength := len(text)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
if text[len(text)-1] == placeholder {
return nil, fmt.Errorf("%w: cannot encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder)
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
##CHUNK 3
textLength = len(text)
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[key[j]-1] = text[i+j]
}
result = append(result, transposition...)
}
return result, nil
}
}
##CHUNK 4
}
func getIndex(wordSet []rune, subString rune) int {
n := len(wordSet)
for i := 0; i < n; i++ {
if wordSet[i] == subString {
return i
}
}
return 0
}
func Encrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
keyLength := len(key)
textLength := len(text)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
if textLength <= 0 {
|
Go-master
| 24
|
func NewPolybius(key string, size int, chars string) (*Polybius, error) {
if size < 0 {
return nil, fmt.Errorf("provided size %d cannot be negative", size)
}
key = strings.ToUpper(key)
if size > len(chars) {
return nil, fmt.Errorf("provided size %d is too small to use to slice string %q of len %d", size, chars, len(chars))
}
for _, r := range chars {
if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') {
return nil, fmt.Errorf("provided string %q should only contain latin characters", chars)
}
}
chars = strings.ToUpper(chars)[:size]
for i, r := range chars {
if strings.ContainsRune(chars[i+1:], r) {
return nil, fmt.Errorf("%q contains same character %q", chars[i+1:], r)
}
}
if len(key) != size*size {
return nil, fmt.Errorf("len(key): %d must be as long as size squared: %d", len(key), size*size)
}
return &Polybius{size, chars, key}, nil
}
|
func NewPolybius(key string, size int, chars string) (*Polybius, error) {
if size < 0 {
return nil, fmt.Errorf("provided size %d cannot be negative", size)
}
key = strings.ToUpper(key)
if size > len(chars) {
return nil, fmt.Errorf("provided size %d is too small to use to slice string %q of len %d", size, chars, len(chars))
}
for _, r := range chars {
if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') {
return nil, fmt.Errorf("provided string %q should only contain latin characters", chars)
}
}
chars = strings.ToUpper(chars)[:size]
for i, r := range chars {
if strings.ContainsRune(chars[i+1:], r) {
return nil, fmt.Errorf("%q contains same character %q", chars[i+1:], r)
}
}
if len(key) != size*size {
return nil, fmt.Errorf("len(key): %d must be as long as size squared: %d", len(key), size*size)
}
return &Polybius{size, chars, key}, nil
}
|
func NewPolybius(key string, size int, chars string) (*Polybius, error) {
if size < 0 {
return nil, fmt.Errorf("provided size %d cannot be negative", size)
}
key = strings.ToUpper(key)
if size > len(chars) {
return nil, fmt.Errorf("provided size %d is too small to use to slice string %q of len %d", size, chars, len(chars))
}
for _, r := range chars {
if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') {
return nil, fmt.Errorf("provided string %q should only contain latin characters", chars)
}
}
chars = strings.ToUpper(chars)[:size]
for i, r := range chars {
if strings.ContainsRune(chars[i+1:], r) {
return nil, fmt.Errorf("%q contains same character %q", chars[i+1:], r)
}
}
if len(key) != size*size {
return nil, fmt.Errorf("len(key): %d must be as long as size squared: %d", len(key), size*size)
}
return &Polybius{size, chars, key}, nil
}
|
NewPolybius
| 24
| 48
|
cipher/polybius/polybius.go
|
#FILE: Go-master/math/factorial/factorial.go
##CHUNK 1
if n == 1 || n == 2 {
return n, nil
}
return prodTree(2, n), nil
}
func prodTree(l int, r int) int {
if l > r {
return 1
}
if l == r {
return l
}
if r-l == 1 {
return l * r
}
m := (l + r) / 2
return prodTree(l, m) * prodTree(m+1, r)
}
#FILE: Go-master/cipher/polybius/polybius_test.go
##CHUNK 1
}
}
func FuzzPolybius(f *testing.F) {
const (
size = 5
characters = "HogeF"
key = "abcdefghijklmnopqrstuvwxy"
)
f.Add(size, characters, key)
f.Fuzz(func(t *testing.T, size int, characters, key string) {
p, err := NewPolybius(key, size, characters)
switch {
case err == nil:
case strings.Contains(err.Error(), "cannot be negative"),
strings.Contains(err.Error(), "is too small"),
strings.Contains(err.Error(), "should only contain latin characters"),
strings.Contains(err.Error(), "contains same character"),
strings.Contains(err.Error(), "must be as long as size squared"):
return
##CHUNK 2
{
name: "truncate characters", size: 5, characters: "HogeFuga", key: "abcdefghijklmnopqrstuvwxy", wantErr: "",
},
{
name: "invalid key", size: 5, characters: "HogeFuga", key: "abcdefghi", wantErr: "len(key): 9 must be as long as size squared: 25",
},
{
name: "invalid characters", size: 5, characters: "HogeH", key: "abcdefghijklmnopqrstuvwxy", wantErr: "\"OGEH\" contains same character 'H'",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, err := NewPolybius(tc.key, tc.size, tc.characters)
if err != nil && err.Error() != tc.wantErr {
t.Errorf("failed NewPolybius: %v", err)
}
})
}
}
#FILE: Go-master/cipher/transposition/transposition.go
##CHUNK 1
}
func Encrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
keyLength := len(key)
textLength := len(text)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
if text[len(text)-1] == placeholder {
return nil, fmt.Errorf("%w: cannot encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder)
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
#FILE: Go-master/structure/circularqueue/circularqueuearray.go
##CHUNK 1
items []T
front int
rear int
size int
}
// NewCircularQueue creates a new CircularQueue with the given size.
// Returns an error if the size is less than or equal to 0.
func NewCircularQueue[T any](size int) (*CircularQueue[T], error) {
if size <= 0 {
return nil, errors.New("size must be greater than 0")
}
return &CircularQueue[T]{
items: make([]T, size),
front: -1,
rear: -1,
size: size,
}, nil
}
#FILE: Go-master/structure/tree/btree_test.go
##CHUNK 1
}
}
}
func TestBTreeDecreasing(t *testing.T) {
maxKeysCases := []int{4, 16}
sizes := []int{100, 1000}
for _, maxKeys := range maxKeysCases {
for _, size := range sizes {
tree := bt.NewBTree[int](maxKeys)
if tree.Search(0) {
t.Errorf("Tree expected to contain 0")
}
for i := size - 1; i >= 0; i-- {
tree.Insert(i)
}
for i := 0; i < size; i++ {
if !tree.Search(i) {
t.Errorf("Tree expected to contain %d", i)
}
##CHUNK 2
tree.Delete(i)
}
for i := 0; i < size; i++ {
hasKey := tree.Search(i)
if i%5 == 0 && hasKey {
t.Errorf("Tree not expected to contain %d", i)
} else if i%5 != 0 && !hasKey {
t.Errorf("Tree expected to contain %d", i)
}
}
}
}
}
func TestBTreeDecreasing(t *testing.T) {
maxKeysCases := []int{4, 16}
sizes := []int{100, 1000}
for _, maxKeys := range maxKeysCases {
for _, size := range sizes {
tree := bt.NewBTree[int](maxKeys)
##CHUNK 3
if i%5 == 0 && hasKey {
t.Errorf("Tree not expected to contain %d", i)
} else if i%5 != 0 && !hasKey {
t.Errorf("Tree expected to contain %d", i)
}
}
}
}
}
func TestBTreeRandom(t *testing.T) {
maxKeysCases := []int{4, 16}
sizes := []int{100, 0xBA5, 0xF00}
for _, maxKeys := range maxKeysCases {
for _, size := range sizes {
rnd := rand.New(rand.NewSource(0))
tree := bt.NewBTree[int](maxKeys)
nums := rnd.Perm(size)
if tree.Search(0) {
t.Errorf("Tree expected to contain 0")
#CURRENT FILE: Go-master/cipher/polybius/polybius.go
##CHUNK 1
}
func (p *Polybius) encipher(char rune) (string, error) {
index := strings.IndexRune(p.key, char)
if index < 0 {
return "", fmt.Errorf("%q does not exist in keys", char)
}
row := index / p.size
col := index % p.size
chars := []rune(p.characters)
return string([]rune{chars[row], chars[col]}), nil
}
func (p *Polybius) decipher(chars []rune) (string, error) {
if len(chars) != 2 {
return "", fmt.Errorf("the size of \"chars\" must be even")
}
row := strings.IndexRune(p.characters, chars[0])
if row < 0 {
return "", fmt.Errorf("%c does not exist in characters", chars[0])
##CHUNK 2
return string([]rune{chars[row], chars[col]}), nil
}
func (p *Polybius) decipher(chars []rune) (string, error) {
if len(chars) != 2 {
return "", fmt.Errorf("the size of \"chars\" must be even")
}
row := strings.IndexRune(p.characters, chars[0])
if row < 0 {
return "", fmt.Errorf("%c does not exist in characters", chars[0])
}
col := strings.IndexRune(p.characters, chars[1])
if col < 0 {
return "", fmt.Errorf("%c does not exist in characters", chars[1])
}
return string(p.key[row*p.size+col]), nil
}
|
Go-master
| 25
|
func EggDropping(eggs, floors int) int {
// Edge case: If there are no floors, no attempts needed
if floors == 0 {
return 0
}
// Edge case: If there is one floor, one attempt needed
if floors == 1 {
return 1
}
// Edge case: If there is one egg, need to test all floors one by one
if eggs == 1 {
return floors
}
// Initialize DP table
dp := make([][]int, eggs+1)
for i := range dp {
dp[i] = make([]int, floors+1)
}
// Fill the DP table for 1 egg
for j := 1; j <= floors; j++ {
dp[1][j] = j
}
// Fill the DP table for more than 1 egg
for i := 2; i <= eggs; i++ {
for j := 2; j <= floors; j++ {
dp[i][j] = int(^uint(0) >> 1) // initialize with a large number
for x := 1; x <= j; x++ {
// Recurrence relation to fill the DP table
res := max.Int(dp[i-1][x-1], dp[i][j-x]) + 1
dp[i][j] = min.Int(dp[i][j], res)
}
}
}
return dp[eggs][floors]
}
|
func EggDropping(eggs, floors int) int {
// Edge case: If there are no floors, no attempts needed
if floors == 0 {
return 0
}
// Edge case: If there is one floor, one attempt needed
if floors == 1 {
return 1
}
// Edge case: If there is one egg, need to test all floors one by one
if eggs == 1 {
return floors
}
// Initialize DP table
dp := make([][]int, eggs+1)
for i := range dp {
dp[i] = make([]int, floors+1)
}
// Fill the DP table for 1 egg
for j := 1; j <= floors; j++ {
dp[1][j] = j
}
// Fill the DP table for more than 1 egg
for i := 2; i <= eggs; i++ {
for j := 2; j <= floors; j++ {
dp[i][j] = int(^uint(0) >> 1) // initialize with a large number
for x := 1; x <= j; x++ {
// Recurrence relation to fill the DP table
res := max.Int(dp[i-1][x-1], dp[i][j-x]) + 1
dp[i][j] = min.Int(dp[i][j], res)
}
}
}
return dp[eggs][floors]
}
|
func EggDropping(eggs, floors int) int {
// Edge case: If there are no floors, no attempts needed
if floors == 0 {
return 0
}
// Edge case: If there is one floor, one attempt needed
if floors == 1 {
return 1
}
// Edge case: If there is one egg, need to test all floors one by one
if eggs == 1 {
return floors
}
// Initialize DP table
dp := make([][]int, eggs+1)
for i := range dp {
dp[i] = make([]int, floors+1)
}
// Fill the DP table for 1 egg
for j := 1; j <= floors; j++ {
dp[1][j] = j
}
// Fill the DP table for more than 1 egg
for i := 2; i <= eggs; i++ {
for j := 2; j <= floors; j++ {
dp[i][j] = int(^uint(0) >> 1) // initialize with a large number
for x := 1; x <= j; x++ {
// Recurrence relation to fill the DP table
res := max.Int(dp[i-1][x-1], dp[i][j-x]) + 1
dp[i][j] = min.Int(dp[i][j], res)
}
}
}
return dp[eggs][floors]
}
|
EggDropping
| 9
| 46
|
dynamic/eggdropping.go
|
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
##CHUNK 2
}
// EditDistanceDP is an optimised implementation which builds on the ideas of the recursive implementation.
// We use dynamic programming to compute the DP table where dp[i][j] denotes the edit distance value
// of first[0..i-1] and second[0..j-1]. Time complexity is O(m * n) where m and n are lengths of the strings,
// first and second respectively.
func EditDistanceDP(first string, second string) int {
m := len(first)
n := len(second)
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
#FILE: Go-master/dynamic/optimalbst.go
##CHUNK 1
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value
sum := sum(freq, i, j)
// Try every key as root and compute cost
for k := i; k <= j; k++ {
// Left cost: dp[i][k-1] is valid only if k > i
var leftCost int
if k > i {
leftCost = dp[i][k-1]
##CHUNK 2
package dynamic
import "github.com/TheAlgorithms/Go/math/min"
// OptimalBST returns the minimum cost of constructing a Binary Search Tree
func OptimalBST(keys []int, freq []int, n int) int {
// Initialize DP table with size n x n
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/matrixmultiplication.go
##CHUNK 1
}
return q
}
// MatrixChainDp function
func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
#FILE: Go-master/dynamic/wildcardmatching.go
##CHUNK 1
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
#FILE: Go-master/dynamic/binomialcoefficient.go
##CHUNK 1
// }
// }
// Bin2 function
func Bin2(n int, k int) int {
var i, j int
B := make([][]int, (n + 1))
for i := range B {
B[i] = make([]int, k+1)
}
for i = 0; i <= n; i++ {
for j = 0; j <= min.Int(i, k); j++ {
if j == 0 || j == i {
B[i][j] = 1
} else {
B[i][j] = B[i-1][j-1] + B[i-1][j]
}
}
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
#CURRENT FILE: Go-master/dynamic/eggdropping.go
|
Go-master
| 26
|
func MaxCoins(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
nums = append([]int{1}, nums...)
nums = append(nums, 1)
dp := make([][]int, n+2)
for i := range dp {
dp[i] = make([]int, n+2)
}
for length := 1; length <= n; length++ {
for left := 1; left+length-1 <= n; left++ {
right := left + length - 1
for k := left; k <= right; k++ {
coins := nums[left-1] * nums[k] * nums[right+1]
dp[left][right] = max.Int(dp[left][right], dp[left][k-1]+dp[k+1][right]+coins)
}
}
}
return dp[1][n]
}
|
func MaxCoins(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
nums = append([]int{1}, nums...)
nums = append(nums, 1)
dp := make([][]int, n+2)
for i := range dp {
dp[i] = make([]int, n+2)
}
for length := 1; length <= n; length++ {
for left := 1; left+length-1 <= n; left++ {
right := left + length - 1
for k := left; k <= right; k++ {
coins := nums[left-1] * nums[k] * nums[right+1]
dp[left][right] = max.Int(dp[left][right], dp[left][k-1]+dp[k+1][right]+coins)
}
}
}
return dp[1][n]
}
|
func MaxCoins(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
nums = append([]int{1}, nums...)
nums = append(nums, 1)
dp := make([][]int, n+2)
for i := range dp {
dp[i] = make([]int, n+2)
}
for length := 1; length <= n; length++ {
for left := 1; left+length-1 <= n; left++ {
right := left + length - 1
for k := left; k <= right; k++ {
coins := nums[left-1] * nums[k] * nums[right+1]
dp[left][right] = max.Int(dp[left][right], dp[left][k-1]+dp[k+1][right]+coins)
}
}
}
return dp[1][n]
}
|
MaxCoins
| 5
| 30
|
dynamic/burstballoons.go
|
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
##CHUNK 2
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
return dp[m][sum]
}
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
##CHUNK 2
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
#FILE: Go-master/dynamic/longestarithmeticsubsequence.go
##CHUNK 1
n := len(nums)
if n <= 1 {
return n
}
dp := make([]map[int]int, n)
for i := range dp {
dp[i] = make(map[int]int)
}
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
#FILE: Go-master/dynamic/optimalbst.go
##CHUNK 1
package dynamic
import "github.com/TheAlgorithms/Go/math/min"
// OptimalBST returns the minimum cost of constructing a Binary Search Tree
func OptimalBST(keys []int, freq []int, n int) int {
// Initialize DP table with size n x n
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
##CHUNK 2
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value
sum := sum(freq, i, j)
// Try every key as root and compute cost
for k := i; k <= j; k++ {
// Left cost: dp[i][k-1] is valid only if k > i
var leftCost int
if k > i {
leftCost = dp[i][k-1]
#FILE: Go-master/dynamic/tilingproblem.go
##CHUNK 1
if n <= 1 {
return 1
}
dp := make([]int, n+1)
dp[0] = 1
dp[1] = 1
for i := 2; i <= n; i++ {
dp[i] = dp[i-1] + dp[i-2]
}
return dp[n]
}
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/matrixmultiplication.go
##CHUNK 1
}
return q
}
// MatrixChainDp function
func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
#CURRENT FILE: Go-master/dynamic/burstballoons.go
|
Go-master
| 27
|
func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
prod := dp[i][k] + dp[k+1][j] + D[i-1]*D[k]*D[j]
dp[i][j] = min.Int(prod, dp[i][j])
}
}
}
return dp[1][N-1]
}
|
func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
prod := dp[i][k] + dp[k+1][j] + D[i-1]*D[k]*D[j]
dp[i][j] = min.Int(prod, dp[i][j])
}
}
}
return dp[1][N-1]
}
|
func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
prod := dp[i][k] + dp[k+1][j] + D[i-1]*D[k]*D[j]
dp[i][j] = min.Int(prod, dp[i][j])
}
}
}
return dp[1][N-1]
}
|
MatrixChainDp
| 25
| 47
|
dynamic/matrixmultiplication.go
|
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
##CHUNK 2
// LpsRec function
func LpsRec(word string) int {
return lpsRec(word, 0, len(word)-1)
}
// LpsDp function
func LpsDp(word string) int {
N := len(word)
dp := make([][]int, N)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/optimalbst.go
##CHUNK 1
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value
sum := sum(freq, i, j)
// Try every key as root and compute cost
for k := i; k <= j; k++ {
// Left cost: dp[i][k-1] is valid only if k > i
var leftCost int
if k > i {
leftCost = dp[i][k-1]
##CHUNK 2
j := i + length - 1
dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value
sum := sum(freq, i, j)
// Try every key as root and compute cost
for k := i; k <= j; k++ {
// Left cost: dp[i][k-1] is valid only if k > i
var leftCost int
if k > i {
leftCost = dp[i][k-1]
} else {
leftCost = 0
}
// Right cost: dp[k+1][j] is valid only if k < j
var rightCost int
if k < j {
rightCost = dp[k+1][j]
} else {
rightCost = 0
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
#FILE: Go-master/dynamic/eggdropping.go
##CHUNK 1
return floors
}
// Initialize DP table
dp := make([][]int, eggs+1)
for i := range dp {
dp[i] = make([]int, floors+1)
}
// Fill the DP table for 1 egg
for j := 1; j <= floors; j++ {
dp[1][j] = j
}
// Fill the DP table for more than 1 egg
for i := 2; i <= eggs; i++ {
for j := 2; j <= floors; j++ {
dp[i][j] = int(^uint(0) >> 1) // initialize with a large number
for x := 1; x <= j; x++ {
// Recurrence relation to fill the DP table
#CURRENT FILE: Go-master/dynamic/matrixmultiplication.go
##CHUNK 1
// MatrixChainRec function
func MatrixChainRec(D []int, i, j int) int {
// d[i-1] x d[i] : dimension of matrix i
if i == j {
return 0
}
q := 1 << 32
for k := i; k < j; k++ {
prod := MatrixChainRec(D, i, k) + MatrixChainRec(D, k+1, j) + D[i-1]*D[k]*D[j]
q = min.Int(prod, q)
}
return q
}
}
/*
func main() {
D := []int{2, 2, 2, 2, 2} // 4 matrices
fmt.Print(matrixChainRec(D, 1, 4), "\n")
##CHUNK 2
// matrix chain multiplication problem
// https://en.wikipedia.org/wiki/Matrix_chain_multiplication
// www.geeksforgeeks.org/dynamic_programming-set-8-matrix-chain-multiplication/
// time complexity: O(n^3)
// space complexity: O(n^2)
package dynamic
import "github.com/TheAlgorithms/Go/math/min"
// MatrixChainRec function
func MatrixChainRec(D []int, i, j int) int {
// d[i-1] x d[i] : dimension of matrix i
if i == j {
return 0
}
q := 1 << 32
for k := i; k < j; k++ {
prod := MatrixChainRec(D, i, k) + MatrixChainRec(D, k+1, j) + D[i-1]*D[k]*D[j]
q = min.Int(prod, q)
|
Go-master
| 28
|
func LongestPalindromicSubstring(s string) string {
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
}
return s[start : start+maxLength]
}
|
func LongestPalindromicSubstring(s string) string {
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
}
return s[start : start+maxLength]
}
|
func LongestPalindromicSubstring(s string) string {
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
}
return s[start : start+maxLength]
}
|
LongestPalindromicSubstring
| 9
| 42
|
dynamic/longestpalindromicsubstring.go
|
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
##CHUNK 2
// LpsRec function
func LpsRec(word string) int {
return lpsRec(word, 0, len(word)-1)
}
// LpsDp function
func LpsDp(word string) int {
N := len(word)
dp := make([][]int, N)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
#FILE: Go-master/dynamic/longestarithmeticsubsequence.go
##CHUNK 1
n := len(nums)
if n <= 1 {
return n
}
dp := make([]map[int]int, n)
for i := range dp {
dp[i] = make(map[int]int)
}
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
##CHUNK 2
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
}
return maxLength
}
#FILE: Go-master/dynamic/optimalbst.go
##CHUNK 1
package dynamic
import "github.com/TheAlgorithms/Go/math/min"
// OptimalBST returns the minimum cost of constructing a Binary Search Tree
func OptimalBST(keys []int, freq []int, n int) int {
// Initialize DP table with size n x n
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
##CHUNK 2
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value
sum := sum(freq, i, j)
// Try every key as root and compute cost
for k := i; k <= j; k++ {
// Left cost: dp[i][k-1] is valid only if k > i
var leftCost int
if k > i {
leftCost = dp[i][k-1]
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/wildcardmatching.go
##CHUNK 1
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
#FILE: Go-master/dynamic/burstballoons.go
##CHUNK 1
nums = append([]int{1}, nums...)
nums = append(nums, 1)
dp := make([][]int, n+2)
for i := range dp {
dp[i] = make([]int, n+2)
}
for length := 1; length <= n; length++ {
for left := 1; left+length-1 <= n; left++ {
right := left + length - 1
for k := left; k <= right; k++ {
coins := nums[left-1] * nums[k] * nums[right+1]
dp[left][right] = max.Int(dp[left][right], dp[left][k-1]+dp[k+1][right]+coins)
}
}
}
return dp[1][n]
#CURRENT FILE: Go-master/dynamic/longestpalindromicsubstring.go
|
Go-master
| 29
|
func PartitionProblem(nums []int) bool {
sum := 0
for _, num := range nums {
sum += num
}
if sum%2 != 0 {
return false
}
target := sum / 2
dp := make([]bool, target+1)
dp[0] = true
for _, num := range nums {
for i := target; i >= num; i-- {
dp[i] = dp[i] || dp[i-num]
}
}
return dp[target]
}
|
func PartitionProblem(nums []int) bool {
sum := 0
for _, num := range nums {
sum += num
}
if sum%2 != 0 {
return false
}
target := sum / 2
dp := make([]bool, target+1)
dp[0] = true
for _, num := range nums {
for i := target; i >= num; i-- {
dp[i] = dp[i] || dp[i-num]
}
}
return dp[target]
}
|
func PartitionProblem(nums []int) bool {
sum := 0
for _, num := range nums {
sum += num
}
if sum%2 != 0 {
return false
}
target := sum / 2
dp := make([]bool, target+1)
dp[0] = true
for _, num := range nums {
for i := target; i >= num; i-- {
dp[i] = dp[i] || dp[i-num]
}
}
return dp[target]
}
|
PartitionProblem
| 10
| 29
|
dynamic/partitionproblem.go
|
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/wordbreak.go
##CHUNK 1
wordSet := make(map[string]bool)
for _, word := range wordDict {
wordSet[word] = true
}
dp := make([]bool, len(s)+1)
dp[0] = true
for i := 1; i <= len(s); i++ {
for j := 0; j < i; j++ {
if dp[j] && wordSet[s[j:i]] {
dp[i] = true
break
}
}
}
return dp[len(s)]
}
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
#FILE: Go-master/dynamic/burstballoons.go
##CHUNK 1
package dynamic
import "github.com/TheAlgorithms/Go/math/max"
// MaxCoins returns the maximum coins we can collect by bursting the balloons
func MaxCoins(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
nums = append([]int{1}, nums...)
nums = append(nums, 1)
dp := make([][]int, n+2)
for i := range dp {
dp[i] = make([]int, n+2)
}
for length := 1; length <= n; length++ {
#FILE: Go-master/structure/tree/tree_test.go
##CHUNK 1
func TestTreeGetOrHas(t *testing.T) {
helper := func(tree TestTree[int], nums []int) {
tree.Push(nums...)
for _, num := range nums {
if !tree.Has(num) {
t.Errorf("Error with Has or Push method")
}
}
min, _ := tree.Min()
max, _ := tree.Max()
if _, ok := tree.Get(min - 1); ok {
t.Errorf("Error with Get method")
}
if _, ok := tree.Get(max + 1); ok {
t.Errorf("Error with Get method")
}
##CHUNK 2
package tree_test
import (
"math/rand"
"reflect"
"sort"
"testing"
bt "github.com/TheAlgorithms/Go/structure/tree"
)
func TestTreeGetOrHas(t *testing.T) {
helper := func(tree TestTree[int], nums []int) {
tree.Push(nums...)
for _, num := range nums {
if !tree.Has(num) {
t.Errorf("Error with Has or Push method")
}
}
#FILE: Go-master/math/moserdebruijnsequence/sequence.go
##CHUNK 1
for i := 0; i < number; i++ {
res := generateNthTerm(i)
sequence = append(sequence, res)
}
return sequence
}
func generateNthTerm(num int) int {
if num == 0 || num == 1 {
return num
}
//number is even
if num%2 == 0 {
return 4 * generateNthTerm(num/2)
}
//number is odd
#FILE: Go-master/project_euler/problem_1/problem1.go
##CHUNK 1
*/
package problem1
func Problem1(n uint) uint {
sum := uint(0)
for i := uint(1); i < n; i++ {
if i%3 == 0 || i%5 == 0 {
sum += i
}
}
return sum
}
#FILE: Go-master/dynamic/interleavingstrings.go
##CHUNK 1
if len(s1)+len(s2) != len(s3) {
return false
}
dp := make([][]bool, len(s1)+1)
for i := range dp {
dp[i] = make([]bool, len(s2)+1)
}
dp[0][0] = true
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
#FILE: Go-master/dynamic/wildcardmatching.go
##CHUNK 1
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
#CURRENT FILE: Go-master/dynamic/partitionproblem.go
|
Go-master
| 30
|
func LongestArithmeticSubsequence(nums []int) int {
n := len(nums)
if n <= 1 {
return n
}
dp := make([]map[int]int, n)
for i := range dp {
dp[i] = make(map[int]int)
}
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
}
return maxLength
}
|
func LongestArithmeticSubsequence(nums []int) int {
n := len(nums)
if n <= 1 {
return n
}
dp := make([]map[int]int, n)
for i := range dp {
dp[i] = make(map[int]int)
}
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
}
return maxLength
}
|
func LongestArithmeticSubsequence(nums []int) int {
n := len(nums)
if n <= 1 {
return n
}
dp := make([]map[int]int, n)
for i := range dp {
dp[i] = make(map[int]int)
}
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
}
return maxLength
}
|
LongestArithmeticSubsequence
| 9
| 33
|
dynamic/longestarithmeticsubsequence.go
|
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
##CHUNK 2
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
##CHUNK 2
)
// Max function - possible duplicate
func Max(a, b int) int {
return int(math.Max(float64(a), float64(b)))
}
// Knapsack solves knapsack problem
// return maxProfit
func Knapsack(maxWeight int, weights, values []int) int {
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
#FILE: Go-master/dynamic/uniquepaths.go
##CHUNK 1
}
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
for i := 0; i < m; i++ {
grid[i][0] = 1
}
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}
##CHUNK 2
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}
return grid[m-1][n-1]
}
#FILE: Go-master/dynamic/tilingproblem.go
##CHUNK 1
if n <= 1 {
return 1
}
dp := make([]int, n+1)
dp[0] = 1
dp[1] = 1
for i := 2; i <= n; i++ {
dp[i] = dp[i-1] + dp[i-2]
}
return dp[n]
}
#FILE: Go-master/dynamic/wordbreak.go
##CHUNK 1
wordSet := make(map[string]bool)
for _, word := range wordDict {
wordSet[word] = true
}
dp := make([]bool, len(s)+1)
dp[0] = true
for i := 1; i <= len(s); i++ {
for j := 0; j < i; j++ {
if dp[j] && wordSet[s[j:i]] {
dp[i] = true
break
}
}
}
return dp[len(s)]
}
#FILE: Go-master/dynamic/longestincreasingsubsequence.go
##CHUNK 1
)
// LongestIncreasingSubsequence returns the longest increasing subsequence
// where all elements of the subsequence are sorted in increasing order
func LongestIncreasingSubsequence(elements []int) int {
n := len(elements)
lis := make([]int, n)
for i := range lis {
lis[i] = 1
}
for i := range lis {
for j := 0; j < i; j++ {
if elements[i] > elements[j] && lis[i] < lis[j]+1 {
lis[i] = lis[j] + 1
}
}
}
res := 0
for _, value := range lis {
res = max.Int(res, value)
#CURRENT FILE: Go-master/dynamic/longestarithmeticsubsequence.go
|
Go-master
| 31
|
func IsInterleave(s1, s2, s3 string) bool {
if len(s1)+len(s2) != len(s3) {
return false
}
dp := make([][]bool, len(s1)+1)
for i := range dp {
dp[i] = make([]bool, len(s2)+1)
}
dp[0][0] = true
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1])
}
}
return dp[len(s1)][len(s2)]
}
|
func IsInterleave(s1, s2, s3 string) bool {
if len(s1)+len(s2) != len(s3) {
return false
}
dp := make([][]bool, len(s1)+1)
for i := range dp {
dp[i] = make([]bool, len(s2)+1)
}
dp[0][0] = true
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1])
}
}
return dp[len(s1)][len(s2)]
}
|
func IsInterleave(s1, s2, s3 string) bool {
if len(s1)+len(s2) != len(s3) {
return false
}
dp := make([][]bool, len(s1)+1)
for i := range dp {
dp[i] = make([]bool, len(s2)+1)
}
dp[0][0] = true
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1])
}
}
return dp[len(s1)][len(s2)]
}
|
IsInterleave
| 9
| 35
|
dynamic/interleavingstrings.go
|
#FILE: Go-master/dynamic/wildcardmatching.go
##CHUNK 1
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
##CHUNK 2
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
}
return dp[len(s)][len(p)]
}
##CHUNK 3
// wildcardmatching.go
// description: Solves the Wildcard Matching problem using dynamic programming
// reference: https://en.wikipedia.org/wiki/Wildcard_matching
// time complexity: O(m*n)
// space complexity: O(m*n)
package dynamic
// IsMatch checks if the string `s` matches the wildcard pattern `p`
func IsMatch(s, p string) bool {
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
##CHUNK 2
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
return dp[m][sum]
}
#FILE: Go-master/dynamic/wordbreak.go
##CHUNK 1
wordSet := make(map[string]bool)
for _, word := range wordDict {
wordSet[word] = true
}
dp := make([]bool, len(s)+1)
dp[0] = true
for i := 1; i <= len(s); i++ {
for j := 0; j < i; j++ {
if dp[j] && wordSet[s[j:i]] {
dp[i] = true
break
}
}
}
return dp[len(s)]
}
#FILE: Go-master/dynamic/abbreviation.go
##CHUNK 1
import (
"strings"
)
// Returns true if it is possible to make a equals b (if b is an abbreviation of a), returns false otherwise
func Abbreviation(a string, b string) bool {
dp := make([][]bool, len(a)+1)
for i := range dp {
dp[i] = make([]bool, len(b)+1)
}
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] = true
}
if string(a[i]) == strings.ToLower(string(a[i])) {
dp[i+1][j] = true
##CHUNK 2
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] = true
}
if string(a[i]) == strings.ToLower(string(a[i])) {
dp[i+1][j] = true
}
}
}
}
return dp[len(a)][len(b)]
}
#FILE: Go-master/dynamic/subsetsum.go
##CHUNK 1
//create subset matrix
arraySize := len(array)
subset := make([][]bool, arraySize+1)
for i := 0; i <= arraySize; i++ {
subset[i] = make([]bool, sum+1)
}
for i := 0; i <= arraySize; i++ {
//sum 0 is always true
subset[i][0] = true
}
for i := 1; i <= sum; i++ {
//empty set is false when sum is not 0
subset[0][i] = false
}
for i := 1; i <= arraySize; i++ {
for j := 1; j <= sum; j++ {
if array[i-1] > j {
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#CURRENT FILE: Go-master/dynamic/interleavingstrings.go
|
Go-master
| 32
|
func OptimalBST(keys []int, freq []int, n int) int {
// Initialize DP table with size n x n
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value
sum := sum(freq, i, j)
// Try every key as root and compute cost
for k := i; k <= j; k++ {
// Left cost: dp[i][k-1] is valid only if k > i
var leftCost int
if k > i {
leftCost = dp[i][k-1]
} else {
leftCost = 0
}
// Right cost: dp[k+1][j] is valid only if k < j
var rightCost int
if k < j {
rightCost = dp[k+1][j]
} else {
rightCost = 0
}
// Total cost for root k
cost := sum + leftCost + rightCost
// Update dp[i][j] with the minimum cost
dp[i][j] = min.Int(dp[i][j], cost)
}
}
}
return dp[0][n-1]
}
|
func OptimalBST(keys []int, freq []int, n int) int {
// Initialize DP table with size n x n
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value
sum := sum(freq, i, j)
// Try every key as root and compute cost
for k := i; k <= j; k++ {
// Left cost: dp[i][k-1] is valid only if k > i
var leftCost int
if k > i {
leftCost = dp[i][k-1]
} else {
leftCost = 0
}
// Right cost: dp[k+1][j] is valid only if k < j
var rightCost int
if k < j {
rightCost = dp[k+1][j]
} else {
rightCost = 0
}
// Total cost for root k
cost := sum + leftCost + rightCost
// Update dp[i][j] with the minimum cost
dp[i][j] = min.Int(dp[i][j], cost)
}
}
}
return dp[0][n-1]
}
|
func OptimalBST(keys []int, freq []int, n int) int {
// Initialize DP table with size n x n
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value
sum := sum(freq, i, j)
// Try every key as root and compute cost
for k := i; k <= j; k++ {
// Left cost: dp[i][k-1] is valid only if k > i
var leftCost int
if k > i {
leftCost = dp[i][k-1]
} else {
leftCost = 0
}
// Right cost: dp[k+1][j] is valid only if k < j
var rightCost int
if k < j {
rightCost = dp[k+1][j]
} else {
rightCost = 0
}
// Total cost for root k
cost := sum + leftCost + rightCost
// Update dp[i][j] with the minimum cost
dp[i][j] = min.Int(dp[i][j], cost)
}
}
}
return dp[0][n-1]
}
|
OptimalBST
| 5
| 51
|
dynamic/optimalbst.go
|
#FILE: Go-master/dynamic/eggdropping.go
##CHUNK 1
return floors
}
// Initialize DP table
dp := make([][]int, eggs+1)
for i := range dp {
dp[i] = make([]int, floors+1)
}
// Fill the DP table for 1 egg
for j := 1; j <= floors; j++ {
dp[1][j] = j
}
// Fill the DP table for more than 1 egg
for i := 2; i <= eggs; i++ {
for j := 2; j <= floors; j++ {
dp[i][j] = int(^uint(0) >> 1) // initialize with a large number
for x := 1; x <= j; x++ {
// Recurrence relation to fill the DP table
##CHUNK 2
for j := 1; j <= floors; j++ {
dp[1][j] = j
}
// Fill the DP table for more than 1 egg
for i := 2; i <= eggs; i++ {
for j := 2; j <= floors; j++ {
dp[i][j] = int(^uint(0) >> 1) // initialize with a large number
for x := 1; x <= j; x++ {
// Recurrence relation to fill the DP table
res := max.Int(dp[i-1][x-1], dp[i][j-x]) + 1
dp[i][j] = min.Int(dp[i][j], res)
}
}
}
return dp[eggs][floors]
}
#FILE: Go-master/dynamic/matrixmultiplication.go
##CHUNK 1
}
return q
}
// MatrixChainDp function
func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
##CHUNK 2
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
prod := dp[i][k] + dp[k+1][j] + D[i-1]*D[k]*D[j]
dp[i][j] = min.Int(prod, dp[i][j])
}
}
}
return dp[1][N-1]
}
/*
##CHUNK 3
// MatrixChainRec function
func MatrixChainRec(D []int, i, j int) int {
// d[i-1] x d[i] : dimension of matrix i
if i == j {
return 0
}
q := 1 << 32
for k := i; k < j; k++ {
prod := MatrixChainRec(D, i, k) + MatrixChainRec(D, k+1, j) + D[i-1]*D[k]*D[j]
q = min.Int(prod, q)
}
return q
}
// MatrixChainDp function
func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
##CHUNK 2
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
#CURRENT FILE: Go-master/dynamic/optimalbst.go
|
Go-master
| 33
|
func DiceThrow(m, n, sum int) int {
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
return dp[m][sum]
}
|
func DiceThrow(m, n, sum int) int {
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
return dp[m][sum]
}
|
func DiceThrow(m, n, sum int) int {
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
return dp[m][sum]
}
|
DiceThrow
| 9
| 32
|
dynamic/dicethrow.go
|
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/wildcardmatching.go
##CHUNK 1
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
#FILE: Go-master/dynamic/burstballoons.go
##CHUNK 1
nums = append([]int{1}, nums...)
nums = append(nums, 1)
dp := make([][]int, n+2)
for i := range dp {
dp[i] = make([]int, n+2)
}
for length := 1; length <= n; length++ {
for left := 1; left+length-1 <= n; left++ {
right := left + length - 1
for k := left; k <= right; k++ {
coins := nums[left-1] * nums[k] * nums[right+1]
dp[left][right] = max.Int(dp[left][right], dp[left][k-1]+dp[k+1][right]+coins)
}
}
}
return dp[1][n]
#FILE: Go-master/dynamic/interleavingstrings.go
##CHUNK 1
if len(s1)+len(s2) != len(s3) {
return false
}
dp := make([][]bool, len(s1)+1)
for i := range dp {
dp[i] = make([]bool, len(s2)+1)
}
dp[0][0] = true
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
#FILE: Go-master/dynamic/subsetsum.go
##CHUNK 1
//create subset matrix
arraySize := len(array)
subset := make([][]bool, arraySize+1)
for i := 0; i <= arraySize; i++ {
subset[i] = make([]bool, sum+1)
}
for i := 0; i <= arraySize; i++ {
//sum 0 is always true
subset[i][0] = true
}
for i := 1; i <= sum; i++ {
//empty set is false when sum is not 0
subset[0][i] = false
}
for i := 1; i <= arraySize; i++ {
for j := 1; j <= sum; j++ {
if array[i-1] > j {
##CHUNK 2
}
for i := 1; i <= sum; i++ {
//empty set is false when sum is not 0
subset[0][i] = false
}
for i := 1; i <= arraySize; i++ {
for j := 1; j <= sum; j++ {
if array[i-1] > j {
subset[i][j] = subset[i-1][j]
}
if array[i-1] <= j {
if j-array[i-1] < 0 || j-array[i-1] > sum {
//out of bounds
return false, ErrInvalidPosition
}
subset[i][j] = subset[i-1][j] || subset[i-1][j-array[i-1]]
#FILE: Go-master/dynamic/eggdropping.go
##CHUNK 1
return floors
}
// Initialize DP table
dp := make([][]int, eggs+1)
for i := range dp {
dp[i] = make([]int, floors+1)
}
// Fill the DP table for 1 egg
for j := 1; j <= floors; j++ {
dp[1][j] = j
}
// Fill the DP table for more than 1 egg
for i := 2; i <= eggs; i++ {
for j := 2; j <= floors; j++ {
dp[i][j] = int(^uint(0) >> 1) // initialize with a large number
for x := 1; x <= j; x++ {
// Recurrence relation to fill the DP table
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
#FILE: Go-master/dynamic/longestarithmeticsubsequence.go
##CHUNK 1
n := len(nums)
if n <= 1 {
return n
}
dp := make([]map[int]int, n)
for i := range dp {
dp[i] = make(map[int]int)
}
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
#FILE: Go-master/dynamic/uniquepaths.go
##CHUNK 1
}
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
for i := 0; i < m; i++ {
grid[i][0] = 1
}
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}
#CURRENT FILE: Go-master/dynamic/dicethrow.go
|
Go-master
| 34
|
func LongestCommonSubsequence(a string, b string) int {
aRunes, aLen := strToRuneSlice(a)
bRunes, bLen := strToRuneSlice(b)
// here we are making a 2d slice of size (aLen+1)*(bLen+1)
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i := 0; i <= aLen; i++ {
for j := 0; j <= bLen; j++ {
if i == 0 || j == 0 {
lcs[i][j] = 0
} else if aRunes[i-1] == bRunes[j-1] {
lcs[i][j] = lcs[i-1][j-1] + 1
} else {
lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])
}
}
}
// returning the length of longest common subsequence
return lcs[aLen][bLen]
}
|
func LongestCommonSubsequence(a string, b string) int {
aRunes, aLen := strToRuneSlice(a)
bRunes, bLen := strToRuneSlice(b)
// here we are making a 2d slice of size (aLen+1)*(bLen+1)
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i := 0; i <= aLen; i++ {
for j := 0; j <= bLen; j++ {
if i == 0 || j == 0 {
lcs[i][j] = 0
} else if aRunes[i-1] == bRunes[j-1] {
lcs[i][j] = lcs[i-1][j-1] + 1
} else {
lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])
}
}
}
// returning the length of longest common subsequence
return lcs[aLen][bLen]
}
|
func LongestCommonSubsequence(a string, b string) int {
aRunes, aLen := strToRuneSlice(a)
bRunes, bLen := strToRuneSlice(b)
// here we are making a 2d slice of size (aLen+1)*(bLen+1)
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i := 0; i <= aLen; i++ {
for j := 0; j <= bLen; j++ {
if i == 0 || j == 0 {
lcs[i][j] = 0
} else if aRunes[i-1] == bRunes[j-1] {
lcs[i][j] = lcs[i-1][j-1] + 1
} else {
lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])
}
}
}
// returning the length of longest common subsequence
return lcs[aLen][bLen]
}
|
LongestCommonSubsequence
| 15
| 39
|
dynamic/longestcommonsubsequence.go
|
#FILE: Go-master/dynamic/binomialcoefficient.go
##CHUNK 1
// }
// }
// Bin2 function
func Bin2(n int, k int) int {
var i, j int
B := make([][]int, (n + 1))
for i := range B {
B[i] = make([]int, k+1)
}
for i = 0; i <= n; i++ {
for j = 0; j <= min.Int(i, k); j++ {
if j == 0 || j == i {
B[i][j] = 1
} else {
B[i][j] = B[i-1][j-1] + B[i-1][j]
}
}
##CHUNK 2
}
for i = 0; i <= n; i++ {
for j = 0; j <= min.Int(i, k); j++ {
if j == 0 || j == i {
B[i][j] = 1
} else {
B[i][j] = B[i-1][j-1] + B[i-1][j]
}
}
}
return B[n][k]
}
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
##CHUNK 2
// LpsRec function
func LpsRec(word string) int {
return lpsRec(word, 0, len(word)-1)
}
// LpsDp function
func LpsDp(word string) int {
N := len(word)
dp := make([][]int, N)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
#FILE: Go-master/dynamic/rodcutting.go
##CHUNK 1
if length == 0 {
return 0
}
q := -1
for i := 1; i <= length; i++ {
q = Max(q, price[i]+CutRodRec(price, length-i))
}
return q
}
// CutRodDp solve the same problem using dynamic programming
func CutRodDp(price []int, length int) int {
r := make([]int, length+1) // a.k.a the memoization array
r[0] = 0 // cost of 0 length rod is 0
for j := 1; j <= length; j++ { // for each length (subproblem)
q := -1
for i := 1; i <= j; i++ {
q = Max(q, price[i]+r[j-i]) // avoiding recursive call
#FILE: Go-master/math/prime/sieve2.go
##CHUNK 1
sieve := make([]int, limit+1) // make a slice of size limit+1
for i := 2; i <= limit; i++ {
if sieve[i] == 0 { // if the number is not marked as composite
primes = append(primes, i) // add it to the list of primes
for j := i * i; j <= limit; j += i { // mark all multiples of i as composite
sieve[j] = 1
}
}
}
return primes
}
#CURRENT FILE: Go-master/dynamic/longestcommonsubsequence.go
|
Go-master
| 35
|
func EditDistanceRecursive(first string, second string, pointerFirst int, pointerSecond int) int {
if pointerFirst == 0 {
return pointerSecond
}
if pointerSecond == 0 {
return pointerFirst
}
// Characters match, so we recur for the remaining portions
if first[pointerFirst-1] == second[pointerSecond-1] {
return EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1)
}
// We have three choices, all with cost of 1 unit
return 1 + min.Int(EditDistanceRecursive(first, second, pointerFirst, pointerSecond-1), // Insert
EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond), // Delete
EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1)) // Replace
}
|
func EditDistanceRecursive(first string, second string, pointerFirst int, pointerSecond int) int {
if pointerFirst == 0 {
return pointerSecond
}
if pointerSecond == 0 {
return pointerFirst
}
// Characters match, so we recur for the remaining portions
if first[pointerFirst-1] == second[pointerSecond-1] {
return EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1)
}
// We have three choices, all with cost of 1 unit
return 1 + min.Int(EditDistanceRecursive(first, second, pointerFirst, pointerSecond-1), // Insert
EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond), // Delete
EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1)) // Replace
}
|
func EditDistanceRecursive(first string, second string, pointerFirst int, pointerSecond int) int {
if pointerFirst == 0 {
return pointerSecond
}
if pointerSecond == 0 {
return pointerFirst
}
// Characters match, so we recur for the remaining portions
if first[pointerFirst-1] == second[pointerSecond-1] {
return EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1)
}
// We have three choices, all with cost of 1 unit
return 1 + min.Int(EditDistanceRecursive(first, second, pointerFirst, pointerSecond-1), // Insert
EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond), // Delete
EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1)) // Replace
}
|
EditDistanceRecursive
| 11
| 30
|
dynamic/editdistance.go
|
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go
##CHUNK 1
// longest palindromic subsequence
// time complexity: O(n^2)
// space complexity: O(n^2)
// http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/
package dynamic
func lpsRec(word string, i, j int) int {
if i == j {
return 1
}
if i > j {
return 0
}
if word[i] == word[j] {
return 2 + lpsRec(word, i+1, j-1)
}
return Max(lpsRec(word, i, j-1), lpsRec(word, i+1, j))
}
#FILE: Go-master/math/mobius.go
##CHUNK 1
// Mu is the Mobius function
// This function returns μ(n) for given number
func Mu(n int) int {
if n <= 1 {
return 1
}
var primeFactorCount int
for i := 1; i <= n; i++ {
if n%i == 0 && prime.OptimizedTrialDivision(int64(i)) {
if n%(i*i) == 0 {
return 0
}
primeFactorCount += 1
}
}
if primeFactorCount%2 == 0 {
return 1
}
return -1
}
#FILE: Go-master/strings/bom/bom.go
##CHUNK 1
// }
// // Checks if state exists. Returns true if it does, false otherwise.
// func stateExists(state int, at map[int]map[uint8]int) bool {
// _, ok := at[state]
// if !ok || state == -1 || at[state] == nil {
// return false
// }
// return true
// }
// // Just some printing of extra information about what the algorithm does.
// func prettyPrint(current int, j int, n int, pos int, t string, oracle map[int]map[uint8]int) {
// if current == 0 && !(getTransition(current, t[pos+j-1], oracle) == -1) {
// fmt.Printf("\n -->(%d)---(%c)--->(%d)", current, t[pos+j-1], getTransition(current, t[pos+j-1], oracle))
// } else if getTransition(current, t[pos+j-1], oracle) == -1 && current != 0 {
// fmt.Printf("\n (%d)---(%c) ", current, t[pos+j-1])
// } else if getTransition(current, t[pos+j-1], oracle) == -1 && current == 0 {
// fmt.Printf("\n -->(%d)---(%c) ", current, t[pos+j-1])
// } else {
##CHUNK 2
// // Just some printing of extra information about what the algorithm does.
// func prettyPrint(current int, j int, n int, pos int, t string, oracle map[int]map[uint8]int) {
// if current == 0 && !(getTransition(current, t[pos+j-1], oracle) == -1) {
// fmt.Printf("\n -->(%d)---(%c)--->(%d)", current, t[pos+j-1], getTransition(current, t[pos+j-1], oracle))
// } else if getTransition(current, t[pos+j-1], oracle) == -1 && current != 0 {
// fmt.Printf("\n (%d)---(%c) ", current, t[pos+j-1])
// } else if getTransition(current, t[pos+j-1], oracle) == -1 && current == 0 {
// fmt.Printf("\n -->(%d)---(%c) ", current, t[pos+j-1])
// } else {
// fmt.Printf("\n (%d)---(%c)--->(%d)", current, t[pos+j-1], getTransition(current, t[pos+j-1], oracle))
// }
// fmt.Printf(" ")
// for a := 0; a < pos+j-1; a++ {
// fmt.Printf("%c", t[a])
// }
// if getTransition(current, t[pos+j-1], oracle) == -1 {
// fmt.Printf("[%c]", t[pos+j-1])
// } else {
// fmt.Printf("[%c]", t[pos+j-1])
#FILE: Go-master/math/factorial/factorial.go
##CHUNK 1
}
// UsingTree This function finds the factorial of a number using a binary tree
func UsingTree(n int) (int, error) {
if n < 0 {
return 0, ErrNegativeArgument
}
if n == 0 {
return 1, nil
}
if n == 1 || n == 2 {
return n, nil
}
return prodTree(2, n), nil
}
func prodTree(l int, r int) int {
if l > r {
return 1
}
#FILE: Go-master/cipher/railfence/railfence.go
##CHUNK 1
for _, char := range line {
if char != 0 {
result.WriteRune(char)
}
}
}
return result.String()
}
func Decrypt(cipherText string, rails int) string {
if rails == 1 || rails >= len(cipherText) {
return cipherText
}
// Placeholder for the decrypted message
decrypted := make([]rune, len(cipherText))
// Calculate the zigzag pattern and place characters accordingly
index := 0
for rail := 0; rail < rails; rail++ {
##CHUNK 2
)
func Encrypt(text string, rails int) string {
if rails == 1 {
return text
}
// Create a matrix for the rail fence pattern
matrix := make([][]rune, rails)
for i := range matrix {
matrix[i] = make([]rune, len(text))
}
// Fill the matrix
dirDown := false
row, col := 0, 0
for _, char := range text {
if row == 0 || row == rails-1 {
dirDown = !dirDown
}
#FILE: Go-master/conversion/decimaltobinary.go
##CHUNK 1
// Reverse() function that will take string,
// and returns the reverse of that string.
func Reverse(str string) string {
rStr := []rune(str)
for i, j := 0, len(rStr)-1; i < len(rStr)/2; i, j = i+1, j-1 {
rStr[i], rStr[j] = rStr[j], rStr[i]
}
return string(rStr)
}
// DecimalToBinary() function that will take Decimal number as int,
// and return its Binary equivalent as a string.
func DecimalToBinary(num int) (string, error) {
if num < 0 {
return "", errors.New("integer must have +ve value")
}
if num == 0 {
return "0", nil
}
##CHUNK 2
// DecimalToBinary() function that will take Decimal number as int,
// and return its Binary equivalent as a string.
func DecimalToBinary(num int) (string, error) {
if num < 0 {
return "", errors.New("integer must have +ve value")
}
if num == 0 {
return "0", nil
}
var result string = ""
for num > 0 {
result += strconv.Itoa(num & 1)
num >>= 1
}
return Reverse(result), nil
}
#FILE: Go-master/compression/huffmancoding.go
##CHUNK 1
q2 = append(q2, node)
}
if len(q1) == 1 { // returns the remaining node in q1, q2
return &q1[0], nil
}
return &q2[0], nil
}
// least removes the node with lowest weight from q1, q2.
// It returns the node with lowest weight and the slices q1, q2 after the update.
func least(q1 []Node, q2 []Node) (Node, []Node, []Node) {
if len(q1) == 0 {
return q2[0], q1, q2[1:]
}
if len(q2) == 0 {
return q1[0], q1[1:], q2
}
if q1[0].weight <= q2[0].weight {
return q1[0], q1[1:], q2
}
#CURRENT FILE: Go-master/dynamic/editdistance.go
|
Go-master
| 36
|
func EditDistanceDP(first string, second string) int {
m := len(first)
n := len(second)
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
if first[i-1] == second[j-1] {
dp[i][j] = dp[i-1][j-1]
continue
}
dp[i][j] = 1 + min.Int(dp[i][j-1], dp[i-1][j], dp[i-1][j-1])
}
}
return dp[m][n]
}
|
func EditDistanceDP(first string, second string) int {
m := len(first)
n := len(second)
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
if first[i-1] == second[j-1] {
dp[i][j] = dp[i-1][j-1]
continue
}
dp[i][j] = 1 + min.Int(dp[i][j-1], dp[i-1][j], dp[i-1][j-1])
}
}
return dp[m][n]
}
|
func EditDistanceDP(first string, second string) int {
m := len(first)
n := len(second)
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
if first[i-1] == second[j-1] {
dp[i][j] = dp[i-1][j-1]
continue
}
dp[i][j] = 1 + min.Int(dp[i][j-1], dp[i-1][j], dp[i-1][j-1])
}
}
return dp[m][n]
}
|
EditDistanceDP
| 36
| 70
|
dynamic/editdistance.go
|
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
##CHUNK 2
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
return dp[m][sum]
}
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
#FILE: Go-master/dynamic/wildcardmatching.go
##CHUNK 1
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
##CHUNK 2
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
}
return dp[len(s)][len(p)]
}
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
#FILE: Go-master/dynamic/eggdropping.go
##CHUNK 1
return floors
}
// Initialize DP table
dp := make([][]int, eggs+1)
for i := range dp {
dp[i] = make([]int, floors+1)
}
// Fill the DP table for 1 egg
for j := 1; j <= floors; j++ {
dp[1][j] = j
}
// Fill the DP table for more than 1 egg
for i := 2; i <= eggs; i++ {
for j := 2; j <= floors; j++ {
dp[i][j] = int(^uint(0) >> 1) // initialize with a large number
for x := 1; x <= j; x++ {
// Recurrence relation to fill the DP table
##CHUNK 2
for j := 1; j <= floors; j++ {
dp[1][j] = j
}
// Fill the DP table for more than 1 egg
for i := 2; i <= eggs; i++ {
for j := 2; j <= floors; j++ {
dp[i][j] = int(^uint(0) >> 1) // initialize with a large number
for x := 1; x <= j; x++ {
// Recurrence relation to fill the DP table
res := max.Int(dp[i-1][x-1], dp[i][j-x]) + 1
dp[i][j] = min.Int(dp[i][j], res)
}
}
}
return dp[eggs][floors]
}
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
#FILE: Go-master/dynamic/uniquepaths.go
##CHUNK 1
}
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
for i := 0; i < m; i++ {
grid[i][0] = 1
}
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}
#CURRENT FILE: Go-master/dynamic/editdistance.go
|
Go-master
| 37
|
func IsSubsetSum(array []int, sum int) (bool, error) {
if sum < 0 {
//not allow negative sum
return false, ErrNegativeSum
}
//create subset matrix
arraySize := len(array)
subset := make([][]bool, arraySize+1)
for i := 0; i <= arraySize; i++ {
subset[i] = make([]bool, sum+1)
}
for i := 0; i <= arraySize; i++ {
//sum 0 is always true
subset[i][0] = true
}
for i := 1; i <= sum; i++ {
//empty set is false when sum is not 0
subset[0][i] = false
}
for i := 1; i <= arraySize; i++ {
for j := 1; j <= sum; j++ {
if array[i-1] > j {
subset[i][j] = subset[i-1][j]
}
if array[i-1] <= j {
if j-array[i-1] < 0 || j-array[i-1] > sum {
//out of bounds
return false, ErrInvalidPosition
}
subset[i][j] = subset[i-1][j] || subset[i-1][j-array[i-1]]
}
}
}
return subset[arraySize][sum], nil
}
|
func IsSubsetSum(array []int, sum int) (bool, error) {
if sum < 0 {
//not allow negative sum
return false, ErrNegativeSum
}
//create subset matrix
arraySize := len(array)
subset := make([][]bool, arraySize+1)
for i := 0; i <= arraySize; i++ {
subset[i] = make([]bool, sum+1)
}
for i := 0; i <= arraySize; i++ {
//sum 0 is always true
subset[i][0] = true
}
for i := 1; i <= sum; i++ {
//empty set is false when sum is not 0
subset[0][i] = false
}
for i := 1; i <= arraySize; i++ {
for j := 1; j <= sum; j++ {
if array[i-1] > j {
subset[i][j] = subset[i-1][j]
}
if array[i-1] <= j {
if j-array[i-1] < 0 || j-array[i-1] > sum {
//out of bounds
return false, ErrInvalidPosition
}
subset[i][j] = subset[i-1][j] || subset[i-1][j-array[i-1]]
}
}
}
return subset[arraySize][sum], nil
}
|
func IsSubsetSum(array []int, sum int) (bool, error) {
if sum < 0 {
//not allow negative sum
return false, ErrNegativeSum
}
//create subset matrix
arraySize := len(array)
subset := make([][]bool, arraySize+1)
for i := 0; i <= arraySize; i++ {
subset[i] = make([]bool, sum+1)
}
for i := 0; i <= arraySize; i++ {
//sum 0 is always true
subset[i][0] = true
}
for i := 1; i <= sum; i++ {
//empty set is false when sum is not 0
subset[0][i] = false
}
for i := 1; i <= arraySize; i++ {
for j := 1; j <= sum; j++ {
if array[i-1] > j {
subset[i][j] = subset[i-1][j]
}
if array[i-1] <= j {
if j-array[i-1] < 0 || j-array[i-1] > sum {
//out of bounds
return false, ErrInvalidPosition
}
subset[i][j] = subset[i-1][j] || subset[i-1][j-array[i-1]]
}
}
}
return subset[arraySize][sum], nil
}
|
IsSubsetSum
| 14
| 55
|
dynamic/subsetsum.go
|
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
##CHUNK 2
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
return dp[m][sum]
}
#FILE: Go-master/dynamic/interleavingstrings.go
##CHUNK 1
if len(s1)+len(s2) != len(s3) {
return false
}
dp := make([][]bool, len(s1)+1)
for i := range dp {
dp[i] = make([]bool, len(s2)+1)
}
dp[0][0] = true
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
##CHUNK 2
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1])
}
}
return dp[len(s1)][len(s2)]
}
#FILE: Go-master/dynamic/wildcardmatching.go
##CHUNK 1
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
##CHUNK 2
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
}
return dp[len(s)][len(p)]
}
#FILE: Go-master/dynamic/wordbreak.go
##CHUNK 1
wordSet := make(map[string]bool)
for _, word := range wordDict {
wordSet[word] = true
}
dp := make([]bool, len(s)+1)
dp[0] = true
for i := 1; i <= len(s); i++ {
for j := 0; j < i; j++ {
if dp[j] && wordSet[s[j:i]] {
dp[i] = true
break
}
}
}
return dp[len(s)]
}
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/math/aliquotsum.go
##CHUNK 1
return 0, ErrNonZeroArgsOnly
default:
var sum int
for i := 1; i <= n/2; i++ {
if n%i == 0 {
sum += i
}
}
return sum, nil
}
}
#FILE: Go-master/dynamic/longestcommonsubsequence.go
##CHUNK 1
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i := 0; i <= aLen; i++ {
for j := 0; j <= bLen; j++ {
if i == 0 || j == 0 {
lcs[i][j] = 0
} else if aRunes[i-1] == bRunes[j-1] {
lcs[i][j] = lcs[i-1][j-1] + 1
} else {
lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])
}
}
}
// returning the length of longest common subsequence
return lcs[aLen][bLen]
}
#CURRENT FILE: Go-master/dynamic/subsetsum.go
|
Go-master
| 38
|
func TrapRainWater(height []int) int {
if len(height) == 0 {
return 0
}
leftMax := make([]int, len(height))
rightMax := make([]int, len(height))
leftMax[0] = height[0]
for i := 1; i < len(height); i++ {
leftMax[i] = int(math.Max(float64(leftMax[i-1]), float64(height[i])))
}
rightMax[len(height)-1] = height[len(height)-1]
for i := len(height) - 2; i >= 0; i-- {
rightMax[i] = int(math.Max(float64(rightMax[i+1]), float64(height[i])))
}
trappedWater := 0
for i := 0; i < len(height); i++ {
trappedWater += int(math.Min(float64(leftMax[i]), float64(rightMax[i]))) - height[i]
}
return trappedWater
}
|
func TrapRainWater(height []int) int {
if len(height) == 0 {
return 0
}
leftMax := make([]int, len(height))
rightMax := make([]int, len(height))
leftMax[0] = height[0]
for i := 1; i < len(height); i++ {
leftMax[i] = int(math.Max(float64(leftMax[i-1]), float64(height[i])))
}
rightMax[len(height)-1] = height[len(height)-1]
for i := len(height) - 2; i >= 0; i-- {
rightMax[i] = int(math.Max(float64(rightMax[i+1]), float64(height[i])))
}
trappedWater := 0
for i := 0; i < len(height); i++ {
trappedWater += int(math.Min(float64(leftMax[i]), float64(rightMax[i]))) - height[i]
}
return trappedWater
}
|
func TrapRainWater(height []int) int {
if len(height) == 0 {
return 0
}
leftMax := make([]int, len(height))
rightMax := make([]int, len(height))
leftMax[0] = height[0]
for i := 1; i < len(height); i++ {
leftMax[i] = int(math.Max(float64(leftMax[i-1]), float64(height[i])))
}
rightMax[len(height)-1] = height[len(height)-1]
for i := len(height) - 2; i >= 0; i-- {
rightMax[i] = int(math.Max(float64(rightMax[i+1]), float64(height[i])))
}
trappedWater := 0
for i := 0; i < len(height); i++ {
trappedWater += int(math.Min(float64(leftMax[i]), float64(rightMax[i]))) - height[i]
}
return trappedWater
}
|
TrapRainWater
| 18
| 42
|
dynamic/traprainwater.go
|
#FILE: Go-master/sort/radixsort.go
##CHUNK 1
digits[(item/exp)%10]++
}
for i := 1; i < 10; i++ {
digits[i] += digits[i-1]
}
for i := len(arr) - 1; i >= 0; i-- {
output[digits[(arr[i]/exp)%10]-1] = arr[i]
digits[(arr[i]/exp)%10]--
}
return output
}
func unsignedRadixSort[T constraints.Integer](arr []T) []T {
if len(arr) == 0 {
return arr
}
maxElement := max.Int(arr...)
for exp := T(1); maxElement/exp > 0; exp *= 10 {
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/matrixmultiplication.go
##CHUNK 1
}
return q
}
// MatrixChainDp function
func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
##CHUNK 2
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
prod := dp[i][k] + dp[k+1][j] + D[i-1]*D[k]*D[j]
dp[i][j] = min.Int(prod, dp[i][j])
}
}
}
return dp[1][N-1]
}
/*
#FILE: Go-master/structure/tree/btree_test.go
##CHUNK 1
if tree.Search(0) {
t.Errorf("Tree expected to contain 0")
}
for i := size - 1; i >= 0; i-- {
tree.Insert(i)
}
for i := 0; i < size; i++ {
if !tree.Search(i) {
t.Errorf("Tree expected to contain %d", i)
}
}
if tree.Search(size + 1) {
t.Errorf("Tree not expected to contain %d", size+1)
}
for i := 0; i < size; i += 5 {
tree.Delete(i)
}
for i := 0; i < size; i++ {
hasKey := tree.Search(i)
##CHUNK 2
}
}
}
func TestBTreeDecreasing(t *testing.T) {
maxKeysCases := []int{4, 16}
sizes := []int{100, 1000}
for _, maxKeys := range maxKeysCases {
for _, size := range sizes {
tree := bt.NewBTree[int](maxKeys)
if tree.Search(0) {
t.Errorf("Tree expected to contain 0")
}
for i := size - 1; i >= 0; i-- {
tree.Insert(i)
}
for i := 0; i < size; i++ {
if !tree.Search(i) {
t.Errorf("Tree expected to contain %d", i)
}
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
#FILE: Go-master/structure/linkedlist/cyclic.go
##CHUNK 1
if places < 0 {
multiple := cl.Size - 1 - places/cl.Size
places += multiple * cl.Size
}
places %= cl.Size
if places > cl.Size/2 {
places = cl.Size - places
for i := 0; i < places; i++ {
cl.Head = cl.Head.Prev
}
} else if places == 0 {
return
} else {
for i := 0; i < places; i++ {
cl.Head = cl.Head.Next
}
}
}
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
##CHUNK 2
// LpsRec function
func LpsRec(word string) int {
return lpsRec(word, 0, len(word)-1)
}
// LpsDp function
func LpsDp(word string) int {
N := len(word)
dp := make([][]int, N)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
#CURRENT FILE: Go-master/dynamic/traprainwater.go
|
Go-master
| 39
|
func LpsDp(word string) int {
N := len(word)
dp := make([][]int, N)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
return dp[0][N-1]
}
|
func LpsDp(word string) int {
N := len(word)
dp := make([][]int, N)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
return dp[0][N-1]
}
|
func LpsDp(word string) int {
N := len(word)
dp := make([][]int, N)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
return dp[0][N-1]
}
|
LpsDp
| 26
| 52
|
dynamic/longestpalindromicsubsequence.go
|
#FILE: Go-master/dynamic/matrixmultiplication.go
##CHUNK 1
}
return q
}
// MatrixChainDp function
func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
##CHUNK 2
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
prod := dp[i][k] + dp[k+1][j] + D[i-1]*D[k]*D[j]
dp[i][j] = min.Int(prod, dp[i][j])
}
}
}
return dp[1][N-1]
}
/*
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
##CHUNK 2
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/wildcardmatching.go
##CHUNK 1
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
#FILE: Go-master/dynamic/longestcommonsubsequence.go
##CHUNK 1
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i := 0; i <= aLen; i++ {
for j := 0; j <= bLen; j++ {
if i == 0 || j == 0 {
lcs[i][j] = 0
} else if aRunes[i-1] == bRunes[j-1] {
lcs[i][j] = lcs[i-1][j-1] + 1
} else {
lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])
}
}
}
// returning the length of longest common subsequence
return lcs[aLen][bLen]
}
#FILE: Go-master/search/selectk.go
##CHUNK 1
func partition(array []int, l, r int) int {
elem, j := array[l], l+1
for i := l + 1; i < r; i++ {
if array[i] <= elem {
array[i], array[j] = array[j], array[i]
j++
}
}
array[l], array[j-1] = array[j-1], array[l]
return j - 1
}
#CURRENT FILE: Go-master/dynamic/longestpalindromicsubsequence.go
|
Go-master
| 40
|
func UniquePaths(m, n int) int {
if m <= 0 || n <= 0 {
return 0
}
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
for i := 0; i < m; i++ {
grid[i][0] = 1
}
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}
return grid[m-1][n-1]
}
|
func UniquePaths(m, n int) int {
if m <= 0 || n <= 0 {
return 0
}
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
for i := 0; i < m; i++ {
grid[i][0] = 1
}
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}
return grid[m-1][n-1]
}
|
func UniquePaths(m, n int) int {
if m <= 0 || n <= 0 {
return 0
}
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
for i := 0; i < m; i++ {
grid[i][0] = 1
}
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}
return grid[m-1][n-1]
}
|
UniquePaths
| 7
| 32
|
dynamic/uniquepaths.go
|
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
##CHUNK 2
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
return dp[m][sum]
}
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/longestarithmeticsubsequence.go
##CHUNK 1
n := len(nums)
if n <= 1 {
return n
}
dp := make([]map[int]int, n)
for i := range dp {
dp[i] = make(map[int]int)
}
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
##CHUNK 2
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
}
return maxLength
}
#FILE: Go-master/dynamic/binomialcoefficient.go
##CHUNK 1
// }
// }
// Bin2 function
func Bin2(n int, k int) int {
var i, j int
B := make([][]int, (n + 1))
for i := range B {
B[i] = make([]int, k+1)
}
for i = 0; i <= n; i++ {
for j = 0; j <= min.Int(i, k); j++ {
if j == 0 || j == i {
B[i][j] = 1
} else {
B[i][j] = B[i-1][j-1] + B[i-1][j]
}
}
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
#FILE: Go-master/math/pascal/pascaltriangle.go
##CHUNK 1
// see pascaltriangle_test.go
package pascal
// GenerateTriangle This function generates a Pascal's triangle of n lines
func GenerateTriangle(n int) [][]int {
var triangle = make([][]int, n)
for i := 0; i < n; i++ {
triangle[i] = make([]int, i+1)
triangle[i][0], triangle[i][i] = 1, 1
for j := 1; j < i; j++ {
triangle[i][j] = triangle[i-1][j] + triangle[i-1][j-1]
}
}
return triangle
}
#FILE: Go-master/dynamic/longestcommonsubsequence.go
##CHUNK 1
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i := 0; i <= aLen; i++ {
for j := 0; j <= bLen; j++ {
if i == 0 || j == 0 {
lcs[i][j] = 0
} else if aRunes[i-1] == bRunes[j-1] {
lcs[i][j] = lcs[i-1][j-1] + 1
} else {
lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])
}
}
}
// returning the length of longest common subsequence
return lcs[aLen][bLen]
}
#CURRENT FILE: Go-master/dynamic/uniquepaths.go
|
Go-master
| 41
|
func Abbreviation(a string, b string) bool {
dp := make([][]bool, len(a)+1)
for i := range dp {
dp[i] = make([]bool, len(b)+1)
}
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] = true
}
if string(a[i]) == strings.ToLower(string(a[i])) {
dp[i+1][j] = true
}
}
}
}
return dp[len(a)][len(b)]
}
|
func Abbreviation(a string, b string) bool {
dp := make([][]bool, len(a)+1)
for i := range dp {
dp[i] = make([]bool, len(b)+1)
}
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] = true
}
if string(a[i]) == strings.ToLower(string(a[i])) {
dp[i+1][j] = true
}
}
}
}
return dp[len(a)][len(b)]
}
|
func Abbreviation(a string, b string) bool {
dp := make([][]bool, len(a)+1)
for i := range dp {
dp[i] = make([]bool, len(b)+1)
}
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] = true
}
if string(a[i]) == strings.ToLower(string(a[i])) {
dp[i+1][j] = true
}
}
}
}
return dp[len(a)][len(b)]
}
|
Abbreviation
| 25
| 46
|
dynamic/abbreviation.go
|
#FILE: Go-master/dynamic/wildcardmatching.go
##CHUNK 1
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
##CHUNK 2
// wildcardmatching.go
// description: Solves the Wildcard Matching problem using dynamic programming
// reference: https://en.wikipedia.org/wiki/Wildcard_matching
// time complexity: O(m*n)
// space complexity: O(m*n)
package dynamic
// IsMatch checks if the string `s` matches the wildcard pattern `p`
func IsMatch(s, p string) bool {
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
#FILE: Go-master/dynamic/interleavingstrings.go
##CHUNK 1
if len(s1)+len(s2) != len(s3) {
return false
}
dp := make([][]bool, len(s1)+1)
for i := range dp {
dp[i] = make([]bool, len(s2)+1)
}
dp[0][0] = true
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
#FILE: Go-master/dynamic/wordbreak.go
##CHUNK 1
wordSet := make(map[string]bool)
for _, word := range wordDict {
wordSet[word] = true
}
dp := make([]bool, len(s)+1)
dp[0] = true
for i := 1; i <= len(s); i++ {
for j := 0; j < i; j++ {
if dp[j] && wordSet[s[j:i]] {
dp[i] = true
break
}
}
}
return dp[len(s)]
}
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
##CHUNK 2
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
dp[i][j] = (s[i] == s[j])
} else {
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
}
if dp[i][j] && length > maxLength {
maxLength = length
start = i
}
}
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/longestarithmeticsubsequence.go
##CHUNK 1
n := len(nums)
if n <= 1 {
return n
}
dp := make([]map[int]int, n)
for i := range dp {
dp[i] = make(map[int]int)
}
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
#CURRENT FILE: Go-master/dynamic/abbreviation.go
|
Go-master
| 42
|
func IsMatch(s, p string) bool {
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
}
return dp[len(s)][len(p)]
}
|
func IsMatch(s, p string) bool {
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
}
return dp[len(s)][len(p)]
}
|
func IsMatch(s, p string) bool {
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else if p[j-1] == '*' {
dp[i][j] = dp[i-1][j] || dp[i][j-1]
}
}
}
return dp[len(s)][len(p)]
}
|
IsMatch
| 9
| 32
|
dynamic/wildcardmatching.go
|
#FILE: Go-master/dynamic/interleavingstrings.go
##CHUNK 1
if len(s1)+len(s2) != len(s3) {
return false
}
dp := make([][]bool, len(s1)+1)
for i := range dp {
dp[i] = make([]bool, len(s2)+1)
}
dp[0][0] = true
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
##CHUNK 2
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {
dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1])
}
}
return dp[len(s1)][len(s2)]
}
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
##CHUNK 2
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
return dp[m][sum]
}
#FILE: Go-master/dynamic/wordbreak.go
##CHUNK 1
wordSet := make(map[string]bool)
for _, word := range wordDict {
wordSet[word] = true
}
dp := make([]bool, len(s)+1)
dp[0] = true
for i := 1; i <= len(s); i++ {
for j := 0; j < i; j++ {
if dp[j] && wordSet[s[j:i]] {
dp[i] = true
break
}
}
}
return dp[len(s)]
}
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/abbreviation.go
##CHUNK 1
import (
"strings"
)
// Returns true if it is possible to make a equals b (if b is an abbreviation of a), returns false otherwise
func Abbreviation(a string, b string) bool {
dp := make([][]bool, len(a)+1)
for i := range dp {
dp[i] = make([]bool, len(b)+1)
}
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] = true
}
if string(a[i]) == strings.ToLower(string(a[i])) {
dp[i+1][j] = true
##CHUNK 2
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] = true
}
if string(a[i]) == strings.ToLower(string(a[i])) {
dp[i+1][j] = true
}
}
}
}
return dp[len(a)][len(b)]
}
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
#FILE: Go-master/dynamic/eggdropping.go
##CHUNK 1
return floors
}
// Initialize DP table
dp := make([][]int, eggs+1)
for i := range dp {
dp[i] = make([]int, floors+1)
}
// Fill the DP table for 1 egg
for j := 1; j <= floors; j++ {
dp[1][j] = j
}
// Fill the DP table for more than 1 egg
for i := 2; i <= eggs; i++ {
for j := 2; j <= floors; j++ {
dp[i][j] = int(^uint(0) >> 1) // initialize with a large number
for x := 1; x <= j; x++ {
// Recurrence relation to fill the DP table
#CURRENT FILE: Go-master/dynamic/wildcardmatching.go
|
Go-master
| 43
|
func Generate(minLength int, maxLength int) string {
var chars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~")
length, err := rand.Int(rand.Reader, big.NewInt(int64(maxLength-minLength)))
if err != nil {
panic(err) // handle this gracefully
}
length.Add(length, big.NewInt(int64(minLength)))
intLength := int(length.Int64())
newPassword := make([]byte, intLength)
randomData := make([]byte, intLength+intLength/4)
charLen := byte(len(chars))
maxrb := byte(256 - (256 % len(chars)))
i := 0
for {
if _, err := io.ReadFull(rand.Reader, randomData); err != nil {
panic(err)
}
for _, c := range randomData {
if c >= maxrb {
continue
}
newPassword[i] = chars[c%charLen]
i++
if i == intLength {
return string(newPassword)
}
}
}
}
|
func Generate(minLength int, maxLength int) string {
var chars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~")
length, err := rand.Int(rand.Reader, big.NewInt(int64(maxLength-minLength)))
if err != nil {
panic(err) // handle this gracefully
}
length.Add(length, big.NewInt(int64(minLength)))
intLength := int(length.Int64())
newPassword := make([]byte, intLength)
randomData := make([]byte, intLength+intLength/4)
charLen := byte(len(chars))
maxrb := byte(256 - (256 % len(chars)))
i := 0
for {
if _, err := io.ReadFull(rand.Reader, randomData); err != nil {
panic(err)
}
for _, c := range randomData {
if c >= maxrb {
continue
}
newPassword[i] = chars[c%charLen]
i++
if i == intLength {
return string(newPassword)
}
}
}
}
|
func Generate(minLength int, maxLength int) string {
var chars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~")
length, err := rand.Int(rand.Reader, big.NewInt(int64(maxLength-minLength)))
if err != nil {
panic(err) // handle this gracefully
}
length.Add(length, big.NewInt(int64(minLength)))
intLength := int(length.Int64())
newPassword := make([]byte, intLength)
randomData := make([]byte, intLength+intLength/4)
charLen := byte(len(chars))
maxrb := byte(256 - (256 % len(chars)))
i := 0
for {
if _, err := io.ReadFull(rand.Reader, randomData); err != nil {
panic(err)
}
for _, c := range randomData {
if c >= maxrb {
continue
}
newPassword[i] = chars[c%charLen]
i++
if i == intLength {
return string(newPassword)
}
}
}
}
|
Generate
| 17
| 48
|
other/password/generator.go
|
#FILE: Go-master/strings/guid/guid.go
##CHUNK 1
for i, ch := range pattern {
if i == versionIndex {
guid.WriteRune(ch)
continue
}
if ch == '-' {
guid.WriteRune(ch)
continue
}
random, err := rand.Int(rand.Reader, big.NewInt(16))
if err != nil {
return "", err
}
guid.WriteString(fmt.Sprintf("%x", random.Int64()))
}
return guid.String(), nil
}
#FILE: Go-master/project_euler/problem_18/problem18.go
##CHUNK 1
tree := &Tree{}
for _, num := range input {
v, err := strconv.Atoi(num)
if err != nil {
panic(err)
}
tree.BFSInsert(NodeValue(v))
}
return tree.MaxPathValueSearch(deep)
}
##CHUNK 2
RightIsNil() bool
HasSpace() bool
Kind() string
SetParent(Node)
CreateChild(NodeValue, int) Node
Insert(Node)
}
)
func Problem18(input []string, deep int) int {
tree := &Tree{}
for _, num := range input {
v, err := strconv.Atoi(num)
if err != nil {
panic(err)
}
tree.BFSInsert(NodeValue(v))
}
#FILE: Go-master/structure/circularqueue/circularqueue_test.go
##CHUNK 1
for i := 0; i < b.N; i++ {
if err := queue.Enqueue(i); err != nil {
b.Error(err)
}
}
})
b.Run("Dequeue", func(b *testing.B) {
queue, _ := NewCircularQueue[int](1000)
for i := 0; i < 1000; i++ {
if err := queue.Enqueue(i); err != nil {
b.Error(err)
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := queue.Dequeue(); err != nil {
b.Error(err)
}
}
##CHUNK 2
if err := queue.Enqueue(i); err != nil {
b.Error(err)
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := queue.Dequeue(); err != nil {
b.Error(err)
}
}
})
b.Run("Peek", func(b *testing.B) {
queue, _ := NewCircularQueue[int](1000)
for i := 0; i < 1000; i++ {
if err := queue.Enqueue(i); err != nil {
b.Error(err)
}
}
b.ResetTimer()
##CHUNK 3
})
b.Run("Peek", func(b *testing.B) {
queue, _ := NewCircularQueue[int](1000)
for i := 0; i < 1000; i++ {
if err := queue.Enqueue(i); err != nil {
b.Error(err)
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := queue.Peek(); err != nil {
b.Error(err)
}
}
})
}
##CHUNK 4
t.Error(err)
}
if err := queue.Enqueue(2); err != nil {
t.Error(err)
}
if err := queue.Enqueue(3); err != nil {
t.Error(err)
}
if _, err := queue.Dequeue(); err != nil {
t.Error(err)
}
if _, err := queue.Dequeue(); err != nil {
t.Error(err)
}
if err := queue.Enqueue(4); err != nil {
t.Error(err)
}
if err := queue.Enqueue(5); err != nil {
t.Error(err)
}
#FILE: Go-master/cipher/dsa/dsa.go
##CHUNK 1
var err error
p, q, bigInt := new(big.Int), new(big.Int), new(big.Int)
one, g, h := big.NewInt(1), big.NewInt(1), big.NewInt(2)
pBytes := make([]byte, L/8)
// GPLoop is a label for the loop
// We use this loop to change the prime q if we don't find a prime p
GPLoop:
for {
// 2. Choose a N-bit prime q
q, err = rand.Prime(rand.Reader, N)
if err != nil {
panic(err)
}
for i := 0; i < 4*L; i++ {
// 3. Choose a L-bit prime p such that p-1 is a multiple of q
// In this case we generate a random number of L bits
if _, err := io.ReadFull(rand.Reader, pBytes); err != nil {
panic(err)
#FILE: Go-master/math/prime/prime_test.go
##CHUNK 1
}
func primalityTestBenchmarkHelper(b *testing.B, f primalityTest) {
for i := 0; i < b.N; i++ {
f(104729)
}
}
// Miller-Rabin Probabilistic test
func millerRabinProbabilisticTester(n int64) bool {
result, err := MillerRabinProbabilistic(n, 40)
if err != nil {
panic(err)
}
return result
}
func TestMillerRabinProbabilistic(t *testing.T) {
#FILE: Go-master/math/pi/montecarlopi_test.go
##CHUNK 1
}
}
func TestMonteCarloPi2(t *testing.T) {
res, err := MonteCarloPiConcurrent(100000000)
if err != nil {
t.Errorf("unexpected error %s", err)
}
result := fmt.Sprintf("%.2f", res)
t.Log(result)
if result != "3.14" {
t.Errorf("Wrong result! Expected:%f, returned:%s ", 3.1415, result)
}
}
func BenchmarkMonteCarloPi2(b *testing.B) {
for i := 0; i < b.N; i++ {
_, err := MonteCarloPiConcurrent(100000000)
if err != nil {
b.Fatalf("unexpected error - %s", err)
#CURRENT FILE: Go-master/other/password/generator.go
|
Go-master
| 44
|
func IsBalanced(input string) bool {
if len(input) == 0 {
return true
}
if len(input)%2 != 0 {
return false
}
// Brackets such as '{', '[', '(' are valid UTF-8 characters,
// which means that only one byte is required to code them,
// so can be stored as bytes.
var stack []byte
for i := 0; i < len(input); i++ {
if input[i] == '(' || input[i] == '{' || input[i] == '[' {
stack = append(stack, input[i])
} else {
if len(stack) > 0 {
pair := string(stack[len(stack)-1]) + string(input[i])
stack = stack[:len(stack)-1]
if pair != "[]" && pair != "{}" && pair != "()" {
// This means that two types of brackets has
// been mixed together, for example "([)]",
// which makes seuqence invalid by definition.
return false
}
} else {
// This means that closing bracket is encountered
// before opening one, which makes all sequence
// invalid by definition.
return false
}
}
}
// If sequence is properly nested, all elements in stack
// has been paired with closing elements. If even one
// element has not been paired with a closing bracket,
// means that sequence is invalid by definition.
return len(stack) == 0
}
|
func IsBalanced(input string) bool {
if len(input) == 0 {
return true
}
if len(input)%2 != 0 {
return false
}
// Brackets such as '{', '[', '(' are valid UTF-8 characters,
// which means that only one byte is required to code them,
// so can be stored as bytes.
var stack []byte
for i := 0; i < len(input); i++ {
if input[i] == '(' || input[i] == '{' || input[i] == '[' {
stack = append(stack, input[i])
} else {
if len(stack) > 0 {
pair := string(stack[len(stack)-1]) + string(input[i])
stack = stack[:len(stack)-1]
if pair != "[]" && pair != "{}" && pair != "()" {
// This means that two types of brackets has
// been mixed together, for example "([)]",
// which makes seuqence invalid by definition.
return false
}
} else {
// This means that closing bracket is encountered
// before opening one, which makes all sequence
// invalid by definition.
return false
}
}
}
// If sequence is properly nested, all elements in stack
// has been paired with closing elements. If even one
// element has not been paired with a closing bracket,
// means that sequence is invalid by definition.
return len(stack) == 0
}
|
func IsBalanced(input string) bool {
if len(input) == 0 {
return true
}
if len(input)%2 != 0 {
return false
}
// Brackets such as '{', '[', '(' are valid UTF-8 characters,
// which means that only one byte is required to code them,
// so can be stored as bytes.
var stack []byte
for i := 0; i < len(input); i++ {
if input[i] == '(' || input[i] == '{' || input[i] == '[' {
stack = append(stack, input[i])
} else {
if len(stack) > 0 {
pair := string(stack[len(stack)-1]) + string(input[i])
stack = stack[:len(stack)-1]
if pair != "[]" && pair != "{}" && pair != "()" {
// This means that two types of brackets has
// been mixed together, for example "([)]",
// which makes seuqence invalid by definition.
return false
}
} else {
// This means that closing bracket is encountered
// before opening one, which makes all sequence
// invalid by definition.
return false
}
}
}
// If sequence is properly nested, all elements in stack
// has been paired with closing elements. If even one
// element has not been paired with a closing bracket,
// means that sequence is invalid by definition.
return len(stack) == 0
}
|
IsBalanced
| 22
| 64
|
other/nested/nestedbrackets.go
|
#FILE: Go-master/structure/stack/stacklinkedlistwithlist.go
##CHUNK 1
element := sl.Stack.Front()
// remove element in stack
sl.Stack.Remove(element)
// return element value
return element.Value, nil
}
return "", fmt.Errorf("stack list is empty")
}
// Length return length of our stack
func (sl *SList) Length() int {
return sl.Stack.Len()
}
// Empty check our stack has value or not
func (sl *SList) IsEmpty() bool {
// check our stack is empty or not
// if is 0 it means our stack is empty otherwise is not empty
return sl.Stack.Len() == 0
}
#FILE: Go-master/graph/depthfirstsearch.go
##CHUNK 1
stack = append(stack, startIdx)
for len(stack) > 0 {
now := stack[len(stack)-1]
route = append(route, nodes[now])
if len(stack) > 1 {
stack = stack[:len(stack)-1]
} else {
stack = stack[:len(stack)-1]
}
for i := 0; i < len(edges[now]); i++ {
if edges[now][i] && NotExist(i, stack) {
stack = append(stack, i)
}
edges[now][i] = false
edges[i][now] = false
}
if route[len(route)-1] == end {
return route, true
}
}
##CHUNK 2
return false
}
}
return true
}
func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool) {
var route []int
var stack []int
startIdx := GetIdx(start, nodes)
stack = append(stack, startIdx)
for len(stack) > 0 {
now := stack[len(stack)-1]
route = append(route, nodes[now])
if len(stack) > 1 {
stack = stack[:len(stack)-1]
} else {
stack = stack[:len(stack)-1]
}
for i := 0; i < len(edges[now]); i++ {
#FILE: Go-master/math/binary/checkisnumberpoweroftwo.go
##CHUNK 1
// This is also true for 0, which is not a power of 2, for which we
// have to add and extra condition.
func IsPowerOfTwo(x int) bool {
return x > 0 && (x&(x-1)) == 0
}
// IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number
// by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000,
// which in decimal system is 8 or = 2 * 2 * 2
func IsPowerOfTwoLeftShift(number uint) bool {
for p := uint(1); p <= number; p = p << 1 {
if number == p {
return true
}
}
return false
}
#FILE: Go-master/strings/parenthesis/parenthesis.go
##CHUNK 1
package parenthesis
// Parenthesis algorithm checks if every opened parenthesis
// is closed correctly. When parcounter is less than 0 when a closing
// parenthesis is detected without an opening parenthesis
// that surrounds it and parcounter will be 0 if all open
// parenthesis are closed correctly.
func Parenthesis(text string) bool {
parcounter := 0
for _, r := range text {
switch r {
case '(':
parcounter++
case ')':
parcounter--
}
if parcounter < 0 {
return false
}
#FILE: Go-master/dynamic/eggdropping.go
##CHUNK 1
// Edge case: If there are no floors, no attempts needed
if floors == 0 {
return 0
}
// Edge case: If there is one floor, one attempt needed
if floors == 1 {
return 1
}
// Edge case: If there is one egg, need to test all floors one by one
if eggs == 1 {
return floors
}
// Initialize DP table
dp := make([][]int, eggs+1)
for i := range dp {
dp[i] = make([]int, floors+1)
}
// Fill the DP table for 1 egg
#FILE: Go-master/graph/floydwarshall.go
##CHUNK 1
type WeightedGraph [][]float64
// Defining maximum value. If two vertices share this value, it means they are not connected
var Inf = math.Inf(1)
// FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm
func FloydWarshall(graph WeightedGraph) WeightedGraph {
// If graph is empty, returns nil
if len(graph) == 0 || len(graph) != len(graph[0]) {
return nil
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
numVertices := len(graph)
#FILE: Go-master/math/prime/primecheck.go
##CHUNK 1
return false
}
// 2 and 3 are prime
if n < 4 {
return true
}
// all numbers divisible by 2 except 2 are not prime
if n%2 == 0 {
return false
}
for i := int64(3); i*i <= n; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
#FILE: Go-master/strings/genetic/genetic.go
##CHUNK 1
debug := conf.Debug
// Just a seed to improve randomness required by the algorithm
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
// Verify that the target contains no genes besides the ones inside genes variable.
for position, r := range target {
invalid := true
for _, n := range charmap {
if n == r {
invalid = false
}
}
if invalid {
message := fmt.Sprintf("character not available in charmap at position: %v", position)
return nil, errors.New(message)
}
}
#FILE: Go-master/strings/bom/bom.go
##CHUNK 1
// }
// // Checks if state exists. Returns true if it does, false otherwise.
// func stateExists(state int, at map[int]map[uint8]int) bool {
// _, ok := at[state]
// if !ok || state == -1 || at[state] == nil {
// return false
// }
// return true
// }
// // Just some printing of extra information about what the algorithm does.
// func prettyPrint(current int, j int, n int, pos int, t string, oracle map[int]map[uint8]int) {
// if current == 0 && !(getTransition(current, t[pos+j-1], oracle) == -1) {
// fmt.Printf("\n -->(%d)---(%c)--->(%d)", current, t[pos+j-1], getTransition(current, t[pos+j-1], oracle))
// } else if getTransition(current, t[pos+j-1], oracle) == -1 && current != 0 {
// fmt.Printf("\n (%d)---(%c) ", current, t[pos+j-1])
// } else if getTransition(current, t[pos+j-1], oracle) == -1 && current == 0 {
// fmt.Printf("\n -->(%d)---(%c) ", current, t[pos+j-1])
// } else {
#CURRENT FILE: Go-master/other/nested/nestedbrackets.go
|
Go-master
| 45
|
func hexToDecimal(hexStr string) (int64, error) {
hexStr = strings.TrimSpace(hexStr)
if len(hexStr) == 0 {
return 0, fmt.Errorf("input string is empty")
}
// Check if the string has a valid hexadecimal prefix
if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") {
hexStr = hexStr[2:]
}
// Validate the hexadecimal string
if !isValidHexadecimal(hexStr) {
return 0, fmt.Errorf("invalid hexadecimal string")
}
var decimalValue int64
for _, char := range hexStr {
var digit int64
if char >= '0' && char <= '9' {
digit = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
digit = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
digit = int64(char - 'a' + 10)
} else {
return 0, fmt.Errorf("invalid character in hexadecimal string: %c", char)
}
decimalValue = decimalValue*16 + digit
}
return decimalValue, nil
}
|
func hexToDecimal(hexStr string) (int64, error) {
hexStr = strings.TrimSpace(hexStr)
if len(hexStr) == 0 {
return 0, fmt.Errorf("input string is empty")
}
// Check if the string has a valid hexadecimal prefix
if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") {
hexStr = hexStr[2:]
}
// Validate the hexadecimal string
if !isValidHexadecimal(hexStr) {
return 0, fmt.Errorf("invalid hexadecimal string")
}
var decimalValue int64
for _, char := range hexStr {
var digit int64
if char >= '0' && char <= '9' {
digit = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
digit = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
digit = int64(char - 'a' + 10)
} else {
return 0, fmt.Errorf("invalid character in hexadecimal string: %c", char)
}
decimalValue = decimalValue*16 + digit
}
return decimalValue, nil
}
|
func hexToDecimal(hexStr string) (int64, error) {
hexStr = strings.TrimSpace(hexStr)
if len(hexStr) == 0 {
return 0, fmt.Errorf("input string is empty")
}
// Check if the string has a valid hexadecimal prefix
if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") {
hexStr = hexStr[2:]
}
// Validate the hexadecimal string
if !isValidHexadecimal(hexStr) {
return 0, fmt.Errorf("invalid hexadecimal string")
}
var decimalValue int64
for _, char := range hexStr {
var digit int64
if char >= '0' && char <= '9' {
digit = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
digit = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
digit = int64(char - 'a' + 10)
} else {
return 0, fmt.Errorf("invalid character in hexadecimal string: %c", char)
}
decimalValue = decimalValue*16 + digit
}
return decimalValue, nil
}
|
hexToDecimal
| 22
| 56
|
conversion/hexadecimaltodecimal.go
|
#FILE: Go-master/conversion/hexadecimaltobinary.go
##CHUNK 1
}
// Check if the hexadecimal string is valid
if !isValidHex(hex) {
return "", errors.New("invalid hexadecimal string: " + hex)
}
// Parse the hexadecimal string to an integer
var decimal int64
for i := 0; i < len(hex); i++ {
char := hex[i]
var value int64
if char >= '0' && char <= '9' {
value = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
value = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
value = int64(char - 'a' + 10)
} else {
return "", errors.New("invalid character in hexadecimal string: " + string(char))
##CHUNK 2
char := hex[i]
var value int64
if char >= '0' && char <= '9' {
value = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
value = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
value = int64(char - 'a' + 10)
} else {
return "", errors.New("invalid character in hexadecimal string: " + string(char))
}
decimal = decimal*16 + value
}
// Convert the integer to a binary string without using predefined functions
var binaryBuilder strings.Builder
if decimal == 0 {
binaryBuilder.WriteString("0")
} else {
for decimal > 0 {
##CHUNK 3
// hexToBinary() function that will take Hexadecimal number as string,
// and return its Binary equivalent as a string.
func hexToBinary(hex string) (string, error) {
// Trim any leading or trailing whitespace
hex = strings.TrimSpace(hex)
// Check if the hexadecimal string is empty
if hex == "" {
return "", errors.New("input string is empty")
}
// Check if the hexadecimal string is valid
if !isValidHex(hex) {
return "", errors.New("invalid hexadecimal string: " + hex)
}
// Parse the hexadecimal string to an integer
var decimal int64
for i := 0; i < len(hex); i++ {
#FILE: Go-master/cipher/railfence/railfence.go
##CHUNK 1
matrix[row][col] = char
col++
if dirDown {
row++
} else {
row--
}
}
var result strings.Builder
for _, line := range matrix {
for _, char := range line {
if char != 0 {
result.WriteRune(char)
}
}
}
return result.String()
}
func Decrypt(cipherText string, rails int) string {
##CHUNK 2
matrix[i] = make([]rune, len(text))
}
// Fill the matrix
dirDown := false
row, col := 0, 0
for _, char := range text {
if row == 0 || row == rails-1 {
dirDown = !dirDown
}
matrix[row][col] = char
col++
if dirDown {
row++
} else {
row--
}
}
var result strings.Builder
for _, line := range matrix {
##CHUNK 3
for _, char := range line {
if char != 0 {
result.WriteRune(char)
}
}
}
return result.String()
}
func Decrypt(cipherText string, rails int) string {
if rails == 1 || rails >= len(cipherText) {
return cipherText
}
// Placeholder for the decrypted message
decrypted := make([]rune, len(cipherText))
// Calculate the zigzag pattern and place characters accordingly
index := 0
for rail := 0; rail < rails; rail++ {
##CHUNK 4
)
func Encrypt(text string, rails int) string {
if rails == 1 {
return text
}
// Create a matrix for the rail fence pattern
matrix := make([][]rune, rails)
for i := range matrix {
matrix[i] = make([]rune, len(text))
}
// Fill the matrix
dirDown := false
row, col := 0, 0
for _, char := range text {
if row == 0 || row == rails-1 {
dirDown = !dirDown
}
#FILE: Go-master/cipher/caesar/caesar.go
##CHUNK 1
// if key is negative value,
// updates "key" the number which congruents to "key" modulo 26
key8 := byte(key%26+26) % 26
var outputBuffer []byte
// b is a byte, which is the equivalent of uint8.
for _, b := range []byte(input) {
newByte := b
if 'A' <= b && b <= 'Z' {
outputBuffer = append(outputBuffer, 'A'+(newByte-'A'+key8)%26)
} else if 'a' <= b && b <= 'z' {
outputBuffer = append(outputBuffer, 'a'+(newByte-'a'+key8)%26)
} else {
outputBuffer = append(outputBuffer, newByte)
}
}
return string(outputBuffer)
}
// Decrypt decrypts by left shift of "key" each character of "input"
#FILE: Go-master/cipher/transposition/transposition.go
##CHUNK 1
}
func Encrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
keyLength := len(key)
textLength := len(text)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
if text[len(text)-1] == placeholder {
return nil, fmt.Errorf("%w: cannot encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder)
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
#FILE: Go-master/project_euler/problem_20/problem20.go
##CHUNK 1
for _, digit := range factorial.String() {
sum += int(digit - '0')
}
return sum
}
// bigFactorial returns the factorial of n as a big.Int
// Use big package to handle large numbers
func bigFactorial(n int) *big.Int {
if n < 0 {
return big.NewInt(0)
}
if n == 0 {
return big.NewInt(1)
}
return big.NewInt(0).Mul(big.NewInt(int64(n)), bigFactorial(n-1))
}
#CURRENT FILE: Go-master/conversion/hexadecimaltodecimal.go
|
Go-master
| 46
|
func Base64Encode(input []byte) string {
var sb strings.Builder
// If not 24 bits (3 bytes) multiple, pad with 0 value bytes, and with "=" for the output
var padding string
for i := len(input) % 3; i > 0 && i < 3; i++ {
var zeroByte byte
input = append(input, zeroByte)
padding += "="
}
// encode 24 bits per 24 bits (3 bytes per 3 bytes)
for i := 0; i < len(input); i += 3 {
// select 3 8-bit input groups, and re-arrange them into 4 6-bit groups
// the literal 0x3F corresponds to the byte "0011 1111"
// the operation "byte & 0x3F" masks the two left-most bits
group := [4]byte{
input[i] >> 2,
(input[i]<<4)&0x3F + input[i+1]>>4,
(input[i+1]<<2)&0x3F + input[i+2]>>6,
input[i+2] & 0x3F,
}
// translate each group into a char using the static map
for _, b := range group {
sb.WriteString(string(Alphabet[int(b)]))
}
}
encoded := sb.String()
// Apply the output padding
encoded = encoded[:len(encoded)-len(padding)] + padding[:]
return encoded
}
|
func Base64Encode(input []byte) string {
var sb strings.Builder
// If not 24 bits (3 bytes) multiple, pad with 0 value bytes, and with "=" for the output
var padding string
for i := len(input) % 3; i > 0 && i < 3; i++ {
var zeroByte byte
input = append(input, zeroByte)
padding += "="
}
// encode 24 bits per 24 bits (3 bytes per 3 bytes)
for i := 0; i < len(input); i += 3 {
// select 3 8-bit input groups, and re-arrange them into 4 6-bit groups
// the literal 0x3F corresponds to the byte "0011 1111"
// the operation "byte & 0x3F" masks the two left-most bits
group := [4]byte{
input[i] >> 2,
(input[i]<<4)&0x3F + input[i+1]>>4,
(input[i+1]<<2)&0x3F + input[i+2]>>6,
input[i+2] & 0x3F,
}
// translate each group into a char using the static map
for _, b := range group {
sb.WriteString(string(Alphabet[int(b)]))
}
}
encoded := sb.String()
// Apply the output padding
encoded = encoded[:len(encoded)-len(padding)] + padding[:]
return encoded
}
|
func Base64Encode(input []byte) string {
var sb strings.Builder
// If not 24 bits (3 bytes) multiple, pad with 0 value bytes, and with "=" for the output
var padding string
for i := len(input) % 3; i > 0 && i < 3; i++ {
var zeroByte byte
input = append(input, zeroByte)
padding += "="
}
// encode 24 bits per 24 bits (3 bytes per 3 bytes)
for i := 0; i < len(input); i += 3 {
// select 3 8-bit input groups, and re-arrange them into 4 6-bit groups
// the literal 0x3F corresponds to the byte "0011 1111"
// the operation "byte & 0x3F" masks the two left-most bits
group := [4]byte{
input[i] >> 2,
(input[i]<<4)&0x3F + input[i+1]>>4,
(input[i+1]<<2)&0x3F + input[i+2]>>6,
input[i+2] & 0x3F,
}
// translate each group into a char using the static map
for _, b := range group {
sb.WriteString(string(Alphabet[int(b)]))
}
}
encoded := sb.String()
// Apply the output padding
encoded = encoded[:len(encoded)-len(padding)] + padding[:]
return encoded
}
|
Base64Encode
| 20
| 53
|
conversion/base64.go
|
#FILE: Go-master/compression/rlecoding.go
##CHUNK 1
}
return result
}
// RLEdecodebytes takes a run-length encoded byte slice and returns the original byte slice
func RLEdecodebytes(data []byte) []byte {
var result []byte
for i := 0; i < len(data); i += 2 {
count := int(data[i])
result = append(result, bytes.Repeat([]byte{data[i+1]}, count)...)
}
return result
}
##CHUNK 2
var result []byte
var count byte = 1
for i := 0; i < len(data); i++ {
if i+1 < len(data) && data[i] == data[i+1] {
count++
continue
}
result = append(result, count, data[i])
count = 1
}
return result
}
// RLEdecodebytes takes a run-length encoded byte slice and returns the original byte slice
func RLEdecodebytes(data []byte) []byte {
var result []byte
for i := 0; i < len(data); i += 2 {
##CHUNK 3
count = 1
}
return result
}
// RLEdecode takes a run-length encoded string and returns the original string
func RLEdecode(data string) string {
var result string
regex := regexp.MustCompile(`(\d+)(\w)`)
for _, match := range regex.FindAllStringSubmatch(data, -1) {
num, _ := strconv.Atoi(match[1])
result += strings.Repeat(match[2], num)
}
return result
}
// RLEncodebytes takes a byte slice and returns its run-length encoding as a byte slice
func RLEncodebytes(data []byte) []byte {
##CHUNK 4
// RLEncode takes a string and returns its run-length encoding
func RLEncode(data string) string {
var result string
count := 1
for i := 0; i < len(data); i++ {
if i+1 < len(data) && data[i] == data[i+1] {
count++
continue
}
result += fmt.Sprintf("%d%c", count, data[i])
count = 1
}
return result
}
// RLEdecode takes a run-length encoded string and returns the original string
func RLEdecode(data string) string {
var result string
regex := regexp.MustCompile(`(\d+)(\w)`)
#FILE: Go-master/hashing/sha256/sha256.go
##CHUNK 1
// of 512 bits.
// The padding methodology is as follows:
// A "1" bit is appended at the end of the input message, followed by m "0" bits such as the length is
// 64 bits short of a 512 bits multiple. The remaining 64 bits are filled with the initial length of the
// message, represented as a 64-bits unsigned integer.
// For more details, see: https://datatracker.ietf.org/doc/html/rfc6234#section-4.1
func pad(message []byte) []byte {
L := make([]byte, 8)
binary.BigEndian.PutUint64(L, uint64(len(message)*8))
message = append(message, 0x80) // "1" bit followed by 7 "0" bits
for (len(message)+8)%64 != 0 {
message = append(message, 0x00) // 8 "0" bits
}
message = append(message, L...)
return message
}
// Hash hashes the input message using the sha256 hashing function, and return a 32 byte array.
// The implementation follows the RGC6234 standard, which is documented
#FILE: Go-master/structure/fenwicktree/fenwicktree.go
##CHUNK 1
prefixSum := 0
for i := pos; i > 0; i -= (i & -i) {
prefixSum += f.bit[i]
}
return prefixSum
}
// RangeSum returns the sum of the elements in the range l to r
// both inclusive.
func (f *FenwickTree) RangeSum(l int, r int) int {
return f.PrefixSum(r) - f.PrefixSum(l-1)
}
// Add Adds value to the element at position pos of the array
// and recomputes the range sums.
func (f *FenwickTree) Add(pos int, value int) {
for i := pos; i <= f.n; i += (i & -i) {
f.bit[i] += value
}
}
#FILE: Go-master/conversion/romantoint.go
##CHUNK 1
// with no error thrown.
func RomanToInt(input string) (int, error) {
if input == "" {
return 0, nil
}
var output int
for _, n := range nums {
for strings.HasPrefix(input, n.sym) {
output += n.val
input = input[len(n.sym):]
}
}
// if we are still left with input string values then the
// input was invalid and an error is returned.
if len(input) > 0 {
return 0, errors.New("invalid roman numeral")
}
return output, nil
}
#CURRENT FILE: Go-master/conversion/base64.go
##CHUNK 1
// Base64Decode decodes the received input base64 string into a byte slice.
// The implementation follows the RFC4648 standard, which is documented
// at https://datatracker.ietf.org/doc/html/rfc4648#section-4
func Base64Decode(input string) []byte {
padding := strings.Count(input, "=") // Number of bytes which will be ignored
var decoded []byte
// select 4 6-bit input groups, and re-arrange them into 3 8-bit groups
for i := 0; i < len(input); i += 4 {
// translate each group into a byte using the static map
byteInput := [4]byte{
byte(strings.IndexByte(Alphabet, input[i])),
byte(strings.IndexByte(Alphabet, input[i+1])),
byte(strings.IndexByte(Alphabet, input[i+2])),
byte(strings.IndexByte(Alphabet, input[i+3])),
}
group := [3]byte{
byteInput[0]<<2 + byteInput[1]>>4,
##CHUNK 2
import (
"strings" // Used for efficient string builder (more efficient than simply appending strings)
)
const Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
// Base64Encode encodes the received input bytes slice into a base64 string.
// The implementation follows the RFC4648 standard, which is documented
}
// Base64Decode decodes the received input base64 string into a byte slice.
// The implementation follows the RFC4648 standard, which is documented
// at https://datatracker.ietf.org/doc/html/rfc4648#section-4
func Base64Decode(input string) []byte {
padding := strings.Count(input, "=") // Number of bytes which will be ignored
var decoded []byte
// select 4 6-bit input groups, and re-arrange them into 3 8-bit groups
for i := 0; i < len(input); i += 4 {
##CHUNK 3
// translate each group into a byte using the static map
byteInput := [4]byte{
byte(strings.IndexByte(Alphabet, input[i])),
byte(strings.IndexByte(Alphabet, input[i+1])),
byte(strings.IndexByte(Alphabet, input[i+2])),
byte(strings.IndexByte(Alphabet, input[i+3])),
}
group := [3]byte{
byteInput[0]<<2 + byteInput[1]>>4,
byteInput[1]<<4 + byteInput[2]>>2,
byteInput[2]<<6 + byteInput[3],
}
decoded = append(decoded, group[:]...)
}
return decoded[:len(decoded)-padding]
}
|
Go-master
| 47
|
func hexToBinary(hex string) (string, error) {
// Trim any leading or trailing whitespace
hex = strings.TrimSpace(hex)
// Check if the hexadecimal string is empty
if hex == "" {
return "", errors.New("input string is empty")
}
// Check if the hexadecimal string is valid
if !isValidHex(hex) {
return "", errors.New("invalid hexadecimal string: " + hex)
}
// Parse the hexadecimal string to an integer
var decimal int64
for i := 0; i < len(hex); i++ {
char := hex[i]
var value int64
if char >= '0' && char <= '9' {
value = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
value = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
value = int64(char - 'a' + 10)
} else {
return "", errors.New("invalid character in hexadecimal string: " + string(char))
}
decimal = decimal*16 + value
}
// Convert the integer to a binary string without using predefined functions
var binaryBuilder strings.Builder
if decimal == 0 {
binaryBuilder.WriteString("0")
} else {
for decimal > 0 {
bit := decimal % 2
if bit == 0 {
binaryBuilder.WriteString("0")
} else {
binaryBuilder.WriteString("1")
}
decimal = decimal / 2
}
}
// Reverse the binary string since the bits are added in reverse order
binaryRunes := []rune(binaryBuilder.String())
for i, j := 0, len(binaryRunes)-1; i < j; i, j = i+1, j-1 {
binaryRunes[i], binaryRunes[j] = binaryRunes[j], binaryRunes[i]
}
return string(binaryRunes), nil
}
|
func hexToBinary(hex string) (string, error) {
// Trim any leading or trailing whitespace
hex = strings.TrimSpace(hex)
// Check if the hexadecimal string is empty
if hex == "" {
return "", errors.New("input string is empty")
}
// Check if the hexadecimal string is valid
if !isValidHex(hex) {
return "", errors.New("invalid hexadecimal string: " + hex)
}
// Parse the hexadecimal string to an integer
var decimal int64
for i := 0; i < len(hex); i++ {
char := hex[i]
var value int64
if char >= '0' && char <= '9' {
value = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
value = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
value = int64(char - 'a' + 10)
} else {
return "", errors.New("invalid character in hexadecimal string: " + string(char))
}
decimal = decimal*16 + value
}
// Convert the integer to a binary string without using predefined functions
var binaryBuilder strings.Builder
if decimal == 0 {
binaryBuilder.WriteString("0")
} else {
for decimal > 0 {
bit := decimal % 2
if bit == 0 {
binaryBuilder.WriteString("0")
} else {
binaryBuilder.WriteString("1")
}
decimal = decimal / 2
}
}
// Reverse the binary string since the bits are added in reverse order
binaryRunes := []rune(binaryBuilder.String())
for i, j := 0, len(binaryRunes)-1; i < j; i, j = i+1, j-1 {
binaryRunes[i], binaryRunes[j] = binaryRunes[j], binaryRunes[i]
}
return string(binaryRunes), nil
}
|
func hexToBinary(hex string) (string, error) {
// Trim any leading or trailing whitespace
hex = strings.TrimSpace(hex)
// Check if the hexadecimal string is empty
if hex == "" {
return "", errors.New("input string is empty")
}
// Check if the hexadecimal string is valid
if !isValidHex(hex) {
return "", errors.New("invalid hexadecimal string: " + hex)
}
// Parse the hexadecimal string to an integer
var decimal int64
for i := 0; i < len(hex); i++ {
char := hex[i]
var value int64
if char >= '0' && char <= '9' {
value = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
value = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
value = int64(char - 'a' + 10)
} else {
return "", errors.New("invalid character in hexadecimal string: " + string(char))
}
decimal = decimal*16 + value
}
// Convert the integer to a binary string without using predefined functions
var binaryBuilder strings.Builder
if decimal == 0 {
binaryBuilder.WriteString("0")
} else {
for decimal > 0 {
bit := decimal % 2
if bit == 0 {
binaryBuilder.WriteString("0")
} else {
binaryBuilder.WriteString("1")
}
decimal = decimal / 2
}
}
// Reverse the binary string since the bits are added in reverse order
binaryRunes := []rune(binaryBuilder.String())
for i, j := 0, len(binaryRunes)-1; i < j; i, j = i+1, j-1 {
binaryRunes[i], binaryRunes[j] = binaryRunes[j], binaryRunes[i]
}
return string(binaryRunes), nil
}
|
hexToBinary
| 23
| 77
|
conversion/hexadecimaltobinary.go
|
#FILE: Go-master/conversion/hexadecimaltodecimal.go
##CHUNK 1
// Check if the string has a valid hexadecimal prefix
if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") {
hexStr = hexStr[2:]
}
// Validate the hexadecimal string
if !isValidHexadecimal(hexStr) {
return 0, fmt.Errorf("invalid hexadecimal string")
}
var decimalValue int64
for _, char := range hexStr {
var digit int64
if char >= '0' && char <= '9' {
digit = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
digit = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
digit = int64(char - 'a' + 10)
} else {
##CHUNK 2
var decimalValue int64
for _, char := range hexStr {
var digit int64
if char >= '0' && char <= '9' {
digit = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
digit = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
digit = int64(char - 'a' + 10)
} else {
return 0, fmt.Errorf("invalid character in hexadecimal string: %c", char)
}
decimalValue = decimalValue*16 + digit
}
return decimalValue, nil
}
##CHUNK 3
// hexToDecimal converts a hexadecimal string to a decimal integer.
func hexToDecimal(hexStr string) (int64, error) {
hexStr = strings.TrimSpace(hexStr)
if len(hexStr) == 0 {
return 0, fmt.Errorf("input string is empty")
}
// Check if the string has a valid hexadecimal prefix
if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") {
hexStr = hexStr[2:]
}
// Validate the hexadecimal string
if !isValidHexadecimal(hexStr) {
return 0, fmt.Errorf("invalid hexadecimal string")
}
##CHUNK 4
package conversion
import (
"fmt"
"regexp"
"strings"
)
var isValidHexadecimal = regexp.MustCompile("^[0-9A-Fa-f]+$").MatchString
// hexToDecimal converts a hexadecimal string to a decimal integer.
func hexToDecimal(hexStr string) (int64, error) {
hexStr = strings.TrimSpace(hexStr)
if len(hexStr) == 0 {
return 0, fmt.Errorf("input string is empty")
}
#FILE: Go-master/cipher/railfence/railfence.go
##CHUNK 1
matrix[row][col] = char
col++
if dirDown {
row++
} else {
row--
}
}
var result strings.Builder
for _, line := range matrix {
for _, char := range line {
if char != 0 {
result.WriteRune(char)
}
}
}
return result.String()
}
func Decrypt(cipherText string, rails int) string {
##CHUNK 2
for _, char := range line {
if char != 0 {
result.WriteRune(char)
}
}
}
return result.String()
}
func Decrypt(cipherText string, rails int) string {
if rails == 1 || rails >= len(cipherText) {
return cipherText
}
// Placeholder for the decrypted message
decrypted := make([]rune, len(cipherText))
// Calculate the zigzag pattern and place characters accordingly
index := 0
for rail := 0; rail < rails; rail++ {
##CHUNK 3
matrix[i] = make([]rune, len(text))
}
// Fill the matrix
dirDown := false
row, col := 0, 0
for _, char := range text {
if row == 0 || row == rails-1 {
dirDown = !dirDown
}
matrix[row][col] = char
col++
if dirDown {
row++
} else {
row--
}
}
var result strings.Builder
for _, line := range matrix {
#FILE: Go-master/dynamic/optimalbst.go
##CHUNK 1
j := i + length - 1
dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value
sum := sum(freq, i, j)
// Try every key as root and compute cost
for k := i; k <= j; k++ {
// Left cost: dp[i][k-1] is valid only if k > i
var leftCost int
if k > i {
leftCost = dp[i][k-1]
} else {
leftCost = 0
}
// Right cost: dp[k+1][j] is valid only if k < j
var rightCost int
if k < j {
rightCost = dp[k+1][j]
} else {
rightCost = 0
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
#FILE: Go-master/dynamic/longestcommonsubsequence.go
##CHUNK 1
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i := 0; i <= aLen; i++ {
for j := 0; j <= bLen; j++ {
if i == 0 || j == 0 {
lcs[i][j] = 0
} else if aRunes[i-1] == bRunes[j-1] {
lcs[i][j] = lcs[i-1][j-1] + 1
} else {
lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])
}
}
}
// returning the length of longest common subsequence
return lcs[aLen][bLen]
}
#CURRENT FILE: Go-master/conversion/hexadecimaltobinary.go
|
Go-master
| 48
|
func add(a, b string) string {
if len(a) < len(b) {
a, b = b, a
}
carry := 0
sum := make([]byte, len(a)+1)
for i := 0; i < len(a); i++ {
d := int(a[len(a)-1-i] - '0')
if i < len(b) {
d += int(b[len(b)-1-i] - '0')
}
d += carry
sum[len(sum)-1-i] = byte(d%10) + '0'
carry = d / 10
}
if carry > 0 {
sum[0] = byte(carry) + '0'
} else {
sum = sum[1:]
}
return string(sum)
}
|
func add(a, b string) string {
if len(a) < len(b) {
a, b = b, a
}
carry := 0
sum := make([]byte, len(a)+1)
for i := 0; i < len(a); i++ {
d := int(a[len(a)-1-i] - '0')
if i < len(b) {
d += int(b[len(b)-1-i] - '0')
}
d += carry
sum[len(sum)-1-i] = byte(d%10) + '0'
carry = d / 10
}
if carry > 0 {
sum[0] = byte(carry) + '0'
} else {
sum = sum[1:]
}
return string(sum)
}
|
func add(a, b string) string {
if len(a) < len(b) {
a, b = b, a
}
carry := 0
sum := make([]byte, len(a)+1)
for i := 0; i < len(a); i++ {
d := int(a[len(a)-1-i] - '0')
if i < len(b) {
d += int(b[len(b)-1-i] - '0')
}
d += carry
sum[len(sum)-1-i] = byte(d%10) + '0'
carry = d / 10
}
if carry > 0 {
sum[0] = byte(carry) + '0'
} else {
sum = sum[1:]
}
return string(sum)
}
|
add
| 123
| 149
|
project_euler/problem_13/problem13.go
|
#FILE: Go-master/sort/shellsort.go
##CHUNK 1
package sort
import "github.com/TheAlgorithms/Go/constraints"
func Shell[T constraints.Ordered](arr []T) []T {
for d := int(len(arr) / 2); d > 0; d /= 2 {
for i := d; i < len(arr); i++ {
for j := i; j >= d && arr[j-d] > arr[j]; j -= d {
arr[j], arr[j-d] = arr[j-d], arr[j]
}
}
}
return arr
}
##CHUNK 2
package sort
import "github.com/TheAlgorithms/Go/constraints"
func Shell[T constraints.Ordered](arr []T) []T {
for d := int(len(arr) / 2); d > 0; d /= 2 {
for i := d; i < len(arr); i++ {
for j := i; j >= d && arr[j-d] > arr[j]; j -= d {
arr[j], arr[j-d] = arr[j-d], arr[j]
}
#FILE: Go-master/project_euler/problem_2/problem2.go
##CHUNK 1
* find the sum of the even-valued terms.
*
* @author ddaniel27
*/
package problem2
func Problem2(n uint) uint {
sum := uint(0)
a, b := uint(1), uint(2)
for b < n {
if b%2 == 0 {
sum += b
}
a, b = b, a+b
}
return sum
}
#FILE: Go-master/dynamic/abbreviation.go
##CHUNK 1
import (
"strings"
)
// Returns true if it is possible to make a equals b (if b is an abbreviation of a), returns false otherwise
func Abbreviation(a string, b string) bool {
dp := make([][]bool, len(a)+1)
for i := range dp {
dp[i] = make([]bool, len(b)+1)
}
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] = true
}
if string(a[i]) == strings.ToLower(string(a[i])) {
dp[i+1][j] = true
##CHUNK 2
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] = true
}
if string(a[i]) == strings.ToLower(string(a[i])) {
dp[i+1][j] = true
}
}
}
}
return dp[len(a)][len(b)]
}
#FILE: Go-master/strings/manacher/longestpalindrome.go
##CHUNK 1
index := 0
maxLen := 0
maxCenterSize := 0
for i := range b {
if i < k {
b[i] = min.Int(b[2*index-i], k-i)
} else {
b[i] = 1
}
for i-b[i] >= 0 && i+b[i] < len(boundaries) && boundaries[i-b[i]] == boundaries[i+b[i]] {
b[i] += 1
}
if maxLen < b[i]-1 {
maxLen = b[i] - 1
maxCenterSize = i
}
if b[i]+i-1 > k {
k = b[i] + i - 1
index = i
}
#FILE: Go-master/structure/linkedlist/cyclic.go
##CHUNK 1
if places < 0 {
multiple := cl.Size - 1 - places/cl.Size
places += multiple * cl.Size
}
places %= cl.Size
if places > cl.Size/2 {
places = cl.Size - places
for i := 0; i < places; i++ {
cl.Head = cl.Head.Prev
}
} else if places == 0 {
return
} else {
for i := 0; i < places; i++ {
cl.Head = cl.Head.Next
}
}
}
#FILE: Go-master/checksum/luhn.go
##CHUNK 1
// Luhn validates the provided data using the Luhn algorithm.
func Luhn(s []byte) bool {
n := len(s)
number := 0
result := 0
for i := 0; i < n; i++ {
number = int(s[i]) - '0'
if i%2 != 0 {
result += number
continue
}
number *= 2
if number > 9 {
number -= 9
}
result += number
}
return result%10 == 0
}
#FILE: Go-master/conversion/hexadecimaltobinary.go
##CHUNK 1
}
// Check if the hexadecimal string is valid
if !isValidHex(hex) {
return "", errors.New("invalid hexadecimal string: " + hex)
}
// Parse the hexadecimal string to an integer
var decimal int64
for i := 0; i < len(hex); i++ {
char := hex[i]
var value int64
if char >= '0' && char <= '9' {
value = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
value = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
value = int64(char - 'a' + 10)
} else {
return "", errors.New("invalid character in hexadecimal string: " + string(char))
#FILE: Go-master/checksum/crc8.go
##CHUNK 1
d = bits.Reverse8(d)
crcResult = table[crcResult^d]
}
return crcResult
}
for _, d := range data {
crcResult = table[crcResult^d]
}
return crcResult
}
// This function get 256-byte (256x8) table for efficient processing.
func getTable(model CRCModel) []uint8 {
table := make([]uint8, 256)
for i := 0; i < 256; i++ {
crc := uint8(i)
for j := 0; j < 8; j++ {
isSetBit := (crc & 0x80) != 0
crc <<= 1
if isSetBit {
#CURRENT FILE: Go-master/project_euler/problem_13/problem13.go
|
Go-master
| 49
|
func Jump(array []int, target int) (int, error) {
n := len(array)
if n == 0 {
return -1, ErrNotFound
}
// the optimal value of step is square root of the length of list
step := int(math.Round(math.Sqrt(float64(n))))
prev := 0 // previous index
curr := step // current index
for array[curr-1] < target {
prev = curr
if prev >= len(array) {
return -1, ErrNotFound
}
curr += step
// prevent jumping over list range
if curr > n {
curr = n
}
}
// perform linear search from index prev to index curr
for array[prev] < target {
prev++
// if reach end of range, indicate target not found
if prev == curr {
return -1, ErrNotFound
}
}
if array[prev] == target {
return prev, nil
}
return -1, ErrNotFound
}
|
func Jump(array []int, target int) (int, error) {
n := len(array)
if n == 0 {
return -1, ErrNotFound
}
// the optimal value of step is square root of the length of list
step := int(math.Round(math.Sqrt(float64(n))))
prev := 0 // previous index
curr := step // current index
for array[curr-1] < target {
prev = curr
if prev >= len(array) {
return -1, ErrNotFound
}
curr += step
// prevent jumping over list range
if curr > n {
curr = n
}
}
// perform linear search from index prev to index curr
for array[prev] < target {
prev++
// if reach end of range, indicate target not found
if prev == curr {
return -1, ErrNotFound
}
}
if array[prev] == target {
return prev, nil
}
return -1, ErrNotFound
}
|
func Jump(array []int, target int) (int, error) {
n := len(array)
if n == 0 {
return -1, ErrNotFound
}
// the optimal value of step is square root of the length of list
step := int(math.Round(math.Sqrt(float64(n))))
prev := 0 // previous index
curr := step // current index
for array[curr-1] < target {
prev = curr
if prev >= len(array) {
return -1, ErrNotFound
}
curr += step
// prevent jumping over list range
if curr > n {
curr = n
}
}
// perform linear search from index prev to index curr
for array[prev] < target {
prev++
// if reach end of range, indicate target not found
if prev == curr {
return -1, ErrNotFound
}
}
if array[prev] == target {
return prev, nil
}
return -1, ErrNotFound
}
|
Jump
| 16
| 56
|
search/jump.go
|
#FILE: Go-master/search/binary.go
##CHUNK 1
endIndex = mid - 1
}
}
//when target greater than every element in array, startIndex will out of bounds
if startIndex >= len(array) {
return -1, ErrNotFound
}
return startIndex, nil
}
// UpperBound returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target.
// return -1 and ErrNotFound if no such element is found.
func UpperBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
##CHUNK 2
// UpperBound returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target.
// return -1 and ErrNotFound if no such element is found.
func UpperBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
endIndex = mid - 1
} else {
startIndex = mid + 1
}
}
//when target greater or equal than every element in array, startIndex will out of bounds
if startIndex >= len(array) {
return -1, ErrNotFound
}
##CHUNK 3
} else if array[mid] < target {
startIndex = mid + 1
} else {
return mid, nil
}
}
return -1, ErrNotFound
}
// LowerBound returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target.
// return -1 and ErrNotFound if no such element is found.
func LowerBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] < target {
startIndex = mid + 1
} else {
##CHUNK 4
// return -1 and ErrNotFound if no such element is found.
func LowerBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] < target {
startIndex = mid + 1
} else {
endIndex = mid - 1
}
}
//when target greater than every element in array, startIndex will out of bounds
if startIndex >= len(array) {
return -1, ErrNotFound
}
return startIndex, nil
}
##CHUNK 5
// Unlike Binary, this function uses iterative method and not recursive.
// If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound.
func BinaryIterative(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
endIndex = mid - 1
} else if array[mid] < target {
startIndex = mid + 1
} else {
return mid, nil
}
}
return -1, ErrNotFound
}
// LowerBound returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target.
##CHUNK 6
package search
// Binary search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target.
// This function uses recursive call to itself.
// If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound.
func Binary(array []int, target int, lowIndex int, highIndex int) (int, error) {
if highIndex < lowIndex || len(array) == 0 {
return -1, ErrNotFound
}
mid := int(lowIndex + (highIndex-lowIndex)/2)
if array[mid] > target {
return Binary(array, target, lowIndex, mid-1)
} else if array[mid] < target {
return Binary(array, target, mid+1, highIndex)
} else {
return mid, nil
}
}
// BinaryIterative search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target.
##CHUNK 7
package search
// Binary search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target.
// This function uses recursive call to itself.
// If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound.
func Binary(array []int, target int, lowIndex int, highIndex int) (int, error) {
if highIndex < lowIndex || len(array) == 0 {
return -1, ErrNotFound
}
mid := int(lowIndex + (highIndex-lowIndex)/2)
#FILE: Go-master/search/jump2.go
##CHUNK 1
package search
import "math"
func Jump2(arr []int, target int) (int, error) {
step := int(math.Round(math.Sqrt(float64(len(arr)))))
rbound := len(arr)
for i := step; i < len(arr); i += step {
if arr[i] > target {
rbound = i
break
}
}
for i := rbound - step; i < rbound; i++ {
if arr[i] == target {
return i, nil
}
if arr[i] > target {
break
#FILE: Go-master/search/selectk.go
##CHUNK 1
package search
func SelectK(array []int, k int) (int, error) {
if k > len(array) {
return -1, ErrNotFound
}
return selectK(array, 0, len(array), len(array)-k), nil
}
// search the element which index is idx
func selectK(array []int, l, r, idx int) int {
index := partition(array, l, r)
if index == idx {
return array[index]
}
if index < idx {
return selectK(array, index+1, r, idx)
}
return selectK(array, l, index, idx)
}
#FILE: Go-master/graph/dijkstra.go
##CHUNK 1
pq.Update(*item)
}
}
}
for pq.Size() > 0 {
curr := pq.Pop().(Item)
if curr.node == end {
break
}
visit(curr)
}
item := nodes[end]
if item == nil {
return -1, false
}
return item.dist, true
}
#CURRENT FILE: Go-master/search/jump.go
|
Go-master
| 50
|
func Interpolation(sortedData []int, guess int) (int, error) {
if len(sortedData) == 0 {
return -1, ErrNotFound
}
var (
low, high = 0, len(sortedData) - 1
lowVal, highVal = sortedData[low], sortedData[high]
)
for lowVal != highVal && (lowVal <= guess) && (guess <= highVal) {
mid := low + int(float64(float64((guess-lowVal)*(high-low))/float64(highVal-lowVal)))
// if guess is found, array can also have duplicate values, so scan backwards and find the first index
if sortedData[mid] == guess {
for mid > 0 && sortedData[mid-1] == guess {
mid--
}
return mid, nil
}
// adjust our guess and continue
if sortedData[mid] > guess {
high, highVal = mid-1, sortedData[high]
} else {
low, lowVal = mid+1, sortedData[low]
}
}
if guess == lowVal {
return low, nil
}
return -1, ErrNotFound
}
|
func Interpolation(sortedData []int, guess int) (int, error) {
if len(sortedData) == 0 {
return -1, ErrNotFound
}
var (
low, high = 0, len(sortedData) - 1
lowVal, highVal = sortedData[low], sortedData[high]
)
for lowVal != highVal && (lowVal <= guess) && (guess <= highVal) {
mid := low + int(float64(float64((guess-lowVal)*(high-low))/float64(highVal-lowVal)))
// if guess is found, array can also have duplicate values, so scan backwards and find the first index
if sortedData[mid] == guess {
for mid > 0 && sortedData[mid-1] == guess {
mid--
}
return mid, nil
}
// adjust our guess and continue
if sortedData[mid] > guess {
high, highVal = mid-1, sortedData[high]
} else {
low, lowVal = mid+1, sortedData[low]
}
}
if guess == lowVal {
return low, nil
}
return -1, ErrNotFound
}
|
func Interpolation(sortedData []int, guess int) (int, error) {
if len(sortedData) == 0 {
return -1, ErrNotFound
}
var (
low, high = 0, len(sortedData) - 1
lowVal, highVal = sortedData[low], sortedData[high]
)
for lowVal != highVal && (lowVal <= guess) && (guess <= highVal) {
mid := low + int(float64(float64((guess-lowVal)*(high-low))/float64(highVal-lowVal)))
// if guess is found, array can also have duplicate values, so scan backwards and find the first index
if sortedData[mid] == guess {
for mid > 0 && sortedData[mid-1] == guess {
mid--
}
return mid, nil
}
// adjust our guess and continue
if sortedData[mid] > guess {
high, highVal = mid-1, sortedData[high]
} else {
low, lowVal = mid+1, sortedData[low]
}
}
if guess == lowVal {
return low, nil
}
return -1, ErrNotFound
}
|
Interpolation
| 14
| 50
|
search/interpolation.go
|
#FILE: Go-master/search/binary.go
##CHUNK 1
} else if array[mid] < target {
startIndex = mid + 1
} else {
return mid, nil
}
}
return -1, ErrNotFound
}
// LowerBound returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target.
// return -1 and ErrNotFound if no such element is found.
func LowerBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] < target {
startIndex = mid + 1
} else {
##CHUNK 2
// Unlike Binary, this function uses iterative method and not recursive.
// If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound.
func BinaryIterative(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
endIndex = mid - 1
} else if array[mid] < target {
startIndex = mid + 1
} else {
return mid, nil
}
}
return -1, ErrNotFound
}
// LowerBound returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target.
##CHUNK 3
// return -1 and ErrNotFound if no such element is found.
func LowerBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] < target {
startIndex = mid + 1
} else {
endIndex = mid - 1
}
}
//when target greater than every element in array, startIndex will out of bounds
if startIndex >= len(array) {
return -1, ErrNotFound
}
return startIndex, nil
}
##CHUNK 4
// UpperBound returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target.
// return -1 and ErrNotFound if no such element is found.
func UpperBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
endIndex = mid - 1
} else {
startIndex = mid + 1
}
}
//when target greater or equal than every element in array, startIndex will out of bounds
if startIndex >= len(array) {
return -1, ErrNotFound
}
##CHUNK 5
endIndex = mid - 1
}
}
//when target greater than every element in array, startIndex will out of bounds
if startIndex >= len(array) {
return -1, ErrNotFound
}
return startIndex, nil
}
// UpperBound returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target.
// return -1 and ErrNotFound if no such element is found.
func UpperBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
##CHUNK 6
if array[mid] > target {
return Binary(array, target, lowIndex, mid-1)
} else if array[mid] < target {
return Binary(array, target, mid+1, highIndex)
} else {
return mid, nil
}
}
// BinaryIterative search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target.
// Unlike Binary, this function uses iterative method and not recursive.
// If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound.
func BinaryIterative(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
endIndex = mid - 1
##CHUNK 7
package search
// Binary search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target.
// This function uses recursive call to itself.
// If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound.
func Binary(array []int, target int, lowIndex int, highIndex int) (int, error) {
if highIndex < lowIndex || len(array) == 0 {
return -1, ErrNotFound
}
mid := int(lowIndex + (highIndex-lowIndex)/2)
if array[mid] > target {
return Binary(array, target, lowIndex, mid-1)
} else if array[mid] < target {
return Binary(array, target, mid+1, highIndex)
} else {
return mid, nil
}
}
// BinaryIterative search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target.
#FILE: Go-master/sort/quicksort.go
##CHUNK 1
arr[index], arr[i] = arr[i], arr[index]
}
}
arr[index+1], arr[high] = arr[high], arr[index+1]
return index + 1
}
// QuicksortRange Sorts the specified range within the array
func QuicksortRange[T constraints.Ordered](arr []T, low, high int) {
if len(arr) <= 1 {
return
}
if low < high {
pivot := Partition(arr, low, high)
QuicksortRange(arr, low, pivot-1)
QuicksortRange(arr, pivot+1, high)
}
}
##CHUNK 2
package sort
import "github.com/TheAlgorithms/Go/constraints"
func Partition[T constraints.Ordered](arr []T, low, high int) int {
index := low - 1
pivotElement := arr[high]
for i := low; i < high; i++ {
if arr[i] <= pivotElement {
index += 1
arr[index], arr[i] = arr[i], arr[index]
}
}
arr[index+1], arr[high] = arr[high], arr[index+1]
return index + 1
}
// QuicksortRange Sorts the specified range within the array
func QuicksortRange[T constraints.Ordered](arr []T, low, high int) {
if len(arr) <= 1 {
#FILE: Go-master/search/selectk.go
##CHUNK 1
package search
func SelectK(array []int, k int) (int, error) {
if k > len(array) {
return -1, ErrNotFound
}
return selectK(array, 0, len(array), len(array)-k), nil
}
// search the element which index is idx
func selectK(array []int, l, r, idx int) int {
index := partition(array, l, r)
if index == idx {
return array[index]
}
if index < idx {
return selectK(array, index+1, r, idx)
}
return selectK(array, l, index, idx)
}
#CURRENT FILE: Go-master/search/interpolation.go
|
Go-master
| 51
|
func Jump2(arr []int, target int) (int, error) {
step := int(math.Round(math.Sqrt(float64(len(arr)))))
rbound := len(arr)
for i := step; i < len(arr); i += step {
if arr[i] > target {
rbound = i
break
}
}
for i := rbound - step; i < rbound; i++ {
if arr[i] == target {
return i, nil
}
if arr[i] > target {
break
}
}
return -1, ErrNotFound
}
|
func Jump2(arr []int, target int) (int, error) {
step := int(math.Round(math.Sqrt(float64(len(arr)))))
rbound := len(arr)
for i := step; i < len(arr); i += step {
if arr[i] > target {
rbound = i
break
}
}
for i := rbound - step; i < rbound; i++ {
if arr[i] == target {
return i, nil
}
if arr[i] > target {
break
}
}
return -1, ErrNotFound
}
|
func Jump2(arr []int, target int) (int, error) {
step := int(math.Round(math.Sqrt(float64(len(arr)))))
rbound := len(arr)
for i := step; i < len(arr); i += step {
if arr[i] > target {
rbound = i
break
}
}
for i := rbound - step; i < rbound; i++ {
if arr[i] == target {
return i, nil
}
if arr[i] > target {
break
}
}
return -1, ErrNotFound
}
|
Jump2
| 4
| 23
|
search/jump2.go
|
#FILE: Go-master/sort/exchangesort.go
##CHUNK 1
func Exchange[T constraints.Ordered](arr []T) []T {
for i := 0; i < len(arr)-1; i++ {
for j := i + 1; j < len(arr); j++ {
if arr[i] > arr[j] {
arr[i], arr[j] = arr[j], arr[i]
}
}
}
return arr
}
#FILE: Go-master/sort/radixsort.go
##CHUNK 1
digits[(item/exp)%10]++
}
for i := 1; i < 10; i++ {
digits[i] += digits[i-1]
}
for i := len(arr) - 1; i >= 0; i-- {
output[digits[(arr[i]/exp)%10]-1] = arr[i]
digits[(arr[i]/exp)%10]--
}
return output
}
func unsignedRadixSort[T constraints.Integer](arr []T) []T {
if len(arr) == 0 {
return arr
}
maxElement := max.Int(arr...)
for exp := T(1); maxElement/exp > 0; exp *= 10 {
#FILE: Go-master/sort/oddevensort.go
##CHUNK 1
// Perform "odd" indexed pass
for i := 1; i < len(arr)-1; i += 2 {
if arr[i] > arr[i+1] {
arr[i], arr[i+1] = arr[i+1], arr[i]
swapped = true
}
}
// Perform "even" indexed pass
for i := 0; i < len(arr)-1; i += 2 {
if arr[i] > arr[i+1] {
arr[i], arr[i+1] = arr[i+1], arr[i]
swapped = true
}
}
}
return arr
}
#FILE: Go-master/search/binary.go
##CHUNK 1
// return -1 and ErrNotFound if no such element is found.
func LowerBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] < target {
startIndex = mid + 1
} else {
endIndex = mid - 1
}
}
//when target greater than every element in array, startIndex will out of bounds
if startIndex >= len(array) {
return -1, ErrNotFound
}
return startIndex, nil
}
##CHUNK 2
} else if array[mid] < target {
startIndex = mid + 1
} else {
return mid, nil
}
}
return -1, ErrNotFound
}
// LowerBound returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target.
// return -1 and ErrNotFound if no such element is found.
func LowerBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] < target {
startIndex = mid + 1
} else {
##CHUNK 3
endIndex = mid - 1
}
}
//when target greater than every element in array, startIndex will out of bounds
if startIndex >= len(array) {
return -1, ErrNotFound
}
return startIndex, nil
}
// UpperBound returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target.
// return -1 and ErrNotFound if no such element is found.
func UpperBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
#FILE: Go-master/graph/depthfirstsearch.go
##CHUNK 1
if nodes[i] == target {
return i
}
}
return -1
}
func NotExist(target int, slice []int) bool {
for i := 0; i < len(slice); i++ {
if slice[i] == target {
return false
}
}
return true
}
func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool) {
var route []int
var stack []int
startIdx := GetIdx(start, nodes)
#FILE: Go-master/search/jump.go
##CHUNK 1
}
// the optimal value of step is square root of the length of list
step := int(math.Round(math.Sqrt(float64(n))))
prev := 0 // previous index
curr := step // current index
for array[curr-1] < target {
prev = curr
if prev >= len(array) {
return -1, ErrNotFound
}
curr += step
// prevent jumping over list range
if curr > n {
curr = n
}
}
##CHUNK 2
return -1, ErrNotFound
}
curr += step
// prevent jumping over list range
if curr > n {
curr = n
}
}
// perform linear search from index prev to index curr
for array[prev] < target {
prev++
// if reach end of range, indicate target not found
if prev == curr {
return -1, ErrNotFound
}
}
#FILE: Go-master/sort/bogosort.go
##CHUNK 1
"math/rand"
"github.com/TheAlgorithms/Go/constraints"
)
func isSorted[T constraints.Number](arr []T) bool {
for i := 0; i < len(arr)-1; i++ {
if arr[i] > arr[i+1] {
return false
}
}
return true
}
func shuffle[T constraints.Number](arr []T) {
for i := range arr {
j := rand.Intn(i + 1)
arr[i], arr[j] = arr[j], arr[i]
}
#CURRENT FILE: Go-master/search/jump2.go
|
Go-master
| 52
|
func doSort(arr []T, left, right int) bool {
if left == right {
return false
}
swapped := false
low := left
high := right
for low < high {
if arr[low] > arr[high] {
arr[low], arr[high] = arr[high], arr[low]
swapped = true
}
low++
high--
}
if low == high && arr[low] > arr[high+1] {
arr[low], arr[high+1] = arr[high+1], arr[low]
swapped = true
}
mid := left + (right-left)/2
leftHalf := doSort(arr, left, mid)
rightHalf := doSort(arr, mid+1, right)
return swapped || leftHalf || rightHalf
}
|
func doSort(arr []T, left, right int) bool {
if left == right {
return false
}
swapped := false
low := left
high := right
for low < high {
if arr[low] > arr[high] {
arr[low], arr[high] = arr[high], arr[low]
swapped = true
}
low++
high--
}
if low == high && arr[low] > arr[high+1] {
arr[low], arr[high+1] = arr[high+1], arr[low]
swapped = true
}
mid := left + (right-left)/2
leftHalf := doSort(arr, left, mid)
rightHalf := doSort(arr, mid+1, right)
return swapped || leftHalf || rightHalf
}
|
func doSort(arr []T, left, right int) bool {
if left == right {
return false
}
swapped := false
low := left
high := right
for low < high {
if arr[low] > arr[high] {
arr[low], arr[high] = arr[high], arr[low]
swapped = true
}
low++
high--
}
if low == high && arr[low] > arr[high+1] {
arr[low], arr[high+1] = arr[high+1], arr[low]
swapped = true
}
mid := left + (right-left)/2
leftHalf := doSort(arr, left, mid)
rightHalf := doSort(arr, mid+1, right)
return swapped || leftHalf || rightHalf
}
|
doSort
| 16
| 43
|
sort/circlesort.go
|
#FILE: Go-master/sort/binaryinsertionsort.go
##CHUNK 1
if arr[mid] > temporary {
high = mid - 1
} else {
low = mid + 1
}
}
for itr := currentIndex; itr > low; itr-- {
arr[itr] = arr[itr-1]
}
arr[low] = temporary
}
return arr
}
##CHUNK 2
import "github.com/TheAlgorithms/Go/constraints"
func BinaryInsertion[T constraints.Ordered](arr []T) []T {
for currentIndex := 1; currentIndex < len(arr); currentIndex++ {
temporary := arr[currentIndex]
low := 0
high := currentIndex - 1
for low <= high {
mid := low + (high-low)/2
if arr[mid] > temporary {
high = mid - 1
} else {
low = mid + 1
}
}
for itr := currentIndex; itr > low; itr-- {
arr[itr] = arr[itr-1]
}
#FILE: Go-master/sort/patiencesort.go
##CHUNK 1
var piles [][]T
for _, card := range arr {
left, right := 0, len(piles)
for left < right {
mid := left + (right-left)/2
if piles[mid][len(piles[mid])-1] >= card {
right = mid
} else {
left = mid + 1
}
}
if left == len(piles) {
piles = append(piles, []T{card})
} else {
piles[left] = append(piles[left], card)
}
}
##CHUNK 2
package sort
import "github.com/TheAlgorithms/Go/constraints"
func Patience[T constraints.Ordered](arr []T) []T {
if len(arr) <= 1 {
return arr
}
var piles [][]T
for _, card := range arr {
left, right := 0, len(piles)
for left < right {
mid := left + (right-left)/2
if piles[mid][len(piles[mid])-1] >= card {
right = mid
} else {
left = mid + 1
#FILE: Go-master/sort/quicksort.go
##CHUNK 1
package sort
import "github.com/TheAlgorithms/Go/constraints"
func Partition[T constraints.Ordered](arr []T, low, high int) int {
index := low - 1
pivotElement := arr[high]
for i := low; i < high; i++ {
if arr[i] <= pivotElement {
index += 1
arr[index], arr[i] = arr[i], arr[index]
}
}
arr[index+1], arr[high] = arr[high], arr[index+1]
return index + 1
}
// QuicksortRange Sorts the specified range within the array
func QuicksortRange[T constraints.Ordered](arr []T, low, high int) {
if len(arr) <= 1 {
##CHUNK 2
arr[index], arr[i] = arr[i], arr[index]
}
}
arr[index+1], arr[high] = arr[high], arr[index+1]
return index + 1
}
// QuicksortRange Sorts the specified range within the array
func QuicksortRange[T constraints.Ordered](arr []T, low, high int) {
if len(arr) <= 1 {
return
}
if low < high {
pivot := Partition(arr, low, high)
QuicksortRange(arr, low, pivot-1)
QuicksortRange(arr, pivot+1, high)
}
}
#FILE: Go-master/sort/combSort.go
##CHUNK 1
n := len(data)
gap := n
swapped := true
for gap != 1 || swapped {
gap = getNextGap(gap)
swapped = false
for i := 0; i < n-gap; i++ {
if data[i] > data[i+gap] {
data[i], data[i+gap] = data[i+gap], data[i]
swapped = true
}
}
}
return data
}
#FILE: Go-master/structure/segmenttree/segmenttree.go
##CHUNK 1
if left == right {
//leaf node
s.SegmentTree[node] = s.Array[left]
} else {
//get sum of left and right nodes
mid := (left + right) / 2
s.Build(2*node, left, mid)
s.Build(2*node+1, mid+1, right)
s.SegmentTree[node] = s.SegmentTree[2*node] + s.SegmentTree[2*node+1]
}
}
// NewSegmentTree returns a new instance of a SegmentTree. It takes an input
// array of integers representing Array, initializes and builds the SegmentTree.
func NewSegmentTree(Array []int) *SegmentTree {
if len(Array) == 0 {
return nil
}
##CHUNK 2
s.Update(2*node, leftNode, mid, firstIndex, min.Int(mid, lastIndex), value)
s.Update(2*node+1, mid+1, rightNode, max.Int(firstIndex, mid+1), lastIndex, value)
s.SegmentTree[node] = s.SegmentTree[2*node] + s.SegmentTree[2*node+1]
}
}
// Build builds the SegmentTree by computing the sum of different ranges.
// node, leftNode and rightNode should always start with 1, 0 and len(Array)-1, respectively.
func (s *SegmentTree) Build(node int, left int, right int) {
if left == right {
//leaf node
s.SegmentTree[node] = s.Array[left]
} else {
//get sum of left and right nodes
mid := (left + right) / 2
s.Build(2*node, left, mid)
s.Build(2*node+1, mid+1, right)
#FILE: Go-master/strings/generateparentheses/generateparentheses.go
##CHUNK 1
func GenerateParenthesis(n int) []string {
result := make([]string, 0)
maxLen := 2 * n
var recursiveComputation func(s []string, left int, right int)
recursiveComputation = func(s []string, left int, right int) {
if len(s) == maxLen {
result = append(result, strings.Join(s, ""))
return
}
if left < n {
s = append(s, "(")
recursiveComputation(s, left+1, right)
s = s[:len(s)-1]
}
if right < left {
s = append(s, ")")
recursiveComputation(s, left, right+1)
_ = s[:len(s)-1]
}
#CURRENT FILE: Go-master/sort/circlesort.go
|
Go-master
| 53
|
func Mode(numbers []T) (T, error) {
countMap := make(map[T]int)
n := len(numbers)
if n == 0 {
return 0, ErrEmptySlice
}
for _, number := range numbers {
countMap[number]++
}
var mode T
count := 0
for k, v := range countMap {
if v > count {
count = v
mode = k
}
}
return mode, nil
}
|
func Mode(numbers []T) (T, error) {
countMap := make(map[T]int)
n := len(numbers)
if n == 0 {
return 0, ErrEmptySlice
}
for _, number := range numbers {
countMap[number]++
}
var mode T
count := 0
for k, v := range countMap {
if v > count {
count = v
mode = k
}
}
return mode, nil
}
|
func Mode(numbers []T) (T, error) {
countMap := make(map[T]int)
n := len(numbers)
if n == 0 {
return 0, ErrEmptySlice
}
for _, number := range numbers {
countMap[number]++
}
var mode T
count := 0
for k, v := range countMap {
if v > count {
count = v
mode = k
}
}
return mode, nil
}
|
Mode
| 20
| 46
|
math/mode.go
|
#FILE: Go-master/project_euler/problem_14/problem14.go
##CHUNK 1
var dictionary = dict{
1: 1,
}
func Problem14(limit uint64) uint64 {
for i := uint64(2); i <= limit; i++ {
weightNextNode(i)
}
var max, maxWeight uint64
for k, v := range dictionary {
if v > maxWeight {
max = k
maxWeight = v
}
}
return max
}
##CHUNK 2
var max, maxWeight uint64
for k, v := range dictionary {
if v > maxWeight {
max = k
maxWeight = v
}
}
return max
}
func weightNextNode(current uint64) uint64 {
var next, weight uint64
if current%2 == 0 {
next = current / 2
} else {
next = (3 * current) + 1
}
if v, ok := dictionary[next]; !ok {
weight = weightNextNode(next) + 1
#FILE: Go-master/sort/countingsort.go
##CHUNK 1
aMin = x
}
if x > aMax {
aMax = x
}
}
count := make([]int, aMax-aMin+1)
for _, x := range data {
count[x-aMin]++ // this is the reason for having only Integer constraint instead of Ordered.
}
z := 0
for i, c := range count {
for c > 0 {
data[z] = T(i) + aMin
z++
c--
}
}
return data
}
##CHUNK 2
import "github.com/TheAlgorithms/Go/constraints"
func Count[T constraints.Integer](data []T) []T {
if len(data) == 0 {
return data
}
var aMin, aMax = data[0], data[0]
for _, x := range data {
if x < aMin {
aMin = x
}
if x > aMax {
aMax = x
}
}
count := make([]int, aMax-aMin+1)
for _, x := range data {
count[x-aMin]++ // this is the reason for having only Integer constraint instead of Ordered.
}
#FILE: Go-master/graph/lowestcommonancestor_test.go
##CHUNK 1
return true
}
for _, e := range fullGraph {
if join(e.from, e.to) == true {
edges = append(edges, e)
}
}
return NewTree(numbersVertex, root, edges)
}
func generateQuery(tree *Tree) []Query {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
const MAXQUERY = 50
var queries []Query
bruteforceLCA := func(u, v int) int {
for u != v {
if tree.GetDepth(u) > tree.GetDepth(v) {
##CHUNK 2
}
func generateQuery(tree *Tree) []Query {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
const MAXQUERY = 50
var queries []Query
bruteforceLCA := func(u, v int) int {
for u != v {
if tree.GetDepth(u) > tree.GetDepth(v) {
u = tree.GetDad(u)
} else {
v = tree.GetDad(v)
}
}
return u
}
for q := 1; q <= MAXQUERY; q++ {
u := rnd.Intn(tree.numbersVertex)
#FILE: Go-master/graph/kahn_test.go
##CHUNK 1
} else {
if actual == nil {
t.Errorf("Kahn(%d, %v) = nil; want valid order", tc.n, tc.dependencies)
} else {
seen := make([]bool, tc.n)
positions := make([]int, tc.n)
for i, v := range actual {
seen[v] = true
positions[v] = i
}
for i, v := range seen {
if !v {
t.Errorf("missing vertex %v", i)
}
}
for _, d := range tc.dependencies {
if positions[d[0]] > positions[d[1]] {
t.Errorf("dependency %v not satisfied", d)
}
}
#FILE: Go-master/graph/coloring/graph_test.go
##CHUNK 1
func getTestGraphsForNegativeTests() (list []*testGraph) {
list = getTestGraphs()
list[0].VertexColors = nil
list[1].VertexColors = map[int]coloring.Color{}
for v := range list[2].VertexColors {
in := len(list[2].VertexColors) - v - 1
list[2].VertexColors[v] = list[2].VertexColors[in]
}
for v := range list[3].VertexColors {
list[3].VertexColors[v] = 1
}
return list[:4]
}
func TestGraphValidateColorsOfVertex_Negative(t *testing.T) {
for i, tt := range getTestGraphsForNegativeTests() {
t.Run(strconv.Itoa(i), func(t *testing.T) {
if err := tt.Graph.ValidateColorsOfVertex(tt.VertexColors); err == nil {
t.Errorf("ValidateColorsOfVertex() error = nil, want some err")
}
#FILE: Go-master/strings/isisogram.go
##CHUNK 1
if letters[l] > 3 {
return false, nil
}
continue
}
letters[l] = 1
}
mapVals := make(map[int]bool)
for _, v := range letters {
mapVals[v] = true
}
if _, ok := mapVals[int(order)]; ok && len(mapVals) == 1 {
return true, nil
}
return false, nil
#FILE: Go-master/sort/bucketsort.go
##CHUNK 1
}
// find the maximum and minimum elements in arr
max := arr[0]
min := arr[0]
for _, v := range arr {
if v > max {
max = v
}
if v < min {
min = v
}
}
// create an empty bucket for each element in arr
bucket := make([][]T, len(arr))
// put each element in the appropriate bucket
for _, v := range arr {
bucketIndex := int((v - min) / (max - min) * T(len(arr)-1))
#CURRENT FILE: Go-master/math/mode.go
|
Go-master
| 54
|
func IsKrishnamurthyNumber(n T) bool {
if n <= 0 {
return false
}
// Preprocessing: Using a slice to store the digit Factorials
digitFact := make([]T, 10)
digitFact[0] = 1 // 0! = 1
for i := 1; i < 10; i++ {
digitFact[i] = digitFact[i-1] * T(i)
}
// Subtract the digit Facotorial from the number
nTemp := n
for n > 0 {
nTemp -= digitFact[n%10]
n /= 10
}
return nTemp == 0
}
|
func IsKrishnamurthyNumber(n T) bool {
if n <= 0 {
return false
}
// Preprocessing: Using a slice to store the digit Factorials
digitFact := make([]T, 10)
digitFact[0] = 1 // 0! = 1
for i := 1; i < 10; i++ {
digitFact[i] = digitFact[i-1] * T(i)
}
// Subtract the digit Facotorial from the number
nTemp := n
for n > 0 {
nTemp -= digitFact[n%10]
n /= 10
}
return nTemp == 0
}
|
func IsKrishnamurthyNumber(n T) bool {
if n <= 0 {
return false
}
// Preprocessing: Using a slice to store the digit Factorials
digitFact := make([]T, 10)
digitFact[0] = 1 // 0! = 1
for i := 1; i < 10; i++ {
digitFact[i] = digitFact[i-1] * T(i)
}
// Subtract the digit Facotorial from the number
nTemp := n
for n > 0 {
nTemp -= digitFact[n%10]
n /= 10
}
return nTemp == 0
}
|
IsKrishnamurthyNumber
| 13
| 33
|
math/krishnamurthy.go
|
#FILE: Go-master/math/isautomorphic.go
##CHUNK 1
import (
"github.com/TheAlgorithms/Go/constraints"
)
func IsAutomorphic[T constraints.Integer](n T) bool {
// handling the negetive number case
if n < 0 {
return false
}
n_sq := n * n
for n > 0 {
if (n % 10) != (n_sq % 10) {
return false
}
n /= 10
n_sq /= 10
}
##CHUNK 2
n_sq := n * n
for n > 0 {
if (n % 10) != (n_sq % 10) {
return false
}
n /= 10
n_sq /= 10
}
return true
}
#FILE: Go-master/math/eulertotient.go
##CHUNK 1
package math
// Phi is the Euler totient function.
// This function computes the number of numbers less then n that are coprime with n.
func Phi(n int64) int64 {
result := n
for i := int64(2); i*i <= n; i += 1 {
if n%i == 0 {
for {
if n%i != 0 {
break
}
n /= i
}
result -= result / i
}
}
if n > 1 {
result -= result / n
#FILE: Go-master/math/factorial/factorial.go
##CHUNK 1
if n < 0 {
return 0, ErrNegativeArgument
}
result := 1
for i := 2; i <= n; i++ {
result *= i
}
return result, nil
}
// Recursive This function recursively computes the factorial of a number
func Recursive(n int) (int, error) {
if n < 0 {
return 0, ErrNegativeArgument
}
if n <= 1 {
return 1, nil
}
prev, _ := Recursive(n - 1)
return n * prev, nil
#FILE: Go-master/math/mobius.go
##CHUNK 1
// Mu is the Mobius function
// This function returns μ(n) for given number
func Mu(n int) int {
if n <= 1 {
return 1
}
var primeFactorCount int
for i := 1; i <= n; i++ {
if n%i == 0 && prime.OptimizedTrialDivision(int64(i)) {
if n%(i*i) == 0 {
return 0
}
primeFactorCount += 1
}
}
if primeFactorCount%2 == 0 {
return 1
}
return -1
}
#FILE: Go-master/project_euler/problem_3/problem3.go
##CHUNK 1
func Problem3(n uint) uint {
i := uint(2)
for n > 1 {
if n%i == 0 {
n /= i
} else {
i++
}
}
return i
}
#FILE: Go-master/checksum/luhn.go
##CHUNK 1
// Luhn validates the provided data using the Luhn algorithm.
func Luhn(s []byte) bool {
n := len(s)
number := 0
result := 0
for i := 0; i < n; i++ {
number = int(s[i]) - '0'
if i%2 != 0 {
result += number
continue
}
number *= 2
if number > 9 {
number -= 9
}
result += number
}
return result%10 == 0
}
#FILE: Go-master/project_euler/problem_20/problem20.go
##CHUNK 1
for _, digit := range factorial.String() {
sum += int(digit - '0')
}
return sum
}
// bigFactorial returns the factorial of n as a big.Int
// Use big package to handle large numbers
func bigFactorial(n int) *big.Int {
if n < 0 {
return big.NewInt(0)
}
if n == 0 {
return big.NewInt(1)
}
return big.NewInt(0).Mul(big.NewInt(int64(n)), bigFactorial(n-1))
}
##CHUNK 2
*
* @author ddaniel27
*/
package problem20
import "math/big"
func Problem20(input int) int {
factorial := bigFactorial(input)
sum := 0
for _, digit := range factorial.String() {
sum += int(digit - '0')
}
return sum
}
// bigFactorial returns the factorial of n as a big.Int
// Use big package to handle large numbers
func bigFactorial(n int) *big.Int {
if n < 0 {
#FILE: Go-master/math/prime/primefactorization.go
##CHUNK 1
result := make(map[int64]int64)
for i := int64(2); i*i <= n; i += 1 {
for {
if n%i != 0 {
break
}
result[i] += 1
n /= i
}
}
if n > 1 {
result[n] += 1
}
return result
}
#CURRENT FILE: Go-master/math/krishnamurthy.go
|
Go-master
| 55
|
func Spigot(n int) string {
pi := ""
boxes := n * 10 / 3
remainders := make([]int, boxes)
for i := 0; i < boxes; i++ {
remainders[i] = 2
}
digitsHeld := 0
for i := 0; i < n; i++ {
carriedOver := 0
sum := 0
for j := boxes - 1; j >= 0; j-- {
remainders[j] *= 10
sum = remainders[j] + carriedOver
quotient := sum / (j*2 + 1)
remainders[j] = sum % (j*2 + 1)
carriedOver = quotient * j
}
remainders[0] = sum % 10
q := sum / 10
switch q {
case 9:
digitsHeld++
case 10:
q = 0
for k := 1; k <= digitsHeld; k++ {
replaced, _ := strconv.Atoi(pi[i-k : i-k+1])
if replaced == 9 {
replaced = 0
} else {
replaced++
}
pi = delChar(pi, i-k)
pi = pi[:i-k] + strconv.Itoa(replaced) + pi[i-k:]
}
digitsHeld = 1
default:
digitsHeld = 1
}
pi += strconv.Itoa(q)
}
return pi
}
|
func Spigot(n int) string {
pi := ""
boxes := n * 10 / 3
remainders := make([]int, boxes)
for i := 0; i < boxes; i++ {
remainders[i] = 2
}
digitsHeld := 0
for i := 0; i < n; i++ {
carriedOver := 0
sum := 0
for j := boxes - 1; j >= 0; j-- {
remainders[j] *= 10
sum = remainders[j] + carriedOver
quotient := sum / (j*2 + 1)
remainders[j] = sum % (j*2 + 1)
carriedOver = quotient * j
}
remainders[0] = sum % 10
q := sum / 10
switch q {
case 9:
digitsHeld++
case 10:
q = 0
for k := 1; k <= digitsHeld; k++ {
replaced, _ := strconv.Atoi(pi[i-k : i-k+1])
if replaced == 9 {
replaced = 0
} else {
replaced++
}
pi = delChar(pi, i-k)
pi = pi[:i-k] + strconv.Itoa(replaced) + pi[i-k:]
}
digitsHeld = 1
default:
digitsHeld = 1
}
pi += strconv.Itoa(q)
}
return pi
}
|
func Spigot(n int) string {
pi := ""
boxes := n * 10 / 3
remainders := make([]int, boxes)
for i := 0; i < boxes; i++ {
remainders[i] = 2
}
digitsHeld := 0
for i := 0; i < n; i++ {
carriedOver := 0
sum := 0
for j := boxes - 1; j >= 0; j-- {
remainders[j] *= 10
sum = remainders[j] + carriedOver
quotient := sum / (j*2 + 1)
remainders[j] = sum % (j*2 + 1)
carriedOver = quotient * j
}
remainders[0] = sum % 10
q := sum / 10
switch q {
case 9:
digitsHeld++
case 10:
q = 0
for k := 1; k <= digitsHeld; k++ {
replaced, _ := strconv.Atoi(pi[i-k : i-k+1])
if replaced == 9 {
replaced = 0
} else {
replaced++
}
pi = delChar(pi, i-k)
pi = pi[:i-k] + strconv.Itoa(replaced) + pi[i-k:]
}
digitsHeld = 1
default:
digitsHeld = 1
}
pi += strconv.Itoa(q)
}
return pi
}
|
Spigot
| 13
| 55
|
math/pi/spigotpi.go
|
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
##CHUNK 2
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
return dp[m][sum]
}
#FILE: Go-master/project_euler/problem_13/problem13.go
##CHUNK 1
for i := 0; i < len(a); i++ {
d := int(a[len(a)-1-i] - '0')
if i < len(b) {
d += int(b[len(b)-1-i] - '0')
}
d += carry
sum[len(sum)-1-i] = byte(d%10) + '0'
carry = d / 10
}
if carry > 0 {
sum[0] = byte(carry) + '0'
} else {
sum = sum[1:]
}
return string(sum)
}
##CHUNK 2
return sum[:10]
}
func add(a, b string) string {
if len(a) < len(b) {
a, b = b, a
}
carry := 0
sum := make([]byte, len(a)+1)
for i := 0; i < len(a); i++ {
d := int(a[len(a)-1-i] - '0')
if i < len(b) {
d += int(b[len(b)-1-i] - '0')
}
d += carry
sum[len(sum)-1-i] = byte(d%10) + '0'
carry = d / 10
#FILE: Go-master/math/pi/montecarlopi.go
##CHUNK 1
if x%n == 0 {
for i := 0; i < n; i++ {
split[i] = x / n
}
} else {
limit := x % n
for i := 0; i < limit; i++ {
split[i] = x/n + 1
}
for i := limit; i < n; i++ {
split[i] = x / n
}
}
return split, nil
}
#FILE: Go-master/dynamic/matrixmultiplication.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
prod := dp[i][k] + dp[k+1][j] + D[i-1]*D[k]*D[j]
dp[i][j] = min.Int(prod, dp[i][j])
}
}
}
return dp[1][N-1]
}
/*
##CHUNK 2
}
return q
}
// MatrixChainDp function
func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
for k := i; k < j; k++ {
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
#FILE: Go-master/dynamic/uniquepaths.go
##CHUNK 1
}
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
for i := 0; i < m; i++ {
grid[i][0] = 1
}
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}
#FILE: Go-master/dynamic/subsetsum.go
##CHUNK 1
}
for i := 1; i <= sum; i++ {
//empty set is false when sum is not 0
subset[0][i] = false
}
for i := 1; i <= arraySize; i++ {
for j := 1; j <= sum; j++ {
if array[i-1] > j {
subset[i][j] = subset[i-1][j]
}
if array[i-1] <= j {
if j-array[i-1] < 0 || j-array[i-1] > sum {
//out of bounds
return false, ErrInvalidPosition
}
subset[i][j] = subset[i-1][j] || subset[i-1][j-array[i-1]]
#CURRENT FILE: Go-master/math/pi/spigotpi.go
|
Go-master
| 56
|
func MonteCarloPiConcurrent(n int) (float64, error) {
numCPU := runtime.GOMAXPROCS(0)
c := make(chan int, numCPU)
pointsToDraw, err := splitInt(n, numCPU) // split the task in sub-tasks of approximately equal sizes
if err != nil {
return 0, err
}
// launch numCPU parallel tasks
for _, p := range pointsToDraw {
go drawPoints(p, c)
}
// collect the tasks results
inside := 0
for i := 0; i < numCPU; i++ {
inside += <-c
}
return float64(inside) / float64(n) * 4, nil
}
|
func MonteCarloPiConcurrent(n int) (float64, error) {
numCPU := runtime.GOMAXPROCS(0)
c := make(chan int, numCPU)
pointsToDraw, err := splitInt(n, numCPU) // split the task in sub-tasks of approximately equal sizes
if err != nil {
return 0, err
}
// launch numCPU parallel tasks
for _, p := range pointsToDraw {
go drawPoints(p, c)
}
// collect the tasks results
inside := 0
for i := 0; i < numCPU; i++ {
inside += <-c
}
return float64(inside) / float64(n) * 4, nil
}
|
func MonteCarloPiConcurrent(n int) (float64, error) {
numCPU := runtime.GOMAXPROCS(0)
c := make(chan int, numCPU)
pointsToDraw, err := splitInt(n, numCPU) // split the task in sub-tasks of approximately equal sizes
if err != nil {
return 0, err
}
// launch numCPU parallel tasks
for _, p := range pointsToDraw {
go drawPoints(p, c)
}
// collect the tasks results
inside := 0
for i := 0; i < numCPU; i++ {
inside += <-c
}
return float64(inside) / float64(n) * 4, nil
}
|
MonteCarloPiConcurrent
| 37
| 56
|
math/pi/montecarlopi.go
|
#FILE: Go-master/math/matrix/copy.go
##CHUNK 1
func (m Matrix[T]) Copy() (Matrix[T], error) {
rows := m.Rows()
columns := m.Columns()
if rows == 0 || columns == 0 {
return Matrix[T]{}, nil
}
zeroVal, err := m.Get(0, 0) // Get the zero value of the element type
if err != nil {
return Matrix[T]{}, err
}
copyMatrix := New(rows, columns, zeroVal)
var wg sync.WaitGroup
wg.Add(rows)
errChan := make(chan error, 1)
for i := 0; i < rows; i++ {
go func(i int) {
defer wg.Done()
for j := 0; j < columns; j++ {
##CHUNK 2
}
copyMatrix := New(rows, columns, zeroVal)
var wg sync.WaitGroup
wg.Add(rows)
errChan := make(chan error, 1)
for i := 0; i < rows; i++ {
go func(i int) {
defer wg.Done()
for j := 0; j < columns; j++ {
val, err := m.Get(i, j)
if err != nil {
select {
case errChan <- err:
default:
}
return
}
err = copyMatrix.Set(i, j, val)
if err != nil {
#FILE: Go-master/cipher/polybius/polybius.go
##CHUNK 1
// Encrypt encrypts with polybius encryption
func (p *Polybius) Encrypt(text string) (string, error) {
encryptedText := ""
for _, char := range strings.ToUpper(text) {
encryptedChar, err := p.encipher(char)
if err != nil {
return "", fmt.Errorf("failed encipher: %w", err)
}
encryptedText += encryptedChar
}
return encryptedText, nil
}
// Decrypt decrypts with polybius encryption
func (p *Polybius) Decrypt(text string) (string, error) {
chars := []rune(strings.ToUpper(text))
decryptedText := ""
for i := 0; i < len(chars); i += 2 {
decryptedChar, err := p.decipher(chars[i:int(math.Min(float64(i+2), float64(len(chars))))])
if err != nil {
##CHUNK 2
return encryptedText, nil
}
// Decrypt decrypts with polybius encryption
func (p *Polybius) Decrypt(text string) (string, error) {
chars := []rune(strings.ToUpper(text))
decryptedText := ""
for i := 0; i < len(chars); i += 2 {
decryptedChar, err := p.decipher(chars[i:int(math.Min(float64(i+2), float64(len(chars))))])
if err != nil {
return "", fmt.Errorf("failed decipher: %w", err)
}
decryptedText += decryptedChar
}
return decryptedText, nil
}
func (p *Polybius) encipher(char rune) (string, error) {
index := strings.IndexRune(p.key, char)
if index < 0 {
#FILE: Go-master/structure/circularqueue/circularqueue_test.go
##CHUNK 1
for i := 0; i < b.N; i++ {
if err := queue.Enqueue(i); err != nil {
b.Error(err)
}
}
})
b.Run("Dequeue", func(b *testing.B) {
queue, _ := NewCircularQueue[int](1000)
for i := 0; i < 1000; i++ {
if err := queue.Enqueue(i); err != nil {
b.Error(err)
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := queue.Dequeue(); err != nil {
b.Error(err)
}
}
##CHUNK 2
if err := queue.Enqueue(i); err != nil {
b.Error(err)
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := queue.Dequeue(); err != nil {
b.Error(err)
}
}
})
b.Run("Peek", func(b *testing.B) {
queue, _ := NewCircularQueue[int](1000)
for i := 0; i < 1000; i++ {
if err := queue.Enqueue(i); err != nil {
b.Error(err)
}
}
b.ResetTimer()
#FILE: Go-master/math/matrix/strassenmatrixmultiply.go
##CHUNK 1
return Matrix[T]{}, err
}
C21, err := M2.Add(M4)
if err != nil {
return Matrix[T]{}, err
}
C22, err := A10.Subtract(M2)
if err != nil {
return Matrix[T]{}, err
}
// Combine subMatrices into the result matrix
var zeroVal T
C := New(n, n, zeroVal)
for i := 0; i < mid; i++ {
for j := 0; j < mid; j++ {
val, err := C11.Get(i, j)
if err != nil {
return Matrix[T]{}, err
#CURRENT FILE: Go-master/math/pi/montecarlopi.go
##CHUNK 1
func drawPoints(n int, c chan<- int) {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
inside := 0
for i := 0; i < n; i++ {
x, y := rnd.Float64(), rnd.Float64()
if x*x+y*y <= 1 {
inside++
}
}
c <- inside
}
// splitInt takes an integer x and splits it within an integer slice of length n in the most uniform
// way possible.
// For example, splitInt(10, 3) will return []int{4, 3, 3}, nil
func splitInt(x int, n int) ([]int, error) {
if x < n {
return nil, fmt.Errorf("x must be < n - given values are x=%d, n=%d", x, n)
}
split := make([]int, n)
##CHUNK 2
import (
"fmt" // Used for error formatting
"math/rand" // Used for random number generation in Monte Carlo method
"runtime" // Used to get information on available CPUs
"time" // Used for seeding the random number generation
)
func MonteCarloPi(randomPoints int) float64 {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
inside := 0
for i := 0; i < randomPoints; i++ {
x := rnd.Float64()
y := rnd.Float64()
if x*x+y*y <= 1 {
inside += 1
}
}
pi := float64(inside) / float64(randomPoints) * 4
return pi
##CHUNK 3
inside := 0
for i := 0; i < randomPoints; i++ {
x := rnd.Float64()
y := rnd.Float64()
if x*x+y*y <= 1 {
inside += 1
}
}
pi := float64(inside) / float64(randomPoints) * 4
return pi
}
// MonteCarloPiConcurrent approximates the value of pi using the Monte Carlo method.
// Unlike the MonteCarloPi function (first version), this implementation uses
// goroutines and channels to parallelize the computation.
// More details on the Monte Carlo method available at https://en.wikipedia.org/wiki/Monte_Carlo_method.
}
// drawPoints draws n random two-dimensional points in the interval [0, 1), [0, 1) and sends through c
// the number of points which where within the circle of center 0 and radius 1 (unit circle)
|
Go-master
| 57
|
func splitInt(x int, n int) ([]int, error) {
if x < n {
return nil, fmt.Errorf("x must be < n - given values are x=%d, n=%d", x, n)
}
split := make([]int, n)
if x%n == 0 {
for i := 0; i < n; i++ {
split[i] = x / n
}
} else {
limit := x % n
for i := 0; i < limit; i++ {
split[i] = x/n + 1
}
for i := limit; i < n; i++ {
split[i] = x / n
}
}
return split, nil
}
|
func splitInt(x int, n int) ([]int, error) {
if x < n {
return nil, fmt.Errorf("x must be < n - given values are x=%d, n=%d", x, n)
}
split := make([]int, n)
if x%n == 0 {
for i := 0; i < n; i++ {
split[i] = x / n
}
} else {
limit := x % n
for i := 0; i < limit; i++ {
split[i] = x/n + 1
}
for i := limit; i < n; i++ {
split[i] = x / n
}
}
return split, nil
}
|
func splitInt(x int, n int) ([]int, error) {
if x < n {
return nil, fmt.Errorf("x must be < n - given values are x=%d, n=%d", x, n)
}
split := make([]int, n)
if x%n == 0 {
for i := 0; i < n; i++ {
split[i] = x / n
}
} else {
limit := x % n
for i := 0; i < limit; i++ {
split[i] = x/n + 1
}
for i := limit; i < n; i++ {
split[i] = x / n
}
}
return split, nil
}
|
splitInt
| 75
| 94
|
math/pi/montecarlopi.go
|
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
#FILE: Go-master/dynamic/longestarithmeticsubsequence.go
##CHUNK 1
n := len(nums)
if n <= 1 {
return n
}
dp := make([]map[int]int, n)
for i := range dp {
dp[i] = make(map[int]int)
}
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
#FILE: Go-master/dynamic/optimalbst.go
##CHUNK 1
package dynamic
import "github.com/TheAlgorithms/Go/math/min"
// OptimalBST returns the minimum cost of constructing a Binary Search Tree
func OptimalBST(keys []int, freq []int, n int) int {
// Initialize DP table with size n x n
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
#FILE: Go-master/project_euler/problem_5/problem5.go
##CHUNK 1
package problem5
func Problem5(limit uint) uint {
n := limit * limit
for {
if isDivisible(n, limit) {
return n
}
n++
}
}
func isDivisible(n, limit uint) bool {
for i := uint(1); i <= limit; i++ {
if n%i != 0 {
return false
}
}
#FILE: Go-master/math/factorial/factorial.go
##CHUNK 1
if n < 0 {
return 0, ErrNegativeArgument
}
result := 1
for i := 2; i <= n; i++ {
result *= i
}
return result, nil
}
// Recursive This function recursively computes the factorial of a number
func Recursive(n int) (int, error) {
if n < 0 {
return 0, ErrNegativeArgument
}
if n <= 1 {
return 1, nil
}
prev, _ := Recursive(n - 1)
return n * prev, nil
#FILE: Go-master/math/binomialcoefficient.go
##CHUNK 1
// This function returns C(n, k) for given n and k
func Combinations(n int, k int) (int, error) {
if n < 0 || k < 0 {
return -1, ErrPosArgsOnly
}
if k > (n - k) {
k = n - k
}
res := 1
for i := 0; i < k; i++ {
res *= (n - i)
res /= (i + 1)
}
return res, nil
}
#FILE: Go-master/strings/genetic/genetic.go
##CHUNK 1
if n == r {
invalid = false
}
}
if invalid {
message := fmt.Sprintf("character not available in charmap at position: %v", position)
return nil, errors.New(message)
}
}
// Generate random starting population
pop := make([]PopulationItem, populationNum)
for i := 0; i < populationNum; i++ {
key := ""
for x := 0; x < utf8.RuneCountInString(target); x++ {
choice := rnd.Intn(len(charmap))
key += string(charmap[choice])
}
pop[i] = PopulationItem{key, 0}
}
#FILE: Go-master/dynamic/uniquepaths.go
##CHUNK 1
}
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
for i := 0; i < m; i++ {
grid[i][0] = 1
}
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}
#FILE: Go-master/math/permutation/heaps.go
##CHUNK 1
// Heap's Algorithm for generating all permutations of n objects
func Heaps(out chan []string, n int) {
elementSetCh := make(chan []string)
go GenerateElementSet(elementSetCh, n)
elementSet := <-elementSetCh
var recursiveGenerate func([]string, int, []string)
var permutations []string
recursiveGenerate = func(previousIteration []string, n int, elements []string) {
if n == 1 {
permutations = append(permutations, strings.Join(elements, ""))
} else {
for i := 0; i < n; i++ {
recursiveGenerate(previousIteration, n-1, elements)
if n%2 == 1 {
tmp := elements[i]
elements[i] = elements[n-1]
elements[n-1] = tmp
} else {
#CURRENT FILE: Go-master/math/pi/montecarlopi.go
##CHUNK 1
func drawPoints(n int, c chan<- int) {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
inside := 0
for i := 0; i < n; i++ {
x, y := rnd.Float64(), rnd.Float64()
if x*x+y*y <= 1 {
inside++
}
}
c <- inside
}
// splitInt takes an integer x and splits it within an integer slice of length n in the most uniform
// way possible.
}
|
Go-master
| 58
|
func Exponentiation(base, exponent, mod int64) (int64, error) {
if mod == 1 {
return 0, nil
}
if exponent < 0 {
return -1, ErrorNegativeExponent
}
_, err := Multiply64BitInt(mod-1, mod-1)
if err != nil {
return -1, err
}
var result int64 = 1
base = base % mod
for exponent > 0 {
if exponent%2 == 1 {
result = (result * base) % mod
}
exponent = exponent >> 1
base = (base * base) % mod
}
return result, nil
}
|
func Exponentiation(base, exponent, mod int64) (int64, error) {
if mod == 1 {
return 0, nil
}
if exponent < 0 {
return -1, ErrorNegativeExponent
}
_, err := Multiply64BitInt(mod-1, mod-1)
if err != nil {
return -1, err
}
var result int64 = 1
base = base % mod
for exponent > 0 {
if exponent%2 == 1 {
result = (result * base) % mod
}
exponent = exponent >> 1
base = (base * base) % mod
}
return result, nil
}
|
func Exponentiation(base, exponent, mod int64) (int64, error) {
if mod == 1 {
return 0, nil
}
if exponent < 0 {
return -1, ErrorNegativeExponent
}
_, err := Multiply64BitInt(mod-1, mod-1)
if err != nil {
return -1, err
}
var result int64 = 1
base = base % mod
for exponent > 0 {
if exponent%2 == 1 {
result = (result * base) % mod
}
exponent = exponent >> 1
base = (base * base) % mod
}
return result, nil
}
|
Exponentiation
| 23
| 49
|
math/modular/exponentiation.go
|
#FILE: Go-master/cipher/diffiehellman/diffiehellmankeyexchange.go
##CHUNK 1
//uses exponentiation by squaring to speed up the process
if mod == 1 {
return 0
}
var r int64 = 1
b = b % mod
for e > 0 {
if e&1 == 1 {
r = (r * b) % mod
}
e = e >> 1
b = (b * b) % mod
}
return r
}
##CHUNK 2
// GenerateMutualKey : generates a mutual key that can be used by only alice and bob
// mutualKey = (shareKey^prvKey)%primeNumber
func GenerateMutualKey(prvKey, shareKey int64) int64 {
return modularExponentiation(shareKey, prvKey, primeNumber)
}
// r = (b^e)%mod
func modularExponentiation(b, e, mod int64) int64 {
//runs in O(log(n)) where n = e
//uses exponentiation by squaring to speed up the process
if mod == 1 {
return 0
}
var r int64 = 1
b = b % mod
for e > 0 {
if e&1 == 1 {
r = (r * b) % mod
}
#FILE: Go-master/math/modular/exponentiation_test.go
##CHUNK 1
name string
description string
base int64
exponent int64
mod int64
expected int64
expectedError error
}
var testCases = []cases{
{
name: "Test 1",
description: "Test 1: 3^6 % 3 == 0",
base: 3,
exponent: 6,
mod: 3,
expected: 0,
expectedError: nil,
},
{
##CHUNK 2
// exponentiation_test.go
// description: Test for ModularExponentiation
// author(s) [Taj](https://github.com/tjgurwara99)
// see exponentiation.go
package modular
import "testing"
type cases struct {
name string
description string
base int64
exponent int64
mod int64
expected int64
expectedError error
}
var testCases = []cases{
#FILE: Go-master/conversion/binarytodecimal.go
##CHUNK 1
if len(binary) > 32 {
return -1, errors.New("binary number must be in range 0 to 2^(31-1)")
}
var result, base int = 0, 1
for i := len(binary) - 1; i >= 0; i-- {
if binary[i] == '1' {
result += base
}
base *= 2
}
return result, nil
}
##CHUNK 2
)
var isValid = regexp.MustCompile("^[0-1]{1,}$").MatchString
// BinaryToDecimal() function that will take Binary number as string,
// and return its Decimal equivalent as an integer.
func BinaryToDecimal(binary string) (int, error) {
if !isValid(binary) {
return -1, errors.New("not a valid binary string")
}
if len(binary) > 32 {
return -1, errors.New("binary number must be in range 0 to 2^(31-1)")
}
var result, base int = 0, 1
for i := len(binary) - 1; i >= 0; i-- {
if binary[i] == '1' {
result += base
}
base *= 2
}
#FILE: Go-master/math/prime/millerrabintest.go
##CHUNK 1
d, _ := formatNum(num)
res, err := modular.Exponentiation(witness, d, num)
if err != nil {
return false, err
}
// miller conditions checks
if res == 1 || res == num-1 {
return true, nil
}
for d != num-1 {
res = (res * res) % num
d *= 2
if res == 1 {
return false, nil
}
if res == num-1 {
return true, nil
}
#FILE: Go-master/math/factorial/factorial.go
##CHUNK 1
if n < 0 {
return 0, ErrNegativeArgument
}
result := 1
for i := 2; i <= n; i++ {
result *= i
}
return result, nil
}
// Recursive This function recursively computes the factorial of a number
func Recursive(n int) (int, error) {
if n < 0 {
return 0, ErrNegativeArgument
}
if n <= 1 {
return 1, nil
}
prev, _ := Recursive(n - 1)
return n * prev, nil
#FILE: Go-master/cipher/dsa/dsa.go
##CHUNK 1
if err != nil {
panic(err)
}
dsa.privKey = x
// 2. Compute y = g^x mod p
dsa.pubKey = new(big.Int).Exp(dsa.G, x, dsa.P)
}
// Sign is signature generation for DSA
// 1. Choose a random integer k from the range [1, q-1]
// 2. Compute r = (g^k mod p) mod q
// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q
func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) {
// 1. Choose a random integer k from the range [1, q-1]
k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1)))
if err != nil {
panic(err)
}
#CURRENT FILE: Go-master/math/modular/exponentiation.go
##CHUNK 1
import (
"errors"
"math"
)
// ErrorIntOverflow For asserting that the values do not overflow in Int64
var ErrorIntOverflow = errors.New("integer overflow")
// ErrorNegativeExponent for asserting that the exponent we receive is positive
var ErrorNegativeExponent = errors.New("negative Exponent provided")
}
// Multiply64BitInt Checking if the integer multiplication overflows
func Multiply64BitInt(left, right int64) (int64, error) {
if math.Abs(float64(left)) > float64(math.MaxInt64)/math.Abs(float64(right)) {
return 0, ErrorIntOverflow
}
return left * right, nil
|
Go-master
| 59
|
func Matrix(n uint) uint {
a, b := 1, 1
c, rc, tc := 1, 0, 0
d, rd := 0, 1
for n != 0 {
if n&1 == 1 {
tc = rc
rc = rc*a + rd*c
rd = tc*b + rd*d
}
ta := a
tb := b
tc = c
a = a*a + b*c
b = ta*b + b*d
c = c*ta + d*c
d = tc*tb + d*d
n >>= 1
}
return uint(rc)
}
|
func Matrix(n uint) uint {
a, b := 1, 1
c, rc, tc := 1, 0, 0
d, rd := 0, 1
for n != 0 {
if n&1 == 1 {
tc = rc
rc = rc*a + rd*c
rd = tc*b + rd*d
}
ta := a
tb := b
tc = c
a = a*a + b*c
b = ta*b + b*d
c = c*ta + d*c
d = tc*tb + d*d
n >>= 1
}
return uint(rc)
}
|
func Matrix(n uint) uint {
a, b := 1, 1
c, rc, tc := 1, 0, 0
d, rd := 0, 1
for n != 0 {
if n&1 == 1 {
tc = rc
rc = rc*a + rd*c
rd = tc*b + rd*d
}
ta := a
tb := b
tc = c
a = a*a + b*c
b = ta*b + b*d
c = c*ta + d*c
d = tc*tb + d*d
n >>= 1
}
return uint(rc)
}
|
Matrix
| 16
| 39
|
math/fibonacci/fibonacci.go
|
#FILE: Go-master/project_euler/problem_9/problem9.go
##CHUNK 1
* Find the product abc.
*
* @author ddaniel27
*/
package problem9
func Problem9() uint {
for a := uint(1); a < 1000; a++ {
for b := a + 1; b < 1000; b++ {
c := 1000 - a - b
if a*a+b*b == c*c {
return a * b * c
}
}
}
return 0
}
##CHUNK 2
/**
* Problem 9 - Special Pythagorean triplet
* @see {@link https://projecteuler.net/problem=9}
*
* A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
* a^2 + b^2 = c^2
*
* For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
*
* There exists exactly one Pythagorean triplet for which a + b + c = 1000.
* Find the product abc.
*
* @author ddaniel27
*/
package problem9
func Problem9() uint {
for a := uint(1); a < 1000; a++ {
for b := a + 1; b < 1000; b++ {
c := 1000 - a - b
#FILE: Go-master/hashing/sha256/sha256.go
##CHUNK 1
w[i] = w[i-16] + s0 + w[i-7] + s1
}
// Actual hashing loop
a, b, c, d, e, f, g, h := h0, h1, h2, h3, h4, h5, h6, h7
for i := 0; i < 64; i++ {
S1 := bits.RotateLeft32(e, -6) ^ bits.RotateLeft32(e, -11) ^ bits.RotateLeft32(e, -25)
ch := (e & f) ^ ((^e) & g)
tmp1 := h + S1 + ch + K[i] + w[i]
S0 := bits.RotateLeft32(a, -2) ^ bits.RotateLeft32(a, -13) ^ bits.RotateLeft32(a, -22)
maj := (a & b) ^ (a & c) ^ (b & c)
tmp2 := S0 + maj
h = g
g = f
f = e
e = d + tmp1
d = c
c = b
b = a
a = tmp1 + tmp2
##CHUNK 2
maj := (a & b) ^ (a & c) ^ (b & c)
tmp2 := S0 + maj
h = g
g = f
f = e
e = d + tmp1
d = c
c = b
b = a
a = tmp1 + tmp2
}
h0 += a
h1 += b
h2 += c
h3 += d
h4 += e
h5 += f
h6 += g
h7 += h
}
#FILE: Go-master/project_euler/problem_13/problem13.go
##CHUNK 1
return sum[:10]
}
func add(a, b string) string {
if len(a) < len(b) {
a, b = b, a
}
carry := 0
sum := make([]byte, len(a)+1)
for i := 0; i < len(a); i++ {
d := int(a[len(a)-1-i] - '0')
if i < len(b) {
d += int(b[len(b)-1-i] - '0')
}
d += carry
sum[len(sum)-1-i] = byte(d%10) + '0'
carry = d / 10
#FILE: Go-master/project_euler/problem_2/problem2.go
##CHUNK 1
* find the sum of the even-valued terms.
*
* @author ddaniel27
*/
package problem2
func Problem2(n uint) uint {
sum := uint(0)
a, b := uint(1), uint(2)
for b < n {
if b%2 == 0 {
sum += b
}
a, b = b, a+b
}
return sum
}
#FILE: Go-master/math/binary/bitcounter.go
##CHUNK 1
// BitCounter - The function returns the number of set bits for an unsigned integer number
func BitCounter(n uint) int {
counter := 0
for n != 0 {
if n&1 == 1 {
counter++
}
n >>= 1
}
return counter
}
#FILE: Go-master/dynamic/longestarithmeticsubsequence.go
##CHUNK 1
n := len(nums)
if n <= 1 {
return n
}
dp := make([]map[int]int, n)
for i := range dp {
dp[i] = make(map[int]int)
}
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[i][diff]+1 > maxLength {
maxLength = dp[i][diff] + 1
}
}
#FILE: Go-master/strings/manacher/longestpalindrome.go
##CHUNK 1
index := 0
maxLen := 0
maxCenterSize := 0
for i := range b {
if i < k {
b[i] = min.Int(b[2*index-i], k-i)
} else {
b[i] = 1
}
for i-b[i] >= 0 && i+b[i] < len(boundaries) && boundaries[i-b[i]] == boundaries[i+b[i]] {
b[i] += 1
}
if maxLen < b[i]-1 {
maxLen = b[i] - 1
maxCenterSize = i
}
if b[i]+i-1 > k {
k = b[i] + i - 1
index = i
}
#CURRENT FILE: Go-master/math/fibonacci/fibonacci.go
##CHUNK 1
sqrt5 := math.Sqrt(5)
phi := (sqrt5 + 1) / 2
powPhi := math.Pow(phi, float64(n))
return uint(powPhi/sqrt5 + 0.5)
}
// Recursive calculates the n-th fibonacci number recursively by adding the previous two Fibonacci numbers.
// This algorithm is extremely slow for bigger numbers, but provides a simpler implementation.
func Recursive(n uint) uint {
if n <= 1 {
return n
}
return Recursive(n-1) + Recursive(n-2)
}
|
Go-master
| 60
|
func NewFromElements(elements [][]T) (Matrix[T], error) {
if !IsValid(elements) {
return Matrix[T]{}, errors.New("rows have different numbers of columns")
}
rows := len(elements)
if rows == 0 {
return Matrix[T]{}, nil // Empty matrix
}
columns := len(elements[0])
matrix := Matrix[T]{
elements: make([][]T, rows),
rows: rows, // Set the rows field
columns: columns, // Set the columns field
}
for i := range matrix.elements {
matrix.elements[i] = make([]T, columns)
copy(matrix.elements[i], elements[i])
}
return matrix, nil
}
|
func NewFromElements(elements [][]T) (Matrix[T], error) {
if !IsValid(elements) {
return Matrix[T]{}, errors.New("rows have different numbers of columns")
}
rows := len(elements)
if rows == 0 {
return Matrix[T]{}, nil // Empty matrix
}
columns := len(elements[0])
matrix := Matrix[T]{
elements: make([][]T, rows),
rows: rows, // Set the rows field
columns: columns, // Set the columns field
}
for i := range matrix.elements {
matrix.elements[i] = make([]T, columns)
copy(matrix.elements[i], elements[i])
}
return matrix, nil
}
|
func NewFromElements(elements [][]T) (Matrix[T], error) {
if !IsValid(elements) {
return Matrix[T]{}, errors.New("rows have different numbers of columns")
}
rows := len(elements)
if rows == 0 {
return Matrix[T]{}, nil // Empty matrix
}
columns := len(elements[0])
matrix := Matrix[T]{
elements: make([][]T, rows),
rows: rows, // Set the rows field
columns: columns, // Set the columns field
}
for i := range matrix.elements {
matrix.elements[i] = make([]T, columns)
copy(matrix.elements[i], elements[i])
}
return matrix, nil
}
|
NewFromElements
| 42
| 63
|
math/matrix/matrix.go
|
#FILE: Go-master/math/matrix/matrix_test.go
##CHUNK 1
func TestMatrixEmptyRowsAndColumns(t *testing.T) {
// Create an empty matrix
emptyMatrix := matrix.New(0, 0, 0)
// Check the number of rows and columns for an empty matrix
rows := emptyMatrix.Rows()
columns := emptyMatrix.Columns()
if rows != 0 {
t.Errorf("Expected 0 rows for an empty matrix, but got %d", rows)
}
if columns != 0 {
t.Errorf("Expected 0 columns for an empty matrix, but got %d", columns)
}
}
// BenchmarkNew benchmarks the New function.
func BenchmarkNew(b *testing.B) {
##CHUNK 2
if err != nil {
t.Fatalf("Failed to copy matrix: %v", err)
}
// Check the number of columns
expectedColumns := len(data[0])
columns := matrix.Columns()
if columns != expectedColumns {
t.Errorf("Expected %d columns, but got %d", expectedColumns, columns)
}
}
func TestMatrixEmptyRowsAndColumns(t *testing.T) {
// Create an empty matrix
emptyMatrix := matrix.New(0, 0, 0)
// Check the number of rows and columns for an empty matrix
rows := emptyMatrix.Rows()
columns := emptyMatrix.Columns()
if rows != 0 {
##CHUNK 3
rows := matrix.Rows()
if rows != expectedRows {
t.Errorf("Expected %d rows, but got %d", expectedRows, rows)
}
}
func TestMatrixColumns(t *testing.T) {
// Create a sample matrix
data := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
matrix, err := matrix.NewFromElements(data)
if err != nil {
t.Fatalf("Failed to copy matrix: %v", err)
}
// Check the number of columns
expectedColumns := len(data[0])
columns := matrix.Columns()
if columns != expectedColumns {
t.Errorf("Expected %d columns, but got %d", expectedColumns, columns)
}
}
##CHUNK 4
}
}
// BenchmarkGet benchmarks the Get method.
func BenchmarkGet(b *testing.B) {
// Create a sample matrix for benchmarking
rows := 100
columns := 100
matrix := matrix.New(rows, columns, 0)
for i := 0; i < b.N; i++ {
_, _ = matrix.Get(50, 50) // Change the row and column indices as needed
}
}
// BenchmarkSet benchmarks the Set method.
func BenchmarkSet(b *testing.B) {
// Create a sample matrix for benchmarking
rows := 100
columns := 100
##CHUNK 5
t.Errorf("Expected 0 rows for an empty matrix, but got %d", rows)
}
if columns != 0 {
t.Errorf("Expected 0 columns for an empty matrix, but got %d", columns)
}
}
// BenchmarkNew benchmarks the New function.
func BenchmarkNew(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = matrix.New(100, 100, 0) // Change the arguments to match your use case
}
}
// BenchmarkNewFromElements benchmarks the NewFromElements function.
func BenchmarkNewFromElements(b *testing.B) {
// Create a sample matrix for benchmarking
rows := 100
columns := 100
#FILE: Go-master/math/matrix/copy.go
##CHUNK 1
func (m Matrix[T]) Copy() (Matrix[T], error) {
rows := m.Rows()
columns := m.Columns()
if rows == 0 || columns == 0 {
return Matrix[T]{}, nil
}
zeroVal, err := m.Get(0, 0) // Get the zero value of the element type
if err != nil {
return Matrix[T]{}, err
}
copyMatrix := New(rows, columns, zeroVal)
var wg sync.WaitGroup
wg.Add(rows)
errChan := make(chan error, 1)
for i := 0; i < rows; i++ {
go func(i int) {
defer wg.Done()
for j := 0; j < columns; j++ {
##CHUNK 2
// copy.go
// description: Copy a matrix
// details: This function creates a new matrix with the same dimensions as the original matrix and copies all the elements from the original matrix to the new matrix.
// time complexity: O(n*m) where n and m are the dimensions of the matrix
// space complexity: O(n*m) where n and m are the dimensions of the matrix
package matrix
import "sync"
func (m Matrix[T]) Copy() (Matrix[T], error) {
rows := m.Rows()
columns := m.Columns()
if rows == 0 || columns == 0 {
return Matrix[T]{}, nil
}
zeroVal, err := m.Get(0, 0) // Get the zero value of the element type
if err != nil {
return Matrix[T]{}, err
#FILE: Go-master/math/matrix/isvalid.go
##CHUNK 1
package matrix
import "github.com/TheAlgorithms/Go/constraints"
// IsValid checks if the input matrix has consistent row lengths.
func IsValid[T constraints.Integer](elements [][]T) bool {
if len(elements) == 0 {
return true
}
columns := len(elements[0])
for _, row := range elements {
if len(row) != columns {
return false
}
}
return true
}
#FILE: Go-master/math/matrix/strassenmatrixmultiply_test.go
##CHUNK 1
// Expected result
expectedData, err := matrixA.Multiply(matrixB)
if err != nil {
t.Error("copyMatrix.Set error: " + err.Error())
}
// Check the dimensions of the result matrix
expectedRows := expectedData.Rows()
expectedColumns := expectedData.Columns()
rows := resultMatrix.Rows()
columns := resultMatrix.Columns()
if rows != expectedRows {
t.Errorf("Expected %d rows in result matrix, but got %d", expectedRows, rows)
}
if columns != expectedColumns {
t.Errorf("Expected %d columns in result matrix, but got %d", expectedColumns, columns)
}
#CURRENT FILE: Go-master/math/matrix/matrix.go
##CHUNK 1
elements [][]T
rows int
columns int
}
// NewMatrix creates a new Matrix based on the provided arguments.
func New[T constraints.Integer](rows, columns int, initial T) Matrix[T] {
if rows < 0 || columns < 0 {
return Matrix[T]{} // Invalid dimensions, return an empty matrix
}
// Initialize the matrix with the specified dimensions and fill it with the initial value.
elements := make([][]T, rows)
var wg sync.WaitGroup
wg.Add(rows)
for i := range elements {
go func(i int) {
defer wg.Done()
elements[i] = make([]T, columns)
|
Go-master
| 61
|
func OptimizedTrialDivision(n int64) bool {
// 0 and 1 are not prime
if n < 2 {
return false
}
// 2 and 3 are prime
if n < 4 {
return true
}
// all numbers divisible by 2 except 2 are not prime
if n%2 == 0 {
return false
}
for i := int64(3); i*i <= n; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
|
func OptimizedTrialDivision(n int64) bool {
// 0 and 1 are not prime
if n < 2 {
return false
}
// 2 and 3 are prime
if n < 4 {
return true
}
// all numbers divisible by 2 except 2 are not prime
if n%2 == 0 {
return false
}
for i := int64(3); i*i <= n; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
|
func OptimizedTrialDivision(n int64) bool {
// 0 and 1 are not prime
if n < 2 {
return false
}
// 2 and 3 are prime
if n < 4 {
return true
}
// all numbers divisible by 2 except 2 are not prime
if n%2 == 0 {
return false
}
for i := int64(3); i*i <= n; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
|
OptimizedTrialDivision
| 27
| 49
|
math/prime/primecheck.go
|
#FILE: Go-master/math/prime/millerrabintest.go
##CHUNK 1
func formatNum(num int64) (d int64, s int64) {
d = num - 1
for num%2 == 0 {
d /= 2
s++
}
return
}
// isTrivial checks if num's primality is easy to determine.
// If it is, it returns true and num's primality. Otherwise
// it returns false and false.
func isTrivial(num int64) (prime bool, trivial bool) {
if num <= 4 {
// 2 and 3 are primes
prime = num == 2 || num == 3
trivial = true
} else {
prime = false
// number is trivial prime if
##CHUNK 2
// If it is, it returns true and num's primality. Otherwise
// it returns false and false.
func isTrivial(num int64) (prime bool, trivial bool) {
if num <= 4 {
// 2 and 3 are primes
prime = num == 2 || num == 3
trivial = true
} else {
prime = false
// number is trivial prime if
// it is divisible by 2
trivial = num%2 == 0
}
return
}
// MillerTest tests whether num is a strong probable prime to a witness.
// Formally: a^d ≡ 1 (mod n) or a^(2^r * d) ≡ -1 (mod n), 0 <= r <= s
func MillerTest(num, witness int64) (bool, error) {
#FILE: Go-master/math/eulertotient.go
##CHUNK 1
package math
// Phi is the Euler totient function.
// This function computes the number of numbers less then n that are coprime with n.
func Phi(n int64) int64 {
result := n
for i := int64(2); i*i <= n; i += 1 {
if n%i == 0 {
for {
if n%i != 0 {
break
}
n /= i
}
result -= result / i
}
}
if n > 1 {
result -= result / n
#FILE: Go-master/project_euler/problem_12/problem12.go
##CHUNK 1
triangle += i
if numDivisors(triangle) >= limit {
return triangle
}
}
}
func numDivisors(n uint) uint {
divisors := uint(0)
for i := uint(1); i*i <= n; i++ {
if n%i == 0 {
divisors += 2
}
}
return divisors
}
#FILE: Go-master/math/prime/primefactorization.go
##CHUNK 1
// primefactorization.go
// description: Prime factorization of a number
// time complexity: O(sqrt(n))
// space complexity: O(sqrt(n))
package prime
// Factorize is a function that computes the exponents
// of each prime in the prime factorization of n
func Factorize(n int64) map[int64]int64 {
result := make(map[int64]int64)
for i := int64(2); i*i <= n; i += 1 {
for {
if n%i != 0 {
break
}
result[i] += 1
n /= i
}
#FILE: Go-master/math/prime/twin.go
##CHUNK 1
package prime
// This function returns twin prime for given number
// returns (n + 2) if both n and (n + 2) are prime
// -1 otherwise
func Twin(n int) (int, bool) {
if OptimizedTrialDivision(int64(n)) && OptimizedTrialDivision(int64(n+2)) {
return n + 2, true
}
return -1, false
}
#FILE: Go-master/math/binary/checkisnumberpoweroftwo.go
##CHUNK 1
// This is also true for 0, which is not a power of 2, for which we
// have to add and extra condition.
func IsPowerOfTwo(x int) bool {
return x > 0 && (x&(x-1)) == 0
}
// IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number
// by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000,
// which in decimal system is 8 or = 2 * 2 * 2
func IsPowerOfTwoLeftShift(number uint) bool {
for p := uint(1); p <= number; p = p << 1 {
if number == p {
return true
}
}
return false
}
#FILE: Go-master/math/pronicnumber.go
##CHUNK 1
package math
import "math"
// PronicNumber returns true if argument passed to the function is pronic and false otherwise.
func PronicNumber(n int) bool {
if n < 0 || n%2 == 1 {
return false
}
x := int(math.Sqrt(float64(n)))
return n == x*(x+1)
}
#CURRENT FILE: Go-master/math/prime/primecheck.go
##CHUNK 1
func TrialDivision(n int64) bool {
if n < 2 {
return false
}
for i := int64(2); i < n; i++ {
if n%i == 0 {
return false
}
}
return true
}
// OptimizedTrialDivision checks primality of an integer using an optimized trial division method.
// The optimizations include not checking divisibility by the even numbers and only checking up to
}
##CHUNK 2
package prime
// A primality test is an algorithm for determining whether an input number is prime. Among other
// fields of mathematics, it is used for cryptography. Unlike integer factorization, primality
// tests do not generally give prime factors, only stating whether the input number is prime or not.
// time complexity: O(sqrt(n))
// space complexity: O(1)
// Source - Wikipedia https://en.wikipedia.org/wiki/Primality_test
// TrialDivision tests whether a number is prime by trying to divide it by the numbers less than it.
func TrialDivision(n int64) bool {
if n < 2 {
return false
}
for i := int64(2); i < n; i++ {
if n%i == 0 {
return false
}
|
chi-master
| 62
|
func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) {
ps := strings.Index(pattern, "{")
ws := strings.Index(pattern, "*")
if ps < 0 && ws < 0 {
return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing
}
// Sanity check
if ps >= 0 && ws >= 0 && ws < ps {
panic("chi: wildcard '*' must be the last pattern in a route, otherwise use a '{param}'")
}
var tail byte = '/' // Default endpoint tail to / byte
if ps >= 0 {
// Param/Regexp pattern is next
nt := ntParam
// Read to closing } taking into account opens and closes in curl count (cc)
cc := 0
pe := ps
for i, c := range pattern[ps:] {
if c == '{' {
cc++
} else if c == '}' {
cc--
if cc == 0 {
pe = ps + i
break
}
}
}
if pe == ps {
panic("chi: route param closing delimiter '}' is missing")
}
key := pattern[ps+1 : pe]
pe++ // set end to next position
if pe < len(pattern) {
tail = pattern[pe]
}
key, rexpat, isRegexp := strings.Cut(key, ":")
if isRegexp {
nt = ntRegexp
}
if len(rexpat) > 0 {
if rexpat[0] != '^' {
rexpat = "^" + rexpat
}
if rexpat[len(rexpat)-1] != '$' {
rexpat += "$"
}
}
return nt, key, rexpat, tail, ps, pe
}
// Wildcard pattern as finale
if ws < len(pattern)-1 {
panic("chi: wildcard '*' must be the last value in a route. trim trailing text or use a '{param}' instead")
}
return ntCatchAll, "*", "", 0, ws, len(pattern)
}
|
func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) {
ps := strings.Index(pattern, "{")
ws := strings.Index(pattern, "*")
if ps < 0 && ws < 0 {
return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing
}
// Sanity check
if ps >= 0 && ws >= 0 && ws < ps {
panic("chi: wildcard '*' must be the last pattern in a route, otherwise use a '{param}'")
}
var tail byte = '/' // Default endpoint tail to / byte
if ps >= 0 {
// Param/Regexp pattern is next
nt := ntParam
// Read to closing } taking into account opens and closes in curl count (cc)
cc := 0
pe := ps
for i, c := range pattern[ps:] {
if c == '{' {
cc++
} else if c == '}' {
cc--
if cc == 0 {
pe = ps + i
break
}
}
}
if pe == ps {
panic("chi: route param closing delimiter '}' is missing")
}
key := pattern[ps+1 : pe]
pe++ // set end to next position
if pe < len(pattern) {
tail = pattern[pe]
}
key, rexpat, isRegexp := strings.Cut(key, ":")
if isRegexp {
nt = ntRegexp
}
if len(rexpat) > 0 {
if rexpat[0] != '^' {
rexpat = "^" + rexpat
}
if rexpat[len(rexpat)-1] != '$' {
rexpat += "$"
}
}
return nt, key, rexpat, tail, ps, pe
}
// Wildcard pattern as finale
if ws < len(pattern)-1 {
panic("chi: wildcard '*' must be the last value in a route. trim trailing text or use a '{param}' instead")
}
return ntCatchAll, "*", "", 0, ws, len(pattern)
}
|
func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) {
ps := strings.Index(pattern, "{")
ws := strings.Index(pattern, "*")
if ps < 0 && ws < 0 {
return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing
}
// Sanity check
if ps >= 0 && ws >= 0 && ws < ps {
panic("chi: wildcard '*' must be the last pattern in a route, otherwise use a '{param}'")
}
var tail byte = '/' // Default endpoint tail to / byte
if ps >= 0 {
// Param/Regexp pattern is next
nt := ntParam
// Read to closing } taking into account opens and closes in curl count (cc)
cc := 0
pe := ps
for i, c := range pattern[ps:] {
if c == '{' {
cc++
} else if c == '}' {
cc--
if cc == 0 {
pe = ps + i
break
}
}
}
if pe == ps {
panic("chi: route param closing delimiter '}' is missing")
}
key := pattern[ps+1 : pe]
pe++ // set end to next position
if pe < len(pattern) {
tail = pattern[pe]
}
key, rexpat, isRegexp := strings.Cut(key, ":")
if isRegexp {
nt = ntRegexp
}
if len(rexpat) > 0 {
if rexpat[0] != '^' {
rexpat = "^" + rexpat
}
if rexpat[len(rexpat)-1] != '$' {
rexpat += "$"
}
}
return nt, key, rexpat, tail, ps, pe
}
// Wildcard pattern as finale
if ws < len(pattern)-1 {
panic("chi: wildcard '*' must be the last value in a route. trim trailing text or use a '{param}' instead")
}
return ntCatchAll, "*", "", 0, ws, len(pattern)
}
|
patNextSegment
| 688
| 754
|
tree.go
|
#FILE: chi-master/middleware/wrap_writer.go
##CHUNK 1
)
// NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to
// hook into various parts of the response process.
func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter {
_, fl := w.(http.Flusher)
bw := basicWriter{ResponseWriter: w}
if protoMajor == 2 {
_, ps := w.(http.Pusher)
if fl && ps {
return &http2FancyWriter{bw}
}
} else {
_, hj := w.(http.Hijacker)
_, rf := w.(io.ReaderFrom)
if fl && hj && rf {
return &httpFancyWriter{bw}
}
##CHUNK 2
_, ps := w.(http.Pusher)
if fl && ps {
return &http2FancyWriter{bw}
}
} else {
_, hj := w.(http.Hijacker)
_, rf := w.(io.ReaderFrom)
if fl && hj && rf {
return &httpFancyWriter{bw}
}
if fl && hj {
return &flushHijackWriter{bw}
}
if hj {
return &hijackWriter{bw}
}
}
if fl {
return &flushWriter{bw}
#FILE: chi-master/mux.go
##CHUNK 1
return
}
if rctx.methodNotAllowed {
mx.MethodNotAllowedHandler(rctx.methodsAllowed...).ServeHTTP(w, r)
} else {
mx.NotFoundHandler().ServeHTTP(w, r)
}
}
func (mx *Mux) nextRoutePath(rctx *Context) string {
routePath := "/"
nx := len(rctx.routeParams.Keys) - 1 // index of last param in list
if nx >= 0 && rctx.routeParams.Keys[nx] == "*" && len(rctx.routeParams.Values) > nx {
routePath = "/" + rctx.routeParams.Values[nx]
}
return routePath
}
// Recursively update data on child routers.
func (mx *Mux) updateSubRoutes(fn func(subMux *Mux)) {
##CHUNK 2
// and routing pattern.
func (mx *Mux) handle(method methodTyp, pattern string, handler http.Handler) *node {
if len(pattern) == 0 || pattern[0] != '/' {
panic(fmt.Sprintf("chi: routing pattern must begin with '/' in '%s'", pattern))
}
// Build the computed routing handler for this routing pattern.
if !mx.inline && mx.handler == nil {
mx.updateRouteHandler()
}
// Build endpoint handler with inline middlewares for the route
var h http.Handler
if mx.inline {
mx.handler = http.HandlerFunc(mx.routeHTTP)
h = Chain(mx.middlewares...).Handler(handler)
} else {
h = handler
}
##CHUNK 3
routePath := "/"
nx := len(rctx.routeParams.Keys) - 1 // index of last param in list
if nx >= 0 && rctx.routeParams.Keys[nx] == "*" && len(rctx.routeParams.Values) > nx {
routePath = "/" + rctx.routeParams.Values[nx]
}
return routePath
}
// Recursively update data on child routers.
func (mx *Mux) updateSubRoutes(fn func(subMux *Mux)) {
for _, r := range mx.tree.routes() {
subMux, ok := r.SubRoutes.(*Mux)
if !ok {
continue
}
fn(subMux)
}
}
// updateRouteHandler builds the single mux handler that is a chain of the middleware
#CURRENT FILE: chi-master/tree.go
##CHUNK 1
// serially loop through each node grouped by the tail delimiter
for idx := 0; idx < len(nds); idx++ {
xn = nds[idx]
// label for param nodes is the delimiter byte
p := strings.IndexByte(xsearch, xn.tail)
if p < 0 {
if xn.tail == '/' {
p = len(xsearch)
} else {
continue
}
} else if ntyp == ntRegexp && p == 0 {
continue
}
if ntyp == ntRegexp && xn.rex != nil {
if !xn.rex.MatchString(xsearch[:p]) {
continue
##CHUNK 2
// tailSort pushes nodes with '/' as the tail to the end of the list for param nodes.
// The list order determines the traversal order.
func (ns nodes) tailSort() {
for i := len(ns) - 1; i >= 0; i-- {
if ns[i].typ > ntStatic && ns[i].tail == '/' {
ns.Swap(i, len(ns)-1)
return
}
}
}
func (ns nodes) findEdge(label byte) *node {
num := len(ns)
idx := 0
i, j := 0, num-1
for i <= j {
idx = i + (j-i)/2
if label > ns[idx].label {
i = idx + 1
} else if label < ns[idx].label {
##CHUNK 3
continue
}
xsearch = xsearch[len(xn.prefix):]
case ntParam, ntRegexp:
// short-circuit and return no matching route for empty param values
if xsearch == "" {
continue
}
// serially loop through each node grouped by the tail delimiter
for idx := 0; idx < len(nds); idx++ {
xn = nds[idx]
// label for param nodes is the delimiter byte
p := strings.IndexByte(xsearch, xn.tail)
if p < 0 {
if xn.tail == '/' {
p = len(xsearch)
##CHUNK 4
n.children[child.typ][i].label = label
n.children[child.typ][i].tail = tail
return
}
}
panic("chi: replacing missing child")
}
func (n *node) getEdge(ntyp nodeTyp, label, tail byte, prefix string) *node {
nds := n.children[ntyp]
for i := 0; i < len(nds); i++ {
if nds[i].label == label && nds[i].tail == tail {
if ntyp == ntRegexp && nds[i].prefix != prefix {
continue
}
return nds[i]
}
}
return nil
}
##CHUNK 5
func (ns nodes) findEdge(label byte) *node {
num := len(ns)
idx := 0
i, j := 0, num-1
for i <= j {
idx = i + (j-i)/2
if label > ns[idx].label {
i = idx + 1
} else if label < ns[idx].label {
j = idx - 1
} else {
i = num // breaks cond
}
}
if ns[idx].label != label {
return nil
}
return ns[idx]
}
|
chi-master
| 63
|
func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter {
_, fl := w.(http.Flusher)
bw := basicWriter{ResponseWriter: w}
if protoMajor == 2 {
_, ps := w.(http.Pusher)
if fl && ps {
return &http2FancyWriter{bw}
}
} else {
_, hj := w.(http.Hijacker)
_, rf := w.(io.ReaderFrom)
if fl && hj && rf {
return &httpFancyWriter{bw}
}
if fl && hj {
return &flushHijackWriter{bw}
}
if hj {
return &hijackWriter{bw}
}
}
if fl {
return &flushWriter{bw}
}
return &bw
}
|
func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter {
_, fl := w.(http.Flusher)
bw := basicWriter{ResponseWriter: w}
if protoMajor == 2 {
_, ps := w.(http.Pusher)
if fl && ps {
return &http2FancyWriter{bw}
}
} else {
_, hj := w.(http.Hijacker)
_, rf := w.(io.ReaderFrom)
if fl && hj && rf {
return &httpFancyWriter{bw}
}
if fl && hj {
return &flushHijackWriter{bw}
}
if hj {
return &hijackWriter{bw}
}
}
if fl {
return &flushWriter{bw}
}
return &bw
}
|
func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter {
_, fl := w.(http.Flusher)
bw := basicWriter{ResponseWriter: w}
if protoMajor == 2 {
_, ps := w.(http.Pusher)
if fl && ps {
return &http2FancyWriter{bw}
}
} else {
_, hj := w.(http.Hijacker)
_, rf := w.(io.ReaderFrom)
if fl && hj && rf {
return &httpFancyWriter{bw}
}
if fl && hj {
return &flushHijackWriter{bw}
}
if hj {
return &hijackWriter{bw}
}
}
if fl {
return &flushWriter{bw}
}
return &bw
}
|
NewWrapResponseWriter
| 14
| 43
|
middleware/wrap_writer.go
|
#FILE: chi-master/middleware/middleware_test.go
##CHUNK 1
func TestWrapWriterHTTP2(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Proto != "HTTP/2.0" {
t.Fatalf("request proto should be HTTP/2.0 but was %s", r.Proto)
}
_, fl := w.(http.Flusher)
if !fl {
t.Fatal("request should have been a http.Flusher")
}
_, hj := w.(http.Hijacker)
if hj {
t.Fatal("request should not have been a http.Hijacker")
}
_, rf := w.(io.ReaderFrom)
if rf {
t.Fatal("request should not have been an io.ReaderFrom")
}
_, ps := w.(http.Pusher)
if !ps {
##CHUNK 2
_, hj := w.(http.Hijacker)
if hj {
t.Fatal("request should not have been a http.Hijacker")
}
_, rf := w.(io.ReaderFrom)
if rf {
t.Fatal("request should not have been an io.ReaderFrom")
}
_, ps := w.(http.Pusher)
if !ps {
t.Fatal("request should have been a http.Pusher")
}
w.Write([]byte("OK"))
})
wmw := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(NewWrapResponseWriter(w, r.ProtoMajor), r)
})
##CHUNK 3
"testing"
"time"
)
var testdataDir string
func init() {
_, filename, _, _ := runtime.Caller(0)
testdataDir = path.Join(path.Dir(filename), "/../testdata")
}
func TestWrapWriterHTTP2(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Proto != "HTTP/2.0" {
t.Fatalf("request proto should be HTTP/2.0 but was %s", r.Proto)
}
_, fl := w.(http.Flusher)
if !fl {
t.Fatal("request should have been a http.Flusher")
}
#FILE: chi-master/tree.go
##CHUNK 1
// Visit the leaf values if any
if (n.endpoints != nil || n.subroutes != nil) && fn(n.endpoints, n.subroutes) {
return true
}
// Recurse on the children
for _, ns := range n.children {
for _, cn := range ns {
if cn.walk(fn) {
return true
}
}
}
return false
}
// patNextSegment returns the next segment details from a pattern:
// node type, param key, regexp string, param tail byte, param starting index, param ending index
func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) {
ps := strings.Index(pattern, "{")
##CHUNK 2
}
}
}
return false
}
// patNextSegment returns the next segment details from a pattern:
// node type, param key, regexp string, param tail byte, param starting index, param ending index
func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) {
ps := strings.Index(pattern, "{")
ws := strings.Index(pattern, "*")
if ps < 0 && ws < 0 {
return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing
}
// Sanity check
if ps >= 0 && ws >= 0 && ws < ps {
panic("chi: wildcard '*' must be the last pattern in a route, otherwise use a '{param}'")
}
##CHUNK 3
ws := strings.Index(pattern, "*")
if ps < 0 && ws < 0 {
return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing
}
// Sanity check
if ps >= 0 && ws >= 0 && ws < ps {
panic("chi: wildcard '*' must be the last pattern in a route, otherwise use a '{param}'")
}
var tail byte = '/' // Default endpoint tail to / byte
if ps >= 0 {
// Param/Regexp pattern is next
nt := ntParam
// Read to closing } taking into account opens and closes in curl count (cc)
cc := 0
pe := ps
#FILE: chi-master/middleware/strip.go
##CHUNK 1
fn := func(w http.ResponseWriter, r *http.Request) {
var path string
rctx := chi.RouteContext(r.Context())
if rctx != nil && rctx.RoutePath != "" {
path = rctx.RoutePath
} else {
path = r.URL.Path
}
if len(path) > 1 && path[len(path)-1] == '/' {
if r.URL.RawQuery != "" {
path = fmt.Sprintf("%s?%s", path[:len(path)-1], r.URL.RawQuery)
} else {
path = path[:len(path)-1]
}
redirectURL := fmt.Sprintf("//%s%s", r.Host, path)
http.Redirect(w, r, redirectURL, 301)
return
}
next.ServeHTTP(w, r)
}
#CURRENT FILE: chi-master/middleware/wrap_writer.go
##CHUNK 1
hj := f.basicWriter.ResponseWriter.(http.Hijacker)
return hj.Hijack()
}
var _ http.Hijacker = &hijackWriter{}
// flushHijackWriter ...
type flushHijackWriter struct {
basicWriter
}
func (f *flushHijackWriter) Flush() {
f.wroteHeader = true
fl := f.basicWriter.ResponseWriter.(http.Flusher)
fl.Flush()
}
func (f *flushHijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hj := f.basicWriter.ResponseWriter.(http.Hijacker)
return hj.Hijack()
##CHUNK 2
basicWriter
}
func (f *httpFancyWriter) Flush() {
f.wroteHeader = true
fl := f.basicWriter.ResponseWriter.(http.Flusher)
fl.Flush()
}
func (f *httpFancyWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hj := f.basicWriter.ResponseWriter.(http.Hijacker)
return hj.Hijack()
}
func (f *http2FancyWriter) Push(target string, opts *http.PushOptions) error {
return f.basicWriter.ResponseWriter.(http.Pusher).Push(target, opts)
}
func (f *httpFancyWriter) ReadFrom(r io.Reader) (int64, error) {
if f.basicWriter.tee != nil {
##CHUNK 3
hj := f.basicWriter.ResponseWriter.(http.Hijacker)
return hj.Hijack()
}
func (f *http2FancyWriter) Push(target string, opts *http.PushOptions) error {
return f.basicWriter.ResponseWriter.(http.Pusher).Push(target, opts)
}
func (f *httpFancyWriter) ReadFrom(r io.Reader) (int64, error) {
if f.basicWriter.tee != nil {
n, err := io.Copy(&f.basicWriter, r)
f.basicWriter.bytes += int(n)
return n, err
}
rf := f.basicWriter.ResponseWriter.(io.ReaderFrom)
f.basicWriter.maybeWriteHeader()
n, err := rf.ReadFrom(r)
f.basicWriter.bytes += int(n)
return n, err
}
|
cli-main
| 64
|
func stringifyFlag(f Flag) string {
// enforce DocGeneration interface on flags to avoid reflection
df, ok := f.(DocGenerationFlag)
if !ok {
return ""
}
placeholder, usage := unquoteUsage(df.GetUsage())
needsPlaceholder := df.TakesValue()
// if needsPlaceholder is true, placeholder is empty
if needsPlaceholder && placeholder == "" {
// try to get type from flag
if tname := df.TypeName(); tname != "" {
placeholder = tname
} else {
placeholder = defaultPlaceholder
}
}
defaultValueString := ""
// don't print default text for required flags
if rf, ok := f.(RequiredFlag); !ok || !rf.IsRequired() {
isVisible := df.IsDefaultVisible()
if s := df.GetDefaultText(); isVisible && s != "" {
defaultValueString = fmt.Sprintf(formatDefault("%s"), s)
}
}
usageWithDefault := strings.TrimSpace(usage + defaultValueString)
pn := prefixedNames(f.Names(), placeholder)
sliceFlag, ok := f.(DocGenerationMultiValueFlag)
if ok && sliceFlag.IsMultiValueFlag() {
pn = pn + " [ " + pn + " ]"
}
return withEnvHint(df.GetEnvVars(), fmt.Sprintf("%s\t%s", pn, usageWithDefault))
}
|
func stringifyFlag(f Flag) string {
// enforce DocGeneration interface on flags to avoid reflection
df, ok := f.(DocGenerationFlag)
if !ok {
return ""
}
placeholder, usage := unquoteUsage(df.GetUsage())
needsPlaceholder := df.TakesValue()
// if needsPlaceholder is true, placeholder is empty
if needsPlaceholder && placeholder == "" {
// try to get type from flag
if tname := df.TypeName(); tname != "" {
placeholder = tname
} else {
placeholder = defaultPlaceholder
}
}
defaultValueString := ""
// don't print default text for required flags
if rf, ok := f.(RequiredFlag); !ok || !rf.IsRequired() {
isVisible := df.IsDefaultVisible()
if s := df.GetDefaultText(); isVisible && s != "" {
defaultValueString = fmt.Sprintf(formatDefault("%s"), s)
}
}
usageWithDefault := strings.TrimSpace(usage + defaultValueString)
pn := prefixedNames(f.Names(), placeholder)
sliceFlag, ok := f.(DocGenerationMultiValueFlag)
if ok && sliceFlag.IsMultiValueFlag() {
pn = pn + " [ " + pn + " ]"
}
return withEnvHint(df.GetEnvVars(), fmt.Sprintf("%s\t%s", pn, usageWithDefault))
}
|
func stringifyFlag(f Flag) string {
// enforce DocGeneration interface on flags to avoid reflection
df, ok := f.(DocGenerationFlag)
if !ok {
return ""
}
placeholder, usage := unquoteUsage(df.GetUsage())
needsPlaceholder := df.TakesValue()
// if needsPlaceholder is true, placeholder is empty
if needsPlaceholder && placeholder == "" {
// try to get type from flag
if tname := df.TypeName(); tname != "" {
placeholder = tname
} else {
placeholder = defaultPlaceholder
}
}
defaultValueString := ""
// don't print default text for required flags
if rf, ok := f.(RequiredFlag); !ok || !rf.IsRequired() {
isVisible := df.IsDefaultVisible()
if s := df.GetDefaultText(); isVisible && s != "" {
defaultValueString = fmt.Sprintf(formatDefault("%s"), s)
}
}
usageWithDefault := strings.TrimSpace(usage + defaultValueString)
pn := prefixedNames(f.Names(), placeholder)
sliceFlag, ok := f.(DocGenerationMultiValueFlag)
if ok && sliceFlag.IsMultiValueFlag() {
pn = pn + " [ " + pn + " ]"
}
return withEnvHint(df.GetEnvVars(), fmt.Sprintf("%s\t%s", pn, usageWithDefault))
}
|
stringifyFlag
| 87
| 124
|
docs.go
|
#FILE: cli-main/command_parse.go
##CHUNK 1
}
// no flag lookup found and short handling is disabled
if !shortOptionHandling {
return &stringSliceArgs{posArgs}, fmt.Errorf("%s%s", providedButNotDefinedErrMsg, flagName)
}
// try to split the flags
for index, c := range flagName {
tracef("processing flag (fName=%[1]q)", string(c))
if sf := cmd.lookupFlag(string(c)); sf == nil {
return &stringSliceArgs{posArgs}, fmt.Errorf("%s%s", providedButNotDefinedErrMsg, flagName)
} else if fb, ok := sf.(boolFlag); ok && fb.IsBoolFlag() {
fv := flagVal
if index == (len(flagName)-1) && flagVal == "" {
fv = "true"
}
if fv == "" {
fv = "true"
}
#FILE: cli-main/command.go
##CHUNK 1
func (cmd *Command) checkRequiredFlag(f Flag) (bool, string) {
if rf, ok := f.(RequiredFlag); ok && rf.IsRequired() {
flagName := f.Names()[0]
if !f.IsSet() {
return false, flagName
}
}
return true, ""
}
func (cmd *Command) checkAllRequiredFlags() requiredFlagsErr {
for pCmd := cmd; pCmd != nil; pCmd = pCmd.parent {
if err := pCmd.checkRequiredFlags(); err != nil {
return err
}
}
return nil
}
##CHUNK 2
for _, pCmd := range cmd.Lineage() {
if f := pCmd.lFlag(name); f != nil {
return f
}
}
tracef("flag NOT found for name %[1]q (cmd=%[2]q)", name, cmd.Name)
cmd.onInvalidFlag(context.TODO(), name)
return nil
}
func (cmd *Command) checkRequiredFlag(f Flag) (bool, string) {
if rf, ok := f.(RequiredFlag); ok && rf.IsRequired() {
flagName := f.Names()[0]
if !f.IsSet() {
return false, flagName
}
}
return true, ""
}
#FILE: cli-main/category.go
##CHUNK 1
if cf, ok := fl.(CategorizableFlag); ok {
visible := false
if vf, ok := fl.(VisibleFlag); ok {
visible = vf.IsVisible()
}
if cf.GetCategory() == "" && visible {
fc.AddFlag("", fl)
}
}
}
}
return fc
}
func (f *defaultFlagCategories) AddFlag(category string, fl Flag) {
if _, ok := f.m[category]; !ok {
f.m[category] = &defaultVisibleFlagCategory{name: category, m: map[string]Flag{}}
}
##CHUNK 2
}
if cat := cf.GetCategory(); cat != "" && visible {
fc.AddFlag(cat, fl)
categorized = true
}
}
}
if categorized {
for _, fl := range fs {
if cf, ok := fl.(CategorizableFlag); ok {
visible := false
if vf, ok := fl.(VisibleFlag); ok {
visible = vf.IsVisible()
}
if cf.GetCategory() == "" && visible {
fc.AddFlag("", fl)
}
}
}
#FILE: cli-main/help.go
##CHUNK 1
}
flag := fmt.Sprintf("%s%s", strings.Repeat("-", count), name)
for _, a := range args {
if a == flag {
return true
}
}
}
return false
}
func printFlagSuggestions(lastArg string, flags []Flag, writer io.Writer) {
// Trim to handle both "-short" and "--long" flags.
cur := strings.TrimLeft(lastArg, "-")
for _, flag := range flags {
if bflag, ok := flag.(*BoolFlag); ok && bflag.Hidden {
continue
}
usage := ""
##CHUNK 2
func printFlagSuggestions(lastArg string, flags []Flag, writer io.Writer) {
// Trim to handle both "-short" and "--long" flags.
cur := strings.TrimLeft(lastArg, "-")
for _, flag := range flags {
if bflag, ok := flag.(*BoolFlag); ok && bflag.Hidden {
continue
}
usage := ""
if docFlag, ok := flag.(DocGenerationFlag); ok {
usage = docFlag.GetUsage()
}
name := strings.TrimSpace(flag.Names()[0])
// this will get total count utf8 letters in flag name
count := utf8.RuneCountInString(name)
if count > 2 {
count = 2 // reuse this count to generate single - or -- in flag completion
}
#CURRENT FILE: cli-main/docs.go
##CHUNK 1
break
}
}
return "", usage
}
func prefixedNames(names []string, placeholder string) string {
var prefixed string
for i, name := range names {
if name == "" {
continue
}
prefixed += prefixFor(name) + name
if placeholder != "" {
prefixed += " " + placeholder
}
if i < len(names)-1 {
prefixed += ", "
}
##CHUNK 2
continue
}
prefixed += prefixFor(name) + name
if placeholder != "" {
prefixed += " " + placeholder
}
if i < len(names)-1 {
prefixed += ", "
}
}
return prefixed
}
func envFormat(envVars []string, prefix, sep, suffix string) string {
if len(envVars) > 0 {
return fmt.Sprintf(" [%s%s%s]", prefix, strings.Join(envVars, sep), suffix)
}
return ""
}
##CHUNK 3
func unquoteUsage(usage string) (string, string) {
for i := 0; i < len(usage); i++ {
if usage[i] == '`' {
for j := i + 1; j < len(usage); j++ {
if usage[j] == '`' {
name := usage[i+1 : j]
usage = usage[:i] + name + usage[j+1:]
return name, usage
}
}
break
}
}
return "", usage
}
func prefixedNames(names []string, placeholder string) string {
var prefixed string
for i, name := range names {
if name == "" {
|
cli-main
| 65
|
func newFlagCategoriesFromFlags(fs []Flag) FlagCategories {
fc := newFlagCategories()
var categorized bool
for _, fl := range fs {
if cf, ok := fl.(CategorizableFlag); ok {
visible := false
if vf, ok := fl.(VisibleFlag); ok {
visible = vf.IsVisible()
}
if cat := cf.GetCategory(); cat != "" && visible {
fc.AddFlag(cat, fl)
categorized = true
}
}
}
if categorized {
for _, fl := range fs {
if cf, ok := fl.(CategorizableFlag); ok {
visible := false
if vf, ok := fl.(VisibleFlag); ok {
visible = vf.IsVisible()
}
if cf.GetCategory() == "" && visible {
fc.AddFlag("", fl)
}
}
}
}
return fc
}
|
func newFlagCategoriesFromFlags(fs []Flag) FlagCategories {
fc := newFlagCategories()
var categorized bool
for _, fl := range fs {
if cf, ok := fl.(CategorizableFlag); ok {
visible := false
if vf, ok := fl.(VisibleFlag); ok {
visible = vf.IsVisible()
}
if cat := cf.GetCategory(); cat != "" && visible {
fc.AddFlag(cat, fl)
categorized = true
}
}
}
if categorized {
for _, fl := range fs {
if cf, ok := fl.(CategorizableFlag); ok {
visible := false
if vf, ok := fl.(VisibleFlag); ok {
visible = vf.IsVisible()
}
if cf.GetCategory() == "" && visible {
fc.AddFlag("", fl)
}
}
}
}
return fc
}
|
func newFlagCategoriesFromFlags(fs []Flag) FlagCategories {
fc := newFlagCategories()
var categorized bool
for _, fl := range fs {
if cf, ok := fl.(CategorizableFlag); ok {
visible := false
if vf, ok := fl.(VisibleFlag); ok {
visible = vf.IsVisible()
}
if cat := cf.GetCategory(); cat != "" && visible {
fc.AddFlag(cat, fl)
categorized = true
}
}
}
if categorized {
for _, fl := range fs {
if cf, ok := fl.(CategorizableFlag); ok {
visible := false
if vf, ok := fl.(VisibleFlag); ok {
visible = vf.IsVisible()
}
if cf.GetCategory() == "" && visible {
fc.AddFlag("", fl)
}
}
}
}
return fc
}
|
newFlagCategoriesFromFlags
| 100
| 133
|
category.go
|
#FILE: cli-main/flag.go
##CHUNK 1
// Sets the category of the flag
SetCategory(string)
}
// LocalFlag is an interface to enable detection of flags which are local
// to current command
type LocalFlag interface {
IsLocal() bool
}
func visibleFlags(fl []Flag) []Flag {
var visible []Flag
for _, f := range fl {
if vf, ok := f.(VisibleFlag); ok && vf.IsVisible() {
visible = append(visible, f)
}
}
return visible
}
##CHUNK 2
func visibleFlags(fl []Flag) []Flag {
var visible []Flag
for _, f := range fl {
if vf, ok := f.(VisibleFlag); ok && vf.IsVisible() {
visible = append(visible, f)
}
}
return visible
}
func FlagNames(name string, aliases []string) []string {
var ret []string
for _, part := range append([]string{name}, aliases...) {
// v1 -> v2 migration warning zone:
// Strip off anything after the first found comma or space, which
// *hopefully* makes it a tiny bit more obvious that unexpected behavior is
// caused by using the v1 form of stringly typed "Name".
ret = append(ret, commaWhitespace.ReplaceAllString(part, ""))
}
#FILE: cli-main/flag_mutex.go
##CHUNK 1
oneSet = true
break
}
if oneSet {
break
}
}
}
if !oneSet && grp.Required {
return &mutuallyExclusiveGroupRequiredFlag{flags: &grp}
}
return nil
}
func (grp MutuallyExclusiveFlags) propagateCategory() {
for _, grpf := range grp.Flags {
for _, f := range grpf {
if cf, ok := f.(CategorizableFlag); ok {
cf.SetCategory(grp.Category)
##CHUNK 2
return &mutuallyExclusiveGroupRequiredFlag{flags: &grp}
}
return nil
}
func (grp MutuallyExclusiveFlags) propagateCategory() {
for _, grpf := range grp.Flags {
for _, f := range grpf {
if cf, ok := f.(CategorizableFlag); ok {
cf.SetCategory(grp.Category)
}
}
}
}
#FILE: cli-main/errors.go
##CHUNK 1
}
if exitErr, ok := err.(ExitCoder); ok {
if err.Error() != "" {
if _, ok := exitErr.(ErrorFormatter); ok {
_, _ = fmt.Fprintf(ErrWriter, "%+v\n", err)
} else {
_, _ = fmt.Fprintln(ErrWriter, err)
}
}
OsExiter(exitErr.ExitCode())
return
}
if multiErr, ok := err.(MultiError); ok {
code := handleMultiError(multiErr)
OsExiter(code)
return
}
}
##CHUNK 2
OsExiter(exitErr.ExitCode())
return
}
if multiErr, ok := err.(MultiError); ok {
code := handleMultiError(multiErr)
OsExiter(code)
return
}
}
func handleMultiError(multiErr MultiError) int {
code := 1
for _, merr := range multiErr.Errors() {
if multiErr2, ok := merr.(MultiError); ok {
code = handleMultiError(multiErr2)
} else if merr != nil {
fmt.Fprintln(ErrWriter, merr)
if exitErr, ok := merr.(ExitCoder); ok {
code = exitErr.ExitCode()
#FILE: cli-main/command.go
##CHUNK 1
}
func (cmd *Command) runFlagActions(ctx context.Context) error {
tracef("runFlagActions")
for fl := range cmd.setFlags {
/*tracef("checking %v:%v", fl.Names(), fl.IsSet())
if !fl.IsSet() {
continue
}*/
//if pf, ok := fl.(LocalFlag); ok && !pf.IsLocal() {
// continue
//}
if af, ok := fl.(ActionableFlag); ok {
if err := af.RunAction(ctx, cmd); err != nil {
return err
}
}
}
#FILE: cli-main/help.go
##CHUNK 1
}
flag := fmt.Sprintf("%s%s", strings.Repeat("-", count), name)
for _, a := range args {
if a == flag {
return true
}
}
}
return false
}
func printFlagSuggestions(lastArg string, flags []Flag, writer io.Writer) {
// Trim to handle both "-short" and "--long" flags.
cur := strings.TrimLeft(lastArg, "-")
for _, flag := range flags {
if bflag, ok := flag.(*BoolFlag); ok && bflag.Hidden {
continue
}
usage := ""
#CURRENT FILE: cli-main/category.go
##CHUNK 1
}
func (fc *defaultVisibleFlagCategory) Flags() []Flag {
vfNames := []string{}
for flName, fl := range fc.m {
if vf, ok := fl.(VisibleFlag); ok {
if vf.IsVisible() {
vfNames = append(vfNames, flName)
}
}
}
sort.Strings(vfNames)
ret := make([]Flag, len(vfNames))
for i, flName := range vfNames {
ret[i] = fc.m[flName]
}
return ret
##CHUNK 2
Flags() []Flag
}
type defaultVisibleFlagCategory struct {
name string
m map[string]Flag
}
func (fc *defaultVisibleFlagCategory) Name() string {
return fc.name
}
func (fc *defaultVisibleFlagCategory) Flags() []Flag {
vfNames := []string{}
for flName, fl := range fc.m {
if vf, ok := fl.(VisibleFlag); ok {
if vf.IsVisible() {
vfNames = append(vfNames, flName)
}
}
|
cli-main
| 66
|
func jaroDistance(a, b string) float64 {
if len(a) == 0 && len(b) == 0 {
return 1
}
if len(a) == 0 || len(b) == 0 {
return 0
}
lenA := float64(len(a))
lenB := float64(len(b))
hashA := make([]bool, len(a))
hashB := make([]bool, len(b))
maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1))
var matches float64
for i := 0; i < len(a); i++ {
start := int(math.Max(0, float64(i-maxDistance)))
end := int(math.Min(lenB-1, float64(i+maxDistance)))
for j := start; j <= end; j++ {
if hashB[j] {
continue
}
if a[i] == b[j] {
hashA[i] = true
hashB[j] = true
matches++
break
}
}
}
if matches == 0 {
return 0
}
var transpositions float64
var j int
for i := 0; i < len(a); i++ {
if !hashA[i] {
continue
}
for !hashB[j] {
j++
}
if a[i] != b[j] {
transpositions++
}
j++
}
transpositions /= 2
return ((matches / lenA) + (matches / lenB) + ((matches - transpositions) / matches)) / 3.0
}
|
func jaroDistance(a, b string) float64 {
if len(a) == 0 && len(b) == 0 {
return 1
}
if len(a) == 0 || len(b) == 0 {
return 0
}
lenA := float64(len(a))
lenB := float64(len(b))
hashA := make([]bool, len(a))
hashB := make([]bool, len(b))
maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1))
var matches float64
for i := 0; i < len(a); i++ {
start := int(math.Max(0, float64(i-maxDistance)))
end := int(math.Min(lenB-1, float64(i+maxDistance)))
for j := start; j <= end; j++ {
if hashB[j] {
continue
}
if a[i] == b[j] {
hashA[i] = true
hashB[j] = true
matches++
break
}
}
}
if matches == 0 {
return 0
}
var transpositions float64
var j int
for i := 0; i < len(a); i++ {
if !hashA[i] {
continue
}
for !hashB[j] {
j++
}
if a[i] != b[j] {
transpositions++
}
j++
}
transpositions /= 2
return ((matches / lenA) + (matches / lenB) + ((matches - transpositions) / matches)) / 3.0
}
|
func jaroDistance(a, b string) float64 {
if len(a) == 0 && len(b) == 0 {
return 1
}
if len(a) == 0 || len(b) == 0 {
return 0
}
lenA := float64(len(a))
lenB := float64(len(b))
hashA := make([]bool, len(a))
hashB := make([]bool, len(b))
maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1))
var matches float64
for i := 0; i < len(a); i++ {
start := int(math.Max(0, float64(i-maxDistance)))
end := int(math.Min(lenB-1, float64(i+maxDistance)))
for j := start; j <= end; j++ {
if hashB[j] {
continue
}
if a[i] == b[j] {
hashA[i] = true
hashB[j] = true
matches++
break
}
}
}
if matches == 0 {
return 0
}
var transpositions float64
var j int
for i := 0; i < len(a); i++ {
if !hashA[i] {
continue
}
for !hashB[j] {
j++
}
if a[i] != b[j] {
transpositions++
}
j++
}
transpositions /= 2
return ((matches / lenA) + (matches / lenB) + ((matches - transpositions) / matches)) / 3.0
}
|
jaroDistance
| 23
| 75
|
suggestions.go
|
#FILE: cli-main/docs.go
##CHUNK 1
func unquoteUsage(usage string) (string, string) {
for i := 0; i < len(usage); i++ {
if usage[i] == '`' {
for j := i + 1; j < len(usage); j++ {
if usage[j] == '`' {
name := usage[i+1 : j]
usage = usage[:i] + name + usage[j+1:]
return name, usage
}
}
break
}
}
return "", usage
}
func prefixedNames(names []string, placeholder string) string {
var prefixed string
for i, name := range names {
if name == "" {
##CHUNK 2
if len(name) == 1 {
prefix = "-"
} else {
prefix = "--"
}
return
}
// Returns the placeholder, if any, and the unquoted usage string.
func unquoteUsage(usage string) (string, string) {
for i := 0; i < len(usage); i++ {
if usage[i] == '`' {
for j := i + 1; j < len(usage); j++ {
if usage[j] == '`' {
name := usage[i+1 : j]
usage = usage[:i] + name + usage[j+1:]
return name, usage
}
}
##CHUNK 3
break
}
}
return "", usage
}
func prefixedNames(names []string, placeholder string) string {
var prefixed string
for i, name := range names {
if name == "" {
continue
}
prefixed += prefixFor(name) + name
if placeholder != "" {
prefixed += " " + placeholder
}
if i < len(names)-1 {
prefixed += ", "
}
#FILE: cli-main/sort.go
##CHUNK 1
if lenShared > len(jRunes) {
lenShared = len(jRunes)
}
for index := 0; index < lenShared; index++ {
ir := iRunes[index]
jr := jRunes[index]
if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr); lir != ljr {
return lir < ljr
}
if ir != jr {
return ir < jr
}
}
return i < j
}
#FILE: cli-main/help.go
##CHUNK 1
}
func wrap(input string, offset int, wrapAt int) string {
var ss []string
lines := strings.Split(input, "\n")
padding := strings.Repeat(" ", offset)
for i, line := range lines {
if line == "" {
ss = append(ss, line)
} else {
wrapped := wrapLine(line, offset, wrapAt, padding)
if i == 0 {
ss = append(ss, wrapped)
} else {
ss = append(ss, padding+wrapped)
}
##CHUNK 2
if line == "" {
ss = append(ss, line)
} else {
wrapped := wrapLine(line, offset, wrapAt, padding)
if i == 0 {
ss = append(ss, wrapped)
} else {
ss = append(ss, padding+wrapped)
}
}
}
return strings.Join(ss, "\n")
}
func wrapLine(input string, offset int, wrapAt int, padding string) string {
if wrapAt <= offset || len(input) <= wrapAt-offset {
return input
}
##CHUNK 3
}
}
return strings.Join(ss, "\n")
}
func wrapLine(input string, offset int, wrapAt int, padding string) string {
if wrapAt <= offset || len(input) <= wrapAt-offset {
return input
}
lineWidth := wrapAt - offset
words := strings.Fields(input)
if len(words) == 0 {
return input
}
wrapped := words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
#FILE: cli-main/flag_test.go
##CHUNK 1
if len(testCase.layoutsPrecisions) == 0 {
err := fl.Set(fl.Name, now.Format(time.RFC3339))
if testCase.expErrValidation != nil {
assert.NoError(t, testCase.expErrValidation(err))
}
}
validLayouts := make([]string, 0, len(testCase.layoutsPrecisions))
invalidLayouts := make([]string, 0, len(testCase.layoutsPrecisions))
// TODO: replace with lo.Filter if acceptable
for layout, prec := range testCase.layoutsPrecisions {
v, err := time.Parse(layout, now.Format(layout))
if err != nil || prec == 0 || now.Truncate(prec).UnixNano() != v.Truncate(prec).UnixNano() {
invalidLayouts = append(invalidLayouts, layout)
continue
}
validLayouts = append(validLayouts, layout)
}
#CURRENT FILE: cli-main/suggestions.go
##CHUNK 1
boostThreshold = 0.7
prefixSize = 4
)
jaroDist := jaroDistance(a, b)
if jaroDist <= boostThreshold {
return jaroDist
}
prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b)))))
var prefixMatch float64
for i := 0; i < prefix; i++ {
if a[i] == b[i] {
prefixMatch++
} else {
break
}
}
return jaroDist + 0.1*prefixMatch*(1.0-jaroDist)
}
##CHUNK 2
var prefixMatch float64
for i := 0; i < prefix; i++ {
if a[i] == b[i] {
prefixMatch++
} else {
break
}
}
return jaroDist + 0.1*prefixMatch*(1.0-jaroDist)
}
func suggestFlag(flags []Flag, provided string, hideHelp bool) string {
distance := 0.0
suggestion := ""
for _, flag := range flags {
flagNames := flag.Names()
if !hideHelp && HelpFlag != nil {
flagNames = append(flagNames, HelpFlag.Names()...)
}
|
cli-main
| 67
|
func jaroWinkler(a, b string) float64 {
const (
boostThreshold = 0.7
prefixSize = 4
)
jaroDist := jaroDistance(a, b)
if jaroDist <= boostThreshold {
return jaroDist
}
prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b)))))
var prefixMatch float64
for i := 0; i < prefix; i++ {
if a[i] == b[i] {
prefixMatch++
} else {
break
}
}
return jaroDist + 0.1*prefixMatch*(1.0-jaroDist)
}
|
func jaroWinkler(a, b string) float64 {
const (
boostThreshold = 0.7
prefixSize = 4
)
jaroDist := jaroDistance(a, b)
if jaroDist <= boostThreshold {
return jaroDist
}
prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b)))))
var prefixMatch float64
for i := 0; i < prefix; i++ {
if a[i] == b[i] {
prefixMatch++
} else {
break
}
}
return jaroDist + 0.1*prefixMatch*(1.0-jaroDist)
}
|
func jaroWinkler(a, b string) float64 {
const (
boostThreshold = 0.7
prefixSize = 4
)
jaroDist := jaroDistance(a, b)
if jaroDist <= boostThreshold {
return jaroDist
}
prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b)))))
var prefixMatch float64
for i := 0; i < prefix; i++ {
if a[i] == b[i] {
prefixMatch++
} else {
break
}
}
return jaroDist + 0.1*prefixMatch*(1.0-jaroDist)
}
|
jaroWinkler
| 81
| 102
|
suggestions.go
|
#FILE: cli-main/docs.go
##CHUNK 1
if len(name) == 1 {
prefix = "-"
} else {
prefix = "--"
}
return
}
// Returns the placeholder, if any, and the unquoted usage string.
func unquoteUsage(usage string) (string, string) {
for i := 0; i < len(usage); i++ {
if usage[i] == '`' {
for j := i + 1; j < len(usage); j++ {
if usage[j] == '`' {
name := usage[i+1 : j]
usage = usage[:i] + name + usage[j+1:]
return name, usage
}
}
##CHUNK 2
func unquoteUsage(usage string) (string, string) {
for i := 0; i < len(usage); i++ {
if usage[i] == '`' {
for j := i + 1; j < len(usage); j++ {
if usage[j] == '`' {
name := usage[i+1 : j]
usage = usage[:i] + name + usage[j+1:]
return name, usage
}
}
break
}
}
return "", usage
}
func prefixedNames(names []string, placeholder string) string {
var prefixed string
for i, name := range names {
if name == "" {
##CHUNK 3
break
}
}
return "", usage
}
func prefixedNames(names []string, placeholder string) string {
var prefixed string
for i, name := range names {
if name == "" {
continue
}
prefixed += prefixFor(name) + name
if placeholder != "" {
prefixed += " " + placeholder
}
if i < len(names)-1 {
prefixed += ", "
}
#FILE: cli-main/help.go
##CHUNK 1
if line == "" {
ss = append(ss, line)
} else {
wrapped := wrapLine(line, offset, wrapAt, padding)
if i == 0 {
ss = append(ss, wrapped)
} else {
ss = append(ss, padding+wrapped)
}
}
}
return strings.Join(ss, "\n")
}
func wrapLine(input string, offset int, wrapAt int, padding string) string {
if wrapAt <= offset || len(input) <= wrapAt-offset {
return input
}
#FILE: cli-main/sort.go
##CHUNK 1
if lenShared > len(jRunes) {
lenShared = len(jRunes)
}
for index := 0; index < lenShared; index++ {
ir := iRunes[index]
jr := jRunes[index]
if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr); lir != ljr {
return lir < ljr
}
if ir != jr {
return ir < jr
}
}
return i < j
}
#CURRENT FILE: cli-main/suggestions.go
##CHUNK 1
break
}
}
}
if matches == 0 {
return 0
}
var transpositions float64
var j int
for i := 0; i < len(a); i++ {
if !hashA[i] {
continue
}
for !hashB[j] {
j++
}
if a[i] != b[j] {
transpositions++
}
##CHUNK 2
// completely different strings.
//
// Adapted from https://github.com/xrash/smetrics/blob/5f08fbb34913bc8ab95bb4f2a89a0637ca922666/jaro.go.
func jaroDistance(a, b string) float64 {
if len(a) == 0 && len(b) == 0 {
return 1
}
if len(a) == 0 || len(b) == 0 {
return 0
}
lenA := float64(len(a))
lenB := float64(len(b))
hashA := make([]bool, len(a))
hashB := make([]bool, len(b))
maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1))
var matches float64
for i := 0; i < len(a); i++ {
start := int(math.Max(0, float64(i-maxDistance)))
##CHUNK 3
lenA := float64(len(a))
lenB := float64(len(b))
hashA := make([]bool, len(a))
hashB := make([]bool, len(b))
maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1))
var matches float64
for i := 0; i < len(a); i++ {
start := int(math.Max(0, float64(i-maxDistance)))
end := int(math.Min(lenB-1, float64(i+maxDistance)))
for j := start; j <= end; j++ {
if hashB[j] {
continue
}
if a[i] == b[j] {
hashA[i] = true
hashB[j] = true
matches++
##CHUNK 4
for i := 0; i < len(a); i++ {
if !hashA[i] {
continue
}
for !hashB[j] {
j++
}
if a[i] != b[j] {
transpositions++
}
j++
}
transpositions /= 2
return ((matches / lenA) + (matches / lenB) + ((matches - transpositions) / matches)) / 3.0
}
// jaroWinkler is more accurate when strings have a common prefix up to a
// defined maximum length.
//
##CHUNK 5
end := int(math.Min(lenB-1, float64(i+maxDistance)))
for j := start; j <= end; j++ {
if hashB[j] {
continue
}
if a[i] == b[j] {
hashA[i] = true
hashB[j] = true
matches++
break
}
}
}
if matches == 0 {
return 0
}
var transpositions float64
var j int
|
cli-main
| 68
|
func suggestFlag(flags []Flag, provided string, hideHelp bool) string {
distance := 0.0
suggestion := ""
for _, flag := range flags {
flagNames := flag.Names()
if !hideHelp && HelpFlag != nil {
flagNames = append(flagNames, HelpFlag.Names()...)
}
for _, name := range flagNames {
newDistance := jaroWinkler(name, provided)
if newDistance > distance {
distance = newDistance
suggestion = name
}
}
}
if len(suggestion) == 1 {
suggestion = "-" + suggestion
} else if len(suggestion) > 1 {
suggestion = "--" + suggestion
}
return suggestion
}
|
func suggestFlag(flags []Flag, provided string, hideHelp bool) string {
distance := 0.0
suggestion := ""
for _, flag := range flags {
flagNames := flag.Names()
if !hideHelp && HelpFlag != nil {
flagNames = append(flagNames, HelpFlag.Names()...)
}
for _, name := range flagNames {
newDistance := jaroWinkler(name, provided)
if newDistance > distance {
distance = newDistance
suggestion = name
}
}
}
if len(suggestion) == 1 {
suggestion = "-" + suggestion
} else if len(suggestion) > 1 {
suggestion = "--" + suggestion
}
return suggestion
}
|
func suggestFlag(flags []Flag, provided string, hideHelp bool) string {
distance := 0.0
suggestion := ""
for _, flag := range flags {
flagNames := flag.Names()
if !hideHelp && HelpFlag != nil {
flagNames = append(flagNames, HelpFlag.Names()...)
}
for _, name := range flagNames {
newDistance := jaroWinkler(name, provided)
if newDistance > distance {
distance = newDistance
suggestion = name
}
}
}
if len(suggestion) == 1 {
suggestion = "-" + suggestion
} else if len(suggestion) > 1 {
suggestion = "--" + suggestion
}
return suggestion
}
|
suggestFlag
| 104
| 129
|
suggestions.go
|
#FILE: cli-main/command.go
##CHUNK 1
hideHelp := cmd.hideHelp()
if commandName != "" {
subCmd := cmd.Command(commandName)
if subCmd == nil {
return "", err
}
flags = subCmd.Flags
hideHelp = hideHelp || subCmd.HideHelp
}
suggestion := SuggestFlag(flags, fl, hideHelp)
if len(suggestion) == 0 {
return "", err
}
return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion) + "\n\n", nil
}
// Names returns the names including short names and aliases.
##CHUNK 2
suggestion := SuggestFlag(flags, fl, hideHelp)
if len(suggestion) == 0 {
return "", err
}
return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion) + "\n\n", nil
}
// Names returns the names including short names and aliases.
func (cmd *Command) Names() []string {
return append([]string{cmd.Name}, cmd.Aliases...)
}
// HasName returns true if Command.Name matches given name
func (cmd *Command) HasName(name string) bool {
return slices.Contains(cmd.Names(), name)
}
// VisibleCategories returns a slice of categories and commands that are
#FILE: cli-main/help.go
##CHUNK 1
tracef("running HelpPrinter")
HelpPrinter(cmd.Root().Writer, tmpl, subCmd)
tracef("returning nil after printing help")
return nil
}
tracef("no matching command found")
if cmd.CommandNotFound == nil {
errMsg := fmt.Sprintf("No help topic for '%v'", commandName)
if cmd.Suggest {
if suggestion := SuggestCommand(cmd.Commands, commandName); suggestion != "" {
errMsg += ". " + suggestion
}
}
tracef("exiting 3 with errMsg %[1]q", errMsg)
return Exit(errMsg, 3)
##CHUNK 2
errMsg := fmt.Sprintf("No help topic for '%v'", commandName)
if cmd.Suggest {
if suggestion := SuggestCommand(cmd.Commands, commandName); suggestion != "" {
errMsg += ". " + suggestion
}
}
tracef("exiting 3 with errMsg %[1]q", errMsg)
return Exit(errMsg, 3)
}
tracef("running CommandNotFound func for %[1]q", commandName)
cmd.CommandNotFound(ctx, cmd, commandName)
return nil
}
// ShowSubcommandHelpAndExit - Prints help for the given subcommand and exits with exit code.
func ShowSubcommandHelpAndExit(cmd *Command, exitCode int) {
##CHUNK 3
} else if argsLen > 0 {
lastArg = args[argsLen-1]
}
if lastArg == "--" {
tracef("No completions due to termination")
return
}
if lastArg == completionFlag {
lastArg = ""
}
if strings.HasPrefix(lastArg, "-") {
tracef("printing flag suggestion for flag[%v] on command %[1]q", lastArg, cmd.Name)
printFlagSuggestions(lastArg, cmd.Flags, cmd.Root().Writer)
return
}
if cmd != nil {
##CHUNK 4
}
}
}
func cliArgContains(flagName string, args []string) bool {
for _, name := range strings.Split(flagName, ",") {
name = strings.TrimSpace(name)
count := utf8.RuneCountInString(name)
if count > 2 {
count = 2
}
flag := fmt.Sprintf("%s%s", strings.Repeat("-", count), name)
for _, a := range args {
if a == flag {
return true
}
}
}
return false
}
#FILE: cli-main/docs.go
##CHUNK 1
if len(name) == 1 {
prefix = "-"
} else {
prefix = "--"
}
return
}
// Returns the placeholder, if any, and the unquoted usage string.
func unquoteUsage(usage string) (string, string) {
for i := 0; i < len(usage); i++ {
if usage[i] == '`' {
for j := i + 1; j < len(usage); j++ {
if usage[j] == '`' {
name := usage[i+1 : j]
usage = usage[:i] + name + usage[j+1:]
return name, usage
}
}
#CURRENT FILE: cli-main/suggestions.go
##CHUNK 1
for _, name := range append(command.Names(), helpName, helpAlias) {
newDistance := jaroWinkler(name, provided)
if newDistance > distance {
distance = newDistance
suggestion = name
}
}
}
return suggestion
}
##CHUNK 2
}
return jaroDist + 0.1*prefixMatch*(1.0-jaroDist)
}
}
// suggestCommand takes a list of commands and a provided string to suggest a
// command name
func suggestCommand(commands []*Command, provided string) (suggestion string) {
distance := 0.0
for _, command := range commands {
for _, name := range append(command.Names(), helpName, helpAlias) {
newDistance := jaroWinkler(name, provided)
if newDistance > distance {
distance = newDistance
suggestion = name
}
}
}
return suggestion
##CHUNK 3
prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b)))))
var prefixMatch float64
for i := 0; i < prefix; i++ {
if a[i] == b[i] {
prefixMatch++
} else {
break
}
}
return jaroDist + 0.1*prefixMatch*(1.0-jaroDist)
}
}
// suggestCommand takes a list of commands and a provided string to suggest a
// command name
func suggestCommand(commands []*Command, provided string) (suggestion string) {
distance := 0.0
for _, command := range commands {
|
cli-main
| 69
|
func checkShellCompleteFlag(c *Command, arguments []string) (bool, []string) {
if (c.parent == nil && !c.EnableShellCompletion) || (c.parent != nil && !c.Root().shellCompletion) {
return false, arguments
}
pos := len(arguments) - 1
lastArg := arguments[pos]
if lastArg != completionFlag {
return false, arguments
}
for _, arg := range arguments {
// If arguments include "--", shell completion is disabled
// because after "--" only positional arguments are accepted.
// https://unix.stackexchange.com/a/11382
if arg == "--" {
return false, arguments[:pos]
}
}
return true, arguments[:pos]
}
|
func checkShellCompleteFlag(c *Command, arguments []string) (bool, []string) {
if (c.parent == nil && !c.EnableShellCompletion) || (c.parent != nil && !c.Root().shellCompletion) {
return false, arguments
}
pos := len(arguments) - 1
lastArg := arguments[pos]
if lastArg != completionFlag {
return false, arguments
}
for _, arg := range arguments {
// If arguments include "--", shell completion is disabled
// because after "--" only positional arguments are accepted.
// https://unix.stackexchange.com/a/11382
if arg == "--" {
return false, arguments[:pos]
}
}
return true, arguments[:pos]
}
|
func checkShellCompleteFlag(c *Command, arguments []string) (bool, []string) {
if (c.parent == nil && !c.EnableShellCompletion) || (c.parent != nil && !c.Root().shellCompletion) {
return false, arguments
}
pos := len(arguments) - 1
lastArg := arguments[pos]
if lastArg != completionFlag {
return false, arguments
}
for _, arg := range arguments {
// If arguments include "--", shell completion is disabled
// because after "--" only positional arguments are accepted.
// https://unix.stackexchange.com/a/11382
if arg == "--" {
return false, arguments[:pos]
}
}
return true, arguments[:pos]
}
|
checkShellCompleteFlag
| 459
| 481
|
help.go
|
#FILE: cli-main/command_run.go
##CHUNK 1
// arguments are parsed according to the Flag and Command
// definitions and the matching Action functions are run.
func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error) {
_, deferErr = cmd.run(ctx, osArgs)
return
}
func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context, deferErr error) {
tracef("running with arguments %[1]q (cmd=%[2]q)", osArgs, cmd.Name)
cmd.setupDefaults(osArgs)
if v, ok := ctx.Value(commandContextKey).(*Command); ok {
tracef("setting parent (cmd=%[1]q) command from context.Context value (cmd=%[2]q)", v.Name, cmd.Name)
cmd.parent = v
}
if cmd.parent == nil {
if cmd.ReadArgsFromStdin {
if args, err := cmd.parseArgsFromStdin(); err != nil {
return ctx, err
##CHUNK 2
}
}
}
tracef("parsed stdin args as %v (cmd=%[2]q)", args, cmd.Name)
return args, nil
}
// Run is the entry point to the command graph. The positional
// arguments are parsed according to the Flag and Command
// definitions and the matching Action functions are run.
func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error) {
_, deferErr = cmd.run(ctx, osArgs)
return
}
func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context, deferErr error) {
tracef("running with arguments %[1]q (cmd=%[2]q)", osArgs, cmd.Name)
cmd.setupDefaults(osArgs)
##CHUNK 3
return ctx, err
}
}
var subCmd *Command
if cmd.parsedArgs.Present() {
tracef("checking positional args %[1]q (cmd=%[2]q)", cmd.parsedArgs, cmd.Name)
name := cmd.parsedArgs.First()
tracef("using first positional argument as sub-command name=%[1]q (cmd=%[2]q)", name, cmd.Name)
if cmd.SuggestCommandFunc != nil && name != "--" {
name = cmd.SuggestCommandFunc(cmd.Commands, name)
}
subCmd = cmd.Command(name)
if subCmd == nil {
hasDefault := cmd.DefaultCommand != ""
isFlagName := slices.Contains(cmd.FlagNames(), name)
#FILE: cli-main/command.go
##CHUNK 1
func (cmd *Command) checkRequiredFlag(f Flag) (bool, string) {
if rf, ok := f.(RequiredFlag); ok && rf.IsRequired() {
flagName := f.Names()[0]
if !f.IsSet() {
return false, flagName
}
}
return true, ""
}
func (cmd *Command) checkAllRequiredFlags() requiredFlagsErr {
for pCmd := cmd; pCmd != nil; pCmd = pCmd.parent {
if err := pCmd.checkRequiredFlags(); err != nil {
return err
}
}
return nil
}
##CHUNK 2
for _, pCmd := range cmd.Lineage() {
if f := pCmd.lFlag(name); f != nil {
return f
}
}
tracef("flag NOT found for name %[1]q (cmd=%[2]q)", name, cmd.Name)
cmd.onInvalidFlag(context.TODO(), name)
return nil
}
func (cmd *Command) checkRequiredFlag(f Flag) (bool, string) {
if rf, ok := f.(RequiredFlag); ok && rf.IsRequired() {
flagName := f.Names()[0]
if !f.IsSet() {
return false, flagName
}
}
return true, ""
}
#FILE: cli-main/suggestions.go
##CHUNK 1
if !hideHelp && HelpFlag != nil {
flagNames = append(flagNames, HelpFlag.Names()...)
}
for _, name := range flagNames {
newDistance := jaroWinkler(name, provided)
if newDistance > distance {
distance = newDistance
suggestion = name
}
}
}
if len(suggestion) == 1 {
suggestion = "-" + suggestion
} else if len(suggestion) > 1 {
suggestion = "--" + suggestion
}
return suggestion
}
#FILE: cli-main/command_parse.go
##CHUNK 1
if sf := cmd.lookupFlag(string(c)); sf == nil {
return &stringSliceArgs{posArgs}, fmt.Errorf("%s%s", providedButNotDefinedErrMsg, flagName)
} else if fb, ok := sf.(boolFlag); ok && fb.IsBoolFlag() {
fv := flagVal
if index == (len(flagName)-1) && flagVal == "" {
fv = "true"
}
if fv == "" {
fv = "true"
}
if err := cmd.set(flagName, sf, fv); err != nil {
tracef("processing flag.2 (fName=%[1]q)", string(c))
return &stringSliceArgs{posArgs}, err
}
} else if index == len(flagName)-1 { // last flag can take an arg
if flagVal == "" {
if len(rargs) == 1 {
return &stringSliceArgs{posArgs}, fmt.Errorf("%s%s", argumentNotProvidedErrMsg, string(c))
}
flagVal = rargs[1]
#CURRENT FILE: cli-main/help.go
##CHUNK 1
tracef("running default complete with flags[%v] on command %[2]q", args, cmd.Name)
} else {
tracef("running default complete with os.Args flags[%v]", args)
}
argsLen := len(args)
lastArg := ""
// parent command will have --generate-shell-completion so we need
// to account for that
if argsLen > 1 {
lastArg = args[argsLen-2]
} else if argsLen > 0 {
lastArg = args[argsLen-1]
}
if lastArg == "--" {
tracef("No completions due to termination")
return
}
if lastArg == completionFlag {
##CHUNK 2
} else if argsLen > 0 {
lastArg = args[argsLen-1]
}
if lastArg == "--" {
tracef("No completions due to termination")
return
}
if lastArg == completionFlag {
lastArg = ""
}
if strings.HasPrefix(lastArg, "-") {
tracef("printing flag suggestion for flag[%v] on command %[1]q", lastArg, cmd.Name)
printFlagSuggestions(lastArg, cmd.Flags, cmd.Root().Writer)
return
}
if cmd != nil {
##CHUNK 3
}
fmt.Fprintln(writer, flagCompletion)
}
}
}
func DefaultCompleteWithFlags(ctx context.Context, cmd *Command) {
args := os.Args
if cmd != nil && cmd.parent != nil {
args = cmd.Args().Slice()
tracef("running default complete with flags[%v] on command %[2]q", args, cmd.Name)
} else {
tracef("running default complete with os.Args flags[%v]", args)
}
argsLen := len(args)
lastArg := ""
// parent command will have --generate-shell-completion so we need
// to account for that
if argsLen > 1 {
lastArg = args[argsLen-2]
|
cli-main
| 70
|
func checkCompletions(ctx context.Context, cmd *Command) bool {
tracef("checking completions on command %[1]q", cmd.Name)
if !cmd.Root().shellCompletion {
tracef("completion not enabled skipping %[1]q", cmd.Name)
return false
}
if argsArguments := cmd.Args(); argsArguments.Present() {
name := argsArguments.First()
if cmd := cmd.Command(name); cmd != nil {
// let the command handle the completion
return false
}
}
tracef("no subcommand found for completion %[1]q", cmd.Name)
if cmd.ShellComplete != nil {
tracef("running shell completion func for command %[1]q", cmd.Name)
cmd.ShellComplete(ctx, cmd)
}
return true
}
|
func checkCompletions(ctx context.Context, cmd *Command) bool {
tracef("checking completions on command %[1]q", cmd.Name)
if !cmd.Root().shellCompletion {
tracef("completion not enabled skipping %[1]q", cmd.Name)
return false
}
if argsArguments := cmd.Args(); argsArguments.Present() {
name := argsArguments.First()
if cmd := cmd.Command(name); cmd != nil {
// let the command handle the completion
return false
}
}
tracef("no subcommand found for completion %[1]q", cmd.Name)
if cmd.ShellComplete != nil {
tracef("running shell completion func for command %[1]q", cmd.Name)
cmd.ShellComplete(ctx, cmd)
}
return true
}
|
func checkCompletions(ctx context.Context, cmd *Command) bool {
tracef("checking completions on command %[1]q", cmd.Name)
if !cmd.Root().shellCompletion {
tracef("completion not enabled skipping %[1]q", cmd.Name)
return false
}
if argsArguments := cmd.Args(); argsArguments.Present() {
name := argsArguments.First()
if cmd := cmd.Command(name); cmd != nil {
// let the command handle the completion
return false
}
}
tracef("no subcommand found for completion %[1]q", cmd.Name)
if cmd.ShellComplete != nil {
tracef("running shell completion func for command %[1]q", cmd.Name)
cmd.ShellComplete(ctx, cmd)
}
return true
}
|
checkCompletions
| 483
| 507
|
help.go
|
#FILE: cli-main/command_run.go
##CHUNK 1
}
} else {
tracef("running ShowCommandHelp with %[1]q", cmd.Name)
if err := ShowCommandHelp(ctx, cmd, cmd.Name); err != nil {
tracef("SILENTLY IGNORING ERROR running ShowCommandHelp with %[1]q %[2]v", cmd.Name, err)
}
}
}
return ctx, err
}
if cmd.checkHelp() {
return ctx, helpCommandAction(ctx, cmd)
} else {
tracef("no help is wanted (cmd=%[1]q)", cmd.Name)
}
if cmd.parent == nil && !cmd.HideVersion && checkVersion(cmd) {
ShowVersion(cmd)
##CHUNK 2
if v, ok := ctx.Value(commandContextKey).(*Command); ok {
tracef("setting parent (cmd=%[1]q) command from context.Context value (cmd=%[2]q)", v.Name, cmd.Name)
cmd.parent = v
}
if cmd.parent == nil {
if cmd.ReadArgsFromStdin {
if args, err := cmd.parseArgsFromStdin(); err != nil {
return ctx, err
} else {
osArgs = append(osArgs, args...)
}
}
// handle the completion flag separately from the flagset since
// completion could be attempted after a flag, but before its value was put
// on the command line. this causes the flagset to interpret the completion
// flag name as the value of the flag before it which is undesirable
// note that we can only do this because the shell autocomplete function
// always appends the completion flag at the end of the command
##CHUNK 3
if cmd.Suggest {
if suggestion, err := cmd.suggestFlagFromError(err, ""); err == nil {
fmt.Fprintf(cmd.Root().ErrWriter, "%s", suggestion)
}
}
if !cmd.hideHelp() {
if cmd.parent == nil {
tracef("running ShowAppHelp")
if err := ShowAppHelp(cmd); err != nil {
tracef("SILENTLY IGNORING ERROR running ShowAppHelp %[1]v (cmd=%[2]q)", err, cmd.Name)
}
} else {
tracef("running ShowCommandHelp with %[1]q", cmd.Name)
if err := ShowCommandHelp(ctx, cmd, cmd.Name); err != nil {
tracef("SILENTLY IGNORING ERROR running ShowCommandHelp with %[1]q %[2]v", cmd.Name, err)
}
}
}
return ctx, err
#FILE: cli-main/command_setup.go
##CHUNK 1
if isRoot && cmd.EnableShellCompletion || cmd.ConfigureShellCompletionCommand != nil {
completionCommand := buildCompletionCommand(cmd.Name)
if cmd.ShellCompletionCommandName != "" {
tracef(
"setting completion command name (%[1]q) from "+
"cmd.ShellCompletionCommandName (cmd=%[2]q)",
cmd.ShellCompletionCommandName, cmd.Name,
)
completionCommand.Name = cmd.ShellCompletionCommandName
}
tracef("appending completionCommand (cmd=%[1]q)", cmd.Name)
cmd.appendCommand(completionCommand)
if cmd.ConfigureShellCompletionCommand != nil {
cmd.ConfigureShellCompletionCommand(completionCommand)
}
}
tracef("setting command categories (cmd=%[1]q)", cmd.Name)
#CURRENT FILE: cli-main/help.go
##CHUNK 1
lastArg = ""
}
if strings.HasPrefix(lastArg, "-") {
tracef("printing flag suggestion for flag[%v] on command %[1]q", lastArg, cmd.Name)
printFlagSuggestions(lastArg, cmd.Flags, cmd.Root().Writer)
return
}
if cmd != nil {
tracef("printing command suggestions on command %[1]q", cmd.Name)
printCommandSuggestions(cmd.Commands, cmd.Root().Writer)
return
}
}
// ShowCommandHelpAndExit - exits with code after showing help
func ShowCommandHelpAndExit(ctx context.Context, cmd *Command, command string, code int) {
_ = ShowCommandHelp(ctx, cmd, command)
os.Exit(code)
##CHUNK 2
tracef("printing command suggestions on command %[1]q", cmd.Name)
printCommandSuggestions(cmd.Commands, cmd.Root().Writer)
return
}
}
// ShowCommandHelpAndExit - exits with code after showing help
func ShowCommandHelpAndExit(ctx context.Context, cmd *Command, command string, code int) {
_ = ShowCommandHelp(ctx, cmd, command)
os.Exit(code)
}
// ShowCommandHelp prints help for the given command
func ShowCommandHelp(ctx context.Context, cmd *Command, commandName string) error {
for _, subCmd := range cmd.Commands {
if !subCmd.HasName(commandName) {
continue
}
tmpl := subCmd.CustomHelpTemplate
##CHUNK 3
tmpl := cmd.CustomHelpTemplate
if tmpl == "" {
tmpl = CommandHelpTemplate
}
tracef("running HelpPrinter with command %[1]q", cmd.Name)
HelpPrinter(cmd.Root().Writer, tmpl, cmd)
return nil
}
tracef("running ShowSubcommandHelp")
return ShowSubcommandHelp(cmd)
}
// ShowAppHelpAndExit - Prints the list of subcommands for the app and exits with exit code.
func ShowAppHelpAndExit(cmd *Command, exitCode int) {
_ = ShowAppHelp(cmd)
os.Exit(exitCode)
##CHUNK 4
} else if argsLen > 0 {
lastArg = args[argsLen-1]
}
if lastArg == "--" {
tracef("No completions due to termination")
return
}
if lastArg == completionFlag {
lastArg = ""
}
if strings.HasPrefix(lastArg, "-") {
tracef("printing flag suggestion for flag[%v] on command %[1]q", lastArg, cmd.Name)
printFlagSuggestions(lastArg, cmd.Flags, cmd.Root().Writer)
return
}
if cmd != nil {
##CHUNK 5
}
fmt.Fprintln(writer, flagCompletion)
}
}
}
func DefaultCompleteWithFlags(ctx context.Context, cmd *Command) {
args := os.Args
if cmd != nil && cmd.parent != nil {
args = cmd.Args().Slice()
tracef("running default complete with flags[%v] on command %[2]q", args, cmd.Name)
} else {
tracef("running default complete with os.Args flags[%v]", args)
}
argsLen := len(args)
lastArg := ""
// parent command will have --generate-shell-completion so we need
// to account for that
if argsLen > 1 {
lastArg = args[argsLen-2]
##CHUNK 6
// commands/subcommands
if cmd.parent == nil {
tracef("returning ShowAppHelp")
_ = ShowAppHelp(cmd)
return nil
}
// Case 3, 5
if (len(cmd.Commands) == 1 && !cmd.HideHelp) ||
(len(cmd.Commands) == 0 && cmd.HideHelp) {
tmpl := cmd.CustomHelpTemplate
if tmpl == "" {
tmpl = CommandHelpTemplate
}
tracef("running HelpPrinter with command %[1]q", cmd.Name)
HelpPrinter(cmd.Root().Writer, tmpl, cmd)
return nil
|
cli-main
| 71
|
func wrap(input string, offset int, wrapAt int) string {
var ss []string
lines := strings.Split(input, "\n")
padding := strings.Repeat(" ", offset)
for i, line := range lines {
if line == "" {
ss = append(ss, line)
} else {
wrapped := wrapLine(line, offset, wrapAt, padding)
if i == 0 {
ss = append(ss, wrapped)
} else {
ss = append(ss, padding+wrapped)
}
}
}
return strings.Join(ss, "\n")
}
|
func wrap(input string, offset int, wrapAt int) string {
var ss []string
lines := strings.Split(input, "\n")
padding := strings.Repeat(" ", offset)
for i, line := range lines {
if line == "" {
ss = append(ss, line)
} else {
wrapped := wrapLine(line, offset, wrapAt, padding)
if i == 0 {
ss = append(ss, wrapped)
} else {
ss = append(ss, padding+wrapped)
}
}
}
return strings.Join(ss, "\n")
}
|
func wrap(input string, offset int, wrapAt int) string {
var ss []string
lines := strings.Split(input, "\n")
padding := strings.Repeat(" ", offset)
for i, line := range lines {
if line == "" {
ss = append(ss, line)
} else {
wrapped := wrapLine(line, offset, wrapAt, padding)
if i == 0 {
ss = append(ss, wrapped)
} else {
ss = append(ss, padding+wrapped)
}
}
}
return strings.Join(ss, "\n")
}
|
wrap
| 522
| 544
|
help.go
|
#FILE: cli-main/flag_test.go
##CHUNK 1
err := (&Command{
Name: "foobar",
UseShortOptionHandling: true,
Action: func(_ context.Context, cmd *Command) error {
wasCalled = true
if !cmd.Bool("i") {
return fmt.Errorf("bool i not set")
}
if !cmd.Bool("t") {
return fmt.Errorf("bool i not set")
}
ss := cmd.StringSlice("net")
if !reflect.DeepEqual(ss, []string{"foo"}) {
return fmt.Errorf("got different slice %q than expected", ss)
}
return nil
##CHUNK 2
if !cmd.Bool("t") {
return fmt.Errorf("bool i not set")
}
ss := cmd.StringSlice("net")
if !reflect.DeepEqual(ss, []string{"foo"}) {
return fmt.Errorf("got different slice %q than expected", ss)
}
return nil
},
Flags: []Flag{
&StringSliceFlag{Name: "net"},
&BoolFlag{Name: "i"},
&BoolFlag{Name: "t"},
},
}).Run(buildTestContext(t), []string{"foobar", "--net=foo", "-it"})
r := require.New(t)
#FILE: cli-main/scripts/build.go
##CHUNK 1
}
lines := strings.Split(string(lineBytes), "\n")
fmt.Fprint(out, strings.Join(lines[1:], "\n"))
if err := os.Remove(filename); err != nil {
return err
}
}
return os.WriteFile("coverage.txt", out.Bytes(), 0o644)
}
func GfmrunActionFunc(ctx context.Context, cmd *cli.Command) error {
docsDir := filepath.Join(cmd.String("top-dir"), "docs")
bash, err := exec.LookPath("bash")
if err != nil {
return err
##CHUNK 2
out := &bytes.Buffer{}
fmt.Fprintf(out, "mode: count\n")
for _, pkg := range packages {
filename := pkg + ".coverprofile"
lineBytes, err := os.ReadFile(filename)
if err != nil {
return err
}
lines := strings.Split(string(lineBytes), "\n")
fmt.Fprint(out, strings.Join(lines[1:], "\n"))
if err := os.Remove(filename); err != nil {
return err
}
}
#FILE: cli-main/suggestions.go
##CHUNK 1
prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b)))))
var prefixMatch float64
for i := 0; i < prefix; i++ {
if a[i] == b[i] {
prefixMatch++
} else {
break
}
}
return jaroDist + 0.1*prefixMatch*(1.0-jaroDist)
}
func suggestFlag(flags []Flag, provided string, hideHelp bool) string {
distance := 0.0
suggestion := ""
for _, flag := range flags {
flagNames := flag.Names()
#CURRENT FILE: cli-main/help.go
##CHUNK 1
}
}
func wrapLine(input string, offset int, wrapAt int, padding string) string {
if wrapAt <= offset || len(input) <= wrapAt-offset {
return input
}
lineWidth := wrapAt - offset
words := strings.Fields(input)
if len(words) == 0 {
return input
}
wrapped := words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spaceLeft {
wrapped += "\n" + padding + word
spaceLeft = lineWidth - len(word)
##CHUNK 2
return a - b
}
func indent(spaces int, v string) string {
pad := strings.Repeat(" ", spaces)
return pad + strings.ReplaceAll(v, "\n", "\n"+pad)
}
func nindent(spaces int, v string) string {
return "\n" + indent(spaces, v)
}
}
func wrapLine(input string, offset int, wrapAt int, padding string) string {
if wrapAt <= offset || len(input) <= wrapAt-offset {
return input
}
lineWidth := wrapAt - offset
words := strings.Fields(input)
##CHUNK 3
if len(words) == 0 {
return input
}
wrapped := words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spaceLeft {
wrapped += "\n" + padding + word
spaceLeft = lineWidth - len(word)
} else {
wrapped += " " + word
spaceLeft -= 1 + len(word)
}
}
return wrapped
}
func offset(input string, fixed int) int {
##CHUNK 4
funcMap := template.FuncMap{
"join": strings.Join,
"subtract": subtract,
"indent": indent,
"nindent": nindent,
"trim": strings.TrimSpace,
"wrap": func(input string, offset int) string { return wrap(input, offset, maxLineLength) },
"offset": offset,
"offsetCommands": offsetCommands,
}
if wa, ok := customFuncs["wrapAt"]; ok {
if wrapAtFunc, ok := wa.(func() int); ok {
wrapAt := wrapAtFunc()
customFuncs["wrap"] = func(input string, offset int) string {
return wrap(input, offset, wrapAt)
}
}
}
##CHUNK 5
if wa, ok := customFuncs["wrapAt"]; ok {
if wrapAtFunc, ok := wa.(func() int); ok {
wrapAt := wrapAtFunc()
customFuncs["wrap"] = func(input string, offset int) string {
return wrap(input, offset, wrapAt)
}
}
}
for key, value := range customFuncs {
funcMap[key] = value
}
w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0)
t := template.Must(template.New("help").Funcs(funcMap).Parse(templ))
if _, err := t.New("helpNameTemplate").Parse(helpNameTemplate); err != nil {
handleTemplateError(err)
}
|
cli-main
| 72
|
func wrapLine(input string, offset int, wrapAt int, padding string) string {
if wrapAt <= offset || len(input) <= wrapAt-offset {
return input
}
lineWidth := wrapAt - offset
words := strings.Fields(input)
if len(words) == 0 {
return input
}
wrapped := words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spaceLeft {
wrapped += "\n" + padding + word
spaceLeft = lineWidth - len(word)
} else {
wrapped += " " + word
spaceLeft -= 1 + len(word)
}
}
return wrapped
}
|
func wrapLine(input string, offset int, wrapAt int, padding string) string {
if wrapAt <= offset || len(input) <= wrapAt-offset {
return input
}
lineWidth := wrapAt - offset
words := strings.Fields(input)
if len(words) == 0 {
return input
}
wrapped := words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spaceLeft {
wrapped += "\n" + padding + word
spaceLeft = lineWidth - len(word)
} else {
wrapped += " " + word
spaceLeft -= 1 + len(word)
}
}
return wrapped
}
|
func wrapLine(input string, offset int, wrapAt int, padding string) string {
if wrapAt <= offset || len(input) <= wrapAt-offset {
return input
}
lineWidth := wrapAt - offset
words := strings.Fields(input)
if len(words) == 0 {
return input
}
wrapped := words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spaceLeft {
wrapped += "\n" + padding + word
spaceLeft = lineWidth - len(word)
} else {
wrapped += " " + word
spaceLeft -= 1 + len(word)
}
}
return wrapped
}
|
wrapLine
| 546
| 570
|
help.go
|
#FILE: cli-main/docs.go
##CHUNK 1
break
}
}
return "", usage
}
func prefixedNames(names []string, placeholder string) string {
var prefixed string
for i, name := range names {
if name == "" {
continue
}
prefixed += prefixFor(name) + name
if placeholder != "" {
prefixed += " " + placeholder
}
if i < len(names)-1 {
prefixed += ", "
}
##CHUNK 2
continue
}
prefixed += prefixFor(name) + name
if placeholder != "" {
prefixed += " " + placeholder
}
if i < len(names)-1 {
prefixed += ", "
}
}
return prefixed
}
func envFormat(envVars []string, prefix, sep, suffix string) string {
if len(envVars) > 0 {
return fmt.Sprintf(" [%s%s%s]", prefix, strings.Join(envVars, sep), suffix)
}
return ""
}
#FILE: cli-main/suggestions.go
##CHUNK 1
}
if len(suggestion) == 1 {
suggestion = "-" + suggestion
} else if len(suggestion) > 1 {
suggestion = "--" + suggestion
}
return suggestion
}
// suggestCommand takes a list of commands and a provided string to suggest a
// command name
func suggestCommand(commands []*Command, provided string) (suggestion string) {
distance := 0.0
for _, command := range commands {
for _, name := range append(command.Names(), helpName, helpAlias) {
newDistance := jaroWinkler(name, provided)
if newDistance > distance {
distance = newDistance
##CHUNK 2
if !hideHelp && HelpFlag != nil {
flagNames = append(flagNames, HelpFlag.Names()...)
}
for _, name := range flagNames {
newDistance := jaroWinkler(name, provided)
if newDistance > distance {
distance = newDistance
suggestion = name
}
}
}
if len(suggestion) == 1 {
suggestion = "-" + suggestion
} else if len(suggestion) > 1 {
suggestion = "--" + suggestion
}
return suggestion
}
#CURRENT FILE: cli-main/help.go
##CHUNK 1
return a - b
}
func indent(spaces int, v string) string {
pad := strings.Repeat(" ", spaces)
return pad + strings.ReplaceAll(v, "\n", "\n"+pad)
}
func nindent(spaces int, v string) string {
return "\n" + indent(spaces, v)
}
func wrap(input string, offset int, wrapAt int) string {
var ss []string
lines := strings.Split(input, "\n")
padding := strings.Repeat(" ", offset)
for i, line := range lines {
##CHUNK 2
}
func wrap(input string, offset int, wrapAt int) string {
var ss []string
lines := strings.Split(input, "\n")
padding := strings.Repeat(" ", offset)
for i, line := range lines {
if line == "" {
ss = append(ss, line)
} else {
wrapped := wrapLine(line, offset, wrapAt, padding)
if i == 0 {
ss = append(ss, wrapped)
} else {
ss = append(ss, padding+wrapped)
}
##CHUNK 3
if line == "" {
ss = append(ss, line)
} else {
wrapped := wrapLine(line, offset, wrapAt, padding)
if i == 0 {
ss = append(ss, wrapped)
} else {
ss = append(ss, padding+wrapped)
}
}
}
return strings.Join(ss, "\n")
}
}
func offset(input string, fixed int) int {
return len(input) + fixed
}
##CHUNK 4
if cmd.ShellComplete != nil {
tracef("running shell completion func for command %[1]q", cmd.Name)
cmd.ShellComplete(ctx, cmd)
}
return true
}
func subtract(a, b int) int {
return a - b
}
func indent(spaces int, v string) string {
pad := strings.Repeat(" ", spaces)
return pad + strings.ReplaceAll(v, "\n", "\n"+pad)
}
func nindent(spaces int, v string) string {
return "\n" + indent(spaces, v)
##CHUNK 5
funcMap := template.FuncMap{
"join": strings.Join,
"subtract": subtract,
"indent": indent,
"nindent": nindent,
"trim": strings.TrimSpace,
"wrap": func(input string, offset int) string { return wrap(input, offset, maxLineLength) },
"offset": offset,
"offsetCommands": offsetCommands,
}
if wa, ok := customFuncs["wrapAt"]; ok {
if wrapAtFunc, ok := wa.(func() int); ok {
wrapAt := wrapAtFunc()
customFuncs["wrap"] = func(input string, offset int) string {
return wrap(input, offset, wrapAt)
}
}
}
##CHUNK 6
if wa, ok := customFuncs["wrapAt"]; ok {
if wrapAtFunc, ok := wa.(func() int); ok {
wrapAt := wrapAtFunc()
customFuncs["wrap"] = func(input string, offset int) string {
return wrap(input, offset, wrapAt)
}
}
}
for key, value := range customFuncs {
funcMap[key] = value
}
w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0)
t := template.Must(template.New("help").Funcs(funcMap).Parse(templ))
if _, err := t.New("helpNameTemplate").Parse(helpNameTemplate); err != nil {
handleTemplateError(err)
}
|
cli-main
| 73
|
func lexicographicLess(i, j string) bool {
iRunes := []rune(i)
jRunes := []rune(j)
lenShared := len(iRunes)
if lenShared > len(jRunes) {
lenShared = len(jRunes)
}
for index := 0; index < lenShared; index++ {
ir := iRunes[index]
jr := jRunes[index]
if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr); lir != ljr {
return lir < ljr
}
if ir != jr {
return ir < jr
}
}
return i < j
}
|
func lexicographicLess(i, j string) bool {
iRunes := []rune(i)
jRunes := []rune(j)
lenShared := len(iRunes)
if lenShared > len(jRunes) {
lenShared = len(jRunes)
}
for index := 0; index < lenShared; index++ {
ir := iRunes[index]
jr := jRunes[index]
if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr); lir != ljr {
return lir < ljr
}
if ir != jr {
return ir < jr
}
}
return i < j
}
|
func lexicographicLess(i, j string) bool {
iRunes := []rune(i)
jRunes := []rune(j)
lenShared := len(iRunes)
if lenShared > len(jRunes) {
lenShared = len(jRunes)
}
for index := 0; index < lenShared; index++ {
ir := iRunes[index]
jr := jRunes[index]
if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr); lir != ljr {
return lir < ljr
}
if ir != jr {
return ir < jr
}
}
return i < j
}
|
lexicographicLess
| 5
| 28
|
sort.go
|
#FILE: cli-main/docs.go
##CHUNK 1
func unquoteUsage(usage string) (string, string) {
for i := 0; i < len(usage); i++ {
if usage[i] == '`' {
for j := i + 1; j < len(usage); j++ {
if usage[j] == '`' {
name := usage[i+1 : j]
usage = usage[:i] + name + usage[j+1:]
return name, usage
}
}
break
}
}
return "", usage
}
func prefixedNames(names []string, placeholder string) string {
var prefixed string
for i, name := range names {
if name == "" {
##CHUNK 2
if len(name) == 1 {
prefix = "-"
} else {
prefix = "--"
}
return
}
// Returns the placeholder, if any, and the unquoted usage string.
func unquoteUsage(usage string) (string, string) {
for i := 0; i < len(usage); i++ {
if usage[i] == '`' {
for j := i + 1; j < len(usage); j++ {
if usage[j] == '`' {
name := usage[i+1 : j]
usage = usage[:i] + name + usage[j+1:]
return name, usage
}
}
##CHUNK 3
break
}
}
return "", usage
}
func prefixedNames(names []string, placeholder string) string {
var prefixed string
for i, name := range names {
if name == "" {
continue
}
prefixed += prefixFor(name) + name
if placeholder != "" {
prefixed += " " + placeholder
}
if i < len(names)-1 {
prefixed += ", "
}
#FILE: cli-main/suggestions.go
##CHUNK 1
break
}
}
}
if matches == 0 {
return 0
}
var transpositions float64
var j int
for i := 0; i < len(a); i++ {
if !hashA[i] {
continue
}
for !hashB[j] {
j++
}
if a[i] != b[j] {
transpositions++
}
##CHUNK 2
lenA := float64(len(a))
lenB := float64(len(b))
hashA := make([]bool, len(a))
hashB := make([]bool, len(b))
maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1))
var matches float64
for i := 0; i < len(a); i++ {
start := int(math.Max(0, float64(i-maxDistance)))
end := int(math.Min(lenB-1, float64(i+maxDistance)))
for j := start; j <= end; j++ {
if hashB[j] {
continue
}
if a[i] == b[j] {
hashA[i] = true
hashB[j] = true
matches++
##CHUNK 3
prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b)))))
var prefixMatch float64
for i := 0; i < prefix; i++ {
if a[i] == b[i] {
prefixMatch++
} else {
break
}
}
return jaroDist + 0.1*prefixMatch*(1.0-jaroDist)
}
func suggestFlag(flags []Flag, provided string, hideHelp bool) string {
distance := 0.0
suggestion := ""
for _, flag := range flags {
flagNames := flag.Names()
##CHUNK 4
// Adapted from https://github.com/xrash/smetrics/blob/5f08fbb34913bc8ab95bb4f2a89a0637ca922666/jaro-winkler.go.
func jaroWinkler(a, b string) float64 {
const (
boostThreshold = 0.7
prefixSize = 4
)
jaroDist := jaroDistance(a, b)
if jaroDist <= boostThreshold {
return jaroDist
}
prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b)))))
var prefixMatch float64
for i := 0; i < prefix; i++ {
if a[i] == b[i] {
prefixMatch++
} else {
break
}
##CHUNK 5
// completely different strings.
//
// Adapted from https://github.com/xrash/smetrics/blob/5f08fbb34913bc8ab95bb4f2a89a0637ca922666/jaro.go.
func jaroDistance(a, b string) float64 {
if len(a) == 0 && len(b) == 0 {
return 1
}
if len(a) == 0 || len(b) == 0 {
return 0
}
lenA := float64(len(a))
lenB := float64(len(b))
hashA := make([]bool, len(a))
hashB := make([]bool, len(b))
maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1))
var matches float64
for i := 0; i < len(a); i++ {
start := int(math.Max(0, float64(i-maxDistance)))
##CHUNK 6
for i := 0; i < len(a); i++ {
if !hashA[i] {
continue
}
for !hashB[j] {
j++
}
if a[i] != b[j] {
transpositions++
}
j++
}
transpositions /= 2
return ((matches / lenA) + (matches / lenB) + ((matches - transpositions) / matches)) / 3.0
}
// jaroWinkler is more accurate when strings have a common prefix up to a
// defined maximum length.
//
#FILE: cli-main/command_test.go
##CHUNK 1
if len(v) > 0 && v[0] < 0 {
return fmt.Errorf("invalid float64 slice")
}
_, err := fmt.Fprintf(cmd.Root().Writer, "%v ", v)
return err
},
},
&Int64Flag{
Name: "f_int",
Local: true,
Action: func(_ context.Context, cmd *Command, v int64) error {
if v < 0 {
return fmt.Errorf("negative int")
}
_, err := fmt.Fprintf(cmd.Root().Writer, "%v ", v)
return err
},
},
&Int64SliceFlag{
Name: "f_int_slice",
#CURRENT FILE: cli-main/sort.go
|
cli-main
| 74
|
func checkBinarySizeActionFunc(ctx context.Context, cmd *cli.Command) (err error) {
const (
cliSourceFilePath = "./examples/example-cli/example-cli.go"
cliBuiltFilePath = "./examples/example-cli/built-example"
helloSourceFilePath = "./examples/example-hello-world/example-hello-world.go"
helloBuiltFilePath = "./examples/example-hello-world/built-example"
desiredMaxBinarySize = 2.2
desiredMinBinarySize = 1.49
mbStringFormatter = "%.1fMB"
)
tags := cmd.String("tags")
// get cli example size
cliSize, err := getSize(ctx, cliSourceFilePath, cliBuiltFilePath, tags)
if err != nil {
return err
}
// get hello world size
helloSize, err := getSize(ctx, helloSourceFilePath, helloBuiltFilePath, tags)
if err != nil {
return err
}
// The CLI size diff is the number we are interested in.
// This tells us how much our CLI package contributes to the binary size.
cliSizeDiff := cliSize - helloSize
// get human readable size, in MB with one decimal place.
// example output is: 35.2MB. (note: this simply an example)
// that output is much easier to reason about than the `35223432`
// that you would see output without the rounding
fileSizeInMB := float64(cliSizeDiff) / float64(1000000)
roundedFileSize := math.Round(fileSizeInMB*10) / 10
roundedFileSizeString := fmt.Sprintf(mbStringFormatter, roundedFileSize)
// check against bounds
isLessThanDesiredMin := roundedFileSize < desiredMinBinarySize
isMoreThanDesiredMax := roundedFileSize > desiredMaxBinarySize
desiredMinSizeString := fmt.Sprintf(mbStringFormatter, desiredMinBinarySize)
desiredMaxSizeString := fmt.Sprintf(mbStringFormatter, desiredMaxBinarySize)
// show guidance
fmt.Printf("\n%s is the current binary size\n", roundedFileSizeString)
// show guidance for min size
if isLessThanDesiredMin {
fmt.Printf(" %s %s is the target min size\n", goodNewsEmoji, desiredMinSizeString)
fmt.Println("") // visual spacing
fmt.Println(" The binary is smaller than the target min size, which is great news!")
fmt.Println(" That means that your changes are shrinking the binary size.")
fmt.Println(" You'll want to go into ./scripts/build.go and decrease")
fmt.Println(" the desiredMinBinarySize, and also probably decrease the ")
fmt.Println(" desiredMaxBinarySize by the same amount. That will ensure that")
fmt.Println(" future PRs will enforce the newly shrunk binary sizes.")
fmt.Println("") // visual spacing
os.Exit(1)
} else {
fmt.Printf(" %s %s is the target min size\n", checksPassedEmoji, desiredMinSizeString)
}
// show guidance for max size
if isMoreThanDesiredMax {
fmt.Printf(" %s %s is the target max size\n", badNewsEmoji, desiredMaxSizeString)
fmt.Println("") // visual spacing
fmt.Println(" The binary is larger than the target max size.")
fmt.Println(" That means that your changes are increasing the binary size.")
fmt.Println(" The first thing you'll want to do is ask your yourself")
fmt.Println(" Is this change worth increasing the binary size?")
fmt.Println(" Larger binary sizes for this package can dissuade its use.")
fmt.Println(" If this change is worth the increase, then we can up the")
fmt.Println(" desired max binary size. To do that you'll want to go into")
fmt.Println(" ./scripts/build.go and increase the desiredMaxBinarySize,")
fmt.Println(" and increase the desiredMinBinarySize by the same amount.")
fmt.Println("") // visual spacing
os.Exit(1)
} else {
fmt.Printf(" %s %s is the target max size\n", checksPassedEmoji, desiredMaxSizeString)
}
return nil
}
|
func checkBinarySizeActionFunc(ctx context.Context, cmd *cli.Command) (err error) {
const (
cliSourceFilePath = "./examples/example-cli/example-cli.go"
cliBuiltFilePath = "./examples/example-cli/built-example"
helloSourceFilePath = "./examples/example-hello-world/example-hello-world.go"
helloBuiltFilePath = "./examples/example-hello-world/built-example"
desiredMaxBinarySize = 2.2
desiredMinBinarySize = 1.49
mbStringFormatter = "%.1fMB"
)
tags := cmd.String("tags")
// get cli example size
cliSize, err := getSize(ctx, cliSourceFilePath, cliBuiltFilePath, tags)
if err != nil {
return err
}
// get hello world size
helloSize, err := getSize(ctx, helloSourceFilePath, helloBuiltFilePath, tags)
if err != nil {
return err
}
// The CLI size diff is the number we are interested in.
// This tells us how much our CLI package contributes to the binary size.
cliSizeDiff := cliSize - helloSize
// get human readable size, in MB with one decimal place.
// example output is: 35.2MB. (note: this simply an example)
// that output is much easier to reason about than the `35223432`
// that you would see output without the rounding
fileSizeInMB := float64(cliSizeDiff) / float64(1000000)
roundedFileSize := math.Round(fileSizeInMB*10) / 10
roundedFileSizeString := fmt.Sprintf(mbStringFormatter, roundedFileSize)
// check against bounds
isLessThanDesiredMin := roundedFileSize < desiredMinBinarySize
isMoreThanDesiredMax := roundedFileSize > desiredMaxBinarySize
desiredMinSizeString := fmt.Sprintf(mbStringFormatter, desiredMinBinarySize)
desiredMaxSizeString := fmt.Sprintf(mbStringFormatter, desiredMaxBinarySize)
// show guidance
fmt.Printf("\n%s is the current binary size\n", roundedFileSizeString)
// show guidance for min size
if isLessThanDesiredMin {
fmt.Printf(" %s %s is the target min size\n", goodNewsEmoji, desiredMinSizeString)
fmt.Println("") // visual spacing
fmt.Println(" The binary is smaller than the target min size, which is great news!")
fmt.Println(" That means that your changes are shrinking the binary size.")
fmt.Println(" You'll want to go into ./scripts/build.go and decrease")
fmt.Println(" the desiredMinBinarySize, and also probably decrease the ")
fmt.Println(" desiredMaxBinarySize by the same amount. That will ensure that")
fmt.Println(" future PRs will enforce the newly shrunk binary sizes.")
fmt.Println("") // visual spacing
os.Exit(1)
} else {
fmt.Printf(" %s %s is the target min size\n", checksPassedEmoji, desiredMinSizeString)
}
// show guidance for max size
if isMoreThanDesiredMax {
fmt.Printf(" %s %s is the target max size\n", badNewsEmoji, desiredMaxSizeString)
fmt.Println("") // visual spacing
fmt.Println(" The binary is larger than the target max size.")
fmt.Println(" That means that your changes are increasing the binary size.")
fmt.Println(" The first thing you'll want to do is ask your yourself")
fmt.Println(" Is this change worth increasing the binary size?")
fmt.Println(" Larger binary sizes for this package can dissuade its use.")
fmt.Println(" If this change is worth the increase, then we can up the")
fmt.Println(" desired max binary size. To do that you'll want to go into")
fmt.Println(" ./scripts/build.go and increase the desiredMaxBinarySize,")
fmt.Println(" and increase the desiredMinBinarySize by the same amount.")
fmt.Println("") // visual spacing
os.Exit(1)
} else {
fmt.Printf(" %s %s is the target max size\n", checksPassedEmoji, desiredMaxSizeString)
}
return nil
}
|
func checkBinarySizeActionFunc(ctx context.Context, cmd *cli.Command) (err error) {
const (
cliSourceFilePath = "./examples/example-cli/example-cli.go"
cliBuiltFilePath = "./examples/example-cli/built-example"
helloSourceFilePath = "./examples/example-hello-world/example-hello-world.go"
helloBuiltFilePath = "./examples/example-hello-world/built-example"
desiredMaxBinarySize = 2.2
desiredMinBinarySize = 1.49
mbStringFormatter = "%.1fMB"
)
tags := cmd.String("tags")
// get cli example size
cliSize, err := getSize(ctx, cliSourceFilePath, cliBuiltFilePath, tags)
if err != nil {
return err
}
// get hello world size
helloSize, err := getSize(ctx, helloSourceFilePath, helloBuiltFilePath, tags)
if err != nil {
return err
}
// The CLI size diff is the number we are interested in.
// This tells us how much our CLI package contributes to the binary size.
cliSizeDiff := cliSize - helloSize
// get human readable size, in MB with one decimal place.
// example output is: 35.2MB. (note: this simply an example)
// that output is much easier to reason about than the `35223432`
// that you would see output without the rounding
fileSizeInMB := float64(cliSizeDiff) / float64(1000000)
roundedFileSize := math.Round(fileSizeInMB*10) / 10
roundedFileSizeString := fmt.Sprintf(mbStringFormatter, roundedFileSize)
// check against bounds
isLessThanDesiredMin := roundedFileSize < desiredMinBinarySize
isMoreThanDesiredMax := roundedFileSize > desiredMaxBinarySize
desiredMinSizeString := fmt.Sprintf(mbStringFormatter, desiredMinBinarySize)
desiredMaxSizeString := fmt.Sprintf(mbStringFormatter, desiredMaxBinarySize)
// show guidance
fmt.Printf("\n%s is the current binary size\n", roundedFileSizeString)
// show guidance for min size
if isLessThanDesiredMin {
fmt.Printf(" %s %s is the target min size\n", goodNewsEmoji, desiredMinSizeString)
fmt.Println("") // visual spacing
fmt.Println(" The binary is smaller than the target min size, which is great news!")
fmt.Println(" That means that your changes are shrinking the binary size.")
fmt.Println(" You'll want to go into ./scripts/build.go and decrease")
fmt.Println(" the desiredMinBinarySize, and also probably decrease the ")
fmt.Println(" desiredMaxBinarySize by the same amount. That will ensure that")
fmt.Println(" future PRs will enforce the newly shrunk binary sizes.")
fmt.Println("") // visual spacing
os.Exit(1)
} else {
fmt.Printf(" %s %s is the target min size\n", checksPassedEmoji, desiredMinSizeString)
}
// show guidance for max size
if isMoreThanDesiredMax {
fmt.Printf(" %s %s is the target max size\n", badNewsEmoji, desiredMaxSizeString)
fmt.Println("") // visual spacing
fmt.Println(" The binary is larger than the target max size.")
fmt.Println(" That means that your changes are increasing the binary size.")
fmt.Println(" The first thing you'll want to do is ask your yourself")
fmt.Println(" Is this change worth increasing the binary size?")
fmt.Println(" Larger binary sizes for this package can dissuade its use.")
fmt.Println(" If this change is worth the increase, then we can up the")
fmt.Println(" desired max binary size. To do that you'll want to go into")
fmt.Println(" ./scripts/build.go and increase the desiredMaxBinarySize,")
fmt.Println(" and increase the desiredMinBinarySize by the same amount.")
fmt.Println("") // visual spacing
os.Exit(1)
} else {
fmt.Printf(" %s %s is the target max size\n", checksPassedEmoji, desiredMaxSizeString)
}
return nil
}
|
checkBinarySizeActionFunc
| 408
| 488
|
scripts/build.go
|
#FILE: cli-main/help.go
##CHUNK 1
// bar1, b2 some other string here
//
// We want to offset the 2nd row usage by some amount so that everything
// is aligned
//
// foo1, foo2, foo3 some string here
// bar1, b2 some other string here
//
// to find that offset we find the length of all the rows and use the max
// to calculate the offset
func offsetCommands(cmds []*Command, fixed int) int {
max := 0
for _, cmd := range cmds {
s := strings.Join(cmd.Names(), ", ")
if len(s) > max {
max = len(s)
}
}
return max + fixed
}
##CHUNK 2
}
func offset(input string, fixed int) int {
return len(input) + fixed
}
// this function tries to find the max width of the names column
// so say we have the following rows for help
//
// foo1, foo2, foo3 some string here
// bar1, b2 some other string here
//
// We want to offset the 2nd row usage by some amount so that everything
// is aligned
//
// foo1, foo2, foo3 some string here
// bar1, b2 some other string here
//
// to find that offset we find the length of all the rows and use the max
// to calculate the offset
##CHUNK 3
func handleTemplateError(err error) {
if err != nil {
tracef("error encountered during template parse: %[1]v", err)
// If the writer is closed, t.Execute will fail, and there's nothing
// we can do to recover.
if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" {
_, _ = fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err)
}
return
}
}
// printHelpCustom is the default implementation of HelpPrinterCustom.
//
// The customFuncs map will be combined with a default template.FuncMap to
// allow using arbitrary functions in template rendering.
func printHelpCustom(out io.Writer, templ string, data interface{}, customFuncs map[string]interface{}) {
const maxLineLength = 10000
tracef("building default funcMap")
#FILE: cli-main/command_run.go
##CHUNK 1
if v, ok := ctx.Value(commandContextKey).(*Command); ok {
tracef("setting parent (cmd=%[1]q) command from context.Context value (cmd=%[2]q)", v.Name, cmd.Name)
cmd.parent = v
}
if cmd.parent == nil {
if cmd.ReadArgsFromStdin {
if args, err := cmd.parseArgsFromStdin(); err != nil {
return ctx, err
} else {
osArgs = append(osArgs, args...)
}
}
// handle the completion flag separately from the flagset since
// completion could be attempted after a flag, but before its value was put
// on the command line. this causes the flagset to interpret the completion
// flag name as the value of the flag before it which is undesirable
// note that we can only do this because the shell autocomplete function
// always appends the completion flag at the end of the command
#FILE: cli-main/value_source.go
##CHUNK 1
// Lookup returns a value from the map source. The lookup name may be a dot-separated path into the map.
// If that is the case, it will recursively traverse the map based on the '.' delimited sections to find
// a nested value for the key.
func (ms *mapSource) Lookup(name string) (any, bool) {
sections := strings.Split(name, ".")
if name == "" || len(sections) == 0 {
return nil, false
}
node := ms.m
// traverse into the map based on the dot-separated sections
if len(sections) >= 2 { // the last section is the value we want, we will return it directly at the end
for _, section := range sections[:len(sections)-1] {
child, ok := node[section]
if !ok {
return nil, false
}
#FILE: cli-main/errors.go
##CHUNK 1
// message and calling OsExiter with the given exit code.
//
// If the given error instead implements MultiError, each error will be checked
// for the ExitCoder interface, and OsExiter will be called with the last exit
// code found, or exit code 1 if no ExitCoder is found.
//
// This function is the default error-handling behavior for an App.
func HandleExitCoder(err error) {
if err == nil {
return
}
if exitErr, ok := err.(ExitCoder); ok {
if err.Error() != "" {
if _, ok := exitErr.(ErrorFormatter); ok {
_, _ = fmt.Fprintf(ErrWriter, "%+v\n", err)
} else {
_, _ = fmt.Fprintln(ErrWriter, err)
}
}
#FILE: cli-main/command_parse.go
##CHUNK 1
// handle positional args
if firstArg[0] != '-' {
// positional argument probably
tracef("rearrange-3 (cmd=%[1]q) check %[2]q", cmd.Name, firstArg)
// if there is a command by that name let the command handle the
// rest of the parsing
if cmd.Command(firstArg) != nil {
posArgs = append(posArgs, rargs...)
return &stringSliceArgs{posArgs}, nil
}
posArgs = append(posArgs, firstArg)
continue
}
numMinuses := 1
// this is same as firstArg == "-"
if len(firstArg) == 1 {
#FILE: cli-main/examples/example-hello-world/example-hello-world.go
##CHUNK 1
// example hello world used for binary size checking
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
#CURRENT FILE: cli-main/scripts/build.go
##CHUNK 1
}
return os.RemoveAll(tmpDir)
}
// checkBinarySizeActionFunc checks the size of an example binary to ensure that we are keeping size down
// this was originally inspired by https://github.com/urfave/cli/issues/1055, and followed up on as a part
}
func GenerateActionFunc(ctx context.Context, cmd *cli.Command) error {
topDir := cmd.String("top-dir")
cliDocs, err := sh(ctx, "go", "doc", "-all", topDir)
if err != nil {
return err
}
return os.WriteFile(
filepath.Join(topDir, "godoc-current.txt"),
[]byte(cliDocs),
##CHUNK 2
gfmArgs := []string{
"--count",
fmt.Sprint(counter),
}
for _, src := range sources {
gfmArgs = append(gfmArgs, "--sources", src)
}
if err := runCmd(ctx, "gfmrun", gfmArgs...); err != nil {
return err
}
return os.RemoveAll(tmpDir)
}
// checkBinarySizeActionFunc checks the size of an example binary to ensure that we are keeping size down
// this was originally inspired by https://github.com/urfave/cli/issues/1055, and followed up on as a part
}
func GenerateActionFunc(ctx context.Context, cmd *cli.Command) error {
|
cli-main
| 75
|
func getSize(ctx context.Context, sourcePath, builtPath, tags string) (int64, error) {
args := []string{"build"}
if tags != "" {
args = append(args, []string{"-tags", tags}...)
}
args = append(args, []string{
"-o", builtPath,
"-ldflags", "-s -w",
sourcePath,
}...)
if err := runCmd(ctx, "go", args...); err != nil {
fmt.Println("issue getting size for example binary")
return 0, err
}
fileInfo, err := os.Stat(builtPath)
if err != nil {
fmt.Println("issue getting size for example binary")
return 0, err
}
return fileInfo.Size(), nil
}
|
func getSize(ctx context.Context, sourcePath, builtPath, tags string) (int64, error) {
args := []string{"build"}
if tags != "" {
args = append(args, []string{"-tags", tags}...)
}
args = append(args, []string{
"-o", builtPath,
"-ldflags", "-s -w",
sourcePath,
}...)
if err := runCmd(ctx, "go", args...); err != nil {
fmt.Println("issue getting size for example binary")
return 0, err
}
fileInfo, err := os.Stat(builtPath)
if err != nil {
fmt.Println("issue getting size for example binary")
return 0, err
}
return fileInfo.Size(), nil
}
|
func getSize(ctx context.Context, sourcePath, builtPath, tags string) (int64, error) {
args := []string{"build"}
if tags != "" {
args = append(args, []string{"-tags", tags}...)
}
args = append(args, []string{
"-o", builtPath,
"-ldflags", "-s -w",
sourcePath,
}...)
if err := runCmd(ctx, "go", args...); err != nil {
fmt.Println("issue getting size for example binary")
return 0, err
}
fileInfo, err := os.Stat(builtPath)
if err != nil {
fmt.Println("issue getting size for example binary")
return 0, err
}
return fileInfo.Size(), nil
}
|
getSize
| 652
| 677
|
scripts/build.go
|
#FILE: cli-main/command_run.go
##CHUNK 1
switch st {
case stateSearchForToken:
if token != "--" {
args = append(args, token)
}
case stateSearchForString:
// make sure string is not empty
for _, t := range token {
if !unicode.IsSpace(t) {
args = append(args, token)
}
}
}
break outer
}
if err != nil {
return nil, err
}
switch st {
case stateSearchForToken:
##CHUNK 2
linenum := 1
token := ""
args := []string{}
breader := bufio.NewReader(cmd.Reader)
outer:
for {
ch, _, err := breader.ReadRune()
if err == io.EOF {
switch st {
case stateSearchForToken:
if token != "--" {
args = append(args, token)
}
case stateSearchForString:
// make sure string is not empty
for _, t := range token {
if !unicode.IsSpace(t) {
args = append(args, token)
#CURRENT FILE: cli-main/scripts/build.go
##CHUNK 1
return os.Chmod(dest, perm)
}
func VetActionFunc(ctx context.Context, cmd *cli.Command) error {
return runCmd(ctx, "go", "vet", cmd.String("top-dir")+"/...")
}
func TestActionFunc(ctx context.Context, cmd *cli.Command) error {
tags := cmd.String("tags")
for _, pkg := range cmd.StringSlice("packages") {
packageName := "github.com/urfave/cli/v3"
if pkg != "cli" {
packageName = fmt.Sprintf("github.com/urfave/cli/v3/%s", pkg)
}
args := []string{"test"}
if tags != "" {
args = append(args, []string{"-tags", tags}...)
##CHUNK 2
for _, pkg := range cmd.StringSlice("packages") {
packageName := "github.com/urfave/cli/v3"
if pkg != "cli" {
packageName = fmt.Sprintf("github.com/urfave/cli/v3/%s", pkg)
}
args := []string{"test"}
if tags != "" {
args = append(args, []string{"-tags", tags}...)
}
args = append(args, []string{
"-v",
"-race",
"--coverprofile", pkg + ".coverprofile",
"--covermode", "atomic",
"--cover", packageName,
packageName,
}...)
##CHUNK 3
}
args = append(args, []string{
"-v",
"-race",
"--coverprofile", pkg + ".coverprofile",
"--covermode", "atomic",
"--cover", packageName,
packageName,
}...)
if err := runCmd(ctx, "go", args...); err != nil {
return err
}
}
return testCleanup(cmd.StringSlice("packages"))
}
func testCleanup(packages []string) error {
##CHUNK 4
}
if _, err := io.Copy(out, resp.Body); err != nil {
return err
}
if err := out.Close(); err != nil {
return err
}
return os.Chmod(dest, perm)
}
func VetActionFunc(ctx context.Context, cmd *cli.Command) error {
return runCmd(ctx, "go", "vet", cmd.String("top-dir")+"/...")
}
func TestActionFunc(ctx context.Context, cmd *cli.Command) error {
tags := cmd.String("tags")
##CHUNK 5
cliSourceFilePath = "./examples/example-cli/example-cli.go"
cliBuiltFilePath = "./examples/example-cli/built-example"
helloSourceFilePath = "./examples/example-hello-world/example-hello-world.go"
helloBuiltFilePath = "./examples/example-hello-world/built-example"
desiredMaxBinarySize = 2.2
desiredMinBinarySize = 1.49
mbStringFormatter = "%.1fMB"
)
tags := cmd.String("tags")
// get cli example size
cliSize, err := getSize(ctx, cliSourceFilePath, cliBuiltFilePath, tags)
if err != nil {
return err
}
// get hello world size
helloSize, err := getSize(ctx, helloSourceFilePath, helloBuiltFilePath, tags)
if err != nil {
##CHUNK 6
gfmArgs := []string{
"--count",
fmt.Sprint(counter),
}
for _, src := range sources {
gfmArgs = append(gfmArgs, "--sources", src)
}
if err := runCmd(ctx, "gfmrun", gfmArgs...); err != nil {
return err
}
return os.RemoveAll(tmpDir)
}
// checkBinarySizeActionFunc checks the size of an example binary to ensure that we are keeping size down
// this was originally inspired by https://github.com/urfave/cli/issues/1055, and followed up on as a part
// of https://github.com/urfave/cli/issues/1057
func checkBinarySizeActionFunc(ctx context.Context, cmd *cli.Command) (err error) {
const (
##CHUNK 7
if err := runCmd(ctx, "go", args...); err != nil {
return err
}
}
return testCleanup(cmd.StringSlice("packages"))
}
func testCleanup(packages []string) error {
out := &bytes.Buffer{}
fmt.Fprintf(out, "mode: count\n")
for _, pkg := range packages {
filename := pkg + ".coverprofile"
lineBytes, err := os.ReadFile(filename)
if err != nil {
return err
##CHUNK 8
if err := app.Run(context.Background(), os.Args); err != nil {
log.Fatal(err)
}
}
func sh(ctx context.Context, exe string, args ...string) (string, error) {
cmd := exec.CommandContext(ctx, exe, args...)
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
fmt.Fprintf(os.Stderr, "# ---> %s\n", cmd)
outBytes, err := cmd.Output()
return string(outBytes), err
}
func topRunAction(arg string, args ...string) cli.ActionFunc {
return func(ctx context.Context, cmd *cli.Command) error {
if err := os.Chdir(cmd.String("top-dir")); err != nil {
return err
}
|
ollama-main
| 76
|
func humanDuration(d time.Duration) string {
seconds := int(d.Seconds())
switch {
case seconds < 1:
return "Less than a second"
case seconds == 1:
return "1 second"
case seconds < 60:
return fmt.Sprintf("%d seconds", seconds)
}
minutes := int(d.Minutes())
switch {
case minutes == 1:
return "About a minute"
case minutes < 60:
return fmt.Sprintf("%d minutes", minutes)
}
hours := int(math.Round(d.Hours()))
switch {
case hours == 1:
return "About an hour"
case hours < 48:
return fmt.Sprintf("%d hours", hours)
case hours < 24*7*2:
return fmt.Sprintf("%d days", hours/24)
case hours < 24*30*2:
return fmt.Sprintf("%d weeks", hours/24/7)
case hours < 24*365*2:
return fmt.Sprintf("%d months", hours/24/30)
}
return fmt.Sprintf("%d years", int(d.Hours())/24/365)
}
|
func humanDuration(d time.Duration) string {
seconds := int(d.Seconds())
switch {
case seconds < 1:
return "Less than a second"
case seconds == 1:
return "1 second"
case seconds < 60:
return fmt.Sprintf("%d seconds", seconds)
}
minutes := int(d.Minutes())
switch {
case minutes == 1:
return "About a minute"
case minutes < 60:
return fmt.Sprintf("%d minutes", minutes)
}
hours := int(math.Round(d.Hours()))
switch {
case hours == 1:
return "About an hour"
case hours < 48:
return fmt.Sprintf("%d hours", hours)
case hours < 24*7*2:
return fmt.Sprintf("%d days", hours/24)
case hours < 24*30*2:
return fmt.Sprintf("%d weeks", hours/24/7)
case hours < 24*365*2:
return fmt.Sprintf("%d months", hours/24/30)
}
return fmt.Sprintf("%d years", int(d.Hours())/24/365)
}
|
func humanDuration(d time.Duration) string {
seconds := int(d.Seconds())
switch {
case seconds < 1:
return "Less than a second"
case seconds == 1:
return "1 second"
case seconds < 60:
return fmt.Sprintf("%d seconds", seconds)
}
minutes := int(d.Minutes())
switch {
case minutes == 1:
return "About a minute"
case minutes < 60:
return fmt.Sprintf("%d minutes", minutes)
}
hours := int(math.Round(d.Hours()))
switch {
case hours == 1:
return "About an hour"
case hours < 48:
return fmt.Sprintf("%d hours", hours)
case hours < 24*7*2:
return fmt.Sprintf("%d days", hours/24)
case hours < 24*30*2:
return fmt.Sprintf("%d weeks", hours/24/7)
case hours < 24*365*2:
return fmt.Sprintf("%d months", hours/24/30)
}
return fmt.Sprintf("%d years", int(d.Hours())/24/365)
}
|
humanDuration
| 11
| 46
|
format/time.go
|
#FILE: ollama-main/format/bytes.go
##CHUNK 1
switch {
case value >= 10:
return fmt.Sprintf("%d %s", int(value), unit)
case value != math.Trunc(value):
return fmt.Sprintf("%.1f %s", value, unit)
default:
return fmt.Sprintf("%d %s", int(value), unit)
}
}
func HumanBytes2(b uint64) string {
switch {
case b >= GibiByte:
return fmt.Sprintf("%.1f GiB", float64(b)/GibiByte)
case b >= MebiByte:
return fmt.Sprintf("%.1f MiB", float64(b)/MebiByte)
case b >= KibiByte:
return fmt.Sprintf("%.1f KiB", float64(b)/KibiByte)
default:
##CHUNK 2
unit = "GB"
case b >= MegaByte:
value = float64(b) / MegaByte
unit = "MB"
case b >= KiloByte:
value = float64(b) / KiloByte
unit = "KB"
default:
return fmt.Sprintf("%d B", b)
}
switch {
case value >= 10:
return fmt.Sprintf("%d %s", int(value), unit)
case value != math.Trunc(value):
return fmt.Sprintf("%.1f %s", value, unit)
default:
return fmt.Sprintf("%d %s", int(value), unit)
}
}
##CHUNK 3
func HumanBytes2(b uint64) string {
switch {
case b >= GibiByte:
return fmt.Sprintf("%.1f GiB", float64(b)/GibiByte)
case b >= MebiByte:
return fmt.Sprintf("%.1f MiB", float64(b)/MebiByte)
case b >= KibiByte:
return fmt.Sprintf("%.1f KiB", float64(b)/KibiByte)
default:
return fmt.Sprintf("%d B", b)
}
}
##CHUNK 4
func HumanBytes(b int64) string {
var value float64
var unit string
switch {
case b >= TeraByte:
value = float64(b) / TeraByte
unit = "TB"
case b >= GigaByte:
value = float64(b) / GigaByte
unit = "GB"
case b >= MegaByte:
value = float64(b) / MegaByte
unit = "MB"
case b >= KiloByte:
value = float64(b) / KiloByte
unit = "KB"
default:
return fmt.Sprintf("%d B", b)
}
#FILE: ollama-main/fs/ggml/gguf.go
##CHUNK 1
switch llm.Version {
case 1:
return uint64(llm.V1.NumKV)
case 2:
return llm.V2.NumKV
default:
return llm.V3.NumKV
}
}
func (llm *gguf) Decode(rs io.ReadSeeker) error {
// decode key-values
for i := 0; uint64(i) < llm.numKV(); i++ {
k, err := readGGUFString(llm, rs)
if err != nil {
return err
}
t, err := readGGUF[uint32](llm, rs)
if err != nil {
##CHUNK 2
case 1:
return uint64(llm.V1.NumTensor)
case 2:
return llm.V2.NumTensor
default:
return llm.V3.NumTensor
}
}
func (llm *gguf) numKV() uint64 {
switch llm.Version {
case 1:
return uint64(llm.V1.NumKV)
case 2:
return llm.V2.NumKV
default:
return llm.V3.NumKV
}
}
#FILE: ollama-main/convert/sentencepiece/sentencepiece_model.pb.go
##CHUNK 1
file_sentencepiece_model_proto_msgTypes[4].Exporter = func(v any, i int) any {
switch v := v.(*SelfTestData_Sample); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_sentencepiece_model_proto_msgTypes[5].Exporter = func(v any, i int) any {
switch v := v.(*ModelProto_SentencePiece); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
##CHUNK 2
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
case 3:
return &v.extensionFields
default:
return nil
}
}
file_sentencepiece_model_proto_msgTypes[2].Exporter = func(v any, i int) any {
switch v := v.(*SelfTestData); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
##CHUNK 3
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
case 3:
return &v.extensionFields
default:
return nil
}
}
file_sentencepiece_model_proto_msgTypes[4].Exporter = func(v any, i int) any {
switch v := v.(*SelfTestData_Sample); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
##CHUNK 4
}
}
file_sentencepiece_model_proto_msgTypes[2].Exporter = func(v any, i int) any {
switch v := v.(*SelfTestData); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
case 3:
return &v.extensionFields
default:
return nil
}
}
file_sentencepiece_model_proto_msgTypes[3].Exporter = func(v any, i int) any {
switch v := v.(*ModelProto); i {
case 0:
return &v.state
#CURRENT FILE: ollama-main/format/time.go
|
ollama-main
| 77
|
func fileDigestMap(path string) (map[string]string, error) {
fl := make(map[string]string)
fi, err := os.Stat(path)
if err != nil {
return nil, err
}
var files []string
if fi.IsDir() {
fs, err := filesForModel(path)
if err != nil {
return nil, err
}
for _, f := range fs {
f, err := filepath.EvalSymlinks(f)
if err != nil {
return nil, err
}
rel, err := filepath.Rel(path, f)
if err != nil {
return nil, err
}
if !filepath.IsLocal(rel) {
return nil, fmt.Errorf("insecure path: %s", rel)
}
files = append(files, f)
}
} else {
files = []string{path}
}
var mu sync.Mutex
var g errgroup.Group
g.SetLimit(max(runtime.GOMAXPROCS(0)-1, 1))
for _, f := range files {
g.Go(func() error {
digest, err := digestForFile(f)
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
fl[f] = digest
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return fl, nil
}
|
func fileDigestMap(path string) (map[string]string, error) {
fl := make(map[string]string)
fi, err := os.Stat(path)
if err != nil {
return nil, err
}
var files []string
if fi.IsDir() {
fs, err := filesForModel(path)
if err != nil {
return nil, err
}
for _, f := range fs {
f, err := filepath.EvalSymlinks(f)
if err != nil {
return nil, err
}
rel, err := filepath.Rel(path, f)
if err != nil {
return nil, err
}
if !filepath.IsLocal(rel) {
return nil, fmt.Errorf("insecure path: %s", rel)
}
files = append(files, f)
}
} else {
files = []string{path}
}
var mu sync.Mutex
var g errgroup.Group
g.SetLimit(max(runtime.GOMAXPROCS(0)-1, 1))
for _, f := range files {
g.Go(func() error {
digest, err := digestForFile(f)
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
fl[f] = digest
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return fl, nil
}
|
func fileDigestMap(path string) (map[string]string, error) {
fl := make(map[string]string)
fi, err := os.Stat(path)
if err != nil {
return nil, err
}
var files []string
if fi.IsDir() {
fs, err := filesForModel(path)
if err != nil {
return nil, err
}
for _, f := range fs {
f, err := filepath.EvalSymlinks(f)
if err != nil {
return nil, err
}
rel, err := filepath.Rel(path, f)
if err != nil {
return nil, err
}
if !filepath.IsLocal(rel) {
return nil, fmt.Errorf("insecure path: %s", rel)
}
files = append(files, f)
}
} else {
files = []string{path}
}
var mu sync.Mutex
var g errgroup.Group
g.SetLimit(max(runtime.GOMAXPROCS(0)-1, 1))
for _, f := range files {
g.Go(func() error {
digest, err := digestForFile(f)
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
fl[f] = digest
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return fl, nil
}
|
fileDigestMap
| 141
| 199
|
parser/parser.go
|
#FILE: ollama-main/cmd/cmd.go
##CHUNK 1
if quantize != "" {
req.Quantize = quantize
}
client, err := api.ClientFromEnvironment()
if err != nil {
return err
}
var g errgroup.Group
g.SetLimit(max(runtime.GOMAXPROCS(0)-1, 1))
files := syncmap.NewSyncMap[string, string]()
for f, digest := range req.Files {
g.Go(func() error {
if _, err := createBlob(cmd, client, f, digest, p); err != nil {
return err
}
// TODO: this is incorrect since the file might be in a subdirectory
#FILE: ollama-main/server/create.go
##CHUNK 1
}
var digest string
var allLayers []*layerGGML
for _, v := range files {
digest = v
layers, err := ggufLayers(digest, fn)
if err != nil {
return nil, err
}
allLayers = append(allLayers, layers...)
}
return allLayers, nil
default:
return nil, errUnknownType
}
}
func detectModelTypeFromFiles(files map[string]string) string {
for fn := range files {
##CHUNK 2
if err != nil {
slog.Error("error converting from safetensors", "error", err)
return nil, err
}
return layers, nil
case "gguf":
if len(files) == 0 {
return nil, errNoFilesProvided
} else if len(files) > 1 && isAdapter {
return nil, errOnlyOneAdapterSupported
}
var digest string
var allLayers []*layerGGML
for _, v := range files {
digest = v
layers, err := ggufLayers(digest, fn)
if err != nil {
return nil, err
}
##CHUNK 3
}
defer os.RemoveAll(tmpDir)
// Set up a root to validate paths
root, err := os.OpenRoot(tmpDir)
if err != nil {
return nil, err
}
defer root.Close()
for fp, digest := range files {
if !fs.ValidPath(fp) {
return nil, fmt.Errorf("%w: %s", errFilePath, fp)
}
if _, err := root.Stat(fp); err != nil && !errors.Is(err, fs.ErrNotExist) {
// Path is likely outside the root
return nil, fmt.Errorf("%w: %s: %s", errFilePath, err, fp)
}
blobPath, err := GetBlobsPath(digest)
if err != nil {
##CHUNK 4
}
}
return ""
}
func convertFromSafetensors(files map[string]string, baseLayers []*layerGGML, isAdapter bool, fn func(resp api.ProgressResponse)) ([]*layerGGML, error) {
tmpDir, err := os.MkdirTemp(envconfig.Models(), "ollama-safetensors")
if err != nil {
return nil, err
}
defer os.RemoveAll(tmpDir)
// Set up a root to validate paths
root, err := os.OpenRoot(tmpDir)
if err != nil {
return nil, err
}
defer root.Close()
for fp, digest := range files {
#FILE: ollama-main/convert/tokenizer.go
##CHUNK 1
}
t := &Tokenizer{
Vocabulary: v,
Pre: "default",
}
addedTokens := make(map[string]token)
if f, err := fsys.Open("tokenizer.json"); errors.Is(err, os.ErrNotExist) {
} else if err != nil {
return nil, err
} else {
defer f.Close()
var tt tokenizer
if err := json.NewDecoder(f).Decode(&tt); err != nil {
return nil, err
}
for _, t := range tt.AddedTokens {
##CHUNK 2
}
}
}
if f, err := fsys.Open("generation_config.json"); errors.Is(err, os.ErrNotExist) {
} else if err != nil {
return nil, err
} else {
defer f.Close()
var p map[string]json.RawMessage
if err := json.NewDecoder(f).Decode(&p); err != nil {
return nil, err
}
for _, st := range specialTokenTypes {
if bts, ok := p[fmt.Sprintf("%s_token_id", st)]; ok {
var ids []int32
if err := json.Unmarshal(bts, &ids); err != nil {
// value is not a list so the existing ID is used
#FILE: ollama-main/server/manifest.go
##CHUNK 1
}
p := filepath.Join(manifests, n.Filepath())
var m Manifest
f, err := os.Open(p)
if err != nil {
return nil, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return nil, err
}
sha256sum := sha256.New()
if err := json.NewDecoder(io.TeeReader(f, sha256sum)).Decode(&m); err != nil {
return nil, err
}
##CHUNK 2
// TODO(mxyng): use something less brittle
matches, err := filepath.Glob(filepath.Join(manifests, "*", "*", "*", "*"))
if err != nil {
return nil, err
}
ms := make(map[model.Name]*Manifest)
for _, match := range matches {
fi, err := os.Stat(match)
if err != nil {
return nil, err
}
if !fi.IsDir() {
rel, err := filepath.Rel(manifests, match)
if err != nil {
if !continueOnError {
return nil, fmt.Errorf("%s %w", match, err)
}
#CURRENT FILE: ollama-main/parser/parser.go
##CHUNK 1
glob := func(pattern, contentType string) ([]string, error) {
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
for _, match := range matches {
if ct, err := detectContentType(match); err != nil {
return nil, err
} else if ct != contentType {
return nil, fmt.Errorf("invalid content type: expected %s for %s", ct, match)
}
}
return matches, nil
}
var files []string
if st, _ := glob(filepath.Join(path, "*.safetensors"), "application/octet-stream"); len(st) > 0 {
// safetensors files might be unresolved git lfs references; skip if they are
|
ollama-main
| 78
|
func filesForModel(path string) ([]string, error) {
detectContentType := func(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
var b bytes.Buffer
b.Grow(512)
if _, err := io.CopyN(&b, f, 512); err != nil && !errors.Is(err, io.EOF) {
return "", err
}
contentType, _, _ := strings.Cut(http.DetectContentType(b.Bytes()), ";")
return contentType, nil
}
glob := func(pattern, contentType string) ([]string, error) {
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
for _, match := range matches {
if ct, err := detectContentType(match); err != nil {
return nil, err
} else if ct != contentType {
return nil, fmt.Errorf("invalid content type: expected %s for %s", ct, match)
}
}
return matches, nil
}
var files []string
if st, _ := glob(filepath.Join(path, "*.safetensors"), "application/octet-stream"); len(st) > 0 {
// safetensors files might be unresolved git lfs references; skip if they are
// covers model-x-of-y.safetensors, model.fp32-x-of-y.safetensors, model.safetensors
files = append(files, st...)
} else if pt, _ := glob(filepath.Join(path, "pytorch_model*.bin"), "application/zip"); len(pt) > 0 {
// pytorch files might also be unresolved git lfs references; skip if they are
// covers pytorch_model-x-of-y.bin, pytorch_model.fp32-x-of-y.bin, pytorch_model.bin
files = append(files, pt...)
} else if pt, _ := glob(filepath.Join(path, "consolidated*.pth"), "application/zip"); len(pt) > 0 {
// pytorch files might also be unresolved git lfs references; skip if they are
// covers consolidated.x.pth, consolidated.pth
files = append(files, pt...)
} else if gg, _ := glob(filepath.Join(path, "*.gguf"), "application/octet-stream"); len(gg) > 0 {
// covers gguf files ending in .gguf
files = append(files, gg...)
} else if gg, _ := glob(filepath.Join(path, "*.bin"), "application/octet-stream"); len(gg) > 0 {
// covers gguf files ending in .bin
files = append(files, gg...)
} else {
return nil, ErrModelNotFound
}
// add configuration files, json files are detected as text/plain
js, err := glob(filepath.Join(path, "*.json"), "text/plain")
if err != nil {
return nil, err
}
files = append(files, js...)
// bert models require a nested config.json
// TODO(mxyng): merge this with the glob above
js, err = glob(filepath.Join(path, "**/*.json"), "text/plain")
if err != nil {
return nil, err
}
files = append(files, js...)
// only include tokenizer.model is tokenizer.json is not present
if !slices.ContainsFunc(files, func(s string) bool {
return slices.Contains(strings.Split(s, string(os.PathSeparator)), "tokenizer.json")
}) {
if tks, _ := glob(filepath.Join(path, "tokenizer.model"), "application/octet-stream"); len(tks) > 0 {
// add tokenizer.model if it exists, tokenizer.json is automatically picked up by the previous glob
// tokenizer.model might be a unresolved git lfs reference; error if it is
files = append(files, tks...)
} else if tks, _ := glob(filepath.Join(path, "**/tokenizer.model"), "text/plain"); len(tks) > 0 {
// some times tokenizer.model is in a subdirectory (e.g. meta-llama/Meta-Llama-3-8B)
files = append(files, tks...)
}
}
return files, nil
}
|
func filesForModel(path string) ([]string, error) {
detectContentType := func(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
var b bytes.Buffer
b.Grow(512)
if _, err := io.CopyN(&b, f, 512); err != nil && !errors.Is(err, io.EOF) {
return "", err
}
contentType, _, _ := strings.Cut(http.DetectContentType(b.Bytes()), ";")
return contentType, nil
}
glob := func(pattern, contentType string) ([]string, error) {
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
for _, match := range matches {
if ct, err := detectContentType(match); err != nil {
return nil, err
} else if ct != contentType {
return nil, fmt.Errorf("invalid content type: expected %s for %s", ct, match)
}
}
return matches, nil
}
var files []string
if st, _ := glob(filepath.Join(path, "*.safetensors"), "application/octet-stream"); len(st) > 0 {
// safetensors files might be unresolved git lfs references; skip if they are
// covers model-x-of-y.safetensors, model.fp32-x-of-y.safetensors, model.safetensors
files = append(files, st...)
} else if pt, _ := glob(filepath.Join(path, "pytorch_model*.bin"), "application/zip"); len(pt) > 0 {
// pytorch files might also be unresolved git lfs references; skip if they are
// covers pytorch_model-x-of-y.bin, pytorch_model.fp32-x-of-y.bin, pytorch_model.bin
files = append(files, pt...)
} else if pt, _ := glob(filepath.Join(path, "consolidated*.pth"), "application/zip"); len(pt) > 0 {
// pytorch files might also be unresolved git lfs references; skip if they are
// covers consolidated.x.pth, consolidated.pth
files = append(files, pt...)
} else if gg, _ := glob(filepath.Join(path, "*.gguf"), "application/octet-stream"); len(gg) > 0 {
// covers gguf files ending in .gguf
files = append(files, gg...)
} else if gg, _ := glob(filepath.Join(path, "*.bin"), "application/octet-stream"); len(gg) > 0 {
// covers gguf files ending in .bin
files = append(files, gg...)
} else {
return nil, ErrModelNotFound
}
// add configuration files, json files are detected as text/plain
js, err := glob(filepath.Join(path, "*.json"), "text/plain")
if err != nil {
return nil, err
}
files = append(files, js...)
// bert models require a nested config.json
// TODO(mxyng): merge this with the glob above
js, err = glob(filepath.Join(path, "**/*.json"), "text/plain")
if err != nil {
return nil, err
}
files = append(files, js...)
// only include tokenizer.model is tokenizer.json is not present
if !slices.ContainsFunc(files, func(s string) bool {
return slices.Contains(strings.Split(s, string(os.PathSeparator)), "tokenizer.json")
}) {
if tks, _ := glob(filepath.Join(path, "tokenizer.model"), "application/octet-stream"); len(tks) > 0 {
// add tokenizer.model if it exists, tokenizer.json is automatically picked up by the previous glob
// tokenizer.model might be a unresolved git lfs reference; error if it is
files = append(files, tks...)
} else if tks, _ := glob(filepath.Join(path, "**/tokenizer.model"), "text/plain"); len(tks) > 0 {
// some times tokenizer.model is in a subdirectory (e.g. meta-llama/Meta-Llama-3-8B)
files = append(files, tks...)
}
}
return files, nil
}
|
func filesForModel(path string) ([]string, error) {
detectContentType := func(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
var b bytes.Buffer
b.Grow(512)
if _, err := io.CopyN(&b, f, 512); err != nil && !errors.Is(err, io.EOF) {
return "", err
}
contentType, _, _ := strings.Cut(http.DetectContentType(b.Bytes()), ";")
return contentType, nil
}
glob := func(pattern, contentType string) ([]string, error) {
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
for _, match := range matches {
if ct, err := detectContentType(match); err != nil {
return nil, err
} else if ct != contentType {
return nil, fmt.Errorf("invalid content type: expected %s for %s", ct, match)
}
}
return matches, nil
}
var files []string
if st, _ := glob(filepath.Join(path, "*.safetensors"), "application/octet-stream"); len(st) > 0 {
// safetensors files might be unresolved git lfs references; skip if they are
// covers model-x-of-y.safetensors, model.fp32-x-of-y.safetensors, model.safetensors
files = append(files, st...)
} else if pt, _ := glob(filepath.Join(path, "pytorch_model*.bin"), "application/zip"); len(pt) > 0 {
// pytorch files might also be unresolved git lfs references; skip if they are
// covers pytorch_model-x-of-y.bin, pytorch_model.fp32-x-of-y.bin, pytorch_model.bin
files = append(files, pt...)
} else if pt, _ := glob(filepath.Join(path, "consolidated*.pth"), "application/zip"); len(pt) > 0 {
// pytorch files might also be unresolved git lfs references; skip if they are
// covers consolidated.x.pth, consolidated.pth
files = append(files, pt...)
} else if gg, _ := glob(filepath.Join(path, "*.gguf"), "application/octet-stream"); len(gg) > 0 {
// covers gguf files ending in .gguf
files = append(files, gg...)
} else if gg, _ := glob(filepath.Join(path, "*.bin"), "application/octet-stream"); len(gg) > 0 {
// covers gguf files ending in .bin
files = append(files, gg...)
} else {
return nil, ErrModelNotFound
}
// add configuration files, json files are detected as text/plain
js, err := glob(filepath.Join(path, "*.json"), "text/plain")
if err != nil {
return nil, err
}
files = append(files, js...)
// bert models require a nested config.json
// TODO(mxyng): merge this with the glob above
js, err = glob(filepath.Join(path, "**/*.json"), "text/plain")
if err != nil {
return nil, err
}
files = append(files, js...)
// only include tokenizer.model is tokenizer.json is not present
if !slices.ContainsFunc(files, func(s string) bool {
return slices.Contains(strings.Split(s, string(os.PathSeparator)), "tokenizer.json")
}) {
if tks, _ := glob(filepath.Join(path, "tokenizer.model"), "application/octet-stream"); len(tks) > 0 {
// add tokenizer.model if it exists, tokenizer.json is automatically picked up by the previous glob
// tokenizer.model might be a unresolved git lfs reference; error if it is
files = append(files, tks...)
} else if tks, _ := glob(filepath.Join(path, "**/tokenizer.model"), "text/plain"); len(tks) > 0 {
// some times tokenizer.model is in a subdirectory (e.g. meta-llama/Meta-Llama-3-8B)
files = append(files, tks...)
}
}
return files, nil
}
|
filesForModel
| 220
| 309
|
parser/parser.go
|
#FILE: ollama-main/cmd/cmd.go
##CHUNK 1
if quantize != "" {
req.Quantize = quantize
}
client, err := api.ClientFromEnvironment()
if err != nil {
return err
}
var g errgroup.Group
g.SetLimit(max(runtime.GOMAXPROCS(0)-1, 1))
files := syncmap.NewSyncMap[string, string]()
for f, digest := range req.Files {
g.Go(func() error {
if _, err := createBlob(cmd, client, f, digest, p); err != nil {
return err
}
// TODO: this is incorrect since the file might be in a subdirectory
#FILE: ollama-main/server/create.go
##CHUNK 1
if err != nil {
slog.Error("error converting from safetensors", "error", err)
return nil, err
}
return layers, nil
case "gguf":
if len(files) == 0 {
return nil, errNoFilesProvided
} else if len(files) > 1 && isAdapter {
return nil, errOnlyOneAdapterSupported
}
var digest string
var allLayers []*layerGGML
for _, v := range files {
digest = v
layers, err := ggufLayers(digest, fn)
if err != nil {
return nil, err
}
##CHUNK 2
}
defer os.RemoveAll(tmpDir)
// Set up a root to validate paths
root, err := os.OpenRoot(tmpDir)
if err != nil {
return nil, err
}
defer root.Close()
for fp, digest := range files {
if !fs.ValidPath(fp) {
return nil, fmt.Errorf("%w: %s", errFilePath, fp)
}
if _, err := root.Stat(fp); err != nil && !errors.Is(err, fs.ErrNotExist) {
// Path is likely outside the root
return nil, fmt.Errorf("%w: %s: %s", errFilePath, err, fp)
}
blobPath, err := GetBlobsPath(digest)
if err != nil {
##CHUNK 3
}
var digest string
var allLayers []*layerGGML
for _, v := range files {
digest = v
layers, err := ggufLayers(digest, fn)
if err != nil {
return nil, err
}
allLayers = append(allLayers, layers...)
}
return allLayers, nil
default:
return nil, errUnknownType
}
}
func detectModelTypeFromFiles(files map[string]string) string {
for fn := range files {
#FILE: ollama-main/discover/amd_common.go
##CHUNK 1
}
}
return true
}
func GetSupportedGFX(libDir string) ([]string, error) {
var ret []string
files, err := filepath.Glob(filepath.Join(libDir, "rocblas", "library", "TensileLibrary_lazy_gfx*.dat"))
if err != nil {
return nil, err
}
for _, file := range files {
ret = append(ret, strings.TrimSuffix(strings.TrimPrefix(filepath.Base(file), "TensileLibrary_lazy_"), ".dat"))
}
return ret, nil
}
func commonAMDValidateLibDir() (string, error) {
// Favor our bundled version
#FILE: ollama-main/convert/tokenizer_test.go
##CHUNK 1
"github.com/google/go-cmp/cmp"
)
func createTokenizerFS(t *testing.T, dir string, files map[string]io.Reader) fs.FS {
t.Helper()
for k, v := range files {
if err := func() error {
f, err := os.Create(filepath.Join(dir, k))
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(f, v); err != nil {
return err
}
return nil
}(); err != nil {
#CURRENT FILE: ollama-main/parser/parser.go
##CHUNK 1
}
rel, err := filepath.Rel(path, f)
if err != nil {
return nil, err
}
if !filepath.IsLocal(rel) {
return nil, fmt.Errorf("insecure path: %s", rel)
}
files = append(files, f)
}
} else {
files = []string{path}
}
var mu sync.Mutex
var g errgroup.Group
g.SetLimit(max(runtime.GOMAXPROCS(0)-1, 1))
##CHUNK 2
files = append(files, f)
}
} else {
files = []string{path}
}
var mu sync.Mutex
var g errgroup.Group
g.SetLimit(max(runtime.GOMAXPROCS(0)-1, 1))
for _, f := range files {
g.Go(func() error {
digest, err := digestForFile(f)
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
fl[f] = digest
##CHUNK 3
}
if len(messages) > 0 {
req.Messages = messages
}
if len(licenses) > 0 {
req.License = licenses
}
return req, nil
}
func fileDigestMap(path string) (map[string]string, error) {
fl := make(map[string]string)
fi, err := os.Stat(path)
if err != nil {
return nil, err
}
var files []string
##CHUNK 4
func fileDigestMap(path string) (map[string]string, error) {
fl := make(map[string]string)
fi, err := os.Stat(path)
if err != nil {
return nil, err
}
var files []string
if fi.IsDir() {
fs, err := filesForModel(path)
if err != nil {
return nil, err
}
for _, f := range fs {
f, err := filepath.EvalSymlinks(f)
if err != nil {
return nil, err
|
ollama-main
| 79
|
func ParseFile(r io.Reader) (*Modelfile, error) {
var cmd Command
var curr state
var currLine int = 1
var b bytes.Buffer
var role string
var f Modelfile
tr := unicode.BOMOverride(unicode.UTF8.NewDecoder())
br := bufio.NewReader(transform.NewReader(r, tr))
for {
r, _, err := br.ReadRune()
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, err
}
if isNewline(r) {
currLine++
}
next, r, err := parseRuneForState(r, curr)
if errors.Is(err, io.ErrUnexpectedEOF) {
return nil, fmt.Errorf("%w: %s", err, b.String())
} else if err != nil {
return nil, &ParserError{
LineNumber: currLine,
Msg: err.Error(),
}
}
// process the state transition, some transitions need to be intercepted and redirected
if next != curr {
switch curr {
case stateName:
if !isValidCommand(b.String()) {
return nil, &ParserError{
LineNumber: currLine,
Msg: errInvalidCommand.Error(),
}
}
// next state sometimes depends on the current buffer value
switch s := strings.ToLower(b.String()); s {
case "from":
cmd.Name = "model"
case "parameter":
// transition to stateParameter which sets command name
next = stateParameter
case "message":
// transition to stateMessage which validates the message role
next = stateMessage
fallthrough
default:
cmd.Name = s
}
case stateParameter:
cmd.Name = b.String()
case stateMessage:
if !isValidMessageRole(b.String()) {
return nil, &ParserError{
LineNumber: currLine,
Msg: errInvalidMessageRole.Error(),
}
}
role = b.String()
case stateComment, stateNil:
// pass
case stateValue:
s, ok := unquote(strings.TrimSpace(b.String()))
if !ok || isSpace(r) {
if _, err := b.WriteRune(r); err != nil {
return nil, err
}
continue
}
if role != "" {
s = role + ": " + s
role = ""
}
cmd.Args = s
f.Commands = append(f.Commands, cmd)
}
b.Reset()
curr = next
}
if strconv.IsPrint(r) {
if _, err := b.WriteRune(r); err != nil {
return nil, err
}
}
}
// flush the buffer
switch curr {
case stateComment, stateNil:
// pass; nothing to flush
case stateValue:
s, ok := unquote(strings.TrimSpace(b.String()))
if !ok {
return nil, io.ErrUnexpectedEOF
}
if role != "" {
s = role + ": " + s
}
cmd.Args = s
f.Commands = append(f.Commands, cmd)
default:
return nil, io.ErrUnexpectedEOF
}
for _, cmd := range f.Commands {
if cmd.Name == "model" {
return &f, nil
}
}
return nil, errMissingFrom
}
|
func ParseFile(r io.Reader) (*Modelfile, error) {
var cmd Command
var curr state
var currLine int = 1
var b bytes.Buffer
var role string
var f Modelfile
tr := unicode.BOMOverride(unicode.UTF8.NewDecoder())
br := bufio.NewReader(transform.NewReader(r, tr))
for {
r, _, err := br.ReadRune()
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, err
}
if isNewline(r) {
currLine++
}
next, r, err := parseRuneForState(r, curr)
if errors.Is(err, io.ErrUnexpectedEOF) {
return nil, fmt.Errorf("%w: %s", err, b.String())
} else if err != nil {
return nil, &ParserError{
LineNumber: currLine,
Msg: err.Error(),
}
}
// process the state transition, some transitions need to be intercepted and redirected
if next != curr {
switch curr {
case stateName:
if !isValidCommand(b.String()) {
return nil, &ParserError{
LineNumber: currLine,
Msg: errInvalidCommand.Error(),
}
}
// next state sometimes depends on the current buffer value
switch s := strings.ToLower(b.String()); s {
case "from":
cmd.Name = "model"
case "parameter":
// transition to stateParameter which sets command name
next = stateParameter
case "message":
// transition to stateMessage which validates the message role
next = stateMessage
fallthrough
default:
cmd.Name = s
}
case stateParameter:
cmd.Name = b.String()
case stateMessage:
if !isValidMessageRole(b.String()) {
return nil, &ParserError{
LineNumber: currLine,
Msg: errInvalidMessageRole.Error(),
}
}
role = b.String()
case stateComment, stateNil:
// pass
case stateValue:
s, ok := unquote(strings.TrimSpace(b.String()))
if !ok || isSpace(r) {
if _, err := b.WriteRune(r); err != nil {
return nil, err
}
continue
}
if role != "" {
s = role + ": " + s
role = ""
}
cmd.Args = s
f.Commands = append(f.Commands, cmd)
}
b.Reset()
curr = next
}
if strconv.IsPrint(r) {
if _, err := b.WriteRune(r); err != nil {
return nil, err
}
}
}
// flush the buffer
switch curr {
case stateComment, stateNil:
// pass; nothing to flush
case stateValue:
s, ok := unquote(strings.TrimSpace(b.String()))
if !ok {
return nil, io.ErrUnexpectedEOF
}
if role != "" {
s = role + ": " + s
}
cmd.Args = s
f.Commands = append(f.Commands, cmd)
default:
return nil, io.ErrUnexpectedEOF
}
for _, cmd := range f.Commands {
if cmd.Name == "model" {
return &f, nil
}
}
return nil, errMissingFrom
}
|
func ParseFile(r io.Reader) (*Modelfile, error) {
var cmd Command
var curr state
var currLine int = 1
var b bytes.Buffer
var role string
var f Modelfile
tr := unicode.BOMOverride(unicode.UTF8.NewDecoder())
br := bufio.NewReader(transform.NewReader(r, tr))
for {
r, _, err := br.ReadRune()
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, err
}
if isNewline(r) {
currLine++
}
next, r, err := parseRuneForState(r, curr)
if errors.Is(err, io.ErrUnexpectedEOF) {
return nil, fmt.Errorf("%w: %s", err, b.String())
} else if err != nil {
return nil, &ParserError{
LineNumber: currLine,
Msg: err.Error(),
}
}
// process the state transition, some transitions need to be intercepted and redirected
if next != curr {
switch curr {
case stateName:
if !isValidCommand(b.String()) {
return nil, &ParserError{
LineNumber: currLine,
Msg: errInvalidCommand.Error(),
}
}
// next state sometimes depends on the current buffer value
switch s := strings.ToLower(b.String()); s {
case "from":
cmd.Name = "model"
case "parameter":
// transition to stateParameter which sets command name
next = stateParameter
case "message":
// transition to stateMessage which validates the message role
next = stateMessage
fallthrough
default:
cmd.Name = s
}
case stateParameter:
cmd.Name = b.String()
case stateMessage:
if !isValidMessageRole(b.String()) {
return nil, &ParserError{
LineNumber: currLine,
Msg: errInvalidMessageRole.Error(),
}
}
role = b.String()
case stateComment, stateNil:
// pass
case stateValue:
s, ok := unquote(strings.TrimSpace(b.String()))
if !ok || isSpace(r) {
if _, err := b.WriteRune(r); err != nil {
return nil, err
}
continue
}
if role != "" {
s = role + ": " + s
role = ""
}
cmd.Args = s
f.Commands = append(f.Commands, cmd)
}
b.Reset()
curr = next
}
if strconv.IsPrint(r) {
if _, err := b.WriteRune(r); err != nil {
return nil, err
}
}
}
// flush the buffer
switch curr {
case stateComment, stateNil:
// pass; nothing to flush
case stateValue:
s, ok := unquote(strings.TrimSpace(b.String()))
if !ok {
return nil, io.ErrUnexpectedEOF
}
if role != "" {
s = role + ": " + s
}
cmd.Args = s
f.Commands = append(f.Commands, cmd)
default:
return nil, io.ErrUnexpectedEOF
}
for _, cmd := range f.Commands {
if cmd.Name == "model" {
return &f, nil
}
}
return nil, errMissingFrom
}
|
ParseFile
| 362
| 491
|
parser/parser.go
|
#FILE: ollama-main/convert/tokenizer_spm.go
##CHUNK 1
switch st := m.AdditionalSpecialTokens.(type) {
case []string:
for _, s := range st {
ast = append(ast, specialToken{Content: s})
}
case []any:
for _, s := range st {
// marshal and unmarshal the object to get the special token
tMap := s.(map[string]any)
data, err := json.Marshal(tMap)
if err != nil {
return nil, err
}
var token specialToken
err = json.Unmarshal(data, &token)
if err != nil {
return nil, err
}
##CHUNK 2
var m struct {
AdditionalSpecialTokens any `json:"additional_special_tokens"`
}
if err := json.NewDecoder(f).Decode(&m); err != nil {
return nil, err
}
var ast []specialToken
switch st := m.AdditionalSpecialTokens.(type) {
case []string:
for _, s := range st {
ast = append(ast, specialToken{Content: s})
}
case []any:
for _, s := range st {
// marshal and unmarshal the object to get the special token
tMap := s.(map[string]any)
data, err := json.Marshal(tMap)
#FILE: ollama-main/convert/tokenizer.go
##CHUNK 1
return nil, err
}
if template, ok := p["chat_template"]; ok {
var s []struct {
Name string `json:"name"`
Template string `json:"template"`
}
if err := json.Unmarshal(template, &t.Template); err == nil {
// noop
} else if err := json.Unmarshal(template, &s); err == nil {
for _, e := range s {
if e.Name == "default" {
t.Template = e.Template
break
}
}
} else {
return nil, fmt.Errorf("invalid chat_template: %w", err)
}
##CHUNK 2
if f, err := fsys.Open("tokenizer_config.json"); errors.Is(err, os.ErrNotExist) {
// noop
} else if err != nil {
return nil, err
} else {
defer f.Close()
var p map[string]json.RawMessage
if err := json.NewDecoder(f).Decode(&p); err != nil {
return nil, err
}
if template, ok := p["chat_template"]; ok {
var s []struct {
Name string `json:"name"`
Template string `json:"template"`
}
if err := json.Unmarshal(template, &t.Template); err == nil {
// noop
##CHUNK 3
} else if err := json.Unmarshal(template, &s); err == nil {
for _, e := range s {
if e.Name == "default" {
t.Template = e.Template
break
}
}
} else {
return nil, fmt.Errorf("invalid chat_template: %w", err)
}
}
for _, st := range specialTokenTypes {
sv := SpecialVocabulary{Type: st}
if bts, ok := p[fmt.Sprintf("add_%s_token", st)]; ok {
if err := json.Unmarshal(bts, &sv.AddToken); err != nil {
return nil, err
}
}
#FILE: ollama-main/openai/openai.go
##CHUNK 1
case []any:
for _, c := range content {
data, ok := c.(map[string]any)
if !ok {
return nil, errors.New("invalid message format")
}
switch data["type"] {
case "text":
text, ok := data["text"].(string)
if !ok {
return nil, errors.New("invalid message format")
}
messages = append(messages, api.Message{Role: msg.Role, Content: text})
case "image_url":
var url string
if urlMap, ok := data["image_url"].(map[string]any); ok {
if url, ok = urlMap["url"].(string); !ok {
return nil, errors.New("invalid message format")
}
} else {
##CHUNK 2
return nil, errors.New("invalid message format")
}
messages = append(messages, api.Message{Role: msg.Role, Content: text})
case "image_url":
var url string
if urlMap, ok := data["image_url"].(map[string]any); ok {
if url, ok = urlMap["url"].(string); !ok {
return nil, errors.New("invalid message format")
}
} else {
if url, ok = data["image_url"].(string); !ok {
return nil, errors.New("invalid message format")
}
}
types := []string{"jpeg", "jpg", "png"}
valid := false
for _, t := range types {
prefix := "data:image/" + t + ";base64,"
if strings.HasPrefix(url, prefix) {
#FILE: ollama-main/template/template.go
##CHUNK 1
func Named(s string) (*named, error) {
templates, err := templatesOnce()
if err != nil {
return nil, err
}
var template *named
score := math.MaxInt
for _, t := range templates {
if s := levenshtein.ComputeDistance(s, t.Template); s < score {
score = s
template = t
}
}
if score < 100 {
return template, nil
}
return nil, errors.New("no matching template found")
#FILE: ollama-main/api/types.go
##CHUNK 1
}
}
out := make(map[string]any)
// iterate params and set values based on json struct tags
for key, vals := range params {
if opt, ok := jsonOpts[key]; !ok {
return nil, fmt.Errorf("unknown parameter '%s'", key)
} else {
field := valueOpts.FieldByName(opt.Name)
if field.IsValid() && field.CanSet() {
switch field.Kind() {
case reflect.Float32:
floatVal, err := strconv.ParseFloat(vals[0], 32)
if err != nil {
return nil, fmt.Errorf("invalid float value %s", vals)
}
out[key] = float32(floatVal)
case reflect.Int:
#CURRENT FILE: ollama-main/parser/parser.go
##CHUNK 1
for _, c := range f.Commands {
switch c.Name {
case "model":
path, err := expandPath(c.Args, relativeDir)
if err != nil {
return nil, err
}
digestMap, err := fileDigestMap(path)
if errors.Is(err, os.ErrNotExist) {
req.From = c.Args
continue
} else if err != nil {
return nil, err
}
if req.Files == nil {
req.Files = digestMap
} else {
|
ollama-main
| 80
|
func parseRuneForState(r rune, cs state) (state, rune, error) {
switch cs {
case stateNil:
switch {
case r == '#':
return stateComment, 0, nil
case isSpace(r), isNewline(r):
return stateNil, 0, nil
default:
return stateName, r, nil
}
case stateName:
switch {
case isAlpha(r):
return stateName, r, nil
case isSpace(r):
return stateValue, 0, nil
default:
return stateNil, 0, errInvalidCommand
}
case stateValue:
switch {
case isNewline(r):
return stateNil, r, nil
case isSpace(r):
return stateNil, r, nil
default:
return stateValue, r, nil
}
case stateParameter:
switch {
case isAlpha(r), isNumber(r), r == '_':
return stateParameter, r, nil
case isSpace(r):
return stateValue, 0, nil
default:
return stateNil, 0, io.ErrUnexpectedEOF
}
case stateMessage:
switch {
case isAlpha(r):
return stateMessage, r, nil
case isSpace(r):
return stateValue, 0, nil
default:
return stateNil, 0, io.ErrUnexpectedEOF
}
case stateComment:
switch {
case isNewline(r):
return stateNil, 0, nil
default:
return stateComment, 0, nil
}
default:
return stateNil, 0, errors.New("")
}
}
|
func parseRuneForState(r rune, cs state) (state, rune, error) {
switch cs {
case stateNil:
switch {
case r == '#':
return stateComment, 0, nil
case isSpace(r), isNewline(r):
return stateNil, 0, nil
default:
return stateName, r, nil
}
case stateName:
switch {
case isAlpha(r):
return stateName, r, nil
case isSpace(r):
return stateValue, 0, nil
default:
return stateNil, 0, errInvalidCommand
}
case stateValue:
switch {
case isNewline(r):
return stateNil, r, nil
case isSpace(r):
return stateNil, r, nil
default:
return stateValue, r, nil
}
case stateParameter:
switch {
case isAlpha(r), isNumber(r), r == '_':
return stateParameter, r, nil
case isSpace(r):
return stateValue, 0, nil
default:
return stateNil, 0, io.ErrUnexpectedEOF
}
case stateMessage:
switch {
case isAlpha(r):
return stateMessage, r, nil
case isSpace(r):
return stateValue, 0, nil
default:
return stateNil, 0, io.ErrUnexpectedEOF
}
case stateComment:
switch {
case isNewline(r):
return stateNil, 0, nil
default:
return stateComment, 0, nil
}
default:
return stateNil, 0, errors.New("")
}
}
|
func parseRuneForState(r rune, cs state) (state, rune, error) {
switch cs {
case stateNil:
switch {
case r == '#':
return stateComment, 0, nil
case isSpace(r), isNewline(r):
return stateNil, 0, nil
default:
return stateName, r, nil
}
case stateName:
switch {
case isAlpha(r):
return stateName, r, nil
case isSpace(r):
return stateValue, 0, nil
default:
return stateNil, 0, errInvalidCommand
}
case stateValue:
switch {
case isNewline(r):
return stateNil, r, nil
case isSpace(r):
return stateNil, r, nil
default:
return stateValue, r, nil
}
case stateParameter:
switch {
case isAlpha(r), isNumber(r), r == '_':
return stateParameter, r, nil
case isSpace(r):
return stateValue, 0, nil
default:
return stateNil, 0, io.ErrUnexpectedEOF
}
case stateMessage:
switch {
case isAlpha(r):
return stateMessage, r, nil
case isSpace(r):
return stateValue, 0, nil
default:
return stateNil, 0, io.ErrUnexpectedEOF
}
case stateComment:
switch {
case isNewline(r):
return stateNil, 0, nil
default:
return stateComment, 0, nil
}
default:
return stateNil, 0, errors.New("")
}
}
|
parseRuneForState
| 493
| 550
|
parser/parser.go
|
#FILE: ollama-main/convert/reader_safetensors.go
##CHUNK 1
return 0, err
}
}
switch st.Kind() {
case tensorKindF32:
return 0, binary.Write(w, binary.LittleEndian, f32s)
case tensorKindF16:
f16s := make([]uint16, len(f32s))
for i := range f32s {
f16s[i] = float16.Fromfloat32(f32s[i]).Bits()
}
return 0, binary.Write(w, binary.LittleEndian, f16s)
default:
return 0, fmt.Errorf("unknown storage type: %d", st.Kind())
}
}
##CHUNK 2
}
f32s = bfloat16.DecodeFloat32(u8s)
default:
return 0, fmt.Errorf("unknown data type: %s", st.dtype)
}
if st.repacker != nil {
f32s, err = st.repacker(st.Name(), f32s, st.Shape())
if err != nil {
return 0, err
}
}
switch st.Kind() {
case tensorKindF32:
return 0, binary.Write(w, binary.LittleEndian, f32s)
case tensorKindF16:
f16s := make([]uint16, len(f32s))
for i := range f32s {
#FILE: ollama-main/fs/ggml/type.go
##CHUNK 1
case "Q4_K":
return TensorTypeQ4_K, nil
case "Q5_K":
return TensorTypeQ5_K, nil
case "Q6_K":
return TensorTypeQ6_K, nil
case "Q8_K":
return TensorTypeQ8_K, nil
case "F64":
return TensorTypeF64, nil
case "BF16":
return TensorTypeBF16, nil
default:
return 0, fmt.Errorf("unsupported quantization type %s", s)
}
}
func (t TensorType) IsQuantized() bool {
switch t {
case TensorTypeF32, TensorTypeF16, TensorTypeBF16:
##CHUNK 2
case "BF16":
return TensorTypeBF16, nil
default:
return 0, fmt.Errorf("unsupported quantization type %s", s)
}
}
func (t TensorType) IsQuantized() bool {
switch t {
case TensorTypeF32, TensorTypeF16, TensorTypeBF16:
return false
default:
return true
}
}
func (t TensorType) RowSize(ne uint64) uint64 {
return t.TypeSize() * ne / t.BlockSize()
}
#FILE: ollama-main/server/internal/client/ollama/registry_test.go
##CHUNK 1
var step atomic.Int64
c, _ := newRegistryClient(t, func(w http.ResponseWriter, r *http.Request) {
switch step.Add(1) {
case 1:
checkRequest(t, r, "GET", "/v2/library/abc/manifests/latest")
io.WriteString(w, `{"layers":[{"size":3,"digest":"sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}]}`)
case 2:
w.Header().Set("Content-Location", "http://blob.store/v2/library/abc/blobs/sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
fmt.Fprintf(w, "%s 0-1\n", blob.DigestFromBytes("ab"))
fmt.Fprintf(w, "%s 2-2\n", blob.DigestFromBytes("c"))
case 3, 4:
switch rng := r.Header.Get("Range"); rng {
case "bytes=0-1":
io.WriteString(w, "ab")
case "bytes=2-2":
io.WriteString(w, "c")
default:
t.Errorf("unexpected range %q", rng)
}
default:
##CHUNK 2
checkRequest(t, r, "GET", "/v2/library/abc/chunksums/sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
w.Header().Set("Content-Location", "http://blob.store/v2/library/abc/blobs/sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
fmt.Fprintf(w, "%s 0-1\n", blob.DigestFromBytes("ab"))
fmt.Fprintf(w, "%s 2-2\n", blob.DigestFromBytes("c"))
case 3, 4:
checkRequest(t, r, "GET", "/v2/library/abc/blobs/sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
switch rng := r.Header.Get("Range"); rng {
case "bytes=0-1":
io.WriteString(w, "ab")
case "bytes=2-2":
t.Logf("writing c")
io.WriteString(w, "c")
default:
t.Errorf("unexpected range %q", rng)
}
default:
t.Errorf("unexpected steps %d: %v", steps.Load(), r)
http.Error(w, "unexpected steps", http.StatusInternalServerError)
}
})
##CHUNK 3
}
func TestPullChunked(t *testing.T) {
var steps atomic.Int64
c, ctx := newRegistryClient(t, func(w http.ResponseWriter, r *http.Request) {
switch steps.Add(1) {
case 1:
checkRequest(t, r, "GET", "/v2/library/abc/manifests/latest")
io.WriteString(w, `{"layers":[{"size":3,"digest":"sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}]}`)
case 2:
checkRequest(t, r, "GET", "/v2/library/abc/chunksums/sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
w.Header().Set("Content-Location", "http://blob.store/v2/library/abc/blobs/sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
fmt.Fprintf(w, "%s 0-1\n", blob.DigestFromBytes("ab"))
fmt.Fprintf(w, "%s 2-2\n", blob.DigestFromBytes("c"))
case 3, 4:
checkRequest(t, r, "GET", "/v2/library/abc/blobs/sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
switch rng := r.Header.Get("Range"); rng {
case "bytes=0-1":
io.WriteString(w, "ab")
case "bytes=2-2":
#FILE: ollama-main/fs/ggml/gguf.go
##CHUNK 1
if err != nil {
return nil, err
}
n, err := readGGUF[uint64](llm, r)
if err != nil {
return nil, err
}
switch t {
case ggufTypeUint8:
a := newArray[uint8](int(n), llm.maxArraySize)
return readGGUFArrayData(llm, r, a)
case ggufTypeInt8:
a := newArray[int8](int(n), llm.maxArraySize)
return readGGUFArrayData(llm, r, a)
case ggufTypeUint16:
a := newArray[uint16](int(n), llm.maxArraySize)
return readGGUFArrayData(llm, r, a)
case ggufTypeInt16:
##CHUNK 2
case 1:
return uint64(llm.V1.NumTensor)
case 2:
return llm.V2.NumTensor
default:
return llm.V3.NumTensor
}
}
func (llm *gguf) numKV() uint64 {
switch llm.Version {
case 1:
return uint64(llm.V1.NumKV)
case 2:
return llm.V2.NumKV
default:
return llm.V3.NumKV
}
}
#FILE: ollama-main/convert/sentencepiece/sentencepiece_model.pb.go
##CHUNK 1
case 3:
return &v.extensionFields
default:
return nil
}
}
file_sentencepiece_model_proto_msgTypes[3].Exporter = func(v any, i int) any {
switch v := v.(*ModelProto); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
case 3:
return &v.extensionFields
default:
return nil
}
}
#CURRENT FILE: ollama-main/parser/parser.go
|
ollama-main
| 81
|
func unquote(s string) (string, bool) {
// TODO: single quotes
if len(s) >= 3 && s[:3] == `"""` {
if len(s) >= 6 && s[len(s)-3:] == `"""` {
return s[3 : len(s)-3], true
}
return "", false
}
if len(s) >= 1 && s[0] == '"' {
if len(s) >= 2 && s[len(s)-1] == '"' {
return s[1 : len(s)-1], true
}
return "", false
}
return s, true
}
|
func unquote(s string) (string, bool) {
// TODO: single quotes
if len(s) >= 3 && s[:3] == `"""` {
if len(s) >= 6 && s[len(s)-3:] == `"""` {
return s[3 : len(s)-3], true
}
return "", false
}
if len(s) >= 1 && s[0] == '"' {
if len(s) >= 2 && s[len(s)-1] == '"' {
return s[1 : len(s)-1], true
}
return "", false
}
return s, true
}
|
func unquote(s string) (string, bool) {
// TODO: single quotes
if len(s) >= 3 && s[:3] == `"""` {
if len(s) >= 6 && s[len(s)-3:] == `"""` {
return s[3 : len(s)-3], true
}
return "", false
}
if len(s) >= 1 && s[0] == '"' {
if len(s) >= 2 && s[len(s)-1] == '"' {
return s[1 : len(s)-1], true
}
return "", false
}
return s, true
}
|
unquote
| 564
| 583
|
parser/parser.go
|
#FILE: ollama-main/types/model/name.go
##CHUNK 1
return len(s) >= 1 && len(s) <= 350
case kindTag:
return len(s) >= 1 && len(s) <= 80
default:
return len(s) >= 1 && len(s) <= 80
}
}
func isValidPart(kind partKind, s string) bool {
if !isValidLen(kind, s) {
return false
}
for i := range s {
if i == 0 {
if !isAlphanumericOrUnderscore(s[i]) {
return false
}
continue
}
switch s[i] {
##CHUNK 2
func (n Name) EqualFold(o Name) bool {
return strings.EqualFold(n.Host, o.Host) &&
strings.EqualFold(n.Namespace, o.Namespace) &&
strings.EqualFold(n.Model, o.Model) &&
strings.EqualFold(n.Tag, o.Tag)
}
func isValidLen(kind partKind, s string) bool {
switch kind {
case kindHost:
return len(s) >= 1 && len(s) <= 350
case kindTag:
return len(s) >= 1 && len(s) <= 80
default:
return len(s) >= 1 && len(s) <= 80
}
}
func isValidPart(kind partKind, s string) bool {
if !isValidLen(kind, s) {
##CHUNK 3
if !isAlphanumericOrUnderscore(s[i]) {
return false
}
}
}
return true
}
func isAlphanumericOrUnderscore(c byte) bool {
return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_'
}
func cutLast(s, sep string) (before, after string, ok bool) {
i := strings.LastIndex(s, sep)
if i >= 0 {
return s[:i], s[i+len(sep):], true
}
return s, "", false
}
##CHUNK 4
case '_', '-':
case '.':
if kind == kindNamespace {
return false
}
case ':':
if kind != kindHost && kind != kindDigest {
return false
}
default:
if !isAlphanumericOrUnderscore(s[i]) {
return false
}
}
}
return true
}
func isAlphanumericOrUnderscore(c byte) bool {
return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_'
#FILE: ollama-main/server/internal/internal/names/name.go
##CHUNK 1
case ':':
if kind != partHost {
return false
}
default:
if !isAlphanumericOrUnderscore(s[i]) {
return false
}
}
}
return true
}
func isAlphanumericOrUnderscore(c byte) bool {
return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_'
}
func (n Name) Host() string { return n.h }
func (n Name) Namespace() string { return n.n }
func (n Name) Model() string { return n.m }
##CHUNK 2
if kind == partHost {
maxlen = 350
}
if len(s) > maxlen {
return false
}
for i := range s {
if i == 0 {
if !isAlphanumericOrUnderscore(s[i]) {
return false
}
continue
}
switch s[i] {
case '_', '-':
case '.':
if kind == partNamespace {
return false
}
#FILE: ollama-main/discover/types.go
##CHUNK 1
// For each GPU, check if it does NOT support flash attention
func (l GpuInfoList) FlashAttentionSupported() bool {
for _, gpu := range l {
supportsFA := gpu.Library == "metal" ||
(gpu.Library == "cuda" && gpu.DriverMajor >= 7) ||
gpu.Library == "rocm"
if !supportsFA {
return false
}
}
return true
}
#FILE: ollama-main/readline/readline.go
##CHUNK 1
return output, nil
default:
if metaDel {
metaDel = false
continue
}
if r >= CharSpace || r == CharEnter || r == CharCtrlJ {
buf.Add(r)
}
}
}
}
func (i *Instance) HistoryEnable() {
i.History.Enabled = true
}
func (i *Instance) HistoryDisable() {
i.History.Enabled = false
#FILE: ollama-main/server/routes.go
##CHUNK 1
return false
}
func allowedHost(host string) bool {
host = strings.ToLower(host)
if host == "" || host == "localhost" {
return true
}
if hostname, err := os.Hostname(); err == nil && host == strings.ToLower(hostname) {
return true
}
tlds := []string{
"localhost",
"local",
"internal",
}
#CURRENT FILE: ollama-main/parser/parser.go
##CHUNK 1
}
func quote(s string) string {
if strings.Contains(s, "\n") || strings.HasPrefix(s, " ") || strings.HasSuffix(s, " ") {
if strings.Contains(s, "\"") {
return `"""` + s + `"""`
}
return `"` + s + `"`
}
return s
}
}
func isAlpha(r rune) bool {
return r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z'
}
func isNumber(r rune) bool {
|
ollama-main
| 82
|
func expandPathImpl(path, relativeDir string, currentUserFunc func() (*user.User, error), lookupUserFunc func(string) (*user.User, error)) (string, error) {
if filepath.IsAbs(path) || strings.HasPrefix(path, "\\") || strings.HasPrefix(path, "/") {
return filepath.Abs(path)
} else if strings.HasPrefix(path, "~") {
var homeDir string
if path == "~" || strings.HasPrefix(path, "~/") {
// Current user's home directory
currentUser, err := currentUserFunc()
if err != nil {
return "", fmt.Errorf("failed to get current user: %w", err)
}
homeDir = currentUser.HomeDir
path = strings.TrimPrefix(path, "~")
} else {
// Specific user's home directory
parts := strings.SplitN(path[1:], "/", 2)
userInfo, err := lookupUserFunc(parts[0])
if err != nil {
return "", fmt.Errorf("failed to find user '%s': %w", parts[0], err)
}
homeDir = userInfo.HomeDir
if len(parts) > 1 {
path = "/" + parts[1]
} else {
path = ""
}
}
path = filepath.Join(homeDir, path)
} else {
path = filepath.Join(relativeDir, path)
}
return filepath.Abs(path)
}
|
func expandPathImpl(path, relativeDir string, currentUserFunc func() (*user.User, error), lookupUserFunc func(string) (*user.User, error)) (string, error) {
if filepath.IsAbs(path) || strings.HasPrefix(path, "\\") || strings.HasPrefix(path, "/") {
return filepath.Abs(path)
} else if strings.HasPrefix(path, "~") {
var homeDir string
if path == "~" || strings.HasPrefix(path, "~/") {
// Current user's home directory
currentUser, err := currentUserFunc()
if err != nil {
return "", fmt.Errorf("failed to get current user: %w", err)
}
homeDir = currentUser.HomeDir
path = strings.TrimPrefix(path, "~")
} else {
// Specific user's home directory
parts := strings.SplitN(path[1:], "/", 2)
userInfo, err := lookupUserFunc(parts[0])
if err != nil {
return "", fmt.Errorf("failed to find user '%s': %w", parts[0], err)
}
homeDir = userInfo.HomeDir
if len(parts) > 1 {
path = "/" + parts[1]
} else {
path = ""
}
}
path = filepath.Join(homeDir, path)
} else {
path = filepath.Join(relativeDir, path)
}
return filepath.Abs(path)
}
|
func expandPathImpl(path, relativeDir string, currentUserFunc func() (*user.User, error), lookupUserFunc func(string) (*user.User, error)) (string, error) {
if filepath.IsAbs(path) || strings.HasPrefix(path, "\\") || strings.HasPrefix(path, "/") {
return filepath.Abs(path)
} else if strings.HasPrefix(path, "~") {
var homeDir string
if path == "~" || strings.HasPrefix(path, "~/") {
// Current user's home directory
currentUser, err := currentUserFunc()
if err != nil {
return "", fmt.Errorf("failed to get current user: %w", err)
}
homeDir = currentUser.HomeDir
path = strings.TrimPrefix(path, "~")
} else {
// Specific user's home directory
parts := strings.SplitN(path[1:], "/", 2)
userInfo, err := lookupUserFunc(parts[0])
if err != nil {
return "", fmt.Errorf("failed to find user '%s': %w", parts[0], err)
}
homeDir = userInfo.HomeDir
if len(parts) > 1 {
path = "/" + parts[1]
} else {
path = ""
}
}
path = filepath.Join(homeDir, path)
} else {
path = filepath.Join(relativeDir, path)
}
return filepath.Abs(path)
}
|
expandPathImpl
| 614
| 649
|
parser/parser.go
|
#FILE: ollama-main/discover/amd_common.go
##CHUNK 1
pathEnv = "PATH"
}
paths := os.Getenv(pathEnv)
for _, path := range filepath.SplitList(paths) {
d, err := filepath.Abs(path)
if err != nil {
continue
}
if rocmLibUsable(d) {
return d, nil
}
}
// Well known location(s)
for _, path := range RocmStandardLocations {
if rocmLibUsable(path) {
return path, nil
}
}
##CHUNK 2
hipLibDir := filepath.Join(hipPath, "bin")
if rocmLibUsable(hipLibDir) {
slog.Debug("detected ROCM via HIP_PATH=" + hipPath)
return hipLibDir, nil
}
}
// Scan the LD_LIBRARY_PATH or PATH
pathEnv := "LD_LIBRARY_PATH"
if runtime.GOOS == "windows" {
pathEnv = "PATH"
}
paths := os.Getenv(pathEnv)
for _, path := range filepath.SplitList(paths) {
d, err := filepath.Abs(path)
if err != nil {
continue
}
if rocmLibUsable(d) {
#FILE: ollama-main/server/modelpath.go
##CHUNK 1
return "", ErrInvalidDigestFormat
}
digest = strings.ReplaceAll(digest, ":", "-")
path := filepath.Join(envconfig.Models(), "blobs", digest)
dirPath := filepath.Dir(path)
if digest == "" {
dirPath = path
}
if err := os.MkdirAll(dirPath, 0o755); err != nil {
return "", fmt.Errorf("%w: ensure path elements are traversable", err)
}
return path, nil
}
##CHUNK 2
Tag: mp.Tag,
}
if !name.IsValid() {
return "", fs.ErrNotExist
}
return filepath.Join(envconfig.Models(), "manifests", name.Filepath()), nil
}
func (mp ModelPath) BaseURL() *url.URL {
return &url.URL{
Scheme: mp.ProtocolScheme,
Host: mp.Registry,
}
}
func GetManifestPath() (string, error) {
path := filepath.Join(envconfig.Models(), "manifests")
if err := os.MkdirAll(path, 0o755); err != nil {
return "", fmt.Errorf("%w: ensure path elements are traversable", err)
}
##CHUNK 3
Scheme: mp.ProtocolScheme,
Host: mp.Registry,
}
}
func GetManifestPath() (string, error) {
path := filepath.Join(envconfig.Models(), "manifests")
if err := os.MkdirAll(path, 0o755); err != nil {
return "", fmt.Errorf("%w: ensure path elements are traversable", err)
}
return path, nil
}
func GetBlobsPath(digest string) (string, error) {
// only accept actual sha256 digests
pattern := "^sha256[:-][0-9a-fA-F]{64}$"
re := regexp.MustCompile(pattern)
if digest != "" && !re.MatchString(digest) {
#FILE: ollama-main/server/routes_test.go
##CHUNK 1
err := fs.WalkDir(fsys, ".", func(path string, info fs.DirEntry, err error) error {
if err != nil {
return err
}
t.Logf(" %s", fs.FormatDirEntry(info))
if info.IsDir() {
return nil
}
path = strings.TrimPrefix(path, mandir)
entries = append(entries, path)
return nil
})
if err != nil {
t.Fatalf("failed to walk directory: %v", err)
}
if len(entries) != 1 {
t.Errorf("len(got) = %d, want 1", len(entries))
return // do not use Fatal so following steps run
}
#FILE: ollama-main/app/lifecycle/paths.go
##CHUNK 1
slog.Warn("error discovering executable directory", "error", err)
AppDir = filepath.Join(localAppData, "Programs", "Ollama")
} else {
AppDir = filepath.Dir(exe)
}
// Make sure we have PATH set correctly for any spawned children
paths := strings.Split(os.Getenv("PATH"), ";")
// Start with whatever we find in the PATH/LD_LIBRARY_PATH
found := false
for _, path := range paths {
d, err := filepath.Abs(path)
if err != nil {
continue
}
if strings.EqualFold(AppDir, d) {
found = true
}
}
if !found {
##CHUNK 2
for _, path := range paths {
d, err := filepath.Abs(path)
if err != nil {
continue
}
if strings.EqualFold(AppDir, d) {
found = true
}
}
if !found {
paths = append(paths, AppDir)
pathVal := strings.Join(paths, ";")
slog.Debug("setting PATH=" + pathVal)
err := os.Setenv("PATH", pathVal)
if err != nil {
slog.Error(fmt.Sprintf("failed to update PATH: %s", err))
}
}
#FILE: ollama-main/cmd/cmd.go
##CHUNK 1
return nil
}
func createBlob(cmd *cobra.Command, client *api.Client, path string, digest string, p *progress.Progress) (string, error) {
realPath, err := filepath.EvalSymlinks(path)
if err != nil {
return "", err
}
bin, err := os.Open(realPath)
if err != nil {
return "", err
}
defer bin.Close()
// Get file info to retrieve the size
fileInfo, err := bin.Stat()
if err != nil {
return "", err
}
#FILE: ollama-main/ml/backend/ggml/ggml/src/ggml.go
##CHUNK 1
// Avoid potentially loading incompatible GGML libraries
paths, ok := os.LookupEnv("OLLAMA_LIBRARY_PATH")
if !ok {
slog.Debug("OLLAMA_LIBRARY_PATH not set, falling back to default", "search", value)
paths = value
}
split := filepath.SplitList(paths)
visited := make(map[string]struct{}, len(split))
for _, path := range split {
abspath, err := filepath.Abs(path)
if err != nil {
slog.Error("failed to get absolute path", "error", err)
continue
}
if abspath != filepath.Dir(exe) && !strings.Contains(abspath, filepath.FromSlash("lib/ollama")) {
slog.Debug("skipping path which is not part of ollama", "path", abspath)
continue
}
#CURRENT FILE: ollama-main/parser/parser.go
|
ollama-main
| 83
|
func Sign(ctx context.Context, bts []byte) (string, error) {
keyPath, err := keyPath()
if err != nil {
return "", err
}
privateKeyFile, err := os.ReadFile(keyPath)
if err != nil {
slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
return "", err
}
privateKey, err := ssh.ParsePrivateKey(privateKeyFile)
if err != nil {
return "", err
}
// get the pubkey, but remove the type
publicKey := ssh.MarshalAuthorizedKey(privateKey.PublicKey())
parts := bytes.Split(publicKey, []byte(" "))
if len(parts) < 2 {
return "", errors.New("malformed public key")
}
signedData, err := privateKey.Sign(rand.Reader, bts)
if err != nil {
return "", err
}
// signature is <pubkey>:<signature>
return fmt.Sprintf("%s:%s", bytes.TrimSpace(parts[1]), base64.StdEncoding.EncodeToString(signedData.Blob)), nil
}
|
func Sign(ctx context.Context, bts []byte) (string, error) {
keyPath, err := keyPath()
if err != nil {
return "", err
}
privateKeyFile, err := os.ReadFile(keyPath)
if err != nil {
slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
return "", err
}
privateKey, err := ssh.ParsePrivateKey(privateKeyFile)
if err != nil {
return "", err
}
// get the pubkey, but remove the type
publicKey := ssh.MarshalAuthorizedKey(privateKey.PublicKey())
parts := bytes.Split(publicKey, []byte(" "))
if len(parts) < 2 {
return "", errors.New("malformed public key")
}
signedData, err := privateKey.Sign(rand.Reader, bts)
if err != nil {
return "", err
}
// signature is <pubkey>:<signature>
return fmt.Sprintf("%s:%s", bytes.TrimSpace(parts[1]), base64.StdEncoding.EncodeToString(signedData.Blob)), nil
}
|
func Sign(ctx context.Context, bts []byte) (string, error) {
keyPath, err := keyPath()
if err != nil {
return "", err
}
privateKeyFile, err := os.ReadFile(keyPath)
if err != nil {
slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
return "", err
}
privateKey, err := ssh.ParsePrivateKey(privateKeyFile)
if err != nil {
return "", err
}
// get the pubkey, but remove the type
publicKey := ssh.MarshalAuthorizedKey(privateKey.PublicKey())
parts := bytes.Split(publicKey, []byte(" "))
if len(parts) < 2 {
return "", errors.New("malformed public key")
}
signedData, err := privateKey.Sign(rand.Reader, bts)
if err != nil {
return "", err
}
// signature is <pubkey>:<signature>
return fmt.Sprintf("%s:%s", bytes.TrimSpace(parts[1]), base64.StdEncoding.EncodeToString(signedData.Blob)), nil
}
|
Sign
| 60
| 91
|
auth/auth.go
|
#FILE: ollama-main/server/internal/client/ollama/registry.go
##CHUNK 1
return "", fmt.Errorf("unsupported private key type: %T", key)
}
url := fmt.Sprintf("https://ollama.com?ts=%d", time.Now().Unix())
// Part 1: the checkData (e.g. the URL with a timestamp)
// Part 2: the public key
pubKeyShort, err := func() ([]byte, error) {
sshPubKey, err := ssh.NewPublicKey(privKey.Public())
if err != nil {
return nil, err
}
pubKeyParts := bytes.Fields(ssh.MarshalAuthorizedKey(sshPubKey))
if len(pubKeyParts) < 2 {
return nil, fmt.Errorf("malformed public key: %q", pubKeyParts)
}
pubKeyShort := pubKeyParts[1]
return pubKeyShort, nil
}()
if err != nil {
##CHUNK 2
return nil, err
}
pubKeyParts := bytes.Fields(ssh.MarshalAuthorizedKey(sshPubKey))
if len(pubKeyParts) < 2 {
return nil, fmt.Errorf("malformed public key: %q", pubKeyParts)
}
pubKeyShort := pubKeyParts[1]
return pubKeyShort, nil
}()
if err != nil {
return "", err
}
// Part 3: the signature
sig := ed25519.Sign(*privKey, []byte(checkData(url)))
// Assemble the token: <checkData>:<pubKey>:<signature>
var b strings.Builder
io.WriteString(&b, base64.StdEncoding.EncodeToString([]byte(url)))
b.WriteByte(':')
#FILE: ollama-main/parser/parser.go
##CHUNK 1
func digestForFile(filename string) (string, error) {
filepath, err := filepath.EvalSymlinks(filename)
if err != nil {
return "", err
}
bin, err := os.Open(filepath)
if err != nil {
return "", err
}
defer bin.Close()
hash := sha256.New()
if _, err := io.Copy(hash, bin); err != nil {
return "", err
}
return fmt.Sprintf("sha256:%x", hash.Sum(nil)), nil
}
##CHUNK 2
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return fl, nil
}
func digestForFile(filename string) (string, error) {
filepath, err := filepath.EvalSymlinks(filename)
if err != nil {
return "", err
}
bin, err := os.Open(filepath)
if err != nil {
return "", err
#FILE: ollama-main/cmd/cmd.go
##CHUNK 1
return nil
}
func createBlob(cmd *cobra.Command, client *api.Client, path string, digest string, p *progress.Progress) (string, error) {
realPath, err := filepath.EvalSymlinks(path)
if err != nil {
return "", err
}
bin, err := os.Open(realPath)
if err != nil {
return "", err
}
defer bin.Close()
// Get file info to retrieve the size
fileInfo, err := bin.Stat()
if err != nil {
return "", err
}
#FILE: ollama-main/server/auth.go
##CHUNK 1
if err != nil {
return "", err
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return "", fmt.Errorf("%d: %v", response.StatusCode, err)
}
if response.StatusCode >= http.StatusBadRequest {
if len(body) > 0 {
return "", fmt.Errorf("%d: %s", response.StatusCode, body)
} else {
return "", fmt.Errorf("%d", response.StatusCode)
}
}
var token api.TokenResponse
if err := json.Unmarshal(body, &token); err != nil {
##CHUNK 2
}
func getAuthorizationToken(ctx context.Context, challenge registryChallenge) (string, error) {
redirectURL, err := challenge.URL()
if err != nil {
return "", err
}
sha256sum := sha256.Sum256(nil)
data := []byte(fmt.Sprintf("%s,%s,%s", http.MethodGet, redirectURL.String(), base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(sha256sum[:])))))
headers := make(http.Header)
signature, err := auth.Sign(ctx, data)
if err != nil {
return "", err
}
headers.Add("Authorization", signature)
response, err := makeRequest(ctx, http.MethodGet, redirectURL, headers, nil, ®istryOptions{})
#CURRENT FILE: ollama-main/auth/auth.go
##CHUNK 1
keyPath, err := keyPath()
if err != nil {
return "", err
}
privateKeyFile, err := os.ReadFile(keyPath)
if err != nil {
slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
return "", err
}
privateKey, err := ssh.ParsePrivateKey(privateKeyFile)
if err != nil {
return "", err
}
publicKey := ssh.MarshalAuthorizedKey(privateKey.PublicKey())
return strings.TrimSpace(string(publicKey)), nil
}
##CHUNK 2
func keyPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".ollama", defaultPrivateKey), nil
}
func GetPublicKey() (string, error) {
keyPath, err := keyPath()
if err != nil {
return "", err
}
privateKeyFile, err := os.ReadFile(keyPath)
if err != nil {
slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
return "", err
}
##CHUNK 3
privateKey, err := ssh.ParsePrivateKey(privateKeyFile)
if err != nil {
return "", err
}
publicKey := ssh.MarshalAuthorizedKey(privateKey.PublicKey())
return strings.TrimSpace(string(publicKey)), nil
}
func NewNonce(r io.Reader, length int) (string, error) {
nonce := make([]byte, length)
if _, err := io.ReadFull(r, nonce); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(nonce), nil
}
}
|
ollama-main
| 84
|
func GetModelArch(modelPath string) (string, error) {
mp := C.CString(modelPath)
defer C.free(unsafe.Pointer(mp))
gguf_ctx := C.gguf_init_from_file(mp, C.struct_gguf_init_params{no_alloc: true, ctx: (**C.struct_ggml_context)(C.NULL)})
if gguf_ctx == nil {
return "", errors.New("unable to load model file")
}
defer C.gguf_free(gguf_ctx)
key := C.CString("general.architecture")
defer C.free(unsafe.Pointer(key))
arch_index := C.gguf_find_key(gguf_ctx, key)
if int(arch_index) < 0 {
return "", errors.New("unknown model architecture")
}
arch := C.gguf_get_val_str(gguf_ctx, arch_index)
return C.GoString(arch), nil
}
|
func GetModelArch(modelPath string) (string, error) {
mp := C.CString(modelPath)
defer C.free(unsafe.Pointer(mp))
gguf_ctx := C.gguf_init_from_file(mp, C.struct_gguf_init_params{no_alloc: true, ctx: (**C.struct_ggml_context)(C.NULL)})
if gguf_ctx == nil {
return "", errors.New("unable to load model file")
}
defer C.gguf_free(gguf_ctx)
key := C.CString("general.architecture")
defer C.free(unsafe.Pointer(key))
arch_index := C.gguf_find_key(gguf_ctx, key)
if int(arch_index) < 0 {
return "", errors.New("unknown model architecture")
}
arch := C.gguf_get_val_str(gguf_ctx, arch_index)
return C.GoString(arch), nil
}
|
func GetModelArch(modelPath string) (string, error) {
mp := C.CString(modelPath)
defer C.free(unsafe.Pointer(mp))
gguf_ctx := C.gguf_init_from_file(mp, C.struct_gguf_init_params{no_alloc: true, ctx: (**C.struct_ggml_context)(C.NULL)})
if gguf_ctx == nil {
return "", errors.New("unable to load model file")
}
defer C.gguf_free(gguf_ctx)
key := C.CString("general.architecture")
defer C.free(unsafe.Pointer(key))
arch_index := C.gguf_find_key(gguf_ctx, key)
if int(arch_index) < 0 {
return "", errors.New("unknown model architecture")
}
arch := C.gguf_get_val_str(gguf_ctx, arch_index)
return C.GoString(arch), nil
}
|
GetModelArch
| 63
| 83
|
llama/llama.go
|
#FILE: ollama-main/parser/parser.go
##CHUNK 1
}
defer bin.Close()
hash := sha256.New()
if _, err := io.Copy(hash, bin); err != nil {
return "", err
}
return fmt.Sprintf("sha256:%x", hash.Sum(nil)), nil
}
func filesForModel(path string) ([]string, error) {
detectContentType := func(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
var b bytes.Buffer
b.Grow(512)
##CHUNK 2
func digestForFile(filename string) (string, error) {
filepath, err := filepath.EvalSymlinks(filename)
if err != nil {
return "", err
}
bin, err := os.Open(filepath)
if err != nil {
return "", err
}
defer bin.Close()
hash := sha256.New()
if _, err := io.Copy(hash, bin); err != nil {
return "", err
}
return fmt.Sprintf("sha256:%x", hash.Sum(nil)), nil
}
##CHUNK 3
func filesForModel(path string) ([]string, error) {
detectContentType := func(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
var b bytes.Buffer
b.Grow(512)
if _, err := io.CopyN(&b, f, 512); err != nil && !errors.Is(err, io.EOF) {
return "", err
}
contentType, _, _ := strings.Cut(http.DetectContentType(b.Bytes()), ";")
return contentType, nil
}
glob := func(pattern, contentType string) ([]string, error) {
#FILE: ollama-main/server/images.go
##CHUNK 1
f, err := os.Open(fp)
if err != nil {
return nil, "", err
}
defer f.Close()
sha256sum := sha256.New()
var manifest Manifest
if err := json.NewDecoder(io.TeeReader(f, sha256sum)).Decode(&manifest); err != nil {
return nil, "", err
}
return &manifest, hex.EncodeToString(sha256sum.Sum(nil)), nil
}
func GetModel(name string) (*Model, error) {
mp := ParseModelPath(name)
manifest, digest, err := GetManifest(mp)
##CHUNK 2
if err := json.NewDecoder(io.TeeReader(f, sha256sum)).Decode(&manifest); err != nil {
return nil, "", err
}
return &manifest, hex.EncodeToString(sha256sum.Sum(nil)), nil
}
func GetModel(name string) (*Model, error) {
mp := ParseModelPath(name)
manifest, digest, err := GetManifest(mp)
if err != nil {
return nil, err
}
model := &Model{
Name: mp.GetFullTagname(),
ShortName: mp.GetShortTagname(),
Digest: digest,
Template: template.DefaultTemplate,
}
#FILE: ollama-main/auth/auth.go
##CHUNK 1
func keyPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".ollama", defaultPrivateKey), nil
}
func GetPublicKey() (string, error) {
keyPath, err := keyPath()
if err != nil {
return "", err
}
privateKeyFile, err := os.ReadFile(keyPath)
if err != nil {
slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
return "", err
}
##CHUNK 2
func NewNonce(r io.Reader, length int) (string, error) {
nonce := make([]byte, length)
if _, err := io.ReadFull(r, nonce); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(nonce), nil
}
func Sign(ctx context.Context, bts []byte) (string, error) {
keyPath, err := keyPath()
if err != nil {
return "", err
}
privateKeyFile, err := os.ReadFile(keyPath)
if err != nil {
slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
return "", err
#FILE: ollama-main/cmd/cmd.go
##CHUNK 1
return nil
}
func createBlob(cmd *cobra.Command, client *api.Client, path string, digest string, p *progress.Progress) (string, error) {
realPath, err := filepath.EvalSymlinks(path)
if err != nil {
return "", err
}
bin, err := os.Open(realPath)
if err != nil {
return "", err
}
defer bin.Close()
// Get file info to retrieve the size
fileInfo, err := bin.Stat()
if err != nil {
return "", err
}
#CURRENT FILE: ollama-main/llama/llama.go
##CHUNK 1
// vision processing
type ClipContext struct {
c *C.struct_clip_ctx
}
func NewClipContext(llamaContext *Context, modelPath string) (*ClipContext, error) {
mp := C.CString(modelPath)
defer C.free(unsafe.Pointer(mp))
c := C.clip_model_load(mp, 1)
if c == nil {
return nil, fmt.Errorf("unable to load clip model: %v", modelPath)
}
projEmbedSize := int(C.clip_n_mmproj_embd(c))
modelEmbedSize := llamaContext.Model().NEmbd()
if projEmbedSize != modelEmbedSize {
return nil, fmt.Errorf("projector embedding size (%d) does not match model (%d)", projEmbedSize, modelEmbedSize)
}
return &ClipContext{c: c}, nil
##CHUNK 2
tokens[i] = int(cTokens[i])
}
return tokens, nil
}
func (m *Model) NEmbd() int {
return int(C.llama_model_n_embd(m.c))
}
// vision processing
type ClipContext struct {
c *C.struct_clip_ctx
}
func NewClipContext(llamaContext *Context, modelPath string) (*ClipContext, error) {
mp := C.CString(modelPath)
defer C.free(unsafe.Pointer(mp))
c := C.clip_model_load(mp, 1)
if c == nil {
|
ollama-main
| 85
|
func LoadModelFromFile(modelPath string, params ModelParams) (*Model, error) {
cparams := C.llama_model_default_params()
cparams.n_gpu_layers = C.int(params.NumGpuLayers)
cparams.main_gpu = C.int32_t(params.MainGpu)
cparams.use_mmap = C.bool(params.UseMmap)
cparams.vocab_only = C.bool(params.VocabOnly)
if len(params.TensorSplit) > 0 {
tensorSplitData := ¶ms.TensorSplit[0]
var tensorSplitPin runtime.Pinner
tensorSplitPin.Pin(tensorSplitData)
defer tensorSplitPin.Unpin()
cparams.tensor_split = (*C.float)(unsafe.Pointer(tensorSplitData))
}
if params.Progress != nil {
handle := cgo.NewHandle(params.Progress)
defer handle.Delete()
var handlePin runtime.Pinner
handlePin.Pin(&handle)
defer handlePin.Unpin()
cparams.progress_callback = C.llama_progress_callback(C.llamaProgressCallback)
cparams.progress_callback_user_data = unsafe.Pointer(&handle)
}
m := Model{c: C.llama_model_load_from_file(C.CString(modelPath), cparams)}
if m.c == nil {
return nil, fmt.Errorf("unable to load model: %s", modelPath)
}
return &m, nil
}
|
func LoadModelFromFile(modelPath string, params ModelParams) (*Model, error) {
cparams := C.llama_model_default_params()
cparams.n_gpu_layers = C.int(params.NumGpuLayers)
cparams.main_gpu = C.int32_t(params.MainGpu)
cparams.use_mmap = C.bool(params.UseMmap)
cparams.vocab_only = C.bool(params.VocabOnly)
if len(params.TensorSplit) > 0 {
tensorSplitData := ¶ms.TensorSplit[0]
var tensorSplitPin runtime.Pinner
tensorSplitPin.Pin(tensorSplitData)
defer tensorSplitPin.Unpin()
cparams.tensor_split = (*C.float)(unsafe.Pointer(tensorSplitData))
}
if params.Progress != nil {
handle := cgo.NewHandle(params.Progress)
defer handle.Delete()
var handlePin runtime.Pinner
handlePin.Pin(&handle)
defer handlePin.Unpin()
cparams.progress_callback = C.llama_progress_callback(C.llamaProgressCallback)
cparams.progress_callback_user_data = unsafe.Pointer(&handle)
}
m := Model{c: C.llama_model_load_from_file(C.CString(modelPath), cparams)}
if m.c == nil {
return nil, fmt.Errorf("unable to load model: %s", modelPath)
}
return &m, nil
}
|
func LoadModelFromFile(modelPath string, params ModelParams) (*Model, error) {
cparams := C.llama_model_default_params()
cparams.n_gpu_layers = C.int(params.NumGpuLayers)
cparams.main_gpu = C.int32_t(params.MainGpu)
cparams.use_mmap = C.bool(params.UseMmap)
cparams.vocab_only = C.bool(params.VocabOnly)
if len(params.TensorSplit) > 0 {
tensorSplitData := ¶ms.TensorSplit[0]
var tensorSplitPin runtime.Pinner
tensorSplitPin.Pin(tensorSplitData)
defer tensorSplitPin.Unpin()
cparams.tensor_split = (*C.float)(unsafe.Pointer(tensorSplitData))
}
if params.Progress != nil {
handle := cgo.NewHandle(params.Progress)
defer handle.Delete()
var handlePin runtime.Pinner
handlePin.Pin(&handle)
defer handlePin.Unpin()
cparams.progress_callback = C.llama_progress_callback(C.llamaProgressCallback)
cparams.progress_callback_user_data = unsafe.Pointer(&handle)
}
m := Model{c: C.llama_model_load_from_file(C.CString(modelPath), cparams)}
if m.c == nil {
return nil, fmt.Errorf("unable to load model: %s", modelPath)
}
return &m, nil
}
|
LoadModelFromFile
| 213
| 248
|
llama/llama.go
|
#FILE: ollama-main/server/images.go
##CHUNK 1
f, err := os.Open(fp)
if err != nil {
return nil, "", err
}
defer f.Close()
sha256sum := sha256.New()
var manifest Manifest
if err := json.NewDecoder(io.TeeReader(f, sha256sum)).Decode(&manifest); err != nil {
return nil, "", err
}
return &manifest, hex.EncodeToString(sha256sum.Sum(nil)), nil
}
func GetModel(name string) (*Model, error) {
mp := ParseModelPath(name)
manifest, digest, err := GetManifest(mp)
#FILE: ollama-main/server/manifest.go
##CHUNK 1
}
func ParseNamedManifest(n model.Name) (*Manifest, error) {
if !n.IsFullyQualified() {
return nil, model.Unqualified(n)
}
manifests, err := GetManifestPath()
if err != nil {
return nil, err
}
p := filepath.Join(manifests, n.Filepath())
var m Manifest
f, err := os.Open(p)
if err != nil {
return nil, err
}
defer f.Close()
##CHUNK 2
}
p := filepath.Join(manifests, n.Filepath())
var m Manifest
f, err := os.Open(p)
if err != nil {
return nil, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return nil, err
}
sha256sum := sha256.New()
if err := json.NewDecoder(io.TeeReader(f, sha256sum)).Decode(&m); err != nil {
return nil, err
}
#FILE: ollama-main/runner/llamarunner/image.go
##CHUNK 1
// cache of images to embeddings
images []imageCache
imageHash maphash.Hash
}
func NewImageContext(llamaContext *llama.Context, modelPath string) (*ImageContext, error) {
arch, err := llama.GetModelArch(modelPath)
if err != nil {
return nil, fmt.Errorf("unable to determine vision architecture: %w (%s)", err, modelPath)
}
var c ImageContext
if arch == "clip" {
c.clip, err = llama.NewClipContext(llamaContext, modelPath)
} else {
return nil, fmt.Errorf("unknown vision model architecture: %s", arch)
}
if err != nil {
#FILE: ollama-main/convert/tokenizer_spm.go
##CHUNK 1
func parseAdditionalSpecialTokens(fsys fs.FS) ([]specialToken, error) {
f, err := fsys.Open("special_tokens_map.json")
if errors.Is(err, os.ErrNotExist) {
return nil, nil
} else if err != nil {
return nil, err
}
defer f.Close()
var m struct {
AdditionalSpecialTokens any `json:"additional_special_tokens"`
}
if err := json.NewDecoder(f).Decode(&m); err != nil {
return nil, err
}
var ast []specialToken
#FILE: ollama-main/convert/tokenizer.go
##CHUNK 1
return nil, err
} else {
defer f.Close()
var tt tokenizer
if err := json.NewDecoder(f).Decode(&tt); err != nil {
return nil, err
}
for _, t := range tt.AddedTokens {
addedTokens[t.Content] = t
}
if len(tt.Model.Merges) == 0 {
// noop; merges is empty
} else if err := json.Unmarshal(tt.Model.Merges, &t.Merges); err == nil {
// noop; merges is []string
} else if merges, err := func() ([][]string, error) {
var merges [][]string
if err := json.Unmarshal(tt.Model.Merges, &merges); err != nil {
#FILE: ollama-main/server/create.go
##CHUNK 1
return nil, err
}
defer fn.Close()
var existing map[string]any
if err := json.NewDecoder(fn).Decode(&existing); err != nil {
return nil, err
}
for k, v := range existing {
if _, exists := p[k]; exists {
continue
}
p[k] = v
}
}
if len(p) == 0 {
return layers, nil
}
#CURRENT FILE: ollama-main/llama/llama.go
##CHUNK 1
func NewClipContext(llamaContext *Context, modelPath string) (*ClipContext, error) {
mp := C.CString(modelPath)
defer C.free(unsafe.Pointer(mp))
c := C.clip_model_load(mp, 1)
if c == nil {
return nil, fmt.Errorf("unable to load clip model: %v", modelPath)
}
projEmbedSize := int(C.clip_n_mmproj_embd(c))
modelEmbedSize := llamaContext.Model().NEmbd()
if projEmbedSize != modelEmbedSize {
return nil, fmt.Errorf("projector embedding size (%d) does not match model (%d)", projEmbedSize, modelEmbedSize)
}
return &ClipContext{c: c}, nil
}
func (c *ClipContext) Free() {
C.clip_free(c.c)
}
##CHUNK 2
func (m *Model) NEmbd() int {
return int(C.llama_model_n_embd(m.c))
}
// vision processing
type ClipContext struct {
c *C.struct_clip_ctx
}
func NewClipContext(llamaContext *Context, modelPath string) (*ClipContext, error) {
mp := C.CString(modelPath)
defer C.free(unsafe.Pointer(mp))
c := C.clip_model_load(mp, 1)
if c == nil {
return nil, fmt.Errorf("unable to load clip model: %v", modelPath)
}
projEmbedSize := int(C.clip_n_mmproj_embd(c))
modelEmbedSize := llamaContext.Model().NEmbd()
##CHUNK 3
C.llama_backend_init()
}
func GetModelArch(modelPath string) (string, error) {
mp := C.CString(modelPath)
defer C.free(unsafe.Pointer(mp))
gguf_ctx := C.gguf_init_from_file(mp, C.struct_gguf_init_params{no_alloc: true, ctx: (**C.struct_ggml_context)(C.NULL)})
if gguf_ctx == nil {
return "", errors.New("unable to load model file")
}
defer C.gguf_free(gguf_ctx)
key := C.CString("general.architecture")
defer C.free(unsafe.Pointer(key))
arch_index := C.gguf_find_key(gguf_ctx, key)
if int(arch_index) < 0 {
return "", errors.New("unknown model architecture")
}
|
ollama-main
| 86
|
func NewBatch(batchSize int, maxSeq int, embedSize int) (*Batch, error) {
b := Batch{
c: C.llama_batch_init(C.int(batchSize*maxSeq), C.int(embedSize), C.int(maxSeq)),
batchSize: batchSize,
maxSeq: maxSeq,
embedSize: embedSize,
}
// Check to see if any of the allocations in llama_batch_init() failed
nilPointer := (embedSize == 0 && b.c.token == nil) || (embedSize != 0 && b.c.embd == nil) ||
b.c.pos == nil || b.c.n_seq_id == nil || b.c.seq_id == nil || b.c.logits == nil ||
slices.Contains(unsafe.Slice(b.c.seq_id, b.allocSize()), nil)
if nilPointer {
C.llama_batch_free(b.c)
return nil, fmt.Errorf("unable to allocate batch (batchSize=%v maxSeq=%v embedSize=%v)", batchSize, maxSeq, embedSize)
}
return &b, nil
}
|
func NewBatch(batchSize int, maxSeq int, embedSize int) (*Batch, error) {
b := Batch{
c: C.llama_batch_init(C.int(batchSize*maxSeq), C.int(embedSize), C.int(maxSeq)),
batchSize: batchSize,
maxSeq: maxSeq,
embedSize: embedSize,
}
// Check to see if any of the allocations in llama_batch_init() failed
nilPointer := (embedSize == 0 && b.c.token == nil) || (embedSize != 0 && b.c.embd == nil) ||
b.c.pos == nil || b.c.n_seq_id == nil || b.c.seq_id == nil || b.c.logits == nil ||
slices.Contains(unsafe.Slice(b.c.seq_id, b.allocSize()), nil)
if nilPointer {
C.llama_batch_free(b.c)
return nil, fmt.Errorf("unable to allocate batch (batchSize=%v maxSeq=%v embedSize=%v)", batchSize, maxSeq, embedSize)
}
return &b, nil
}
|
func NewBatch(batchSize int, maxSeq int, embedSize int) (*Batch, error) {
b := Batch{
c: C.llama_batch_init(C.int(batchSize*maxSeq), C.int(embedSize), C.int(maxSeq)),
batchSize: batchSize,
maxSeq: maxSeq,
embedSize: embedSize,
}
// Check to see if any of the allocations in llama_batch_init() failed
nilPointer := (embedSize == 0 && b.c.token == nil) || (embedSize != 0 && b.c.embd == nil) ||
b.c.pos == nil || b.c.n_seq_id == nil || b.c.seq_id == nil || b.c.logits == nil ||
slices.Contains(unsafe.Slice(b.c.seq_id, b.allocSize()), nil)
if nilPointer {
C.llama_batch_free(b.c)
return nil, fmt.Errorf("unable to allocate batch (batchSize=%v maxSeq=%v embedSize=%v)", batchSize, maxSeq, embedSize)
}
return &b, nil
}
|
NewBatch
| 312
| 331
|
llama/llama.go
|
#FILE: ollama-main/server/create_test.go
##CHUNK 1
files := map[string]string{
tt.filePath: model,
"config.json": config,
"tokenizer.json": tokenizer,
}
_, err := convertFromSafetensors(files, nil, false, func(resp api.ProgressResponse) {})
if (tt.wantErr == nil && err != nil) ||
(tt.wantErr != nil && err == nil) ||
(tt.wantErr != nil && !errors.Is(err, tt.wantErr)) {
t.Errorf("convertFromSafetensors() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
##CHUNK 2
{
name: "ValidRelativePath",
filePath: "model.safetensors",
wantErr: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create the minimum required file map for convertFromSafetensors
files := map[string]string{
tt.filePath: model,
"config.json": config,
"tokenizer.json": tokenizer,
}
_, err := convertFromSafetensors(files, nil, false, func(resp api.ProgressResponse) {})
if (tt.wantErr == nil && err != nil) ||
(tt.wantErr != nil && err == nil) ||
#FILE: ollama-main/llm/server.go
##CHUNK 1
} else if kvct != "" && kvct != "f16" {
slog.Warn("quantized kv cache requested but flash attention disabled", "type", kvct)
}
// mmap has issues with partial offloading on metal
for _, g := range gpus {
if g.Library == "metal" &&
uint64(opts.NumGPU) > 0 &&
uint64(opts.NumGPU) < f.KV().BlockCount()+1 {
opts.UseMMap = new(bool)
*opts.UseMMap = false
}
}
// Windows CUDA should not use mmap for best performance
// Linux with a model larger than free space, mmap leads to thrashing
// For CPU loads we want the memory to be allocated, not FS cache
if (runtime.GOOS == "windows" && gpus[0].Library == "cuda" && opts.UseMMap == nil) ||
(runtime.GOOS == "linux" && systemFreeMemory < estimate.TotalSize && opts.UseMMap == nil) ||
(gpus[0].Library == "cpu" && opts.UseMMap == nil) ||
##CHUNK 2
*opts.UseMMap = false
}
}
// Windows CUDA should not use mmap for best performance
// Linux with a model larger than free space, mmap leads to thrashing
// For CPU loads we want the memory to be allocated, not FS cache
if (runtime.GOOS == "windows" && gpus[0].Library == "cuda" && opts.UseMMap == nil) ||
(runtime.GOOS == "linux" && systemFreeMemory < estimate.TotalSize && opts.UseMMap == nil) ||
(gpus[0].Library == "cpu" && opts.UseMMap == nil) ||
(opts.UseMMap != nil && !*opts.UseMMap) {
params = append(params, "--no-mmap")
}
// TODO - NUMA support currently doesn't work properly
params = append(params, "--parallel", strconv.Itoa(numParallel))
if estimate.TensorSplit != "" {
params = append(params, "--tensor-split", estimate.TensorSplit)
#FILE: ollama-main/server/internal/client/ollama/registry_test.go
##CHUNK 1
}
func TestPushSizeMismatch(t *testing.T) {
rc, _ := newClient(t, nil)
ctx, _ := withTraceUnexpected(t.Context())
got := rc.Push(ctx, "sizemismatch", nil)
if got == nil || !strings.Contains(got.Error(), "size mismatch") {
t.Errorf("err = %v; want size mismatch", got)
}
}
func TestPushInvalid(t *testing.T) {
rc, _ := newClient(t, nil)
err := rc.Push(t.Context(), "invalid", nil)
if err == nil || !strings.Contains(err.Error(), "invalid manifest") {
t.Errorf("err = %v; want invalid manifest", err)
}
}
func TestPushExistsAtRemote(t *testing.T) {
##CHUNK 2
t.Errorf("err = %v; want %v", err, fs.ErrNotExist)
}
}
func TestPushNullLayer(t *testing.T) {
rc, _ := newClient(t, nil)
err := rc.Push(t.Context(), "null", nil)
if err == nil || !strings.Contains(err.Error(), "invalid manifest") {
t.Errorf("err = %v; want invalid manifest", err)
}
}
func TestPushSizeMismatch(t *testing.T) {
rc, _ := newClient(t, nil)
ctx, _ := withTraceUnexpected(t.Context())
got := rc.Push(ctx, "sizemismatch", nil)
if got == nil || !strings.Contains(got.Error(), "size mismatch") {
t.Errorf("err = %v; want size mismatch", got)
}
}
#FILE: ollama-main/server/routes.go
##CHUNK 1
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
return func(c *gin.Context) {
if addr == nil {
c.Next()
return
}
if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
c.Next()
return
}
host, _, err := net.SplitHostPort(c.Request.Host)
if err != nil {
host = c.Request.Host
}
if addr, err := netip.ParseAddr(host); err == nil {
if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
c.Next()
#FILE: ollama-main/model/model.go
##CHUNK 1
func canNil(t reflect.Type) bool {
return t.Kind() == reflect.Chan ||
t.Kind() == reflect.Func ||
t.Kind() == reflect.Interface ||
t.Kind() == reflect.Map ||
t.Kind() == reflect.Pointer ||
t.Kind() == reflect.Slice
}
func Forward(ctx ml.Context, m Model, inputs []int32, batch input.Batch) (ml.Tensor, error) {
if len(batch.Positions) != len(batch.Sequences) {
return nil, fmt.Errorf("length of positions (%v) must match length of seqs (%v)", len(batch.Positions), len(batch.Sequences))
}
if len(batch.Positions) < 1 {
return nil, errors.New("batch size cannot be less than 1")
}
batch.Inputs = ctx.Input().FromIntSlice(inputs, len(inputs))
##CHUNK 2
for _, part := range parts[1:] {
if value, ok := strings.CutPrefix(part, "alt:"); ok {
tag.Alternate = append(tag.Alternate, value)
}
}
}
return
}
func canNil(t reflect.Type) bool {
return t.Kind() == reflect.Chan ||
t.Kind() == reflect.Func ||
t.Kind() == reflect.Interface ||
t.Kind() == reflect.Map ||
t.Kind() == reflect.Pointer ||
t.Kind() == reflect.Slice
}
#FILE: ollama-main/runner/llamarunner/runner.go
##CHUNK 1
if batch == nil || batch.NumTokens() == 0 {
return nil
}
err := s.lc.Decode(batch)
if err != nil {
return fmt.Errorf("failed to decode batch: %w", err)
}
for i, seq := range s.seqs {
if seq == nil {
continue
}
// After calling Decode, pending inputs are now in the cache
if len(seq.pendingInputs) > 0 {
seq.cache.Inputs = append(seq.cache.Inputs, seq.pendingInputs...)
seq.pendingInputs = []input{}
}
#CURRENT FILE: ollama-main/llama/llama.go
|
ollama-main
| 87
|
func NewSamplingContext(model *Model, params SamplingParams) (*SamplingContext, error) {
var cparams C.struct_common_sampler_cparams
cparams.top_k = C.int32_t(params.TopK)
cparams.top_p = C.float(params.TopP)
cparams.min_p = C.float(params.MinP)
cparams.typical_p = C.float(params.TypicalP)
cparams.temp = C.float(params.Temp)
cparams.penalty_last_n = C.int32_t(params.RepeatLastN)
cparams.penalty_repeat = C.float(params.PenaltyRepeat)
cparams.penalty_freq = C.float(params.PenaltyFreq)
cparams.penalty_present = C.float(params.PenaltyPresent)
cparams.seed = C.uint32_t(params.Seed)
grammar := C.CString(params.Grammar)
defer C.free(unsafe.Pointer(grammar))
cparams.grammar = grammar
context := &SamplingContext{c: C.common_sampler_cinit(model.c, &cparams)}
if context.c == nil {
return nil, errors.New("unable to create sampling context")
}
runtime.SetFinalizer(context, func(s *SamplingContext) { C.common_sampler_cfree(s.c) })
return context, nil
}
|
func NewSamplingContext(model *Model, params SamplingParams) (*SamplingContext, error) {
var cparams C.struct_common_sampler_cparams
cparams.top_k = C.int32_t(params.TopK)
cparams.top_p = C.float(params.TopP)
cparams.min_p = C.float(params.MinP)
cparams.typical_p = C.float(params.TypicalP)
cparams.temp = C.float(params.Temp)
cparams.penalty_last_n = C.int32_t(params.RepeatLastN)
cparams.penalty_repeat = C.float(params.PenaltyRepeat)
cparams.penalty_freq = C.float(params.PenaltyFreq)
cparams.penalty_present = C.float(params.PenaltyPresent)
cparams.seed = C.uint32_t(params.Seed)
grammar := C.CString(params.Grammar)
defer C.free(unsafe.Pointer(grammar))
cparams.grammar = grammar
context := &SamplingContext{c: C.common_sampler_cinit(model.c, &cparams)}
if context.c == nil {
return nil, errors.New("unable to create sampling context")
}
runtime.SetFinalizer(context, func(s *SamplingContext) { C.common_sampler_cfree(s.c) })
return context, nil
}
|
func NewSamplingContext(model *Model, params SamplingParams) (*SamplingContext, error) {
var cparams C.struct_common_sampler_cparams
cparams.top_k = C.int32_t(params.TopK)
cparams.top_p = C.float(params.TopP)
cparams.min_p = C.float(params.MinP)
cparams.typical_p = C.float(params.TypicalP)
cparams.temp = C.float(params.Temp)
cparams.penalty_last_n = C.int32_t(params.RepeatLastN)
cparams.penalty_repeat = C.float(params.PenaltyRepeat)
cparams.penalty_freq = C.float(params.PenaltyFreq)
cparams.penalty_present = C.float(params.PenaltyPresent)
cparams.seed = C.uint32_t(params.Seed)
grammar := C.CString(params.Grammar)
defer C.free(unsafe.Pointer(grammar))
cparams.grammar = grammar
context := &SamplingContext{c: C.common_sampler_cinit(model.c, &cparams)}
if context.c == nil {
return nil, errors.New("unable to create sampling context")
}
runtime.SetFinalizer(context, func(s *SamplingContext) { C.common_sampler_cfree(s.c) })
return context, nil
}
|
NewSamplingContext
| 536
| 561
|
llama/llama.go
|
#FILE: ollama-main/sample/samplers.go
##CHUNK 1
minP: minP,
temperature: temperature,
grammar: grammar,
}
}
type GrammarSampler struct {
grammar *llama.Grammar
}
func NewGrammarSampler(model model.TextProcessor, grammarStr string) (*GrammarSampler, error) {
vocabIds := make([]uint32, len(model.Vocabulary().Values))
pieces := make([]string, len(model.Vocabulary().Values))
for i := range model.Vocabulary().Values {
pieces[i], _ = model.Decode([]int32{int32(i)})
vocabIds[i] = uint32(i)
}
grammar := llama.NewGrammar(grammarStr, vocabIds, pieces, model.Vocabulary().EOS)
if grammar == nil {
##CHUNK 2
func NewGrammarSampler(model model.TextProcessor, grammarStr string) (*GrammarSampler, error) {
vocabIds := make([]uint32, len(model.Vocabulary().Values))
pieces := make([]string, len(model.Vocabulary().Values))
for i := range model.Vocabulary().Values {
pieces[i], _ = model.Decode([]int32{int32(i)})
vocabIds[i] = uint32(i)
}
grammar := llama.NewGrammar(grammarStr, vocabIds, pieces, model.Vocabulary().EOS)
if grammar == nil {
return nil, errors.New("sample: failed to initialize grammar")
}
return &GrammarSampler{grammar: grammar}, nil
}
func (g *GrammarSampler) Apply(tokens []token) {
tds := make([]llama.TokenData, len(tokens))
for i, token := range tokens {
tds[i].ID = token.id
##CHUNK 3
return -1, err
}
if s.grammar != nil {
// optimization: first check if the max logit is accepted by the grammar
// if the max logit is rejected, apply the grammar to all logits (slower)
top := []token{t}
s.grammar.Apply(top)
if !math.IsInf(float64(top[0].value), -1) {
s.grammar.Accept(top[0].id)
return top[0].id, nil
}
// since .sample has side effects of modifying the tokens
// we need to reset them before applying the grammar and
// sampling again
for i := range logits {
tokens[i].id = int32(i)
tokens[i].value = logits[i]
}
#FILE: ollama-main/sample/samplers_test.go
##CHUNK 1
tokens[i].id = int32(i)
tokens[i].value = logits[i]
}
grammar.Apply(tokens)
nonInfCount := 0
infCount := 0
for _, tok := range tokens {
if math.IsInf(float64(tok.value), -1) {
infCount++
} else {
nonInfCount++
}
}
if nonInfCount == 0 {
t.Error("expected at least one non -inf token after grammar application, got none")
}
if infCount == 0 {
t.Error("expected some -inf tokens after grammar application, got none")
}
#CURRENT FILE: ollama-main/llama/llama.go
##CHUNK 1
func FreeModel(model *Model) {
C.llama_model_free(model.c)
}
func NewContextWithModel(model *Model, params ContextParams) (*Context, error) {
c := Context{
c: C.llama_init_from_model(model.c, params.c),
numThreads: int(params.c.n_threads),
}
if c.c == nil {
return nil, errors.New("unable to create llama context")
}
return &c, nil
}
func (m *Model) NumVocab() int {
return int(C.llama_vocab_n_tokens(m.Vocab()))
}
##CHUNK 2
}
m := Model{c: C.llama_model_load_from_file(C.CString(modelPath), cparams)}
if m.c == nil {
return nil, fmt.Errorf("unable to load model: %s", modelPath)
}
return &m, nil
}
func FreeModel(model *Model) {
C.llama_model_free(model.c)
}
func NewContextWithModel(model *Model, params ContextParams) (*Context, error) {
c := Context{
c: C.llama_init_from_model(model.c, params.c),
numThreads: int(params.c.n_threads),
}
if c.c == nil {
##CHUNK 3
func (s *SamplingContext) Sample(llamaContext *Context, idx int) int {
return int(C.common_sampler_csample(s.c, llamaContext.c, C.int(idx)))
}
func (s *SamplingContext) Accept(id int, applyGrammar bool) {
C.common_sampler_caccept(s.c, C.llama_token(id), C.bool(applyGrammar))
}
// SchemaToGrammar converts the provided JSON schema to a grammar. It returns
// nil if the provided schema is invalid JSON or an invalid JSON schema.
func SchemaToGrammar(schema []byte) []byte {
cStr := C.CString(string(schema))
defer C.free(unsafe.Pointer(cStr))
// Allocate buffer for grammar based on schema length but with upper bound
maxLen := max(32768, min(1024*1024, len(schema)*4))
buf := make([]byte, maxLen)
// Call C function to convert schema to grammar
##CHUNK 4
return true
}
func LoadModelFromFile(modelPath string, params ModelParams) (*Model, error) {
cparams := C.llama_model_default_params()
cparams.n_gpu_layers = C.int(params.NumGpuLayers)
cparams.main_gpu = C.int32_t(params.MainGpu)
cparams.use_mmap = C.bool(params.UseMmap)
cparams.vocab_only = C.bool(params.VocabOnly)
if len(params.TensorSplit) > 0 {
tensorSplitData := ¶ms.TensorSplit[0]
var tensorSplitPin runtime.Pinner
tensorSplitPin.Pin(tensorSplitData)
defer tensorSplitPin.Unpin()
cparams.tensor_split = (*C.float)(unsafe.Pointer(tensorSplitData))
}
##CHUNK 5
C.grammar_apply(g.c, tda)
for i := range tokens {
tokens[i].Logit = float32(tds[i].logit)
}
}
func (g *Grammar) Accept(token int32) {
g.mu.Lock()
defer g.mu.Unlock()
// Check if grammar was freed
if g.c == nil {
return
}
C.grammar_accept(g.c, C.llama_token(token))
}
##CHUNK 6
return nil, errors.New("unable to create llama context")
}
return &c, nil
}
func (m *Model) NumVocab() int {
return int(C.llama_vocab_n_tokens(m.Vocab()))
}
func (m *Model) TokenIsEog(token int) bool {
return bool(C.llama_vocab_is_eog(m.Vocab(), C.llama_token(token)))
}
func (m *Model) AddBOSToken() bool {
return bool(C.llama_vocab_get_add_bos(m.Vocab()))
}
func (m *Model) ApplyLoraFromFile(context *Context, loraPath string, scale float32, threads int) error {
cLoraPath := C.CString(loraPath)
|
ollama-main
| 88
|
func eat(s *Parser) (string, string, bool) {
switch s.state {
case thinkingState_LookingForOpening:
trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace)
if strings.HasPrefix(trimmed, s.OpeningTag) {
after := strings.Join(strings.Split(trimmed, s.OpeningTag)[1:], s.OpeningTag)
after = strings.TrimLeftFunc(after, unicode.IsSpace)
// after might contain more than just thinking tokens, so we continue
// parsing instead of returning it as thinking tokens here
s.acc.Reset()
s.acc.WriteString(after)
if after == "" {
s.state = thinkingState_ThinkingStartedEatingWhitespace
} else {
s.state = thinkingState_Thinking
}
return "", "", true
} else if strings.HasPrefix(s.OpeningTag, trimmed) {
// partial opening seen, so let's keep accumulating
return "", "", false
} else if trimmed == "" {
// saw whitespace only, so let's keep accumulating
return "", "", false
} else {
// didn't see an opening tag, but we have content, so thinking was skipped
s.state = thinkingState_ThinkingDone
// note that we use the original content, not the trimmed one because we
// don't want to eat any whitespace in the real content if there were no
// thinking tags
return "", s.acc.String(), false
}
case thinkingState_ThinkingStartedEatingWhitespace:
trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace)
s.acc.Reset()
if trimmed == "" {
return "", "", false
} else {
s.state = thinkingState_Thinking
s.acc.WriteString(trimmed)
return "", "", true
}
case thinkingState_Thinking:
acc := s.acc.String()
if strings.Contains(acc, s.ClosingTag) {
split := strings.Split(acc, s.ClosingTag)
thinking := split[0]
remaining := strings.Join(split[1:], s.ClosingTag)
remaining = strings.TrimLeftFunc(remaining, unicode.IsSpace)
s.acc.Reset()
if remaining == "" {
s.state = thinkingState_ThinkingDoneEatingWhitespace
} else {
s.state = thinkingState_ThinkingDone
}
return thinking, remaining, false
} else if overlapLen := overlap(acc, s.ClosingTag); overlapLen > 0 {
thinking := acc[:len(acc)-overlapLen]
remaining := acc[len(acc)-overlapLen:]
s.acc.Reset()
// keep track of the candidate closing tag. We have to buffer it until it
// becomes disambiguated
s.acc.WriteString(remaining)
return thinking, "", false
} else {
// purely just thinking tokens, so we can return them
s.acc.Reset()
return acc, "", false
}
case thinkingState_ThinkingDoneEatingWhitespace:
trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace)
s.acc.Reset()
// if we see non-whitespace, we're done eating the leading whitespace of the content
if trimmed != "" {
s.state = thinkingState_ThinkingDone
}
return "", trimmed, false
case thinkingState_ThinkingDone:
acc := s.acc.String()
s.acc.Reset()
return "", acc, false
default:
panic("unknown state")
}
}
|
func eat(s *Parser) (string, string, bool) {
switch s.state {
case thinkingState_LookingForOpening:
trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace)
if strings.HasPrefix(trimmed, s.OpeningTag) {
after := strings.Join(strings.Split(trimmed, s.OpeningTag)[1:], s.OpeningTag)
after = strings.TrimLeftFunc(after, unicode.IsSpace)
// after might contain more than just thinking tokens, so we continue
// parsing instead of returning it as thinking tokens here
s.acc.Reset()
s.acc.WriteString(after)
if after == "" {
s.state = thinkingState_ThinkingStartedEatingWhitespace
} else {
s.state = thinkingState_Thinking
}
return "", "", true
} else if strings.HasPrefix(s.OpeningTag, trimmed) {
// partial opening seen, so let's keep accumulating
return "", "", false
} else if trimmed == "" {
// saw whitespace only, so let's keep accumulating
return "", "", false
} else {
// didn't see an opening tag, but we have content, so thinking was skipped
s.state = thinkingState_ThinkingDone
// note that we use the original content, not the trimmed one because we
// don't want to eat any whitespace in the real content if there were no
// thinking tags
return "", s.acc.String(), false
}
case thinkingState_ThinkingStartedEatingWhitespace:
trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace)
s.acc.Reset()
if trimmed == "" {
return "", "", false
} else {
s.state = thinkingState_Thinking
s.acc.WriteString(trimmed)
return "", "", true
}
case thinkingState_Thinking:
acc := s.acc.String()
if strings.Contains(acc, s.ClosingTag) {
split := strings.Split(acc, s.ClosingTag)
thinking := split[0]
remaining := strings.Join(split[1:], s.ClosingTag)
remaining = strings.TrimLeftFunc(remaining, unicode.IsSpace)
s.acc.Reset()
if remaining == "" {
s.state = thinkingState_ThinkingDoneEatingWhitespace
} else {
s.state = thinkingState_ThinkingDone
}
return thinking, remaining, false
} else if overlapLen := overlap(acc, s.ClosingTag); overlapLen > 0 {
thinking := acc[:len(acc)-overlapLen]
remaining := acc[len(acc)-overlapLen:]
s.acc.Reset()
// keep track of the candidate closing tag. We have to buffer it until it
// becomes disambiguated
s.acc.WriteString(remaining)
return thinking, "", false
} else {
// purely just thinking tokens, so we can return them
s.acc.Reset()
return acc, "", false
}
case thinkingState_ThinkingDoneEatingWhitespace:
trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace)
s.acc.Reset()
// if we see non-whitespace, we're done eating the leading whitespace of the content
if trimmed != "" {
s.state = thinkingState_ThinkingDone
}
return "", trimmed, false
case thinkingState_ThinkingDone:
acc := s.acc.String()
s.acc.Reset()
return "", acc, false
default:
panic("unknown state")
}
}
|
func eat(s *Parser) (string, string, bool) {
switch s.state {
case thinkingState_LookingForOpening:
trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace)
if strings.HasPrefix(trimmed, s.OpeningTag) {
after := strings.Join(strings.Split(trimmed, s.OpeningTag)[1:], s.OpeningTag)
after = strings.TrimLeftFunc(after, unicode.IsSpace)
// after might contain more than just thinking tokens, so we continue
// parsing instead of returning it as thinking tokens here
s.acc.Reset()
s.acc.WriteString(after)
if after == "" {
s.state = thinkingState_ThinkingStartedEatingWhitespace
} else {
s.state = thinkingState_Thinking
}
return "", "", true
} else if strings.HasPrefix(s.OpeningTag, trimmed) {
// partial opening seen, so let's keep accumulating
return "", "", false
} else if trimmed == "" {
// saw whitespace only, so let's keep accumulating
return "", "", false
} else {
// didn't see an opening tag, but we have content, so thinking was skipped
s.state = thinkingState_ThinkingDone
// note that we use the original content, not the trimmed one because we
// don't want to eat any whitespace in the real content if there were no
// thinking tags
return "", s.acc.String(), false
}
case thinkingState_ThinkingStartedEatingWhitespace:
trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace)
s.acc.Reset()
if trimmed == "" {
return "", "", false
} else {
s.state = thinkingState_Thinking
s.acc.WriteString(trimmed)
return "", "", true
}
case thinkingState_Thinking:
acc := s.acc.String()
if strings.Contains(acc, s.ClosingTag) {
split := strings.Split(acc, s.ClosingTag)
thinking := split[0]
remaining := strings.Join(split[1:], s.ClosingTag)
remaining = strings.TrimLeftFunc(remaining, unicode.IsSpace)
s.acc.Reset()
if remaining == "" {
s.state = thinkingState_ThinkingDoneEatingWhitespace
} else {
s.state = thinkingState_ThinkingDone
}
return thinking, remaining, false
} else if overlapLen := overlap(acc, s.ClosingTag); overlapLen > 0 {
thinking := acc[:len(acc)-overlapLen]
remaining := acc[len(acc)-overlapLen:]
s.acc.Reset()
// keep track of the candidate closing tag. We have to buffer it until it
// becomes disambiguated
s.acc.WriteString(remaining)
return thinking, "", false
} else {
// purely just thinking tokens, so we can return them
s.acc.Reset()
return acc, "", false
}
case thinkingState_ThinkingDoneEatingWhitespace:
trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace)
s.acc.Reset()
// if we see non-whitespace, we're done eating the leading whitespace of the content
if trimmed != "" {
s.state = thinkingState_ThinkingDone
}
return "", trimmed, false
case thinkingState_ThinkingDone:
acc := s.acc.String()
s.acc.Reset()
return "", acc, false
default:
panic("unknown state")
}
}
|
eat
| 76
| 159
|
thinking/parser.go
|
#FILE: ollama-main/model/sentencepiece.go
##CHUNK 1
// so they are buffered correctly by the runner instead
// of being sent back to the api as "<0xEA>"
if len(data) == 6 && strings.HasPrefix(data, "<0x") && strings.HasSuffix(data, ">") {
byteVal, err := strconv.ParseUint(data[1:5], 0, 8)
if err != nil {
return "", fmt.Errorf("failed to parse hex byte: %v", err)
}
if err := sb.WriteByte(byte(byteVal)); err != nil {
return "", err
}
} else {
if _, err := sb.WriteString(data); err != nil {
return "", err
}
}
}
slog.Log(context.TODO(), logutil.LevelTrace, "decoded", "ids", ids, "string", sb.String())
return sb.String(), nil
#FILE: ollama-main/readline/readline.go
##CHUNK 1
return "", io.EOF
}
code += string(r)
}
if code == CharBracketedPasteStart {
i.Pasting = true
} else if code == CharBracketedPasteEnd {
i.Pasting = false
}
case KeyDel:
if buf.DisplaySize() > 0 {
buf.Delete()
}
metaDel = true
case MetaStart:
buf.MoveToStart()
case MetaEnd:
buf.MoveToEnd()
default:
#FILE: ollama-main/discover/amd_linux.go
##CHUNK 1
}
// Quick check for AMD driver so we can skip amdgpu discovery if not present
func AMDDetected() bool {
// Some driver versions (older?) don't have a version file, so just lookup the parent dir
sysfsDir := filepath.Dir(DriverVersionFile)
_, err := os.Stat(sysfsDir)
if errors.Is(err, os.ErrNotExist) {
slog.Debug("amdgpu driver not detected " + sysfsDir)
return false
} else if err != nil {
slog.Debug("error looking up amd driver", "path", sysfsDir, "error", err)
return false
}
return true
}
// Prefer to use host installed ROCm, as long as it meets our minimum requirements
// failing that, tell the user how to download it on their own
func AMDValidateLibDir() (string, error) {
#FILE: ollama-main/thinking/parser_test.go
##CHUNK 1
input: " more content",
wantThinking: "",
wantContent: "more content",
wantStateAfter: thinkingState_ThinkingDone,
},
},
},
}
for _, c := range cases {
parser := Parser{
OpeningTag: "<think>",
ClosingTag: "</think>",
}
if c.skip {
continue
}
for i, step := range c.steps {
thinking, content := parser.AddContent(step.input)
if content != step.wantContent || thinking != step.wantThinking {
#FILE: ollama-main/integration/api_test.go
##CHUNK 1
if buf.Len() == 0 {
t.Errorf("generate never started. Timed out after :%s", initialTimeout.String())
} else {
t.Errorf("generate stalled. Response so far:%s", buf.String())
}
case <-done:
if genErr != nil {
t.Fatalf("failed with %s request prompt %s ", req.Model, req.Prompt)
}
// Verify the response contains the expected data
response := buf.String()
atLeastOne := false
for _, resp := range anyResp {
if strings.Contains(strings.ToLower(response), resp) {
atLeastOne = true
break
}
}
if !atLeastOne {
t.Errorf("none of %v found in %s", anyResp, response)
#FILE: ollama-main/server/auth.go
##CHUNK 1
if err != nil {
return "", err
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return "", fmt.Errorf("%d: %v", response.StatusCode, err)
}
if response.StatusCode >= http.StatusBadRequest {
if len(body) > 0 {
return "", fmt.Errorf("%d: %s", response.StatusCode, body)
} else {
return "", fmt.Errorf("%d", response.StatusCode)
}
}
var token api.TokenResponse
if err := json.Unmarshal(body, &token); err != nil {
#FILE: ollama-main/types/model/name.go
##CHUNK 1
}
func cutLast(s, sep string) (before, after string, ok bool) {
i := strings.LastIndex(s, sep)
if i >= 0 {
return s[:i], s[i+len(sep):], true
}
return s, "", false
}
// cutPromised cuts the last part of s at the last occurrence of sep. If sep is
// found, the part before and after sep are returned as-is unless empty, in
// which case they are returned as MissingPart, which will cause
// [Name.IsValid] to return false.
func cutPromised(s, sep string) (before, after string, ok bool) {
before, after, ok = cutLast(s, sep)
if !ok {
return before, after, false
}
return cmp.Or(before, MissingPart), cmp.Or(after, MissingPart), true
#FILE: ollama-main/model/model.go
##CHUNK 1
slog.Log(context.TODO(), logutil.LevelTrace, "found tensor", "", tensor)
vv.Set(reflect.ValueOf(tensor))
break
}
}
} else if tt.Kind() == reflect.Pointer || tt.Kind() == reflect.Interface {
setPointer(base, vv, tagsCopy)
} else if tt.Kind() == reflect.Slice || tt.Kind() == reflect.Array {
for i := range vv.Len() {
vvv := vv.Index(i)
if vvv.Kind() == reflect.Pointer || vvv.Kind() == reflect.Interface {
setPointer(base, vvv, append(tagsCopy, Tag{Name: strconv.Itoa(i)}))
} else {
vvv.Set(populateFields(base, vvv, append(tagsCopy, Tag{Name: strconv.Itoa(i)})...))
}
}
}
if !canNil(tt) || !vv.IsNil() {
allNil = false
#FILE: ollama-main/server/internal/client/ollama/registry.go
##CHUNK 1
var d blob.Digest
if digest != "" {
var err error
d, err = blob.ParseDigest(digest)
if err != nil {
err = withPublicMessagef(ErrNameInvalid, "invalid digest: %q", digest)
return "", names.Name{}, blob.Digest{}, err
}
if name == "" {
// We have can resolve a manifest from a digest only,
// so skip name validation and return the scheme and
// digest.
return scheme, names.Name{}, d, nil
}
}
n, err := r.parseName(name)
if err != nil {
return "", names.Name{}, blob.Digest{}, err
#CURRENT FILE: ollama-main/thinking/parser.go
##CHUNK 1
acc strings.Builder
}
// AddContent returns the thinking content and the non-thinking content that
// should be immediately sent to the user. It will internally buffer if it needs
// to see more raw content to disambiguate
func (s *Parser) AddContent(content string) (string, string) {
s.acc.WriteString(content)
var thinkingSb, remainingSb strings.Builder
var thinking, remaining string
keepLooping := true
// we loop because we might pass through multiple parsing states in a single
// call to addContent, and we want to make sure callers don't have to wait for
// data that's already unambiguous
for keepLooping {
thinking, remaining, keepLooping = eat(s)
thinkingSb.WriteString(thinking)
remainingSb.WriteString(remaining)
|
ollama-main
| 89
|
func InferTags(t *template.Template) (string, string) {
ancestors := []parse.Node{}
openingTag := ""
closingTag := ""
enterFn := func(n parse.Node) bool {
ancestors = append(ancestors, n)
switch x := n.(type) {
case *parse.FieldNode:
if len(x.Ident) > 0 && x.Ident[0] == "Thinking" {
var mostRecentRange *parse.RangeNode
for i := len(ancestors) - 1; i >= 0; i-- {
if r, ok := ancestors[i].(*parse.RangeNode); ok {
mostRecentRange = r
break
}
}
if mostRecentRange == nil || !rangeUsesField(mostRecentRange, "Messages") {
return true
}
// TODO(drifkin): to be more robust, check that it's in the action
// part, not the `if`'s pipeline part. We do match on the nearest list
// that starts and ends with text nodes, which makes this not strictly
// necessary for our heuristic
// go up to the nearest ancestor that is a *parse.ListNode
for i := len(ancestors) - 1; i >= 0; i-- {
if l, ok := ancestors[i].(*parse.ListNode); ok {
firstNode := l.Nodes[0]
if t, ok := firstNode.(*parse.TextNode); ok {
openingTag = strings.TrimSpace(t.String())
}
lastNode := l.Nodes[len(l.Nodes)-1]
if t, ok := lastNode.(*parse.TextNode); ok {
closingTag = strings.TrimSpace(t.String())
}
break
}
}
}
}
return true
}
exitFn := func(n parse.Node) {
ancestors = ancestors[:len(ancestors)-1]
}
templateVisit(t.Root, enterFn, exitFn)
return openingTag, closingTag
}
|
func InferTags(t *template.Template) (string, string) {
ancestors := []parse.Node{}
openingTag := ""
closingTag := ""
enterFn := func(n parse.Node) bool {
ancestors = append(ancestors, n)
switch x := n.(type) {
case *parse.FieldNode:
if len(x.Ident) > 0 && x.Ident[0] == "Thinking" {
var mostRecentRange *parse.RangeNode
for i := len(ancestors) - 1; i >= 0; i-- {
if r, ok := ancestors[i].(*parse.RangeNode); ok {
mostRecentRange = r
break
}
}
if mostRecentRange == nil || !rangeUsesField(mostRecentRange, "Messages") {
return true
}
// TODO(drifkin): to be more robust, check that it's in the action
// part, not the `if`'s pipeline part. We do match on the nearest list
// that starts and ends with text nodes, which makes this not strictly
// necessary for our heuristic
// go up to the nearest ancestor that is a *parse.ListNode
for i := len(ancestors) - 1; i >= 0; i-- {
if l, ok := ancestors[i].(*parse.ListNode); ok {
firstNode := l.Nodes[0]
if t, ok := firstNode.(*parse.TextNode); ok {
openingTag = strings.TrimSpace(t.String())
}
lastNode := l.Nodes[len(l.Nodes)-1]
if t, ok := lastNode.(*parse.TextNode); ok {
closingTag = strings.TrimSpace(t.String())
}
break
}
}
}
}
return true
}
exitFn := func(n parse.Node) {
ancestors = ancestors[:len(ancestors)-1]
}
templateVisit(t.Root, enterFn, exitFn)
return openingTag, closingTag
}
|
func InferTags(t *template.Template) (string, string) {
ancestors := []parse.Node{}
openingTag := ""
closingTag := ""
enterFn := func(n parse.Node) bool {
ancestors = append(ancestors, n)
switch x := n.(type) {
case *parse.FieldNode:
if len(x.Ident) > 0 && x.Ident[0] == "Thinking" {
var mostRecentRange *parse.RangeNode
for i := len(ancestors) - 1; i >= 0; i-- {
if r, ok := ancestors[i].(*parse.RangeNode); ok {
mostRecentRange = r
break
}
}
if mostRecentRange == nil || !rangeUsesField(mostRecentRange, "Messages") {
return true
}
// TODO(drifkin): to be more robust, check that it's in the action
// part, not the `if`'s pipeline part. We do match on the nearest list
// that starts and ends with text nodes, which makes this not strictly
// necessary for our heuristic
// go up to the nearest ancestor that is a *parse.ListNode
for i := len(ancestors) - 1; i >= 0; i-- {
if l, ok := ancestors[i].(*parse.ListNode); ok {
firstNode := l.Nodes[0]
if t, ok := firstNode.(*parse.TextNode); ok {
openingTag = strings.TrimSpace(t.String())
}
lastNode := l.Nodes[len(l.Nodes)-1]
if t, ok := lastNode.(*parse.TextNode); ok {
closingTag = strings.TrimSpace(t.String())
}
break
}
}
}
}
return true
}
exitFn := func(n parse.Node) {
ancestors = ancestors[:len(ancestors)-1]
}
templateVisit(t.Root, enterFn, exitFn)
return openingTag, closingTag
}
|
InferTags
| 61
| 117
|
thinking/template.go
|
#FILE: ollama-main/llm/memory.go
##CHUNK 1
} else {
overflow += gpuZeroOverhead
}
// For all the layers, find where they can fit on the GPU(s)
for i := int(f.KV().BlockCount()) - 1; i >= 0; i-- {
// Some models have inconsistent layer sizes
if blk, ok := layers[fmt.Sprintf("blk.%d", i)]; ok {
layerSize = blk.Size()
layerSize += kv[i]
memoryWeights += blk.Size()
}
if opts.NumGPU >= 0 && layerCount >= opts.NumGPU {
// Stop allocating on GPU(s) once we hit the users target NumGPU
overflow += layerSize
continue
}
// distribute the layers across the GPU(s) that have space
##CHUNK 2
continue
}
gpusWithSpace = append(gpusWithSpace, gs{i, &gpus[i]})
gpuAllocations[i] += gpus[i].MinimumMemory + layerSize // We hold off on graph until we know partial vs. full
}
var gpuZeroID int
if len(gpusWithSpace) > 0 {
gpuZeroID = gpusWithSpace[0].i
gpuAllocations[gpuZeroID] += gpuZeroOverhead
} else {
overflow += gpuZeroOverhead
}
// For all the layers, find where they can fit on the GPU(s)
for i := int(f.KV().BlockCount()) - 1; i >= 0; i-- {
// Some models have inconsistent layer sizes
if blk, ok := layers[fmt.Sprintf("blk.%d", i)]; ok {
layerSize = blk.Size()
layerSize += kv[i]
#FILE: ollama-main/convert/tokenizer.go
##CHUNK 1
var p map[string]json.RawMessage
if err := json.NewDecoder(f).Decode(&p); err != nil {
return nil, err
}
for _, st := range specialTokenTypes {
if bts, ok := p[fmt.Sprintf("%s_token_id", st)]; ok {
var ids []int32
if err := json.Unmarshal(bts, &ids); err != nil {
// value is not a list so the existing ID is used
continue
}
if i := slices.IndexFunc(t.SpecialVocabulary, func(sv *SpecialVocabulary) bool {
return sv.Type == st
}); i >= 0 {
t.SpecialVocabulary[i].IDs = ids
}
}
}
#FILE: ollama-main/template/template.go
##CHUNK 1
return err
}
}
system = m.Content
case "user":
if response != "" {
if err := execute(); err != nil {
return err
}
}
prompt = m.Content
case "assistant":
response = m.Content
}
}
var cut bool
nodes := deleteNode(t.Template.Root.Copy(), func(n parse.Node) bool {
if field, ok := n.(*parse.FieldNode); ok && slices.Contains(field.Ident, "Response") {
cut = true
#FILE: ollama-main/tools/template.go
##CHUNK 1
tag = strings.TrimSpace(tag)
if tag == "" {
tag = "{"
}
return tag
}
// findToolCallNode searches for and returns an IfNode with .ToolCalls
func findToolCallNode(nodes []parse.Node) *parse.IfNode {
isToolCallsNode := func(n *parse.IfNode) bool {
for _, cmd := range n.Pipe.Cmds {
for _, arg := range cmd.Args {
if field, ok := arg.(*parse.FieldNode); ok {
if slices.Contains(field.Ident, "ToolCalls") {
return true
}
}
}
}
##CHUNK 2
isToolCallsNode := func(n *parse.IfNode) bool {
for _, cmd := range n.Pipe.Cmds {
for _, arg := range cmd.Args {
if field, ok := arg.(*parse.FieldNode); ok {
if slices.Contains(field.Ident, "ToolCalls") {
return true
}
}
}
}
return false
}
for _, node := range nodes {
switch n := node.(type) {
case *parse.IfNode:
if isToolCallsNode(n) {
return n
}
// Recursively search in nested IfNodes
#FILE: ollama-main/convert/convert.go
##CHUNK 1
if t, ok := conv.(moreParser); ok {
if err := t.parseMore(fsys); err != nil {
return err
}
}
t, err := parseTokenizer(fsys, conv.specialTokenTypes())
if err != nil {
return err
}
vocabSize := int(cmp.Or(p.VocabSize, p.TextModel.VocabSize))
switch {
case vocabSize == 0:
slog.Debug("vocabulary size was not explicitly set by the model", "default size", len(t.Vocabulary.Tokens))
case vocabSize > len(t.Vocabulary.Tokens):
slog.Debug("vocabulary is smaller than expected, padding with dummy tokens", "expect", vocabSize, "actual", len(t.Vocabulary.Tokens))
for i := range vocabSize - len(t.Vocabulary.Tokens) {
t.Vocabulary.Tokens = append(t.Vocabulary.Tokens, fmt.Sprintf("[PAD%d]", i))
#FILE: ollama-main/model/models/llama4/process_image.go
##CHUNK 1
seen := make(map[int]bool)
for i := 1; i <= n/2; i++ {
if n%i == 0 && !seen[i] {
result = append(result, i)
seen[i] = true
}
}
result = append(result, n)
sort.Ints(result)
return result
}
func (p ImageProcessor) supportedResolutions() []image.Point {
var resolutions []image.Point
aspectMap := make(map[float64][]image.Point)
for i := p.patchSize; i >= 1; i-- {
#CURRENT FILE: ollama-main/thinking/template.go
##CHUNK 1
}
if exitFn != nil {
exitFn(n)
}
}
// InferTags uses a heuristic to infer the tags that surround thinking traces:
// We look for a range node that iterates over "Messages" and then look for a
// reference to "Thinking" like `{{.Thinking}}`. We then go up to the nearest
// ListNode and take the first and last TextNodes as the opening and closing
}
// checks to see if the given field name is present in the pipeline of the given range node
func rangeUsesField(rangeNode *parse.RangeNode, field string) bool {
found := false
enterFn := func(n parse.Node) bool {
switch x := n.(type) {
case *parse.FieldNode:
if x.Ident[0] == field {
found = true
##CHUNK 2
}
// checks to see if the given field name is present in the pipeline of the given range node
func rangeUsesField(rangeNode *parse.RangeNode, field string) bool {
found := false
enterFn := func(n parse.Node) bool {
switch x := n.(type) {
case *parse.FieldNode:
if x.Ident[0] == field {
found = true
}
}
return true
}
templateVisit(rangeNode.BranchNode.Pipe, enterFn, nil)
return found
}
|
ollama-main
| 90
|
func NewSampler(temperature float32, topK int, topP float32, minP float32, seed int, grammar *GrammarSampler) Sampler {
var rng *rand.Rand
if seed != -1 {
// PCG requires two parameters: sequence and stream
// Use original seed for sequence
sequence := uint64(seed)
// Use golden ratio hash to generate statistically independent seeds
rng = rand.New(rand.NewPCG(sequence, sequence^0x9E3779B9))
}
if temperature < 0.0 {
temperature = 0.0
}
if topP < 0.0 {
topP = 0.0
}
if topP >= 1.0 {
topP = 1.0
}
if minP < 0.0 {
minP = 0.0
}
if minP >= 1.0 {
minP = 1.0
}
return Sampler{
rng: rng,
topK: topK,
topP: topP,
minP: minP,
temperature: temperature,
grammar: grammar,
}
}
|
func NewSampler(temperature float32, topK int, topP float32, minP float32, seed int, grammar *GrammarSampler) Sampler {
var rng *rand.Rand
if seed != -1 {
// PCG requires two parameters: sequence and stream
// Use original seed for sequence
sequence := uint64(seed)
// Use golden ratio hash to generate statistically independent seeds
rng = rand.New(rand.NewPCG(sequence, sequence^0x9E3779B9))
}
if temperature < 0.0 {
temperature = 0.0
}
if topP < 0.0 {
topP = 0.0
}
if topP >= 1.0 {
topP = 1.0
}
if minP < 0.0 {
minP = 0.0
}
if minP >= 1.0 {
minP = 1.0
}
return Sampler{
rng: rng,
topK: topK,
topP: topP,
minP: minP,
temperature: temperature,
grammar: grammar,
}
}
|
func NewSampler(temperature float32, topK int, topP float32, minP float32, seed int, grammar *GrammarSampler) Sampler {
var rng *rand.Rand
if seed != -1 {
// PCG requires two parameters: sequence and stream
// Use original seed for sequence
sequence := uint64(seed)
// Use golden ratio hash to generate statistically independent seeds
rng = rand.New(rand.NewPCG(sequence, sequence^0x9E3779B9))
}
if temperature < 0.0 {
temperature = 0.0
}
if topP < 0.0 {
topP = 0.0
}
if topP >= 1.0 {
topP = 1.0
}
if minP < 0.0 {
minP = 0.0
}
if minP >= 1.0 {
minP = 1.0
}
return Sampler{
rng: rng,
topK: topK,
topP: topP,
minP: minP,
temperature: temperature,
grammar: grammar,
}
}
|
NewSampler
| 129
| 164
|
sample/samplers.go
|
#FILE: ollama-main/sample/samplers_benchmark_test.go
##CHUNK 1
for b.Loop() {
sampler.Sample(logits)
}
})
}
configs := []struct {
name string
temperature float32
topK int
topP float32
minP float32
seed int
}{
{"Greedy", 0, -1, 0, 0, -1},
{"Temperature", 0.8, -1, 0, 0, -1},
{"TopK", 0.8, 50, 0, 0, -1},
{"TopP", 0.8, -1, 0.9, 0, -1},
{"MinP", 0.8, -1, 0, 0.05, -1},
{"WithSeed", 0.8, 50, 0, 0, 42},
##CHUNK 2
topP float32
minP float32
seed int
}{
{"Greedy", 0, -1, 0, 0, -1},
{"Temperature", 0.8, -1, 0, 0, -1},
{"TopK", 0.8, 50, 0, 0, -1},
{"TopP", 0.8, -1, 0.9, 0, -1},
{"MinP", 0.8, -1, 0, 0.05, -1},
{"WithSeed", 0.8, 50, 0, 0, 42},
}
// Fixed size for common vocab size
size := 128000
logits := make([]float32, size)
for i := range logits {
logits[i] = float32(rand.Float64()*10 - 5)
}
for _, tc := range configs {
#FILE: ollama-main/openai/openai.go
##CHUNK 1
if r.MaxTokens != nil {
options["num_predict"] = *r.MaxTokens
}
if r.Temperature != nil {
options["temperature"] = *r.Temperature
} else {
options["temperature"] = 1.0
}
if r.Seed != nil {
options["seed"] = *r.Seed
}
options["frequency_penalty"] = r.FrequencyPenalty
options["presence_penalty"] = r.PresencePenalty
if r.TopP != 0.0 {
##CHUNK 2
if r.Seed != nil {
options["seed"] = *r.Seed
}
options["frequency_penalty"] = r.FrequencyPenalty
options["presence_penalty"] = r.PresencePenalty
if r.TopP != 0.0 {
options["top_p"] = r.TopP
} else {
options["top_p"] = 1.0
}
return api.GenerateRequest{
Model: r.Model,
Prompt: r.Prompt,
Options: options,
Stream: &r.Stream,
#FILE: ollama-main/sample/transforms.go
##CHUNK 1
if p == 1.0 {
return ts
}
// Find cutoff index where cumulative sum exceeds p
var sum float32
for i, t := range ts {
sum += t.value
if sum > float32(p) {
return ts[:i+1]
}
}
return ts
}
// minP filters tokens with probabilities >= p * max_prob
// requires ts to be sorted in descending order of probabilities
func minP(ts []token, p float32) []token {
maxProb := ts[0].value
##CHUNK 2
for i := k - 1; i >= 0; i-- {
result[i] = heap.Pop(&h).(token)
}
return result
}
// topP limits tokens to those with cumulative probability p
// requires ts to be sorted in descending order of probabilities
func topP(ts []token, p float32) []token {
if p == 1.0 {
return ts
}
// Find cutoff index where cumulative sum exceeds p
var sum float32
for i, t := range ts {
sum += t.value
if sum > float32(p) {
return ts[:i+1]
##CHUNK 3
}
}
return ts
}
// minP filters tokens with probabilities >= p * max_prob
// requires ts to be sorted in descending order of probabilities
func minP(ts []token, p float32) []token {
maxProb := ts[0].value
threshold := maxProb * p
for i, t := range ts {
if t.value < threshold {
return ts[:i]
}
}
return ts
}
#FILE: ollama-main/server/routes_test.go
##CHUNK 1
isNormalized := func(vec []float32) (res bool) {
sum := 0.0
for _, v := range vec {
sum += float64(v * v)
}
if math.Abs(sum-1) > 1e-6 {
return sum == 0
} else {
return true
}
}
for _, tc := range testCases {
t.Run("", func(t *testing.T) {
normalized := normalize(tc.input)
if !isNormalized(normalized) {
t.Errorf("Vector %v is not normalized", tc.input)
}
})
}
#CURRENT FILE: ollama-main/sample/samplers.go
##CHUNK 1
)
// token represents information about a single token during sampling
type token struct {
id int32 // The token's unique identifier
value float32 // The raw logit or probability from the model
}
type Sampler struct {
rng *rand.Rand
topK int
topP float32
minP float32
temperature float32
grammar *GrammarSampler
}
func (s *Sampler) Sample(logits []float32) (int32, error) {
if len(logits) == 0 {
return -1, errors.New("sample: no logits provided to sample")
##CHUNK 2
topK int
topP float32
minP float32
temperature float32
grammar *GrammarSampler
}
func (s *Sampler) Sample(logits []float32) (int32, error) {
if len(logits) == 0 {
return -1, errors.New("sample: no logits provided to sample")
}
tokens := make([]token, len(logits))
for i := range logits {
tokens[i].id = int32(i)
tokens[i].value = logits[i]
}
t, err := s.sample(tokens)
if err != nil {
|
ollama-main
| 91
|
func Named(s string) (*named, error) {
templates, err := templatesOnce()
if err != nil {
return nil, err
}
var template *named
score := math.MaxInt
for _, t := range templates {
if s := levenshtein.ComputeDistance(s, t.Template); s < score {
score = s
template = t
}
}
if score < 100 {
return template, nil
}
return nil, errors.New("no matching template found")
}
|
func Named(s string) (*named, error) {
templates, err := templatesOnce()
if err != nil {
return nil, err
}
var template *named
score := math.MaxInt
for _, t := range templates {
if s := levenshtein.ComputeDistance(s, t.Template); s < score {
score = s
template = t
}
}
if score < 100 {
return template, nil
}
return nil, errors.New("no matching template found")
}
|
func Named(s string) (*named, error) {
templates, err := templatesOnce()
if err != nil {
return nil, err
}
var template *named
score := math.MaxInt
for _, t := range templates {
if s := levenshtein.ComputeDistance(s, t.Template); s < score {
score = s
template = t
}
}
if score < 100 {
return template, nil
}
return nil, errors.New("no matching template found")
}
|
Named
| 70
| 90
|
template/template.go
|
#FILE: ollama-main/server/model.go
##CHUNK 1
layers = append(layers, &layerGGML{layer, nil})
}
}
return layers, nil
}
func detectChatTemplate(layers []*layerGGML) ([]*layerGGML, error) {
for _, layer := range layers {
if s := layer.GGML.KV().ChatTemplate(); s != "" {
if t, err := template.Named(s); err != nil {
slog.Debug("template detection", "error", err, "template", s)
} else {
layer, err := NewLayer(t.Reader(), "application/vnd.ollama.image.template")
if err != nil {
return nil, err
}
layer.status = fmt.Sprintf("using autodetected template %s", t.Name)
layers = append(layers, &layerGGML{layer, nil})
##CHUNK 2
}
defer blob.Close()
f, err := ggml.Decode(blob, -1)
if err != nil {
return nil, err
}
layers = append(layers, &layerGGML{layer, f})
default:
layers = append(layers, &layerGGML{layer, nil})
}
}
return layers, nil
}
func detectChatTemplate(layers []*layerGGML) ([]*layerGGML, error) {
for _, layer := range layers {
if s := layer.GGML.KV().ChatTemplate(); s != "" {
#FILE: ollama-main/convert/tokenizer.go
##CHUNK 1
return nil, err
}
if template, ok := p["chat_template"]; ok {
var s []struct {
Name string `json:"name"`
Template string `json:"template"`
}
if err := json.Unmarshal(template, &t.Template); err == nil {
// noop
} else if err := json.Unmarshal(template, &s); err == nil {
for _, e := range s {
if e.Name == "default" {
t.Template = e.Template
break
}
}
} else {
return nil, fmt.Errorf("invalid chat_template: %w", err)
}
##CHUNK 2
if f, err := fsys.Open("tokenizer_config.json"); errors.Is(err, os.ErrNotExist) {
// noop
} else if err != nil {
return nil, err
} else {
defer f.Close()
var p map[string]json.RawMessage
if err := json.NewDecoder(f).Decode(&p); err != nil {
return nil, err
}
if template, ok := p["chat_template"]; ok {
var s []struct {
Name string `json:"name"`
Template string `json:"template"`
}
if err := json.Unmarshal(template, &t.Template); err == nil {
// noop
##CHUNK 3
}
t := &Tokenizer{
Vocabulary: v,
Pre: "default",
}
addedTokens := make(map[string]token)
if f, err := fsys.Open("tokenizer.json"); errors.Is(err, os.ErrNotExist) {
} else if err != nil {
return nil, err
} else {
defer f.Close()
var tt tokenizer
if err := json.NewDecoder(f).Decode(&tt); err != nil {
return nil, err
}
for _, t := range tt.AddedTokens {
##CHUNK 4
} else if err := json.Unmarshal(template, &s); err == nil {
for _, e := range s {
if e.Name == "default" {
t.Template = e.Template
break
}
}
} else {
return nil, fmt.Errorf("invalid chat_template: %w", err)
}
}
for _, st := range specialTokenTypes {
sv := SpecialVocabulary{Type: st}
if bts, ok := p[fmt.Sprintf("add_%s_token", st)]; ok {
if err := json.Unmarshal(bts, &sv.AddToken); err != nil {
return nil, err
}
}
#FILE: ollama-main/server/create.go
##CHUNK 1
func setSystem(layers []Layer, s string) ([]Layer, error) {
layers = removeLayer(layers, "application/vnd.ollama.image.system")
if s != "" {
blob := strings.NewReader(s)
layer, err := NewLayer(blob, "application/vnd.ollama.image.system")
if err != nil {
return nil, err
}
layers = append(layers, layer)
}
return layers, nil
}
func setLicense(layers []Layer, l string) ([]Layer, error) {
blob := strings.NewReader(l)
layer, err := NewLayer(blob, "application/vnd.ollama.image.license")
if err != nil {
return nil, err
}
#FILE: ollama-main/fs/ggml/gguf.go
##CHUNK 1
// writeGGUFArray writes a slice s of type E to the write with a gguf type of t
func writeGGUFArray[S ~[]E, E any](w io.Writer, t uint32, s S) error {
if err := binary.Write(w, binary.LittleEndian, ggufTypeArray); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, t); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, uint64(len(s))); err != nil {
return err
}
if t == ggufTypeString {
for _, e := range any(s).([]string) {
if err := binary.Write(w, binary.LittleEndian, uint64(len(e))); err != nil {
return err
}
#CURRENT FILE: ollama-main/template/template.go
##CHUNK 1
return string(b)
},
}
func Parse(s string) (*Template, error) {
tmpl := template.New("").Option("missingkey=zero").Funcs(funcs)
tmpl, err := tmpl.Parse(s)
if err != nil {
return nil, err
}
t := Template{Template: tmpl, raw: s}
if vars := t.Vars(); !slices.Contains(vars, "messages") && !slices.Contains(vars, "response") {
// touch up the template and append {{ .Response }}
tmpl.Tree.Root.Nodes = append(tmpl.Tree.Root.Nodes, &response)
}
return &t, nil
}
##CHUNK 2
//go:embed index.json
var indexBytes []byte
//go:embed *.gotmpl
//go:embed *.json
var templatesFS embed.FS
var templatesOnce = sync.OnceValues(func() ([]*named, error) {
var templates []*named
if err := json.Unmarshal(indexBytes, &templates); err != nil {
return nil, err
}
for _, t := range templates {
bts, err := templatesFS.ReadFile(t.Name + ".gotmpl")
if err != nil {
return nil, err
}
|
ollama-main
| 92
|
func New(modelPath string, params ml.BackendParams) (Model, error) {
b, err := ml.NewBackend(modelPath, params)
if err != nil {
return nil, err
}
arch := b.Config().Architecture()
f, ok := models[arch]
if !ok {
return nil, fmt.Errorf("unsupported model architecture %q", arch)
}
m, err := f(b.Config())
if err != nil {
return nil, err
}
base := Base{b: b, config: m.Config()}
v := reflect.ValueOf(m)
v.Elem().Set(populateFields(base, v.Elem()))
return m, nil
}
|
func New(modelPath string, params ml.BackendParams) (Model, error) {
b, err := ml.NewBackend(modelPath, params)
if err != nil {
return nil, err
}
arch := b.Config().Architecture()
f, ok := models[arch]
if !ok {
return nil, fmt.Errorf("unsupported model architecture %q", arch)
}
m, err := f(b.Config())
if err != nil {
return nil, err
}
base := Base{b: b, config: m.Config()}
v := reflect.ValueOf(m)
v.Elem().Set(populateFields(base, v.Elem()))
return m, nil
}
|
func New(modelPath string, params ml.BackendParams) (Model, error) {
b, err := ml.NewBackend(modelPath, params)
if err != nil {
return nil, err
}
arch := b.Config().Architecture()
f, ok := models[arch]
if !ok {
return nil, fmt.Errorf("unsupported model architecture %q", arch)
}
m, err := f(b.Config())
if err != nil {
return nil, err
}
base := Base{b: b, config: m.Config()}
v := reflect.ValueOf(m)
v.Elem().Set(populateFields(base, v.Elem()))
return m, nil
}
|
New
| 100
| 122
|
model/model.go
|
#FILE: ollama-main/server/routes.go
##CHUNK 1
}
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
name := model.ParseName(req.Model)
if !name.IsValid() {
return nil, ErrModelPathInvalid
}
name, err := getExistingName(name)
if err != nil {
return nil, err
}
m, err := GetModel(name.String())
if err != nil {
return nil, err
}
modelDetails := api.ModelDetails{
ParentModel: m.ParentModel,
Format: m.Config.ModelFormat,
#FILE: ollama-main/convert/convert.go
##CHUNK 1
case "CohereForCausalLM":
conv = &commandrModel{}
default:
return fmt.Errorf("unsupported architecture %q", p.Architectures[0])
}
if err := json.Unmarshal(bts, conv); err != nil {
return err
}
if t, ok := conv.(moreParser); ok {
if err := t.parseMore(fsys); err != nil {
return err
}
}
t, err := parseTokenizer(fsys, conv.specialTokenTypes())
if err != nil {
return err
}
#FILE: ollama-main/ml/backend/ggml/ggml.go
##CHUNK 1
// btDeviceMemory maps from a buffer type to the memory allocations associated with that device
btDeviceMemory map[*C.struct_ggml_backend_buffer_type]*ml.DeviceMemory
flashAttention bool
// maxGraphNodes is the maximum allowed number of graph nodes in this scheduler
maxGraphNodes int
}
func New(modelPath string, params ml.BackendParams) (ml.Backend, error) {
r, err := os.Open(modelPath)
if err != nil {
return nil, err
}
defer r.Close()
meta, err := fsggml.Decode(r, -1)
if err != nil {
return nil, err
}
#FILE: ollama-main/server/internal/client/ollama/registry.go
##CHUNK 1
res, err := r.send(ctx, "GET", manifestURL, nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
data, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
// TODO(bmizerany): return digest here
m, err := unmarshalManifest(n, data)
if err != nil {
return nil, fmt.Errorf("%s: %w", name, errors.Join(ErrManifestInvalid, err))
}
return m, nil
}
type chunksum struct {
URL string
Chunk blob.Chunk
##CHUNK 2
if err != nil {
return nil, err
}
}
data, err := os.ReadFile(c.GetFile(d))
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("%w: %s", ErrModelNotFound, name)
}
return nil, err
}
m, err := unmarshalManifest(n, data)
if err != nil {
return nil, fmt.Errorf("%s: %w", name, errors.Join(ErrManifestInvalid, err))
}
return m, nil
}
// Resolve resolves a name to a Manifest in the remote registry.
func (r *Registry) Resolve(ctx context.Context, name string) (*Manifest, error) {
#FILE: ollama-main/parser/parser.go
##CHUNK 1
ps, err := api.FormatParams(map[string][]string{c.Name: {c.Args}})
if err != nil {
return nil, err
}
for k, v := range ps {
if ks, ok := params[k].([]string); ok {
params[k] = append(ks, v.([]string)...)
} else if vs, ok := v.([]string); ok {
params[k] = vs
} else {
params[k] = v
}
}
}
}
if len(params) > 0 {
req.Parameters = params
#CURRENT FILE: ollama-main/model/model.go
##CHUNK 1
}
return getTextProcessor(meta.KV())
}
func getTextProcessor(kv fsggml.KV) (TextProcessor, error) {
arch := kv.Architecture()
f, ok := models[arch]
if !ok {
return nil, fmt.Errorf("unsupported model architecture %q", arch)
}
m, err := f(kv)
if err != nil {
return nil, err
}
tp, ok := m.(TextProcessor)
if !ok {
return nil, fmt.Errorf("%v is not a TextProcessor", m)
}
return tp, nil
}
##CHUNK 2
func NewTextProcessor(s string) (TextProcessor, error) {
r, err := os.Open(s)
if err != nil {
return nil, err
}
defer r.Close()
meta, err := fsggml.Decode(r, -1)
if err != nil {
return nil, err
}
return getTextProcessor(meta.KV())
}
func getTextProcessor(kv fsggml.KV) (TextProcessor, error) {
arch := kv.Architecture()
f, ok := models[arch]
if !ok {
return nil, fmt.Errorf("unsupported model architecture %q", arch)
}
##CHUNK 3
// Register registers a model constructor for the given architecture
func Register(name string, f func(fs.Config) (Model, error)) {
if _, ok := models[name]; ok {
panic("model: model already registered")
}
models[name] = f
}
}
func NewTextProcessor(s string) (TextProcessor, error) {
r, err := os.Open(s)
if err != nil {
return nil, err
}
defer r.Close()
meta, err := fsggml.Decode(r, -1)
if err != nil {
return nil, err
##CHUNK 4
m, err := f(kv)
if err != nil {
return nil, err
}
tp, ok := m.(TextProcessor)
if !ok {
return nil, fmt.Errorf("%v is not a TextProcessor", m)
}
return tp, nil
}
func populateFields(base Base, v reflect.Value, tags ...Tag) reflect.Value {
t := v.Type()
if t.Kind() == reflect.Struct {
allNil := true
for i := range t.NumField() {
tt := t.Field(i).Type
vv := v.Field(i)
if !vv.CanSet() {
|
ollama-main
| 93
|
func Forward(ctx ml.Context, m Model, inputs []int32, batch input.Batch) (ml.Tensor, error) {
if len(batch.Positions) != len(batch.Sequences) {
return nil, fmt.Errorf("length of positions (%v) must match length of seqs (%v)", len(batch.Positions), len(batch.Sequences))
}
if len(batch.Positions) < 1 {
return nil, errors.New("batch size cannot be less than 1")
}
batch.Inputs = ctx.Input().FromIntSlice(inputs, len(inputs))
cache := m.Config().Cache
if cache != nil {
err := cache.StartForward(ctx, batch, false)
if err != nil {
return nil, err
}
}
t, err := m.Forward(ctx, batch)
if err != nil {
return nil, err
}
ctx.Forward(t).Compute(t)
return t, nil
}
|
func Forward(ctx ml.Context, m Model, inputs []int32, batch input.Batch) (ml.Tensor, error) {
if len(batch.Positions) != len(batch.Sequences) {
return nil, fmt.Errorf("length of positions (%v) must match length of seqs (%v)", len(batch.Positions), len(batch.Sequences))
}
if len(batch.Positions) < 1 {
return nil, errors.New("batch size cannot be less than 1")
}
batch.Inputs = ctx.Input().FromIntSlice(inputs, len(inputs))
cache := m.Config().Cache
if cache != nil {
err := cache.StartForward(ctx, batch, false)
if err != nil {
return nil, err
}
}
t, err := m.Forward(ctx, batch)
if err != nil {
return nil, err
}
ctx.Forward(t).Compute(t)
return t, nil
}
|
func Forward(ctx ml.Context, m Model, inputs []int32, batch input.Batch) (ml.Tensor, error) {
if len(batch.Positions) != len(batch.Sequences) {
return nil, fmt.Errorf("length of positions (%v) must match length of seqs (%v)", len(batch.Positions), len(batch.Sequences))
}
if len(batch.Positions) < 1 {
return nil, errors.New("batch size cannot be less than 1")
}
batch.Inputs = ctx.Input().FromIntSlice(inputs, len(inputs))
cache := m.Config().Cache
if cache != nil {
err := cache.StartForward(ctx, batch, false)
if err != nil {
return nil, err
}
}
t, err := m.Forward(ctx, batch)
if err != nil {
return nil, err
}
ctx.Forward(t).Compute(t)
return t, nil
}
|
Forward
| 280
| 307
|
model/model.go
|
#FILE: ollama-main/runner/ollamarunner/runner.go
##CHUNK 1
batch.Inputs = ctx.Input().FromIntSlice(batchInputs, len(batchInputs))
cache := s.model.Config().Cache
if cache != nil {
err := cache.StartForward(ctx, batch, true)
if err != nil {
return err
}
}
t, err := s.model.Forward(ctx, batch)
if err != nil {
return err
}
ctx.Forward(t).Reserve()
return nil
}
##CHUNK 2
}
batch.Positions[i] = int32(i)
}
batch.Outputs = make([]int32, s.parallel)
for i := range batch.Outputs {
batch.Outputs[i] = int32(i)
}
batch.Inputs = ctx.Input().FromIntSlice(batchInputs, len(batchInputs))
cache := s.model.Config().Cache
if cache != nil {
err := cache.StartForward(ctx, batch, true)
if err != nil {
return err
}
}
#FILE: ollama-main/convert/convert_mllama.go
##CHUNK 1
return nil, err
}
if err := t.Transpose(); err != nil {
return nil, err
}
} else {
t, err = tensor.Tanh(t)
if err != nil {
return nil, err
}
if name == "v.position_embd.gate" {
t, err = tensor.Sub(float32(1), t)
if err != nil {
return nil, err
}
}
}
##CHUNK 2
heads := m.VisionModel.AttentionHeads
if err := t.Reshape(append([]int{int(heads), 2, dims[0] / int(heads) / 2}, dims[1:]...)...); err != nil {
return nil, err
}
if err := t.T(0, 2, 1, 3); err != nil {
return nil, err
}
if err := t.Reshape(dims...); err != nil {
return nil, err
}
if err := t.Transpose(); err != nil {
return nil, err
}
} else {
t, err = tensor.Tanh(t)
if err != nil {
return nil, err
#FILE: ollama-main/server/create.go
##CHUNK 1
} else {
kv, err := kvFromLayers(baseLayers)
if err != nil {
return nil, err
}
fn(api.ProgressResponse{Status: "converting adapter"})
mediaType = "application/vnd.ollama.image.adapter"
if err := convert.ConvertAdapter(os.DirFS(tmpDir), t, kv); err != nil {
return nil, err
}
}
if _, err := t.Seek(0, io.SeekStart); err != nil {
return nil, err
}
layer, err := NewLayer(t, mediaType)
if err != nil {
return nil, err
}
##CHUNK 2
return nil, err
}
if err := createLink(blobPath, filepath.Join(tmpDir, fp)); err != nil {
return nil, err
}
}
t, err := os.CreateTemp(tmpDir, "fp16")
if err != nil {
return nil, err
}
defer t.Close()
var mediaType string
if !isAdapter {
fn(api.ProgressResponse{Status: "converting model"})
mediaType = "application/vnd.ollama.image.model"
if err := convert.ConvertModel(os.DirFS(tmpDir), t); err != nil {
return nil, err
}
##CHUNK 3
if !fs.ValidPath(fp) {
return nil, fmt.Errorf("%w: %s", errFilePath, fp)
}
if _, err := root.Stat(fp); err != nil && !errors.Is(err, fs.ErrNotExist) {
// Path is likely outside the root
return nil, fmt.Errorf("%w: %s: %s", errFilePath, err, fp)
}
blobPath, err := GetBlobsPath(digest)
if err != nil {
return nil, err
}
if err := createLink(blobPath, filepath.Join(tmpDir, fp)); err != nil {
return nil, err
}
}
t, err := os.CreateTemp(tmpDir, "fp16")
if err != nil {
return nil, err
#FILE: ollama-main/fs/ggml/gguf.go
##CHUNK 1
func newArray[T any](size, maxSize int) *array[T] {
a := array[T]{size: size}
if maxSize < 0 || size <= maxSize {
a.values = make([]T, size)
}
return &a
}
func readGGUFArray(llm *gguf, r io.Reader) (any, error) {
t, err := readGGUF[uint32](llm, r)
if err != nil {
return nil, err
}
n, err := readGGUF[uint64](llm, r)
if err != nil {
return nil, err
}
switch t {
#FILE: ollama-main/model/models/llama4/model.go
##CHUNK 1
return &m, nil
}
func (m *Model) EncodeMultimodal(ctx ml.Context, multimodalData []byte) ([]input.Multimodal, error) {
if len(m.VisionModel.Layers) < 1 {
return nil, model.ErrNoVisionModel
}
img, _, err := image.Decode(bytes.NewReader(multimodalData))
if err != nil {
return nil, err
}
pixelsLocal, pixelsGlobal, size, err := m.ProcessImage(img)
if err != nil {
return nil, err
}
tilesLocal := ctx.Input().FromFloatSlice(pixelsLocal, size.X, size.Y, m.numChannels)
#FILE: ollama-main/server/manifest.go
##CHUNK 1
// TODO(mxyng): use something less brittle
matches, err := filepath.Glob(filepath.Join(manifests, "*", "*", "*", "*"))
if err != nil {
return nil, err
}
ms := make(map[model.Name]*Manifest)
for _, match := range matches {
fi, err := os.Stat(match)
if err != nil {
return nil, err
}
if !fi.IsDir() {
rel, err := filepath.Rel(manifests, match)
if err != nil {
if !continueOnError {
return nil, fmt.Errorf("%s %w", match, err)
}
#CURRENT FILE: ollama-main/model/model.go
|
ollama-main
| 94
|
func NewSentencePieceModel(vocab *Vocabulary) SentencePieceModel {
slog.Log(context.TODO(), logutil.LevelTrace, "Tokens", "num tokens", len(vocab.Values), "vals", vocab.Values[:5], "scores", vocab.Scores[:5], "types", vocab.Types[:5])
counter := map[int]int{}
var maxTokenLen int
for cnt := range vocab.Types {
switch vocab.Types[cnt] {
case TOKEN_TYPE_NORMAL, TOKEN_TYPE_USER_DEFINED, TOKEN_TYPE_UNUSED:
maxTokenLen = max(maxTokenLen, len(vocab.Values[cnt]))
fallthrough
default:
counter[int(vocab.Types[cnt])] += 1
}
}
slog.Log(context.TODO(), logutil.LevelTrace, "Token counts", "normal", counter[TOKEN_TYPE_NORMAL], "unknown", counter[TOKEN_TYPE_UNKNOWN], "control", counter[TOKEN_TYPE_CONTROL],
"user defined", counter[TOKEN_TYPE_USER_DEFINED], "unused", counter[TOKEN_TYPE_UNUSED], "byte", counter[TOKEN_TYPE_BYTE],
"max token len", maxTokenLen)
return SentencePieceModel{
maxTokenLen: maxTokenLen,
vocab: vocab,
}
}
|
func NewSentencePieceModel(vocab *Vocabulary) SentencePieceModel {
slog.Log(context.TODO(), logutil.LevelTrace, "Tokens", "num tokens", len(vocab.Values), "vals", vocab.Values[:5], "scores", vocab.Scores[:5], "types", vocab.Types[:5])
counter := map[int]int{}
var maxTokenLen int
for cnt := range vocab.Types {
switch vocab.Types[cnt] {
case TOKEN_TYPE_NORMAL, TOKEN_TYPE_USER_DEFINED, TOKEN_TYPE_UNUSED:
maxTokenLen = max(maxTokenLen, len(vocab.Values[cnt]))
fallthrough
default:
counter[int(vocab.Types[cnt])] += 1
}
}
slog.Log(context.TODO(), logutil.LevelTrace, "Token counts", "normal", counter[TOKEN_TYPE_NORMAL], "unknown", counter[TOKEN_TYPE_UNKNOWN], "control", counter[TOKEN_TYPE_CONTROL],
"user defined", counter[TOKEN_TYPE_USER_DEFINED], "unused", counter[TOKEN_TYPE_UNUSED], "byte", counter[TOKEN_TYPE_BYTE],
"max token len", maxTokenLen)
return SentencePieceModel{
maxTokenLen: maxTokenLen,
vocab: vocab,
}
}
|
func NewSentencePieceModel(vocab *Vocabulary) SentencePieceModel {
slog.Log(context.TODO(), logutil.LevelTrace, "Tokens", "num tokens", len(vocab.Values), "vals", vocab.Values[:5], "scores", vocab.Scores[:5], "types", vocab.Types[:5])
counter := map[int]int{}
var maxTokenLen int
for cnt := range vocab.Types {
switch vocab.Types[cnt] {
case TOKEN_TYPE_NORMAL, TOKEN_TYPE_USER_DEFINED, TOKEN_TYPE_UNUSED:
maxTokenLen = max(maxTokenLen, len(vocab.Values[cnt]))
fallthrough
default:
counter[int(vocab.Types[cnt])] += 1
}
}
slog.Log(context.TODO(), logutil.LevelTrace, "Token counts", "normal", counter[TOKEN_TYPE_NORMAL], "unknown", counter[TOKEN_TYPE_UNKNOWN], "control", counter[TOKEN_TYPE_CONTROL],
"user defined", counter[TOKEN_TYPE_USER_DEFINED], "unused", counter[TOKEN_TYPE_UNUSED], "byte", counter[TOKEN_TYPE_BYTE],
"max token len", maxTokenLen)
return SentencePieceModel{
maxTokenLen: maxTokenLen,
vocab: vocab,
}
}
|
NewSentencePieceModel
| 26
| 49
|
model/sentencepiece.go
|
#FILE: ollama-main/model/bytepairencoding.go
##CHUNK 1
}
}
for _, merge := range merges {
if len(merge.runes) > 0 {
// TODO: handle the edge case where the rune isn't in the vocabulary
if id := bpe.vocab.Encode(string(merge.runes)); id >= 0 {
ids = append(ids, id)
}
}
}
}
}
slog.Log(context.TODO(), logutil.LevelTrace, "encoded", "string", s, "ids", ids)
if addSpecial && len(ids) > 0 {
ids = bpe.vocab.addSpecials(ids)
}
##CHUNK 2
}
}
}
slog.Log(context.TODO(), logutil.LevelTrace, "encoded", "string", s, "ids", ids)
if addSpecial && len(ids) > 0 {
ids = bpe.vocab.addSpecials(ids)
}
return ids, nil
}
type lazyIdsString struct {
ids []int32
}
func (l lazyIdsString) LogValue() slog.Value {
return slog.AnyValue(fmt.Sprint(l.ids))
}
#FILE: ollama-main/model/model.go
##CHUNK 1
values[i] = value
}
return values
}
names := fn(tagsCopy)
for _, name := range names {
if tensor := base.Backend().Get(strings.Join(name, ".")); tensor != nil {
slog.Log(context.TODO(), logutil.LevelTrace, "found tensor", "", tensor)
vv.Set(reflect.ValueOf(tensor))
break
}
}
} else if tt.Kind() == reflect.Pointer || tt.Kind() == reflect.Interface {
setPointer(base, vv, tagsCopy)
} else if tt.Kind() == reflect.Slice || tt.Kind() == reflect.Array {
for i := range vv.Len() {
vvv := vv.Index(i)
##CHUNK 2
slog.Log(context.TODO(), logutil.LevelTrace, "found tensor", "", tensor)
vv.Set(reflect.ValueOf(tensor))
break
}
}
} else if tt.Kind() == reflect.Pointer || tt.Kind() == reflect.Interface {
setPointer(base, vv, tagsCopy)
} else if tt.Kind() == reflect.Slice || tt.Kind() == reflect.Array {
for i := range vv.Len() {
vvv := vv.Index(i)
if vvv.Kind() == reflect.Pointer || vvv.Kind() == reflect.Interface {
setPointer(base, vvv, append(tagsCopy, Tag{Name: strconv.Itoa(i)}))
} else {
vvv.Set(populateFields(base, vvv, append(tagsCopy, Tag{Name: strconv.Itoa(i)})...))
}
}
}
if !canNil(tt) || !vv.IsNil() {
allNil = false
#FILE: ollama-main/readline/buffer.go
##CHUNK 1
b.Buf.Add(r)
}
b.Pos += 1
if insert {
b.drawRemaining()
}
}
func (b *Buffer) countRemainingLineWidth(place int) int {
var sum int
counter := -1
var prevLen int
for place <= b.LineWidth {
counter += 1
sum += prevLen
if r, ok := b.Buf.Get(b.Pos + counter); ok {
place += runewidth.RuneWidth(r)
##CHUNK 2
func (b *Buffer) countRemainingLineWidth(place int) int {
var sum int
counter := -1
var prevLen int
for place <= b.LineWidth {
counter += 1
sum += prevLen
if r, ok := b.Buf.Get(b.Pos + counter); ok {
place += runewidth.RuneWidth(r)
prevLen = len(string(r))
} else {
break
}
}
return sum
}
func (b *Buffer) drawRemaining() {
#CURRENT FILE: ollama-main/model/sentencepiece.go
##CHUNK 1
} else {
slog.Debug("unknown byte token", "byte", b, "token", byteToken)
}
}
ids = append(ids, result...)
}
}
}
slog.Log(context.TODO(), logutil.LevelTrace, "encoded", "string", s, "ids", ids)
if addSpecial && len(ids) > 0 {
ids = spm.vocab.addSpecials(ids)
}
return ids, nil
}
type candidate struct {
##CHUNK 2
if err != nil {
return "", fmt.Errorf("failed to parse hex byte: %v", err)
}
if err := sb.WriteByte(byte(byteVal)); err != nil {
return "", err
}
} else {
if _, err := sb.WriteString(data); err != nil {
return "", err
}
}
}
slog.Log(context.TODO(), logutil.LevelTrace, "decoded", "ids", ids, "string", sb.String())
return sb.String(), nil
}
##CHUNK 3
"github.com/ollama/ollama/logutil"
)
const spmWhitespaceSep = "▁"
type SentencePieceModel struct {
maxTokenLen int
vocab *Vocabulary
}
var _ TextProcessor = (*SentencePieceModel)(nil)
func (spm SentencePieceModel) Vocabulary() *Vocabulary {
return spm.vocab
}
}
func (spm SentencePieceModel) Is(id int32, special Special) bool {
return spm.vocab.Is(id, special)
}
##CHUNK 4
slog.Log(context.TODO(), logutil.LevelTrace, "encoded", "string", s, "ids", ids)
if addSpecial && len(ids) > 0 {
ids = spm.vocab.addSpecials(ids)
}
return ids, nil
}
type candidate struct {
a, b int
score float32
size int
}
type queue []*candidate
func (q queue) Len() int { return len(q) }
func (q queue) Less(i, j int) bool {
|
ollama-main
| 95
|
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: newTextModel(c),
VisionModel: newVisionModel(c),
ImageProcessor: newImageProcessor(c),
MultiModalProjector: newMultiModalProjector(c),
}
m.Cache = kvcache.NewCausalCache(m.TextModel.Shift)
return m, nil
}
|
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: newTextModel(c),
VisionModel: newVisionModel(c),
ImageProcessor: newImageProcessor(c),
MultiModalProjector: newMultiModalProjector(c),
}
m.Cache = kvcache.NewCausalCache(m.TextModel.Shift)
return m, nil
}
|
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: newTextModel(c),
VisionModel: newVisionModel(c),
ImageProcessor: newImageProcessor(c),
MultiModalProjector: newMultiModalProjector(c),
}
m.Cache = kvcache.NewCausalCache(m.TextModel.Shift)
return m, nil
}
|
New
| 32
| 58
|
model/models/mistral3/model.go
|
#FILE: ollama-main/model/models/qwen25vl/model.go
##CHUNK 1
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: NewTextModel(c),
VisionModel: newVisionModel(c),
ImageProcessor: newImageProcessor(c),
}
##CHUNK 2
*VisionModel `gguf:"v,vision"`
ImageProcessor
}
// Implement MultimodalProcessor interface
var _ model.MultimodalProcessor = (*Model)(nil)
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
#FILE: ollama-main/model/models/mllama/model.go
##CHUNK 1
)
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
##CHUNK 2
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
VisionModel: newVisionModel(c),
TextModel: newTextModel(c),
}
encoderCache := kvcache.NewEncoderCache()
encoderCache.SetConfig(ml.CacheConfig{})
m.Cache = kvcache.NewWrapperCache(encoderCache, kvcache.NewCausalCache(m.TextModel.Shift))
return &m, nil
}
#FILE: ollama-main/model/models/llama4/model.go
##CHUNK 1
return p.Linear1.Forward(ctx, visionOutputs)
}
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer",
`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
##CHUNK 2
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
VisionModel: newVisionModel(c),
TextModel: newTextModel(c),
}
m.Cache = kvcache.NewWrapperCache(
kvcache.NewChunkedAttentionCache(int32(c.Uint("attention.chunk_size", 8192)), m.Shift),
kvcache.NewCausalCache(m.Shift),
)
#FILE: ollama-main/model/models/llama/model.go
##CHUNK 1
*Options
}
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
#FILE: ollama-main/model/models/qwen3/model.go
##CHUNK 1
}
}
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
`(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`,
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: layers,
#FILE: ollama-main/model/models/qwen2/model.go
##CHUNK 1
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Options: Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
headDim: int(c.Uint("attention.key_length")),
#FILE: ollama-main/model/models/gemma3/model.go
##CHUNK 1
Scores: c.Floats("tokenizer.ggml.scores"),
Types: c.Ints("tokenizer.ggml.token_type"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{
int32(c.Uint("tokenizer.ggml.eos_token_id")),
int32(c.Uint("tokenizer.ggml.eot_token_id", 106)),
},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
VisionModel: newVisionModel(c),
TextModel: newTextModel(c),
MultiModalProjector: &MultiModalProjector{
tokensPerImage: int(c.Uint("mm_tokens_per_image", 256)),
},
#CURRENT FILE: ollama-main/model/models/mistral3/model.go
|
ollama-main
| 96
|
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
headDim: int(c.Uint("attention.key_length")),
ropeDim: int(c.Uint("rope.dimension_count")),
eps: c.Float("attention.layer_norm_rms_epsilon"),
ropeBase: c.Float("rope.freq_base"),
ropeScale: c.Float("rope.freq_scale", 1),
},
}
m.Cache = kvcache.NewCausalCache(m.Shift)
return &m, nil
}
|
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
headDim: int(c.Uint("attention.key_length")),
ropeDim: int(c.Uint("rope.dimension_count")),
eps: c.Float("attention.layer_norm_rms_epsilon"),
ropeBase: c.Float("rope.freq_base"),
ropeScale: c.Float("rope.freq_scale", 1),
},
}
m.Cache = kvcache.NewCausalCache(m.Shift)
return &m, nil
}
|
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
headDim: int(c.Uint("attention.key_length")),
ropeDim: int(c.Uint("rope.dimension_count")),
eps: c.Float("attention.layer_norm_rms_epsilon"),
ropeBase: c.Float("rope.freq_base"),
ropeScale: c.Float("rope.freq_scale", 1),
},
}
m.Cache = kvcache.NewCausalCache(m.Shift)
return &m, nil
}
|
New
| 34
| 67
|
model/models/llama/model.go
|
#FILE: ollama-main/model/models/qwen2/model.go
##CHUNK 1
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Options: Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
headDim: int(c.Uint("attention.key_length")),
##CHUNK 2
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Options: Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
headDim: int(c.Uint("attention.key_length")),
ropeDim: int(c.Uint("rope.dimension_count")),
ropeBase: c.Float("rope.freq_base"),
ropeScale: c.Float("rope.freq_scale", 1),
eps: c.Float("attention.layer_norm_rms_epsilon"),
},
}
m.Cache = kvcache.NewCausalCache(m.Shift)
return &m, nil
}
#FILE: ollama-main/model/models/gemma2/model.go
##CHUNK 1
func New(c fs.Config) (model.Model, error) {
m := Model{
SentencePieceModel: model.NewSentencePieceModel(
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Scores: c.Floats("tokenizer.ggml.scores"),
Types: c.Ints("tokenizer.ggml.token_type"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
##CHUNK 2
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
attnKeyLen: int(c.Uint("attention.key_length")),
attnValLen: int(c.Uint("attention.value_length")),
eps: c.Float("attention.layer_norm_rms_epsilon"),
ropeBase: c.Float("rope.freq_base", 10000.0),
ropeScale: c.Float("rope.freq_scale", 1.0),
attnLogitSoftcap: c.Float("attn_logit_softcapping"),
finalLogitSoftcap: c.Float("final_logit_softcapping"),
},
}
#FILE: ollama-main/model/models/mllama/model.go
##CHUNK 1
)
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
#FILE: ollama-main/model/models/qwen3/model.go
##CHUNK 1
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: layers,
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
keyLength: int(c.Uint("attention.key_length")),
valueLength: int(c.Uint("attention.value_length")),
eps: c.Float("attention.layer_norm_rms_epsilon"),
ropeBase: c.Float("rope.freq_base"),
ropeScale: c.Float("rope.freq_scale", 1),
numExperts: int(c.Uint("expert_count")),
##CHUNK 2
}
}
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
`(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`,
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: layers,
#FILE: ollama-main/model/models/llama4/model.go
##CHUNK 1
return p.Linear1.Forward(ctx, visionOutputs)
}
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer",
`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
#FILE: ollama-main/model/models/mistral3/model.go
##CHUNK 1
var _ model.TextProcessor = (*Model)(nil)
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: newTextModel(c),
#FILE: ollama-main/model/models/qwen25vl/model.go
##CHUNK 1
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: NewTextModel(c),
VisionModel: newVisionModel(c),
ImageProcessor: newImageProcessor(c),
}
#CURRENT FILE: ollama-main/model/models/llama/model.go
|
ollama-main
| 97
|
func New(c fs.Config) (model.Model, error) {
m := Model{
SentencePieceModel: model.NewSentencePieceModel(
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Scores: c.Floats("tokenizer.ggml.scores"),
Types: c.Ints("tokenizer.ggml.token_type"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
attnKeyLen: int(c.Uint("attention.key_length")),
attnValLen: int(c.Uint("attention.value_length")),
eps: c.Float("attention.layer_norm_rms_epsilon"),
ropeBase: c.Float("rope.freq_base", 10000.0),
ropeScale: c.Float("rope.freq_scale", 1.0),
attnLogitSoftcap: c.Float("attn_logit_softcapping"),
finalLogitSoftcap: c.Float("final_logit_softcapping"),
},
}
slidingWindowLen := int32(c.Uint("attention.sliding_window"))
m.Cache = kvcache.NewWrapperCache(kvcache.NewSWACache(slidingWindowLen, m.Shift), kvcache.NewCausalCache(m.Shift))
m.Cache.SetConfig(ml.CacheConfig{})
return &m, nil
}
|
func New(c fs.Config) (model.Model, error) {
m := Model{
SentencePieceModel: model.NewSentencePieceModel(
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Scores: c.Floats("tokenizer.ggml.scores"),
Types: c.Ints("tokenizer.ggml.token_type"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
attnKeyLen: int(c.Uint("attention.key_length")),
attnValLen: int(c.Uint("attention.value_length")),
eps: c.Float("attention.layer_norm_rms_epsilon"),
ropeBase: c.Float("rope.freq_base", 10000.0),
ropeScale: c.Float("rope.freq_scale", 1.0),
attnLogitSoftcap: c.Float("attn_logit_softcapping"),
finalLogitSoftcap: c.Float("final_logit_softcapping"),
},
}
slidingWindowLen := int32(c.Uint("attention.sliding_window"))
m.Cache = kvcache.NewWrapperCache(kvcache.NewSWACache(slidingWindowLen, m.Shift), kvcache.NewCausalCache(m.Shift))
m.Cache.SetConfig(ml.CacheConfig{})
return &m, nil
}
|
func New(c fs.Config) (model.Model, error) {
m := Model{
SentencePieceModel: model.NewSentencePieceModel(
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Scores: c.Floats("tokenizer.ggml.scores"),
Types: c.Ints("tokenizer.ggml.token_type"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
attnKeyLen: int(c.Uint("attention.key_length")),
attnValLen: int(c.Uint("attention.value_length")),
eps: c.Float("attention.layer_norm_rms_epsilon"),
ropeBase: c.Float("rope.freq_base", 10000.0),
ropeScale: c.Float("rope.freq_scale", 1.0),
attnLogitSoftcap: c.Float("attn_logit_softcapping"),
finalLogitSoftcap: c.Float("final_logit_softcapping"),
},
}
slidingWindowLen := int32(c.Uint("attention.sliding_window"))
m.Cache = kvcache.NewWrapperCache(kvcache.NewSWACache(slidingWindowLen, m.Shift), kvcache.NewCausalCache(m.Shift))
m.Cache.SetConfig(ml.CacheConfig{})
return &m, nil
}
|
New
| 40
| 76
|
model/models/gemma2/model.go
|
#FILE: ollama-main/model/models/llama/model.go
##CHUNK 1
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
headDim: int(c.Uint("attention.key_length")),
ropeDim: int(c.Uint("rope.dimension_count")),
eps: c.Float("attention.layer_norm_rms_epsilon"),
ropeBase: c.Float("rope.freq_base"),
##CHUNK 2
*Options
}
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
##CHUNK 3
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
headDim: int(c.Uint("attention.key_length")),
ropeDim: int(c.Uint("rope.dimension_count")),
eps: c.Float("attention.layer_norm_rms_epsilon"),
ropeBase: c.Float("rope.freq_base"),
ropeScale: c.Float("rope.freq_scale", 1),
},
}
m.Cache = kvcache.NewCausalCache(m.Shift)
return &m, nil
}
type SelfAttention struct {
#FILE: ollama-main/model/models/qwen3/model.go
##CHUNK 1
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: layers,
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
keyLength: int(c.Uint("attention.key_length")),
valueLength: int(c.Uint("attention.value_length")),
eps: c.Float("attention.layer_norm_rms_epsilon"),
ropeBase: c.Float("rope.freq_base"),
ropeScale: c.Float("rope.freq_scale", 1),
numExperts: int(c.Uint("expert_count")),
##CHUNK 2
}
}
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
`(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`,
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: layers,
#FILE: ollama-main/model/models/qwen2/model.go
##CHUNK 1
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Options: Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
headDim: int(c.Uint("attention.key_length")),
#FILE: ollama-main/model/models/llama4/model.go
##CHUNK 1
return p.Linear1.Forward(ctx, visionOutputs)
}
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer",
`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
#FILE: ollama-main/model/models/mllama/model.go
##CHUNK 1
)
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
#FILE: ollama-main/model/models/mistral3/model.go
##CHUNK 1
var _ model.TextProcessor = (*Model)(nil)
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: newTextModel(c),
#FILE: ollama-main/model/models/gemma3/model.go
##CHUNK 1
// TODO: inputProjection must be transposed since they're incompatible with visionOutputs
visionOutputs = p.InputProjection.Weight.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx).Mulmat(ctx, visionOutputs)
return visionOutputs
}
func New(c fs.Config) (model.Model, error) {
m := Model{
SentencePieceModel: model.NewSentencePieceModel(
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Scores: c.Floats("tokenizer.ggml.scores"),
Types: c.Ints("tokenizer.ggml.token_type"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{
int32(c.Uint("tokenizer.ggml.eos_token_id")),
int32(c.Uint("tokenizer.ggml.eot_token_id", 106)),
},
#CURRENT FILE: ollama-main/model/models/gemma2/model.go
|
ollama-main
| 98
|
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer",
`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
VisionModel: newVisionModel(c),
TextModel: newTextModel(c),
}
m.Cache = kvcache.NewWrapperCache(
kvcache.NewChunkedAttentionCache(int32(c.Uint("attention.chunk_size", 8192)), m.Shift),
kvcache.NewCausalCache(m.Shift),
)
return &m, nil
}
|
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer",
`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
VisionModel: newVisionModel(c),
TextModel: newTextModel(c),
}
m.Cache = kvcache.NewWrapperCache(
kvcache.NewChunkedAttentionCache(int32(c.Uint("attention.chunk_size", 8192)), m.Shift),
kvcache.NewCausalCache(m.Shift),
)
return &m, nil
}
|
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer",
`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
VisionModel: newVisionModel(c),
TextModel: newTextModel(c),
}
m.Cache = kvcache.NewWrapperCache(
kvcache.NewChunkedAttentionCache(int32(c.Uint("attention.chunk_size", 8192)), m.Shift),
kvcache.NewCausalCache(m.Shift),
)
return &m, nil
}
|
New
| 33
| 62
|
model/models/llama4/model.go
|
#FILE: ollama-main/model/models/mllama/model.go
##CHUNK 1
)
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
##CHUNK 2
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
VisionModel: newVisionModel(c),
TextModel: newTextModel(c),
}
encoderCache := kvcache.NewEncoderCache()
encoderCache.SetConfig(ml.CacheConfig{})
m.Cache = kvcache.NewWrapperCache(encoderCache, kvcache.NewCausalCache(m.TextModel.Shift))
return &m, nil
}
#FILE: ollama-main/model/models/qwen25vl/model.go
##CHUNK 1
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: NewTextModel(c),
VisionModel: newVisionModel(c),
ImageProcessor: newImageProcessor(c),
}
##CHUNK 2
*VisionModel `gguf:"v,vision"`
ImageProcessor
}
// Implement MultimodalProcessor interface
var _ model.MultimodalProcessor = (*Model)(nil)
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
#FILE: ollama-main/model/models/mistral3/model.go
##CHUNK 1
var _ model.TextProcessor = (*Model)(nil)
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: newTextModel(c),
##CHUNK 2
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: newTextModel(c),
VisionModel: newVisionModel(c),
ImageProcessor: newImageProcessor(c),
MultiModalProjector: newMultiModalProjector(c),
}
m.Cache = kvcache.NewCausalCache(m.TextModel.Shift)
return m, nil
}
#FILE: ollama-main/model/models/llama/model.go
##CHUNK 1
*Options
}
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
#FILE: ollama-main/model/models/qwen3/model.go
##CHUNK 1
}
}
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
`(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`,
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: layers,
#FILE: ollama-main/model/models/qwen2/model.go
##CHUNK 1
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Options: Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
headDim: int(c.Uint("attention.key_length")),
#FILE: ollama-main/model/models/gemma2/model.go
##CHUNK 1
func New(c fs.Config) (model.Model, error) {
m := Model{
SentencePieceModel: model.NewSentencePieceModel(
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Scores: c.Floats("tokenizer.ggml.scores"),
Types: c.Ints("tokenizer.ggml.token_type"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
#CURRENT FILE: ollama-main/model/models/llama4/model.go
|
ollama-main
| 99
|
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: NewTextModel(c),
VisionModel: newVisionModel(c),
ImageProcessor: newImageProcessor(c),
}
m.Cache = kvcache.NewCausalCache(m.TextModel.Shift)
return m, nil
}
|
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: NewTextModel(c),
VisionModel: newVisionModel(c),
ImageProcessor: newImageProcessor(c),
}
m.Cache = kvcache.NewCausalCache(m.TextModel.Shift)
return m, nil
}
|
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: NewTextModel(c),
VisionModel: newVisionModel(c),
ImageProcessor: newImageProcessor(c),
}
m.Cache = kvcache.NewCausalCache(m.TextModel.Shift)
return m, nil
}
|
New
| 28
| 53
|
model/models/qwen25vl/model.go
|
#FILE: ollama-main/model/models/mllama/model.go
##CHUNK 1
)
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
#FILE: ollama-main/model/models/llama/model.go
##CHUNK 1
*Options
}
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
#FILE: ollama-main/model/models/mistral3/model.go
##CHUNK 1
var _ model.TextProcessor = (*Model)(nil)
func New(c fs.Config) (model.Model, error) {
m := &Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: newTextModel(c),
##CHUNK 2
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
TextModel: newTextModel(c),
VisionModel: newVisionModel(c),
ImageProcessor: newImageProcessor(c),
MultiModalProjector: newMultiModalProjector(c),
}
m.Cache = kvcache.NewCausalCache(m.TextModel.Shift)
return m, nil
}
#FILE: ollama-main/model/models/llama4/model.go
##CHUNK 1
return p.Linear1.Forward(ctx, visionOutputs)
}
func New(c fs.Config) (model.Model, error) {
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer",
`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
##CHUNK 2
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
ImageProcessor: newImageProcessor(c),
VisionModel: newVisionModel(c),
TextModel: newTextModel(c),
}
m.Cache = kvcache.NewWrapperCache(
kvcache.NewChunkedAttentionCache(int32(c.Uint("attention.chunk_size", 8192)), m.Shift),
kvcache.NewCausalCache(m.Shift),
)
#FILE: ollama-main/model/models/qwen3/model.go
##CHUNK 1
}
}
m := Model{
BytePairEncoding: model.NewBytePairEncoding(
`(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`,
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: layers,
#FILE: ollama-main/model/models/qwen2/model.go
##CHUNK 1
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Options: Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
numKVHeads: int(c.Uint("attention.head_count_kv")),
headDim: int(c.Uint("attention.key_length")),
##CHUNK 2
}
func (m Model) Shift(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) {
ropeDim := cmp.Or(m.ropeDim, m.hiddenSize/m.numHeads)
return fast.RoPE(ctx, key, shift, ropeDim, m.ropeBase, m.ropeScale, rope.WithTypeNeoX()), nil
}
func New(c fs.Config) (model.Model, error) {
m := Model{
Layers: make([]DecoderLayer, c.Uint("block_count")),
BytePairEncoding: model.NewBytePairEncoding(
c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Types: c.Ints("tokenizer.ggml.token_type"),
Merges: c.Strings("tokenizer.ggml.merges"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
#FILE: ollama-main/model/models/gemma2/model.go
##CHUNK 1
func New(c fs.Config) (model.Model, error) {
m := Model{
SentencePieceModel: model.NewSentencePieceModel(
&model.Vocabulary{
Values: c.Strings("tokenizer.ggml.tokens"),
Scores: c.Floats("tokenizer.ggml.scores"),
Types: c.Ints("tokenizer.ggml.token_type"),
AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
EOS: append(
[]int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
c.Ints("tokenizer.ggml.eos_token_ids")...,
),
},
),
Layers: make([]Layer, c.Uint("block_count")),
Options: &Options{
hiddenSize: int(c.Uint("embedding_length")),
numHeads: int(c.Uint("attention.head_count")),
#CURRENT FILE: ollama-main/model/models/qwen25vl/model.go
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.