File: utils.go

package info (click to toggle)
mirrorbits 0.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 984 kB
  • sloc: sh: 675; makefile: 93
file content (239 lines) | stat: -rw-r--r-- 5,750 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Copyright (c) 2014-2019 Ludovic Fauvet
// Licensed under the MIT license

package utils

import (
	"fmt"
	"math"
	"os"
	"strings"
	"time"

	"github.com/etix/mirrorbits/core"
)

const (
	// DegToRad is a constant to convert degrees to radians
	DegToRad = 0.017453292519943295769236907684886127134428718885417 // N[Pi/180, 50]
	// RadToDeg is a constant to convert radians to degrees
	RadToDeg = 57.295779513082320876798154814105170332405472466564 // N[180/Pi, 50]
)

// HasAnyPrefix reports whether the string s begins with any of the prefixes
func HasAnyPrefix(s string, prefixes ...string) bool {
	for _, p := range prefixes {
		if strings.HasPrefix(s, p) {
			return true
		}
	}
	return false
}

// NormalizeURL adds a trailing slash to the URL
func NormalizeURL(url string) string {
	if url != "" && !strings.HasSuffix(url, "/") {
		url += "/"
	}
	return url
}

// GetDistanceKm returns the distance in km between two coordinates
func GetDistanceKm(lat1, lon1, lat2, lon2 float32) float32 {
	var R float32 = 6371 // radius of the earth in Km
	dLat := (lat2 - lat1) * float32(DegToRad)
	dLon := (lon2 - lon1) * float32(DegToRad)
	a := math.Sin(float64(dLat/2))*math.Sin(float64(dLat/2)) + math.Cos(float64(lat1*DegToRad))*math.Cos(float64(lat2*DegToRad))*math.Sin(float64(dLon/2))*math.Sin(float64(dLon/2))

	c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
	return R * float32(c)
}

// Min returns the smallest of the two values
func Min(v1, v2 int) int {
	if v1 < v2 {
		return v1
	}
	return v2
}

// Max returns the highest of the two values
func Max(v1, v2 int) int {
	if v1 > v2 {
		return v1
	}
	return v2
}

// Add does a simple addition
func Add(x, y int) int {
	return x + y
}

// Version returns the version as a string
func Version() string {
	return core.VERSION
}

// Hostname return the host name as a string
func Hostname() string {
	hostname, _ := os.Hostname()
	return hostname
}

// IsInSlice returns true is `a` is contained in `list`
// Warning: this is slow, don't use it for long datasets
func IsInSlice(a string, list []string) bool {
	for _, b := range list {
		if b == a {
			return true
		}
	}
	return false
}

// IsStopped returns true if a stop has been requested
func IsStopped(stop <-chan struct{}) bool {
	select {
	case <-stop:
		return true
	default:
		return false
	}
}

// ReadableSize returns a file size in a human readable form
func ReadableSize(value int64) string {
	units := []string{"bytes", "KB", "MB", "GB", "TB"}

	v := float64(value)

	for _, u := range units {
		if v < 1024 || u == "TB" {
			return fmt.Sprintf("%3.1f %s", v, u)
		}
		v /= 1024
	}
	return ""
}

// ElapsedSec returns true if lastTimestamp + elapsed time is in the past
func ElapsedSec(lastTimestamp int64, elapsedTime int64) bool {
	if lastTimestamp+elapsedTime < time.Now().UTC().Unix() {
		return true
	}
	return false
}

// Plural returns a single 's' if there are more than one value
func Plural(value interface{}) string {
	n, ok := value.(int)
	if ok && n > 1 || n < -1 {
		return "s"
	}
	return ""
}

// ConcatURL concatenate the url and path
func ConcatURL(url, path string) string {
	if strings.HasSuffix(url, "/") && strings.HasPrefix(path, "/") {
		return url[:len(url)-1] + path
	}
	if !strings.HasSuffix(url, "/") && !strings.HasPrefix(path, "/") {
		return url + "/" + path
	}
	return url + path
}

// FormattedDateUTC returns the date formatted as RFC1123
func FormattedDateUTC(t time.Time) string {
	return t.UTC().Format(time.RFC1123)
}

// IsZero returns whether the date represents the zero time instant
func IsZero(t time.Time) bool {
	return t.IsZero()
}

// TimeKeyCoverage returns a slice of strings covering the date range
// used in the redis backend.
func TimeKeyCoverage(start, end time.Time) (dates []string) {
	if start.Day() == end.Day() && start.Month() == end.Month() && start.Year() == end.Year() {
		dates = append(dates, start.Format("2006_01_02"))
		return
	}

	if start.Day() != 1 {
		month := start.Month()
		for {
			if start.Month() != month || start.Equal(end) {
				break
			}
			dates = append(dates, start.Format("2006_01_02"))
			start = start.AddDate(0, 0, 1)
		}
	}

	for {
		tmpyear := time.Date(start.Year()+1, 1, 1, 0, 0, 0, 0, start.Location())
		tmpmonth := time.Date(start.Year(), start.Month()+1, 1, 0, 0, 0, 0, start.Location())
		if start.Day() == 1 && start.Month() == 1 && (tmpyear.Before(end) || tmpyear.Equal(end)) {
			dates = append(dates, start.Format("2006"))
			start = tmpyear
		} else if tmpmonth.Before(end) || tmpmonth.Equal(end) {
			dates = append(dates, start.Format("2006_01"))
			start = tmpmonth
		} else {
			break
		}
	}

	for {
		if start.AddDate(0, 0, 1).After(end) {
			break
		}
		dates = append(dates, start.Format("2006_01_02"))
		start = start.AddDate(0, 0, 1)
	}

	return
}

// FuzzyTimeStr returns the duration as fuzzy time
func FuzzyTimeStr(duration time.Duration) string {
	hours := duration.Hours()
	minutes := duration.Minutes()

	if int(minutes) == 0 {
		return "up-to-date"
	}

	if minutes < 0 {
		return "in the future"
	}

	if hours < 1 {
		return fmt.Sprintf("%d minute%s ago", int(duration.Minutes()), Plural(int(duration.Minutes())))
	}

	if hours/24 < 1 {
		return fmt.Sprintf("%d hour%s ago", int(hours), Plural(int(hours)))
	}

	if hours/24/365 > 1 {
		return fmt.Sprintf("%d year%s ago", int(hours/24/365), Plural(int(hours/24/365)))
	}

	return fmt.Sprintf("%d day%s ago", int(hours/24), Plural(int(hours/24)))
}

// SanitizeLocationCodes sanitizes the given location codes
func SanitizeLocationCodes(input string) string {
	input = strings.Replace(input, ",", " ", -1)
	ccodes := strings.Fields(input)
	output := ""
	for _, c := range ccodes {
		output += strings.ToUpper(c) + " "
	}
	return strings.TrimRight(output, " ")
}