go: duration loop

Here is a simple duration loop go program https://play.golang.org/p/ly9U9EUr2of

package main

import (
	"fmt"
	"time"
)

func main() {
	duration := time.Second *10
	fmt.Println("Hello, duration loop "+duration.String()+" long")
	
	t1 := time.Now()
	
	for t2:= time.Now(); t2.Sub(t1) < duration; t2 = time.Now(){
	   	fmt.Println(t2.String())
		time.Sleep(time.Second)
	
	}
}

Posted in golang, workday | Leave a comment

go: proverbs

Rob Pike at Gopherfest on November 18, 2015 mentioned several thoughtful go proverbs, as you may see on this video. Here they are:

  1. Don’t communicate by sharing memory, share memory by communicating.
  2. Concurrency is not parallelism.
  3. Channels orchestrate; mutexes serialize.
  4. The bigger the interface, the weaker the abstraction.
  5. Smaller the interface, more useful.
  6. Make the zero value useful.
  7. interface{} says nothing.
  8. Gofmt’s style is no one’s favorite, yet gofmt is everyone favorite.
  9. A little copying is better than a little dependency.
  10. Syscall must always be guarded with build tags.
  11. Cgo must always be guarded with build tags.
  12. Cgo is not Go.
  13. With the unsafe package there are no guarantees.
  14. Clear is better then clever.
  15. Reflection is never clear.
  16. Errors are values.
  17. Don’t just check errors, handle them gracefully.
  18. Design the architecture, name the components, document the details.
  19. Documentation is for users.

Many more proverbs possible, but they must be short, poetic, general, about Go more than about programming. Contradictory is OK. Life and programming are full of contradictions.

Greg Osuri made Go proverbs illustrated.

Posted in golang, workday | Leave a comment

go: printing struct & array

Printing struct https://play.golang.org/p/BvMIqF3Pmc9

package main

import "fmt"

type point struct {
    x, y int
}

func main() {
    p := point{1, 2}
    fmt.Println("Printing struct point:")
    fmt.Printf(" type          %%T: %T\n", p)
    fmt.Printf(" just values   %%v: %v\n", p)
    fmt.Printf(" +field names %%+v: %+v\n", p)
    fmt.Printf(" go syntax    %%#v: %#v\n", p)
    fmt.Println()

    ptr := &p
    fmt.Println("Printing pointer to struct point:")
    fmt.Printf(" type          %%T: %T\n", ptr)
    fmt.Printf(" just values   %%v: %v\n", ptr)
    fmt.Printf(" +field names %%+v: %+v\n", ptr)
    fmt.Printf(" go syntax    %%#v: %#v\n", ptr)
    fmt.Println()

    arrP := []point{point{1, 2},point{3, 4}}
    fmt.Println("Printing array of struct points:")
    fmt.Printf(" type          %%T: %T\n", arrP)
    fmt.Printf(" just values   %%v: %v\n", arrP)
    fmt.Printf(" +field names %%+v: %+v\n", arrP)
    fmt.Printf(" go syntax    %%#v: %#v\n", arrP)
}

Output:

Printing struct point:
 type          %T: main.point
 just values   %v: {1 2}
 +field names %+v: {x:1 y:2}
 go syntax    %#v: main.point{x:1, y:2}

Printing pointer to struct point:
 type          %T: *main.point
 just values   %v: &{1 2}
 +field names %+v: &{x:1 y:2}
 go syntax    %#v: &main.point{x:1, y:2}

Printing array of struct points:
 type          %T: []main.point
 just values   %v: [{1 2} {3 4}]
 +field names %+v: [{x:1 y:2} {x:3 y:4}]
 go syntax    %#v: []main.point{main.point{x:1, y:2}, main.point{x:3, y:4}}
Posted in golang, workday | Leave a comment

go: add elements to array

Here is one way, how to add elements to array in go language, see https://play.golang.org/p/nCLX23ymRUM

package main

import (
	"fmt"
)

type MyRecord struct {
	Name  string
	Phone string
}

var recA = MyRecord{Name: "Anna", Phone: "123"}
var recB = MyRecord{Name: "Bob", Phone: "456"}

type Records []MyRecord

func buildAppendedArrayPtr() {
	arr := make(Records, 0)
	arrPtr := &arr
	arrPtr = appendToArrayPtr(arrPtr, recA)
	arrPtr = appendToArrayPtr(arrPtr, recB)

	fmt.Printf("%v %T %d \n", arrPtr, arrPtr, len(*arrPtr))

	for i, rec := range *arrPtr {
		fmt.Printf("%d. %v\n", i, rec)
	}
}

func appendToArrayPtr(recordsPtr *Records, myRecord MyRecord) *Records {
	arr := append(*recordsPtr, myRecord)
	return &arr
}

func main() {
	buildAppendedArrayPtr()
}

Posted in golang, workday | Leave a comment

GIMP: first script-fu

GIMP is great tool for images manipulation. Even better is to automate as much as possible through scripts.
Lets say we would create file named my-first.scm and this file will be placed into sub-directory scripts. Location would depend on the operation system.
Here is example from Windows 10:
C:\Users\JoeDoe\AppData\Roaming\GIMP\2.10\scripts\my-first.scm

File could have content:

(define (ten) (+ 5 5))
(define (square x) (* x x))

In GIMP, scripts have to be refreshed: Filters/Scripts-Fu/Refresh scripts
Then we can open console Filters/Script-Fu/Console and in command line write command:
(ten)
We should see output 10.
(square 5)
We should see output 25.

At https://stackoverflow.com/questions/5811378/how-do-i-write-a-custom-auto-crop-script-using-the-gimp has been published very useful Edger Script. If you would copy and paste it into file, let’s say C:\Users\JoeDoe\AppData\Roaming\GIMP\2.10\scripts\my-edger.scm and then refresh scripts. Script takes arguments input-file, output file, top, right, bottom, left. Example executing it from the console is below:

(script-fu-wirebear-edger "I:\\Pictures\\IMG-000.png" "I:\\Pictures\\Edged-IMG-000.png" 10 20 30 40)
Posted in workday | Leave a comment

base64

Base64 encoding is widely used and there are nice online tools, for example https://www.base64decode.org/.

On command line could be convenient choice to use openssl with argument base64 to encode or two arguments base64 -d to decode. Tool reads from stdin, or from file with argument -in and writes to stdout or to the file with arguments -out .

echo Blog | openssl base64
QmxvZwo=
echo AB | openssl base64
QUIK
echo QUIK | openssl base64 -d
AB
Posted in workday | Leave a comment

go: interface example

Go is fresh fast relatively new language. One of the key to utilize it’s power are interfaces. Here is example of the geometry interfaces. See https://play.golang.org/p/nQ_ylb2jXKS

package main

import (
	"fmt"
	"math"
)

//https://www.mathsisfun.com/area.html

type geometry interface {
	area() float64
	perimeter() float64
}

type square struct {
	side float64
}
type rectangle struct {
	width, height float64
}
type triangle struct {
	a, b, c float64
}
type circle struct {
	radius float64
}

func (s square) area() float64 {
	return s.side * s.side
}
func (s square) perimeter() float64 {
	return 4 * s.side
}
func (r rectangle) area() float64 {
	return r.width * r.height
}
func (r rectangle) perimeter() float64 {
	return 2*r.width + 2*r.height
}
func (t triangle) area() float64 {
	cosGama := (t.c*t.c - t.a*t.a - t.b*t.b) / (2 * t.a * t.b)
	if math.Abs(cosGama) > 1.0 {
		fmt.Println("Input values are not for triangle")
		return -1
	}
	sinGama := math.Sqrt(1.0 - cosGama*cosGama)
	heightA := t.b * sinGama
	// fmt.Printf("triangle:  cos=%f, sin=%f,hA=%f\n",cosGama,sinGama,heightA)
	return t.a * heightA
}
func (t triangle) perimeter() float64 {
	return t.a + t.b + t.c
}
func (c circle) area() float64 {
	return math.Pi * c.radius * c.radius
}
func (c circle) perimeter() float64 {
	return 2 * math.Pi * c.radius
}
func measure(g geometry) {
	fmt.Println(g)
	fmt.Printf("area     : %f \n", g.area())
	fmt.Printf("perimeter: %f \n", g.perimeter())
}
func main() {
	s := square{side: 2}
	r := rectangle{width: 3, height: 4}
	t1 := triangle{a: 3, b: 4, c: 5}
	t2 := triangle{a: 1, b: 1, c: 1}
	t3 := triangle{a: 1, b: 1, c: 30}
	c := circle{radius: 5}
	
	measure(s)
	measure(r)
	measure(t1)
	measure(t2)
	measure(t3)
	measure(c)
}

Posted in golang, workday | Leave a comment

HTTPS Tomcat

Here are some notes from install and run HTTPS Tomcat on digitalocean inpired by Mavi’s blog.

on digitalocean:
Ubuntu 18.04 x64
Memory:1GB, vCPU:1, SSD_Disk:25GB, Transfer:1TB, price:$5/mo
Hostname:ubuntu18
IP:1.2.3.4

on my DNS provider web:
Edit DNS A records for example.com and www.example.com

ssh session to example.com, user root

# snap install docker
2018-08-29T15:33:20Z INFO Waiting for restart...
docker 17.06.2-ce from 'docker-inc' installed

#snap info certbot
#snap install --edge certbot

#apt-get update
#apt-get install software-properties-common
#add-apt-repository ppa:certbot/certbot
#apt-get update
#apt-get install certbot 
.
.
.Setting up certbot (0.26.1-1+ubuntu18.04.1+certbot+2) ...
Created symlink /etc/systemd/system/timers.target.wants/certbot.timer → /lib/systemd/system/certbot.timer.
certbot.service is a disabled or a static unit, not starting it.

#certbot certonly
...I choosed 1. spin up a temporary webserver (standalone)


#apt install docker-compose


#cd /root/app
#docker-compose up

and, yes, I see Tomcat at https://example.com

Posted in workday | Leave a comment

CSV: How to sort by several columns in Java8



CSV_SortByThreeColumns.java

package example.stream;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Comparator;
import java.util.stream.Stream;
/**
 * Let's say there is a comma delimited file with the first line describing column names:
 * Name, State, Years of experience
 * Here is how to sort lines from the most experienced people, then by state and name
 */

public class CSV_SortByThreeColumns {
    private static void printSortedByExperienceAndStateAndNameFromStreamedLines(Stream<String> stream){
        Comparator<String> byExperience = Comparator.comparing(
                line -> Integer.parseInt(line.split(",")[2]), Comparator.reverseOrder()
        );// by Years of experience - reversed
        Comparator<String> byExperienceAndState = byExperience.thenComparing(
                line -> line.split(",")[1]
        );// by State
        Comparator<String> comparator = byExperienceAndState.thenComparing(
                line -> line.split(",")[0]
        );// by Name
        stream
                .skip(1L)
                .sorted(comparator)
                .forEach(System.out::println);
    }
    public static void main(String[] args) throws IOException {
        //BufferedReader reader = Files.newBufferedReader(Paths.get("a.csv"));
        BufferedReader reader = new BufferedReader(new StringReader(
                        "Name,State,Years of experience\n" +
                        "John,MN,1\n" +
                        "Zita,CA,2\n" +
                        "Adam,CA,5\n" +
                        "Dough,CA,20\n" +
                        "Richard,MN,6\n" +
                        "Robert,CT,6"));
        printSortedByExperienceAndStateAndNameFromStreamedLines(reader.lines());
    }
}

Output:

Dough,CA,20
Robert,CT,6
Richard,MN,6
Adam,CA,5
Zita,CA,2
John,MN,1

Links: stream(package summary), Stream<T>, Comparator<T>

Posted in Java8, workday | Leave a comment

CSV: How to skip the first line in Java8



CSV_SkipFirstLine.java

package example.stream;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.stream.Stream;

/**
 * Let's say there is a comma delimited file with the first line describing column names.
 * In this example a person name and state.
 * Here is how to skip the first line using Java8 stream
 */
public class CSV_SkipFirstLine {
    private static void skipFirstAndPrintRestOfLinesFromStream(Stream<String> stream){
        stream
                .skip(1L)
                .forEach(System.out::println);
    }
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new StringReader(
                        "Name,State\n" +
                        "John,MN\n" +
                        "Zita,CA\n" +
                        "Adam,CA\n" +
                        "Dough,CA\n" +
                        "Richard,MN\n" +
                        "Robert,CT"));
        skipFirstAndPrintRestOfLinesFromStream(reader.lines());
    }
}

Output:

John,MN
Zita,CA
Adam,CA
Dough,CA
Richard,MN
Robert,CT
Posted in Java8, workday | Leave a comment