working on it ...

Filters

Explore Public Snippets

Sort by

Found 24k snippets

    public by Kingsley Huynh  5561  29  5  0

    Golang HTTP Handler to Upload Image => Resize => Convert to JPEG => Save to Disk.

    Golang HTTP Handler to Upload Image = Resize = Convert to JPEG = Save to Disk. : gistfile1.go
    Go
    func UploadHandler(w http.ResponseWriter, r *http.Request) {
    
    	file, _, err := r.FormFile("file")
    	if err != nil {
    		log.Println(err)
    		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
    		return
    	}
    
    	img, _, err := image.Decode(file)
    	if err != nil {
    		log.Println(err)
    		http.Error(w, http.StatusText(http.StatusUnsupportedMediaType), http.StatusUnsupportedMediaType)
    		return
    	}
    
    	m := resize.Resize(1000, 0, img, resize.Lanczos3)
    
    	out, err := os.Create("test_resized.jpg")
    	if err != nil {
    		log.Println(err)
    		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
    		return
    	}
    	defer out.Close()
    
    	// Encode into jpeg http://blog.golang.org/go-image-package
    	err = jpeg.Encode(out, m, nil)
    	if err != nil {
    		log.Println(err)
    		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
    		return
    	}
    }
    
    

    external by Frank He  3  0  1  0

    slow client

    slow client: client.go
    package main
    
    import (
    	"fmt"
    	"net/http"
    	"os"
    	"time"
    
    	"google3/base/go/flag"
    )
    
    var (
    	url             = flag.String("url", "", "URL")
    	transportBuffer = flag.Int("transport_buffer", 10, "transport buffer size in bytes used by HTTP client")
    	readBuffer      = flag.Int("read_buffer", 1, "read buffer size in bytes used for reading bytes from the trasport buffer")
    	readInterval    = flag.Duration("read_interval", time.Second, "interval to read from the transport buffer into the read buffer")
    )
    
    func main() {
    	flag.Parse()
    	fmt.Println("=======================\n")
    	fmt.Printf("URL: %s\ntransport_buffer: %d\nread_buffer:%d\nread_interval: %v\n", *url, *transportBuffer, *readBuffer, *readInterval)
    	transport := &http.Transport{
    		ReadBufferSize: *transportBuffer,
    	}
    	fmt.Println("=======================\n\n")
    	client := &http.Client{Transport: transport}
    	response, err := client.Get(*url)
    	if err != nil {
    		fmt.Printf("%v\n", err)
    		os.Exit(1)
    	}
    	defer response.Body.Close()
    	for k, v := range response.Header {
    		fmt.Printf("%s:%s\n", k, v)
    	}
    
    	buffer := make([]byte, *readBuffer)
    	for {
    		n, err := response.Body.Read(buffer)
    		if err != nil {
    			fmt.Printf("Read error: %v\n", err)
    			os.Exit(1)
    		}
    		fmt.Printf("Read %d bytes: %s\n", n, string(buffer))
    		time.Sleep(*readInterval)
    	}
    }
    
    

    external by Frank He  2  0  1  0

    Example Upstream

    Example Upstream : upstream.go
    package main
    
    import (
    	"fmt"
    	"io"
    	"math"
    	"net/http"
    	"net/http/httputil"
    	"strconv"
    	"strings"
    	"time"
    )
    
    var (
    	server *http.Server
    )
    
    func handler(w http.ResponseWriter, r *http.Request) {
    	io.WriteString(w, "hello, world!!!\n")
    }
    
    // By default, it returns 5 chunks, one per second
    // /chunked?interval=500ms to change the interval
    // /chunked?infinite=true to change to return infinite number of chunks
    // /chunked?size_bytes=1000 to change the size of chunk.
    func chunkedHandler(w http.ResponseWriter, r *http.Request) {
    	requestDump, _ := httputil.DumpRequest(r, true)
    	fmt.Printf("%s", string(requestDump))
    	flusher, ok := w.(http.Flusher)
    	if !ok {
    		panic("expected http.ResponseWriter to be an http.Flusher")
    	}
    	interval := time.Second
    	if in := r.URL.Query().Get("interval"); in != "" {
    		if d, err := time.ParseDuration(in); err == nil {
    			interval = d
    		}
    	}
    	var count int64
    	count = 5
    	if r.URL.Query().Get("infinite") != "" {
    		count = math.MaxInt64
    	}
    	fixedSizeChunk := ""
    	if sz := r.URL.Query().Get("size_bytes"); sz != "" {
    		if i, err := strconv.Atoi(sz); err == nil {
    			fixedSizeChunk = strings.Repeat("a", i)
    		}
    	}
    	fmt.Printf("[%v] send a chunk every %v for %d times\n", time.Now(), interval, count)
    	if fixedSizeChunk != "" {
    		fmt.Printf("[%v] fixed size chunk is set to %d\n", time.Now(), len(fixedSizeChunk))
    	}
    	var i int64
    	for ; i < count; i++ {
    		chunk := fmt.Sprintf("[%v] Chunk #%d\n", time.Now(), i)
    		if fixedSizeChunk != "" {
    			chunk = fixedSizeChunk
    		}
    		//fmt.Printf("%s", chunk)
    		if _, err := fmt.Fprintf(w, "%s", chunk); err != nil {
    			fmt.Printf("failed to flush the chunk: %s\n", chunk)
    			return
    		}
    		flusher.Flush() // Trigger "chunked" encoding and send a chunk...
    		time.Sleep(interval)
    	}
    	fmt.Printf("[%v] %d chunks were sent.\n", time.Now(), count)
    }
    
    func main() {
    	http.HandleFunc("/", handler)
    	http.HandleFunc("/chunked", chunkedHandler)
    	server = &http.Server{Addr: ":8080"}
    	fmt.Printf("[%v] Start listening ...\n", time.Now())
    	server.ListenAndServe()
    }
    
    
    

    external by Merwane Draï  2  0  1  0

    Concurrent Fibonacci sequence calculation w/ Golang

    Concurrent Fibonacci sequence calculation w/ Golang: fibonacci.go
    package main
    
    import(
      "fmt"
      "time"
    )
    
    func main(){
      defer elapsed()()
      jobs := make(chan int, 100)
      results := make(chan int, 100)
    
      // concurrent workers
      // remove or add some to test different configs
      go worker(jobs, results)
      go worker(jobs, results)
      go worker(jobs, results)
      go worker(jobs, results)
    
    
      for i := 0; i < 100; i++ {
        jobs <- i
      }
      close(jobs)
    
      for j := 0; j < 50; j++ {
        fmt.Println(<-results)
      }
    }
    
    func worker(jobs <-chan int, results chan<- int){
      for n := range jobs {
        results <- fib(n)
      }
    }
    
    func fib(n int) int {
      if n <= 1 {
        return n
      }
      return fib(n-1) + fib(n-2)
    }
    
    // calculate time elapsed
    func elapsed() func(){
      start := time.Now()
      return func(){
        fmt.Printf("Calculation took %v\n", time.Since(start))
      }
    }
    // Happy Fibonacci day :)
    
    

    external by HauptJ  2  0  1  0

    Rotate Matrix Clockwise: https://leetcode.com/problems/rotate-image/

    Rotate Matrix Clockwise: https://leetcode.com/problems/rotate-image/: rotateMatrixClockwise.go
    func rotate(matrix [][]int) [][]int {
        length := len(matrix)
        
        // swap bottom and top rows
        for j := 0; j < length; j++{
            temp := matrix[0][j]
            matrix[0][j] = matrix[length -1][j]
            matrix[length -1][j] = temp
        }
        
        // swap i, j
        for i := 0; i < length; i++{
            for j := 0; j < length; j++ {
                temp := matrix[i][j]
                matrix[i][j] = matrix[j][i]
                matrix[j][i] = temp
            }
        }
        return matrix
    }
    
    
    /*swap matrix[2][0] with matrix[0][0] swap bottom and top 
    swap matrix[1][0] with matrix[0][1] swap i, j
    swap matrix[0][0] with matrix[0][2]
    
    swap matrix[2][1] with matrix[1][0]
    swap matrix[1][1] with matrix[1][1] swap i, j
    swap matrix[0][1] with matrix[1][2]
    
    swap matrix[2][2] with matrix[2][0]
    swap matrix[1][2] with matrix[2][1] swap j, j
    swap matrix[0][2] with matrix[2][2]
    
    
    length = len(matrix)
    temp= matrix[i][j]
    matrix[len-1][j] = matrix[0][j]
    matrix[len-1][j+1] = matrix[0][j+1]
    matrix[len-1][j+2] = matrix[0][j+2] J+2 = len-1
    
    
    // swap bottom and top rows
    for j := 0; j < length-1; j++ {
        temp := matrix[0][j]
        matrix[0][j] = matrix[length-1][j]
        matrix[length-1][j] = temp
    }
    
    // swap i, j
    for i := 0; i < length -1; i++{
        for j := 0; j < length -1; j++ {
            temp := matrix[i][j]
            matrix[i][j] = matrix[j][i]
            matrix[j][i] = temp
        }
    }*/
    
    

    external by alex-leonhardt  2  0  1  0

    concurrently run a command using waitGroups and channels

    concurrently run a command using waitGroups and channels: main.go
    package main
    
    import (
    	"fmt"
    	"math/rand"
    	"os/exec"
    	"sync"
    	"time"
    )
    
    func doLS(path string) ([]byte, error) {
    	cmd := exec.Command("ls", "-l", path)
    	return cmd.CombinedOutput()
    }
    
    func main() {
    
    	outputs := make(chan string)
    
    	var wg sync.WaitGroup
    
    	wg.Add(1)
    	go func() {
    		out, _ := doLS("/usr")
    		time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
    		outputs <- string(out)
    		wg.Done()
    	}()
    
    	wg.Add(1)
    	go func() {
    		out, _ := doLS("/")
    		time.Sleep(time.Duration(rand.Intn(5000)) * time.Millisecond)
    		outputs <- string(out)
    		wg.Done()
    	}()
    
    	go func() {
    
    		for outputs != nil {
    			fmt.Println("...")
    			select {
    			case m, ok := <-outputs:
    				if !ok {
    					outputs = nil
    					break
    				}
    				fmt.Println(m)
    			}
    		}
    
    	}()
    
    	wg.Wait()
    	close(outputs)
    
    }
    
    
    

    external by salrashid123  2  0  1  0

    cloud tasks fanout

    cloud tasks fanout: tasks.go
    client, err := cloudtasks.NewClient(ctx)
    if err != nil {
    	log.Fatalf("NewClient: %v", err)
    }
    
    destName := fmt.Sprintf("%s", event.Metadata["name"])
    destFormats := event.Metadata["formats"]
    s := strings.Split(fmt.Sprintf("%v", destFormats), ",")
    
    for _, destFmt := range s {
    	data := url.Values{}
    	data.Set("format", destFmt)
    	data.Set("source", event.Name)
    	data.Set("name", destName+"."+destFmt)
    
    	logger.Printf("Converting source [%s], to [%s] as format [%s]", event.Name, destName, destFmt)
    
    
    	taskID := uuid.New().String()
    
    	parentName := fmt.Sprintf("projects/%s/locations/%s/queues/%s", os.Getenv("GCLOUD_PROJECT"), locationID, queueID)
    	queuePath := fmt.Sprintf("%s/tasks/%s", parentName, taskID)
    	
    
    	url := cloudRunURL + "/convert"
    	req := &taskspb.CreateTaskRequest{
    		Parent: parentName,
    		Task: &taskspb.Task{
    			Name: queuePath,
    			MessageType: &taskspb.Task_HttpRequest{
    				HttpRequest: &taskspb.HttpRequest{
    					HttpMethod: taskspb.HttpMethod_POST,
    					Url:        url,
    					Headers:    map[string]string{"Content-type": "application/x-www-form-urlencoded"},
    					Body:       []byte(data.Encode()),
    					AuthorizationHeader: &taskspb.HttpRequest_OidcToken{
    						OidcToken: &taskspb.OidcToken{
    							ServiceAccountEmail: serviceAccount,
    							Audience:            cloudRunURL,
    						},
    					},
    				},
    			},
    		},
    	}
    	resp, err := client.CreateTask(ctx, req)
    	if err != nil {
    		logger.Fatalf("ERROR: %v", err.Error())
    	}
    	logger.Printf("Enqueued Task %s", resp.GetName())
    }
    
    
    

    external by qrntz  2  0  1  0

    go error monad

    go error monad: error.go
    package main
    
    import (
        "errors"
        "log"
    )
    
    type F func() error
    
    func errCompose(pipeline ...F) (e error, ok bool) {
        ok = true
    
        for _, f := range pipeline {
            e = f()
    
            if e != nil {
                ok = false
                break
            }
        }
    
        return
    }
    
    func main() {
        good := func() error {
            log.Println("good function called")
            return nil
        }
    
        good2 := func() error {
            log.Println("good function 2 called")
            return nil
        }
    
        bad := func() error {
            log.Println("bad function called")
            return errors.New("bad function returned error")
        }
    
        // if pipeline succeeds, handler does not get called
        if _, ok := errCompose(good, good, good); !ok {
            log.Println("this shouldn't happen")
        }
    
        // pipeline interrupts at first error
        if e, ok := errCompose(good, bad, good2); !ok {
            log.Println("good2 was not called:", e)
        }
    }
    
    
    

    external by Marcelo  2  0  1  0

    Graphs tp2 final https://br.spoj.com/problems/OLIMP/ Adriana Daniel Higor Henrique Marcelo

    Graphs tp2 final https://br.spoj.com/problems/OLIMP/ Adriana Daniel Higor Henrique Marcelo : main.go
    package main
    
    import "fmt"
    
    const (
    	white = 0
    	blue  = 1
    	red   = 2
    )
    
    type airportsQueue struct {
    	O, D         int
    	queue, color []int
    }
    
    func (queue *airportsQueue) init(airport int) {
    	queue.queue = make([]int, airport+2)
    	queue.color = make([]int, airport)
    }
    
    func (queue *airportsQueue) add(airport int) {
    	queue.queue[queue.D] = airport
    	queue.D++
    	queue.color[airport] = blue
    }
    
    func (queue *airportsQueue) remove() int {
    	aux := queue.queue[queue.O]
    	queue.O++
    	queue.color[aux] = red
    
    	return aux
    }
    
    type travel struct {
    	O     int
    	D     int
    	capacity int
    }
    
    type queueTravel []travel
    
    type analysedFlux struct {
    	path     []int
    	capacity int
    }
    
    type fordScheduler struct {
    	airportsV int
    	O         int
    	D         int
    	sits      [][]int
    	pred      []int
    	flow      [][]int
    }
    
    
    
    // set the bigger value to compare on future
    const maxSize = 99999
    
    func (schedulerFord *fordScheduler) bfs(start int, target int) bool {
    	var u, v int
    
    	q := &airportsQueue{O: 0, D: 0}
    	q.init(schedulerFord.airportsV + 1)
    
    	q.add(start)
    	schedulerFord.pred[start] = -1
    	for q.O != q.D {
    		u = q.remove()
    
    		for v = 0; v < schedulerFord.airportsV; v++ {
    			if q.color[v] == white && schedulerFord.sits[u][v]-schedulerFord.flow[u][v] > 0 {
    				q.add(v)
    				schedulerFord.pred[v] = u
    			}
    		}
    	}
    
    	return q.color[target] == red
    }
    
    func min(input1 int, input2 int) int {
    	if input1 < input2 {
    		return input1
    	}
    	return input2
    }
    
    func (schedulerFord *fordScheduler) maxFlow() []analysedFlux {
    	var maxflowAux = 0
    	var travelCount = make([]int, 0)
    
    	// used to calc number of days spent
    	indexFlowWithA := make([]analysedFlux, 0)
    	indexFlow := 0
    
    	for schedulerFord.bfs(schedulerFord.O, schedulerFord.D) {
    		// increment is the number of Atletas that can be transported on the way
    		increment := maxSize
    		for u := schedulerFord.airportsV - 1; schedulerFord.pred[u] >= 0; u = schedulerFord.pred[u] {
    			increment = min(increment, schedulerFord.sits[schedulerFord.pred[u]][u]-schedulerFord.flow[schedulerFord.pred[u]][u])
    		}
    
    		// Flow is the path will be filled by Atletas
    		aux := 0
    		pathProvider := make([]int, 0)
    		for u := schedulerFord.airportsV - 1; schedulerFord.pred[u] >= 0; u = schedulerFord.pred[u] {
    			schedulerFord.flow[schedulerFord.pred[u]][u] += increment
    			schedulerFord.flow[u][schedulerFord.pred[u]] -= increment
    			pathProvider = append(pathProvider, u)
    			aux++
    		}
    
    		indexFlowWithA = append(indexFlowWithA, analysedFlux{
    			path:     make([]int, aux),
    			capacity: 0,
    		})
    		pathProvider = append(pathProvider, 1)
    		indexFlowWithA[indexFlow].path = pathProvider
    		indexFlowWithA[indexFlow].capacity = increment
    
    		travelCount = append(travelCount, increment)
    		maxflowAux += increment
    		indexFlow++
    	}
    
    	return indexFlowWithA
    }
    
    func (schedulerFord *fordScheduler) findBiggerTravel(travels queueTravel) int {
    	// schedulerFord is a appointer to reiceve in another function the memory  address
    	element := 0
    	for _, travel := range travels {
    		if travel.O > element {
    			element = travel.O
    		}
    		if travel.D > element {
    			element = travel.D
    		}
    	}
    	return element
    }
    
    func (schedulerFord *fordScheduler) startNew(OInput int, DInput int, edges queueTravel) {
    	index := schedulerFord.findBiggerTravel(edges) + 1
    	schedulerFord.airportsV = index
    
    	// create matriz to set graph sits (indicates during bfs)
    	// create matriz to set graph flow (indicates before bfs, on ford alg)
    	schedulerFord.sits = make([][]int, index)
    	schedulerFord.flow = make([][]int, index)
    
    	for i := range schedulerFord.sits { // dos not make difference use sits or flow (they have same size)
    		schedulerFord.flow[i] = make([]int, index)
    		schedulerFord.sits[i] = make([]int, index)
    	}
    
    	schedulerFord.O = OInput // origem input
    	schedulerFord.D = DInput // destination input, or sink, or target
    
    	schedulerFord.pred = make([]int, index)
    
    	for _, edge := range edges {
    		schedulerFord.sits[edge.O][edge.D] = edge.capacity
    	}
    }
    
    
    func readEntry() (int, int, int) {
    	var n, m, a int
    	_, _ = fmt.Scanf("%d %d %d", &n, &m, &a) // the _ is for ignore possible erors
    
    	// conditions from enunciado
    	if n < 2 || n > 50 {
    		return 0, 0, 0
    	}
    	if m < 1 || m > 2450 {
    		return 0, 0, 0
    	}
    	if a < 1 || a > 50 {
    		return 0, 0, 0
    	}
    
    	return n, m, a
    }
    
    func readEntryLine(n int) (int, int, int) {
    	var o, d, s int
    	_, _ = fmt.Scanf("%d %d %d", &o, &d, &s)
    	// conditions from enunciado
    	if o < 1 || o > n {
    		return 0, 0, 0
    	}
    	if (d < 1 || d > n) && o == d {
    		return 0, 0, 0
    	}
    	if s < 1 || s > 50 {
    		return 0, 0, 0
    	}
    
    	return o, d, s
    }
    
    func fordFulkersonAlgorithm(o int, d int, a queueTravel) []analysedFlux {
    	var funcCaller = &fordScheduler{}
    	// initialize caller with entrys
    	funcCaller.startNew(o, d, a)
    	// call max flow function (made embased in ford fulkerson alg)
    	return funcCaller.maxFlow() // return an array with the path and the capacity to transport Atletas (max flow)
    }
    
    func output(input []int){
    	// output
    	for i:=0; i < len(input); i++{
    		if len(input) == i+1{
    			fmt.Print(input[i])
    		}else{
    			fmt.Println(input[i])
    		}
    	}
    }
    
    func main() {
    	var daysSpentInTestCase = make([]int, 0)
    
    	for {
    		// read entrys
    		
    		n, m, a := readEntry()
    		// N: Airports
    		// M: Travels avaible
    		// A: Atletas to travel
    		if n == m && m == a && a == 0 {
    			output(daysSpentInTestCase)
    			return
    		}
    
    		var i int
    		var tr = queueTravel{}
    
    		for i = 0; i < m; i++ {
    			o, d, s := readEntryLine(n)
    			// O: Origem (source)
    			// D: Destino (sink)
    			// S: Sits (Weigth of edge)
    			tr = append(tr, travel{O: o, D: d, capacity: s})
    		}
    
    		// here we calculate Ford Fulkerson Max Flow
    		flux := fordFulkersonAlgorithm(1, n, tr)
    
    		day := 1
    		var reached int
    		for reached < a {
    			for i := 0; i < len(flux); i++ {
    				if day >= len(flux[i].path)-1 {
    					reached += flux[i].capacity
    				}
    			}
    			day++
    		}
    		daysSpentInTestCase = append(daysSpentInTestCase, day-1)
    	}
    }
    
    
    

    external by Marcelo  4  0  1  0

    tp2 grafos, professor Cléber

    tp2 grafos, professor Cléber: main.go
    package main
    
    import "fmt"
    
    const (
    	white = 0
    	blue  = 1
    	red   = 2
    )
    
    type airportsQueue struct {
    	O, D         int
    	queue, color []int
    }
    
    func (queue *airportsQueue) init(airport int) {
    	queue.queue = make([]int, airport+2)
    	queue.color = make([]int, airport)
    }
    
    func (queue *airportsQueue) add(airport int) {
    	queue.queue[queue.D] = airport
    	queue.D++
    	queue.color[airport] = blue
    }
    
    func (queue *airportsQueue) remove() int {
    	aux := queue.queue[queue.O]
    	queue.O++
    	queue.color[aux] = red
    
    	return aux
    }
    
    type travel struct {
    	tail     int
    	head     int
    	capacity int
    }
    
    type analysedFlux struct {
    	path     []int
    	capacity int
    }
    
    type queueTravel []travel
    
    const maxSize = int(^uint(0) >> 1)
    
    type fordScheduler struct {
    	airportsV int
    	O         int
    	D         int
    	sits      [][]int
    	pred      []int
    	flow      [][]int
    }
    
    func (gs *fordScheduler) bfs(start int, target int) bool {
    	var u, v int
    
    	q := &airportsQueue{O: 0, D: 0}
    	q.init(gs.airportsV + 1)
    
    	q.add(start)
    	gs.pred[start] = -1
    	for q.O != q.D {
    		u = q.remove()
    
    		for v = 0; v < gs.airportsV; v++ {
    			if q.color[v] == white && gs.sits[u][v]-gs.flow[u][v] > 0 {
    				q.add(v)
    				gs.pred[v] = u
    			}
    		}
    	}
    
    	return q.color[target] == red
    }
    
    func min(input1 int, input2 int) int {
    	if input1 < input2 {
    		return input1
    	}
    	return input2
    }
    
    func (gs *fordScheduler) maxFlow() []analysedFlux {
    	var maxflow int = 0
    	var travelCount = make([]int, 0)
    
    	// used to calc number of days spent
    	indexFlowWithA := make([]analysedFlux, 0)
    	indexFlow := 0
    
    	for gs.bfs(gs.O, gs.D) {
    		// increment is the number of Atletas that can be transported on the way
    		increment := maxSize
    		for u := gs.airportsV - 1; gs.pred[u] >= 0; u = gs.pred[u] {
    			increment = min(increment, gs.sits[gs.pred[u]][u]-gs.flow[gs.pred[u]][u])
    		}
    
    		// Flow is the path will be filled by Atletas
    		aux := 0
    		pathProvider := make([]int, 0)
    		for u := gs.airportsV - 1; gs.pred[u] >= 0; u = gs.pred[u] {
    			gs.flow[gs.pred[u]][u] += increment
    			gs.flow[u][gs.pred[u]] -= increment
    			pathProvider = append(pathProvider, u)
    			aux++
    		}
    
    		indexFlowWithA = append(indexFlowWithA, analysedFlux{
    			path:     make([]int, aux),
    			capacity: 0,
    		})
    		pathProvider = append(pathProvider, 1)
    		indexFlowWithA[indexFlow].path = pathProvider
    		indexFlowWithA[indexFlow].capacity = increment
    
    		travelCount = append(travelCount, increment)
    		maxflow += increment
    		indexFlow++
    	}
    
    	return indexFlowWithA
    }
    
    func (gs *fordScheduler) findBiggerTravel(travels queueTravel) int {
    	element := 0
    	for _, travel := range travels {
    		if travel.tail > element {
    			element = travel.tail
    		}
    		if travel.head > element {
    			element = travel.head
    		}
    	}
    	return element
    }
    
    func (gs *fordScheduler) startNew(OInput int, DInput int, edges queueTravel) {
    	index := gs.findBiggerTravel(edges) + 1
    	gs.airportsV = index
    
    	gs.sits = make([][]int, index)
    	gs.flow = make([][]int, index)
    
    	for i := range gs.sits { // dos not make difference use sits or flow (they have same size)
    		gs.flow[i] = make([]int, index)
    		gs.sits[i] = make([]int, index)
    	}
    
    	gs.O = OInput
    	gs.D = DInput
    
    	gs.pred = make([]int, index)
    
    	for _, edge := range edges {
    		gs.sits[edge.tail][edge.head] = edge.capacity
    	}
    }
    
    
    func readEntry() (int, int, int) {
    	var n, m, a int
    	_, _ = fmt.Scanf("%d %d %d", &n, &m, &a)
    
    	if n < 2 || n > 50 {
    		return 0, 0, 0
    	}
    	if m < 1 || m > 2450 {
    		return 0, 0, 0
    	}
    	if a < 1 || a > 50 {
    		return 0, 0, 0
    	}
    
    	return n, m, a
    }
    
    func readEntryLine(n int) (int, int, int) {
    	var o, d, s int
    	_, _ = fmt.Scanf("%d %d %d", &o, &d, &s)
    
    	if o < 1 || o > n {
    		return 0, 0, 0
    	}
    	if (d < 1 || d > n) && o == d {
    		return 0, 0, 0
    	}
    	if s < 1 || s > 50 {
    		return 0, 0, 0
    	}
    
    	return o, d, s
    }
    
    func fordFulkersonAlgotithm(o int, d int, a queueTravel) []analysedFlux {
    	var funcCaller = &fordScheduler{}
    	funcCaller.startNew(o, d, a)
    	return funcCaller.maxFlow()
    }
    
    func output(input []int){
    	// output
    	for i:=0; i < len(input); i++{
    		fmt.Println(input[i])
    	}
    }
    
    func main() {
    	var daysSpentInTestCase = make([]int, 0)
    
    	for {
    		n, m, a := readEntry()
    		if n == m && m == a && a == 0 {
    			output(daysSpentInTestCase)
    			return
    		}
    
    		var i int
    		var tr = queueTravel{}
    
    		for i = 0; i < m; i++ {
    			o, d, s := readEntryLine(n)
    			tr = append(tr, travel{tail: o, head: d, capacity: s})
    		}
    
    		// here we calculate Ford Fulkerson
    		flux := fordFulkersonAlgotithm(1, n, tr)
    
    		day := 1
    		var reached int
    		for reached < a {
    			for i := 0; i < len(flux); i++ {
    				if day >= len(flux[i].path)-1 {
    					reached += flux[i].capacity
    				}
    			}
    			day++
    		}
    		daysSpentInTestCase = append(daysSpentInTestCase, day-1)
    	}
    }
    
    
    
    • Public Snippets
    • Channels Snippets