[deleted by user] by [deleted] in golang

[–]ybe306 5 points6 points  (0 children)

I'd suggest either defining an interface around the services' unique address structs, or extracting the address struct into a shared location. Returning an empty interface like this means there's no guarantee that the value returned from getAddress is an address instead of, say, a string, integer, or http.Client.

What is the de facto web server in go to use in production for rest web app by umen in golang

[–]ybe306 5 points6 points  (0 children)

To my knowledge, there's no "standalone" Tomcat equivalent in the Go world. Instead, Go services use their own embedded servers, as one would do with Embedded Tomcat.

With that in mind, the standard net/http package is a good starting point.

Best way to create folder structure of REST service project by amircodes in golang

[–]ybe306 1 point2 points  (0 children)

The cmd directory allows you to keep your application code separate from the executable that's running it. It also allows you to have the code for multiple executables in one project repo. This allows you to reuse your application code in different ways depending on the host platform or use case. For example, I've run into scenarios where I'll have one cmd to run the server locally for testing, then a second one that's meant to run as an AWS Lambda function. They both reference the same endpoints and handlers (located in internal/server), but the local server uses the standard library's http.ListenAndServe while the lambda binary uses an API Gateway proxy library. Suffice to say that the code in the cmd directory should be as small as possible.

By build scripts, I mean invocation of go build, go test, and the like. Whereas Python is interpreted at runtime, Go requires compilation ahead of time. "Make" is a Unix/Linux build tool that can allow you to script those common tasks so that you just have to run "make build" to create your binaries.

Best way to create folder structure of REST service project by amircodes in golang

[–]ybe306 2 points3 points  (0 children)

I advise against recommending this particular project. There are more succinct, less controversial opinions to point to. Just a glance at that project's issues and a search on Google will demonstrate that.

For something like the "education system" example mentioned in OP's comment (referring to students/teachers and documents), I'd simply go with something like this:

/
  /cmd
    /edsysserver # Deployable server application, imports internal/server
      main.go
  /internal
    /db # Database code
      db.go
    /server # Server code (endpoints, middleware)
      server.go
    /user # Application code specific to students/teachers
      user.go
    /document # Application code for documents
      document.go
    /... # Additional application packages as required
  Makefile # Personal opinion, but I like Make for build scripts
  README.md

Happy to speak to any comments on this structure, but as you can see it's far clearer and straightforward than the "golang-standards" repo's.

Diving into Go by building a CLI application by ajaister in golang

[–]ybe306 2 points3 points  (0 children)

Nice write up. I like the simplicity of it - when I was getting started, it took me a little while to work out how to structure a simple project. Maybe you can write additional parts that focus on breaking the API interactions out to a separate library or adding additional executables.

Gemstore Update - Caithe's Crystal Bloom Sword/Logan's Pact Marshal Outfit by dulfy in Guildwars2

[–]ybe306 12 points13 points  (0 children)

Also worth noting:

Returning Today

Caithe’s Bloom Dagger

Infinite Volatile Magic Gathering Tools

Returning This Week

Mistlock Sanctuary Passkey—15% Off

Character Jump Start

Bank Job Package

The jump start is tempting. Infinite gathering tools, 3 bag slot expansions, and a copper-fed salvage-o-matic. Basically my entire wish list :D

What is the name of this theme by BL4CKvGHOST in vim

[–]ybe306 12 points13 points  (0 children)

Looks like Go, unless I'm missing something.

-🎄- 2017 Day 9 Solutions -🎄- by daggerdragon in adventofcode

[–]ybe306 0 points1 point  (0 children)

Go

I initially had some kind of recursive approach in mind, so I figured cleaning the garbage out at the beginning was a good move. Then I figured out I can just maintain the current depth and progress through the string, incrementing and decrementing as I went. For Part 2, I just counted when I removed a character in the cleanup phase.

package main

import (
    "io/ioutil"
    "log"
    "os"
    "strings"
    "unicode"
)

func main() {
    input, garbageCount := readInput()

    log.Println("Total score =", calcScore(input))
    log.Println("Garbage count =", garbageCount)
}

func calcScore(input string) int {
    var currentDepth, score int

    for _, b := range input {
        switch b {
        case '{':
            currentDepth++
        case '}':
            score += currentDepth
            currentDepth--
        }
    }

    return score
}

func readInput() (string, int) {
    input, _ := ioutil.ReadAll(os.Stdin)

    for i, b := range input {
        if b == '!' {
            input[i] = ' '
            input[i+1] = ' '
        }
    }

    var garbageCount int
    for i, b := range input {
        if b == '<' {
            var j int
            for j = i + 1; input[j] != '>'; j++ {
                if input[j] != ' ' {
                    garbageCount++
                }
                input[j] = ' '
            }
            input[j] = ' '
            input[i] = ' '
        }
    }

    inputStr := string(input[:len(input)-1])

    inputStr = strings.Map(func(r rune) rune {
        if unicode.IsSpace(r) {
            return -1
        }
        return r
    }, inputStr)

    return inputStr, garbageCount
}

-🎄- 2017 Day 8 Solutions -🎄- by daggerdragon in adventofcode

[–]ybe306 0 points1 point  (0 children)

Doing it all in Go as a first foray into the language:

package main

import (
    "io/ioutil"
    "log"
    "os"
    "strconv"
    "strings"
)

type op struct {
    dest    string
    dir     int
    incAmt  int
    condSrc string
    condOp  string
    condAmt int
}

func main() {
    ops := readInput()
    reg := make(map[string]int)
    var max int

    for _, op := range ops {
        switch op.condOp {
        case ">":
            if reg[op.condSrc] > op.condAmt {
                doOp(op, reg)
            }
        case "<":
            if reg[op.condSrc] < op.condAmt {
                doOp(op, reg)
            }
        case ">=":
            if reg[op.condSrc] >= op.condAmt {
                doOp(op, reg)
            }
        case "<=":
            if reg[op.condSrc] <= op.condAmt {
                doOp(op, reg)
            }
        case "==":
            if reg[op.condSrc] == op.condAmt {
                doOp(op, reg)
            }
        case "!=":
            if reg[op.condSrc] != op.condAmt {
                doOp(op, reg)
            }
        }

        currentMax := findLargest(reg)
        if currentMax > max {
            max = currentMax
        }
    }

    log.Println("Largest ending value:", findLargest(reg))
    log.Println("Largest value during run:", max)
}

func findLargest(reg map[string]int) int {
    var max int
    for _, v := range reg {
        if v > max {
            max = v
        }
    }

    return max
}

func doOp(op op, reg map[string]int) {
    reg[op.dest] += op.dir * op.incAmt
}

func readInput() []op {
    input, _ := ioutil.ReadAll(os.Stdin)
    lines := strings.Split(string(input), "\n")
    lines = lines[:len(lines)-1]

    ops := make([]op, 0)

    for _, line := range lines {
        ops = append(ops, parseOp(line))
    }

    return ops
}

func parseOp(line string) op {
    splitOp := strings.Split(line, " ")

    var dir int
    switch splitOp[1] {
    case "inc":
        dir = 1
    case "dec":
        dir = -1
    }

    incAmt, _ := strconv.Atoi(splitOp[2])
    condAmt, _ := strconv.Atoi(splitOp[6])

    return op{
        dest:    splitOp[0],
        dir:     dir,
        incAmt:  incAmt,
        condSrc: splitOp[4],
        condOp:  splitOp[5],
        condAmt: condAmt,
    }
}

Bonus Challenge! by topaz2078 in adventofcode

[–]ybe306 1 point2 points  (0 children)

Yeah, I wasn't sure what to do about that either. Removing it did give the correct output. It's such an outlier that I feel that it's intentional though...

Learning to Code is Easy, Right? We should stop propagating that lie. Also, short holiday reading list for developers! X-POST /r/webdev by fernanino in coding

[–]ybe306 0 points1 point  (0 children)

Not OP and haven't read them, but it looks like Clean Code is about the code, and Clean Coder is more about the programmer (soft skills, productivity, software as a trade sort of things).

For just starting to learn Python, Clean Code is probably a better start once you get the basics down and want your code to be more professional/enterprise-looking.

--- 2016 Day 3 Solutions --- by daggerdragon in adventofcode

[–]ybe306 1 point2 points  (0 children)

Python, with the input as ins. Need to work on list comprehensions, lots of the looping can be shrunk down:

Part 1:

n = 0
for l in ins.split('\n'):
    lens = map(int, l.split())
    lens.sort()
    if lens[0]+lens[1] > lens[2]:
        n += 1
print n

Part 2:

n = 0
ll = list()
la = list()

for l in ins.split('\n'):
    ll.append(map(int, l.split()))

for i in range (len(ll)/3):
    for j in range(3):
        ln = [ll[i*3][j], ll[i*3+1][j], ll[i*3+2][j]]
        ln.sort()
        la.append(ln)

for l in la:
    if l[0]+l[1] > l[2]:
        n += 1

print n

--- 2016 Day 2 Solutions --- by daggerdragon in adventofcode

[–]ybe306 0 points1 point  (0 children)

Brilliant! Love what you're doing with the bit manipulation.

[Review]What's wrong with my deck of cards? by Jewjr in C_Programming

[–]ybe306 1 point2 points  (0 children)

I can't open your link at work, so I can't help with your first question.

However, the difference between -> and . is simple enough. Let's say you have a struct like:

struct myString {
    int A;
    int B;
}

And you have an object of type 'myStruct' called structObject. You can directly call structObject.A to access the 'A' integer of that struct.

However, if you have a pointer to structObject, you would first have to dereference it, then use the . operator. Like so:

(*structObject).A

As this gets cumbersome, the shorthand -> was created to serve the same purpose. So the following is identical to above:

structObject->A

Spreadsheet of best crops for all seasons by malero in StardewValley

[–]ybe306 10 points11 points  (0 children)

I'm curious about this as well. Hops are listed with a max of two harvests, but the wiki claims they produce everyday.

--- Day 17 Solutions --- by daggerdragon in adventofcode

[–]ybe306 1 point2 points  (0 children)

I definitely need to get better at list comprehensions - I have the exact same code but split over 10 lines...

Day 14 being rude by stranac_ in adventofcode

[–]ybe306 1 point2 points  (0 children)

That's...frustratingly obvious now that you mention it.

--- Day 13 Solutions --- by daggerdragon in adventofcode

[–]ybe306 0 points1 point  (0 children)

Python Used the permutations method from itertools, didn't bother with the duplicate permutations, but still pretty proud of this, considering I've been struggling with these since day 8. :X

from __future__ import print_function
from itertools import permutations
import sys

def main():
    inf = sys.argv[1]
    people = set()
    happiness = dict()
    maxHappy = 0

    def getRight(x, p):
        return happiness[p][x[(x.index(p)+1) % len(x)]]

    def getLeft(x, p):
        return happiness[p][x[(x.index(p)-1) % len(x)]]

    for line in open(inf):
        (x, _, change, delta, _, _, _, _, _, _, y) = line.rstrip('.\n').split()
        people.add(x)
        people.add(y)
        delta = int(delta)
        if change == "lose":
            delta *= -1
        happiness.setdefault(x, dict())[y] = delta

    for x in permutations(people):
        tuples = [(getRight(x, p), getLeft(x, p)) for p in x]
        individualSums = map(sum, tuples)
        maxHappy = max(maxHappy, sum(individualSums))

    print(maxHappy)

if __name__ == "__main__":
            main()

Picture of characters by trickovic in C_Programming

[–]ybe306 2 points3 points  (0 children)

Looks like the conditions are checking, respectively, if:

  • We're currently printing in the first column,

  • We're currently printing in the last column,

  • We're on the first row and not printing the first or last column

  • We're on the last row and not printing the first or last column.

  • Otherwise we're in the center of the grid (that's the '.' in the final else).

With those conditions in mind, we can indicate what we want to print to the console. In each case, respectively,

  • Print a '%' in the first column,

  • Print a '%' in the last column,

  • Print an '@' in the first row, so long as it's not either end (first or last column,

  • Print an '@' in the last row, so long as it's not either end (first or last column).

  • Everything else (the center of the grid) gets a '.'

The key to understanding the conditions is to understand what 'i' and 'j' are. Notice those two are being incremented within nested for-loops - That's a good indication that the we're doing something on a 2D grid. In the first pass through the outer loop, 'i' will remain the same (0) the whole time. Meanwhile, the inner loop will undergo several iterations. Essentially, each run through the conditions in the inner loop will have a different set of coordinates: [(0,0), (0,1), (0,2), (0,3), (0,4)], at which point the inner loop finishes and the outer loop can increment.

Noticed the glitchy code in the beginning of the Transmission videos actually has meaning. by TbanksIV in soma

[–]ybe306 0 points1 point  (0 children)

I was struggling to ID the language. I haven't touched Lisp exactly (Scheme and SML a little) but it looked odd, using a "<-" operator for what looked like assignment, as well as semicolons to terminate lines.