示例#1
0
func formatHeader(flag int, t time.Time, file string, line int, funcname string) string {
	var buf bytes.Buffer
	buf.WriteByte('[')
	needspace := false
	if flag&(DateFlag|TimeFlag|MsecFlag) != 0 {
		if flag&DateFlag != 0 {
			year, month, day := t.Date()
			writespace(&buf, needspace)
			fmt.Fprintf(&buf, "%04d/%02d/%02d", year, month, day)
			needspace = true
		}
		if flag&(TimeFlag|MsecFlag) != 0 {
			hour, min, sec := t.Clock()
			writespace(&buf, needspace)
			fmt.Fprintf(&buf, "%02d:%02d:%02d", hour, min, sec)
			if flag&MsecFlag != 0 {
				fmt.Fprintf(&buf, ".%06d", t.Nanosecond()/1e3)
			}
			needspace = true
		}
	}
	if flag&(LongFileFlag|ShortFileFlag|FuncNameFlag) != 0 {
		if flag&ShortFileFlag != 0 {
			file = shortfilename(file)
		}
		writespace(&buf, needspace)
		fmt.Fprintf(&buf, "%s:%d", file, line)
		if flag&FuncNameFlag != 0 {
			fmt.Fprintf(&buf, " (%s)", shortfuncname(funcname))
		}
		needspace = true
	}
	buf.WriteByte(']')
	return buf.String()
}
示例#2
0
func MonteCarloCons(f Function2, cons Constraint2, xMin float64, xMax float64, yMin float64, yMax float64) []float64 {
	var seed time.Time
	seed = time.Now()
	rand.Seed(int64(seed.Nanosecond()))

	//get an inital best-value estimate based on the minimum values for the optimization range
	x := xMin
	y := yMin
	eval := f(x, y)
	xRange := xMax - xMin
	yRange := yMax - yMin
	maxValues := []float64{eval, x, y} //store the best values seen so far
	for i := 0; i < 1e6; i++ {

		//assign a new random value for x and y
		x = rand.Float64()*xRange + xMin
		y = rand.Float64()*yRange + yMin

		//decide if the random values lie within the given constraint function
		if cons(x, y) {
			eval = f(x, y)
			if eval >= maxValues[0] {
				maxValues = []float64{eval, x, y}
			}
		}
	}
	return []float64{maxValues[1], maxValues[2]}
}
示例#3
0
func (l *Logger) formatHeader(t time.Time) string {
	var s string

	//*buf = append(*buf, l.prefix...)
	if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
		if l.flag&Ldate != 0 {
			year, month, day := t.Date()
			s += itoa(year, 4)
			s += "/"
			s += itoa(int(month), 2)
			s += "/"
			s += itoa(day, 2)
		}
		if l.flag&(Ltime|Lmicroseconds) != 0 {
			hour, min, sec := t.Clock()

			s += " "
			s += itoa(hour, 2)
			s += ":"
			s += itoa(min, 2)
			s += ":"
			s += itoa(sec, 2)
			if l.flag&Lmicroseconds != 0 {
				s += "."
				s += itoa(t.Nanosecond()/1e3, 6)
			}
		}

		s += " "
	}
	return s
}
示例#4
0
文件: clock.go 项目: theclapp/js
func (s *simClock) drawNeedle(t time.Time) {
	s.Save()
	defer s.Restore()
	needle := func(angle float64, lineWidth float64, ratio float64, color string) {
		s.BeginPath()
		s.StrokeStyle = color
		s.LineWidth = lineWidth
		r := s.r * ratio
		angle = angle - math.Pi/2
		x := r * math.Cos(angle)
		y := r * math.Sin(angle)
		s.MoveTo(0, 0)
		s.LineTo(x, y)
		s.Stroke()
	}
	// houre
	angleHour := float64(t.Hour()) / 6.0 * math.Pi
	needle(angleHour, 5.0, s.hourNeedleRatio, "black")
	// minute
	angleMinute := float64(t.Minute()) / 30.0 * math.Pi
	needle(angleMinute, 3.0, s.minuteNeedleRatio, "black")
	// second
	angleSecond := (float64(t.Second()) + float64(t.Nanosecond())/1000000000.0) / 30.0 * math.Pi
	needle(angleSecond, 1.0, s.secondNeedleRatio, "red")
}
示例#5
0
// dateSize returns the size needed to store a given time.Time.
func dateSize(v time.Time) (length uint8) {
	var (
		month, day, hour, min, sec uint8
		year                       uint16
		msec                       uint32
	)

	year = uint16(v.Year())
	month = uint8(v.Month())
	day = uint8(v.Day())
	hour = uint8(v.Hour())
	min = uint8(v.Minute())
	sec = uint8(v.Second())
	msec = uint32(v.Nanosecond() / 1000)

	if hour == 0 && min == 0 && sec == 0 && msec == 0 {
		if year == 0 && month == 0 && day == 0 {
			return 0
		} else {
			length = 4
		}
	} else if msec == 0 {
		length = 7
	} else {
		length = 11
	}
	length++ // 1 extra byte needed to store the length itself
	return
}
示例#6
0
func (w *Writer) writeTime(v interface{}, t time.Time) (err error) {
	w.setRef(v)
	s := w.Stream
	year, month, day := t.Date()
	hour, min, sec := t.Clock()
	nsec := t.Nanosecond()
	tag := TagSemicolon
	if t.Location() == time.UTC {
		tag = TagUTC
	}
	if hour == 0 && min == 0 && sec == 0 && nsec == 0 {
		if _, err = s.Write(formatDate(year, int(month), day)); err == nil {
			err = s.WriteByte(tag)
		}
	} else if year == 1970 && month == 1 && day == 1 {
		if _, err = s.Write(formatTime(hour, min, sec, nsec)); err == nil {
			err = s.WriteByte(tag)
		}
	} else if _, err = s.Write(formatDate(year, int(month), day)); err == nil {
		if _, err = s.Write(formatTime(hour, min, sec, nsec)); err == nil {
			err = s.WriteByte(tag)
		}
	}
	return err
}
示例#7
0
func main() {
	p := fmt.Println
	var t time.Time = time.Now()
	fmt.Println(t)
	fmt.Println(t.Format(time.RFC3339))
	fmt.Println(t.Format(time.RFC3339Nano))

	t1, e := time.Parse(
		time.RFC3339,
		"2012-11-01T22:08:41-04:00")
	p(t1)

	p(t.Format("3:04PM"))
	p(t.Format("Mon Jan _2 15:04:05 2006"))
	p(t.Format("2006-01-02T15:04:05.999999-07:00"))
	form := "3 04 PM"
	t2, e := time.Parse(form, "8 41 PM")
	p(t2)
	fmt.Printf("%d - %02d - %02d T %02d : %02d : %02d . %d -00:00\n",
		t.Year(), t.Month(), t.Day(),
		t.Hour(), t.Minute(), t.Second(), t.Nanosecond())
	ansic := "Mon Jan _2 15:04:05 2006"
	_, e = time.Parse(ansic, "8:41PM")
	p(e)
}
示例#8
0
// remove the time component of a datetime to get just a date at 00:00:00
func TruncDate(t time.Time) time.Time {
	hour, min, sec := t.Clock()
	nano := t.Nanosecond()

	d := time.Duration(0) - (time.Duration(nano) + time.Duration(sec)*time.Second + time.Duration(min)*time.Minute + time.Duration(hour)*time.Hour)
	return t.Add(d)
}
示例#9
0
func (r *Rrd) calculateElapsedSteps(timestamp time.Time) ElapsedPdpSteps {
	interval := float64(timestamp.Sub(r.LastUpdate).Nanoseconds()) / 1e9

	procPdpAge := r.LastUpdate.Unix() % int64(r.Step/time.Second)
	procPdpSt := r.LastUpdate.Unix() - procPdpAge

	occuPdpAge := timestamp.Unix() % int64(r.Step/time.Second)
	occuPdpSt := timestamp.Unix() - occuPdpAge

	var preInt float64
	var postInt float64
	if occuPdpSt > procPdpSt {
		preInt = float64(occuPdpSt - r.LastUpdate.Unix())
		preInt -= float64(r.LastUpdate.Nanosecond()) / 1e9
		postInt = float64(occuPdpAge)
		postInt += float64(timestamp.Nanosecond()) / 1e9
	} else {
		preInt = interval
		postInt = 0
	}

	procPdpCount := procPdpSt / int64(r.Step/time.Second)

	return ElapsedPdpSteps{
		Interval:     interval,
		Steps:        uint64(occuPdpSt-procPdpSt) / uint64(r.Step/time.Second),
		PreInt:       preInt,
		PostInt:      postInt,
		ProcPdpCount: uint64(procPdpCount),
	}
}
示例#10
0
文件: time.go 项目: juztin/am
// TimeWithLocation returns a time.Time using the given location,
// while using the time values from the given time (day, hour, minutes, etc.)
func TimeWithLocation(l *time.Location, t time.Time) time.Time {
	y, m, d := t.Date()
	if l == nil {
		l = time.UTC
	}
	return time.Date(y, m, d, t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), l)
}
示例#11
0
func (f *RrdRawFile) StoreLastUpdate(lastUpdate time.Time) error {
	writer := f.dataFile.Writer(f.baseHeaderSize)
	if err := writer.WriteUnival(unival(lastUpdate.Unix())); err != nil {
		return errors.Wrap(err, 0)
	}
	return writer.WriteUnival(unival(lastUpdate.Nanosecond() / 1000))
}
示例#12
0
func quakeProto(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result {
	if res := weft.CheckQuery(r, []string{}, []string{}); !res.Ok {
		return res
	}

	var q haz.Quake
	var res *weft.Result

	if q.PublicID, res = getPublicIDPath(r); !res.Ok {
		return res
	}

	var t time.Time
	var mt time.Time
	var err error

	if err = db.QueryRow(quakeProtoSQL, q.PublicID).Scan(&t, &mt,
		&q.Depth, &q.Magnitude, &q.Locality, &q.Mmi, &q.Quality,
		&q.Longitude, &q.Latitude); err != nil {
		return weft.ServiceUnavailableError(err)
	}

	q.Time = &haz.Timestamp{Sec: t.Unix(), Nsec: int64(t.Nanosecond())}
	q.ModificationTime = &haz.Timestamp{Sec: mt.Unix(), Nsec: int64(mt.Nanosecond())}

	var by []byte

	if by, err = proto.Marshal(&q); err != nil {
		return weft.ServiceUnavailableError(err)
	}

	b.Write(by)
	h.Set("Content-Type", protobuf)
	return &weft.StatusOK
}
示例#13
0
文件: types.go 项目: leobcn/dbr
func parseDateTime(str string, loc *time.Location) (time.Time, error) {
	var t time.Time
	var err error

	base := "0000-00-00 00:00:00.0000000"
	switch len(str) {
	case 10, 19, 21, 22, 23, 24, 25, 26:
		if str == base[:len(str)] {
			return t, err
		}
		t, err = time.Parse(timeFormat[:len(str)], str)
	default:
		err = ErrInvalidTimestring
		return t, err
	}

	// Adjust location
	if err == nil && loc != time.UTC {
		y, mo, d := t.Date()
		h, mi, s := t.Clock()
		t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil
	}

	return t, err
}
示例#14
0
func (fs *fileStorage) doLog(t time.Time, str string) {
	if fs.logSize > logSizeThreshold {
		// Rotate log file.
		fs.logw.Close()
		fs.logw = nil
		fs.logSize = 0
		rename(filepath.Join(fs.path, "LOG"), filepath.Join(fs.path, "LOG.old"))
	}
	if fs.logw == nil {
		var err error
		fs.logw, err = os.OpenFile(filepath.Join(fs.path, "LOG"), os.O_WRONLY|os.O_CREATE, 0644)
		if err != nil {
			return
		}
		// Force printDay on new log file.
		fs.day = 0
	}
	fs.printDay(t)
	hour, min, sec := t.Clock()
	msec := t.Nanosecond() / 1e3
	// time
	fs.buf = itoa(fs.buf[:0], hour, 2)
	fs.buf = append(fs.buf, ':')
	fs.buf = itoa(fs.buf, min, 2)
	fs.buf = append(fs.buf, ':')
	fs.buf = itoa(fs.buf, sec, 2)
	fs.buf = append(fs.buf, '.')
	fs.buf = itoa(fs.buf, msec, 6)
	fs.buf = append(fs.buf, ' ')
	// write
	fs.buf = append(fs.buf, []byte(str)...)
	fs.buf = append(fs.buf, '\n')
	fs.logw.Write(fs.buf)
}
示例#15
0
文件: log.go 项目: gofs/logex
func (l *Logger) formatPrefix(level int, t time.Time, file string, line int) {
	// prefix: "D0806 10:45:19.598 bvc.go:100] "
	l.buf = append(l.buf, levelStr[level])

	_, month, day := t.Date()
	l.itoa(int(month), 2)
	l.itoa(day, 2)
	l.buf = append(l.buf, ' ')

	hour, min, sec := t.Clock()
	l.itoa(hour, 2)
	l.buf = append(l.buf, ':')
	l.itoa(min, 2)
	l.buf = append(l.buf, ':')
	l.itoa(sec, 2)
	l.buf = append(l.buf, '.')
	l.itoa(t.Nanosecond()/1e6, 3)
	l.buf = append(l.buf, ' ')

	short := file
	for i := len(file) - 1; i > 0; i-- {
		if file[i] == '/' {
			short = file[i+1:]
			break
		}
	}
	l.buf = append(l.buf, short...)
	l.buf = append(l.buf, ':')
	l.itoa(line, -1)
	l.buf = append(l.buf, "] "...)
}
示例#16
0
func (l *Logger) formatHeader(buf *bytes.Buffer, t time.Time, file string, line int, lvl int, reqId string, Func string) {
	if l.prefix != "" {
		buf.WriteString(l.prefix)
	}
	if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
		if l.flag&Ldate != 0 {
			year, month, day := t.Date()
			itoa(buf, year, 4)
			buf.WriteByte('/')
			itoa(buf, int(month), 2)
			buf.WriteByte('/')
			itoa(buf, day, 2)
			buf.WriteByte(' ')
		}
		if l.flag&(Ltime|Lmicroseconds) != 0 {
			hour, min, sec := t.Clock()
			itoa(buf, hour, 2)
			buf.WriteByte(':')
			itoa(buf, min, 2)
			buf.WriteByte(':')
			itoa(buf, sec, 2)
			if l.flag&Lmicroseconds != 0 {
				buf.WriteByte('.')
				itoa(buf, t.Nanosecond()/1e3, 6)
			}
			buf.WriteByte(' ')
		}
	}
	if reqId != "" {
		buf.WriteByte('[')
		buf.WriteString(reqId)
		buf.WriteByte(']')
	}
	if l.flag&Llevel != 0 {
		buf.WriteString(levels[lvl])
	}
	if l.flag&Lmodule != 0 {
		buf.WriteByte('[')
		buf.WriteString(Func)
		buf.WriteByte(']')

		buf.WriteByte(' ')
	}
	if l.flag&(Lshortfile|Llongfile) != 0 {
		if l.flag&Lshortfile != 0 {
			short := file
			for i := len(file) - 1; i > 0; i-- {
				if file[i] == '/' {
					short = file[i+1:]
					break
				}
			}
			file = short
		}
		buf.WriteString(file)
		buf.WriteByte(':')
		itoa(buf, line, -1)
		buf.WriteString(": ")
	}
}
示例#17
0
文件: clock.go 项目: rickb777/date
// NewAt returns a new Clock with specified hour, minute, second and millisecond.
func NewAt(t time.Time) Clock {
	hour, minute, second := t.Clock()
	hx := Clock(hour) * Hour
	mx := Clock(minute) * Minute
	sx := Clock(second) * Second
	ms := Clock(t.Nanosecond() / int(time.Millisecond))
	return Clock(hx + mx + sx + ms)
}
示例#18
0
func (s *Session) SetTimestamp(ts time.Time) {
	dtime := C.struct_dnet_time{
		tsec:  C.uint64_t(ts.Unix()),
		tnsec: C.uint64_t(ts.Nanosecond()),
	}

	C.session_set_timestamp(s.session, &dtime)
}
示例#19
0
func (v *Float) fromTime(t time.Time) error {
	// Represent the unix timestamp as a float (with fractional seconds)
	secs := float64(t.Unix())
	nano := float64(t.Nanosecond())
	val := secs + nano/nanoSecondsInSec
	*v = Float(val)
	return nil
}
示例#20
0
// WriteTime writes a time.Time in a byte-sortable way.
//
// This method truncates the time to microseconds and drops the timezone,
// because that's the (undocumented) way that the appengine SDK does it.
func WriteTime(buf Buffer, t time.Time) error {
	name, off := t.Zone()
	if name != "UTC" || off != 0 {
		panic(fmt.Errorf("helper: UTC OR DEATH: %s", t))
	}
	_, err := cmpbin.WriteUint(buf, uint64(t.Unix())*1e6+uint64(t.Nanosecond()/1e3))
	return err
}
示例#21
0
文件: properties.go 项目: shkw/gae
// TimeToInt converts a time value to a datastore-appropraite integer value.
//
// This method truncates the time to microseconds and drops the timezone,
// because that's the (undocumented) way that the appengine SDK does it.
func TimeToInt(t time.Time) int64 {
	if t.IsZero() {
		return 0
	}

	t = RoundTime(t)
	return t.Unix()*1e6 + int64(t.Nanosecond()/1e3)
}
示例#22
0
文件: zk_test.go 项目: snaury/gozk
func checkTimeBetween(c *C, what string, t, t0, t1 time.Time) {
	// Truncate the start time to millisecond resolution, as
	// time stamps get similarly truncated.
	t0 = t0.Add(-time.Duration(t0.Nanosecond() % 1e6))
	if t.Before(t0) || t.After(t1) {
		c.Errorf("%s out of range; expected between %v and %v, got %v", what, t0.Format(time.StampNano), t1.Format(time.StampNano), t.Format(time.StampNano))
	}
}
示例#23
0
// EncodeTimeDescending is the descending version of EncodeTimeAscending.
func EncodeTimeDescending(b []byte, t time.Time) []byte {
	// Read the unix absolute time. This is the absolute time and is
	// not time zone offset dependent.
	b = append(b, timeDescMarker)
	b = EncodeVarintDescending(b, t.Unix())
	b = EncodeVarintDescending(b, int64(t.Nanosecond()))
	return b
}
示例#24
0
// Returns t as string in MySQL format Converts time.Time zero to MySQL zero.
func TimeString(t time.Time) string {
	if t.IsZero() {
		return "0000-00-00 00:00:00"
	}
	if t.Nanosecond() == 0 {
		return t.Format(TimeFormat[:19])
	}
	return t.Format(TimeFormat)
}
示例#25
0
func (d *testingStorage) doPrint(str string, t time.Time) {
	if d.log == nil {
		return
	}

	hour, min, sec := t.Clock()
	msec := t.Nanosecond() / 1e3
	d.log.Logf("<%02d:%02d:%02d.%06d> %s\n", hour, min, sec, msec, str)
}
示例#26
0
// EncodeTime encodes a time value, appends it to the supplied buffer,
// and returns the final buffer. The encoding is guaranteed to be ordered
// Such that if t1.Before(t2) then after EncodeTime(b1, t1), and
// EncodeTime(b2, t1), Compare(b1, b2) < 0. The time zone offset not
// included in the encoding.
func EncodeTime(b []byte, t time.Time) []byte {
	// Read the unix absolute time. This is the absolute time and is
	// not time zone offset dependent.
	sec := t.Unix()
	nsec := t.Nanosecond()
	b = EncodeVarint(b, sec)
	b = EncodeVarint(b, int64(nsec))
	return b
}
示例#27
0
func formatPAXTime(t time.Time) string {
	sec := t.Unix()
	usec := t.Nanosecond()
	s := strconv.FormatInt(sec, 10)
	if usec != 0 {
		s = fmt.Sprintf("%s.%09d", s, usec)
	}
	return s
}
示例#28
0
// SinceEpoch returns the amount of time since unix epoch
func sinceEpoch(t time.Time) (result Duration) {
	result.Seconds = t.Unix()
	result.Nanoseconds = int32(t.Nanosecond())
	if result.Seconds < 0 && result.Nanoseconds > 0 {
		result.Seconds++
		result.Nanoseconds -= oneBillion
	}
	return
}
示例#29
0
文件: time.go 项目: gcnonato/msgpack
func (e *Encoder) EncodeTime(tm time.Time) error {
	if err := e.W.WriteByte(0x92); err != nil {
		return err
	}
	if err := e.EncodeInt64(tm.Unix()); err != nil {
		return err
	}
	return e.EncodeInt(tm.Nanosecond())
}
示例#30
0
// AppendTime appends a time.Time to the slice as a MessagePack extension
func AppendTime(b []byte, t time.Time) []byte {
	o, n := ensure(b, TimeSize)
	t = t.UTC()
	o[n] = mext8
	o[n+1] = 12
	o[n+2] = TimeExtension
	putUnix(o[n+3:], t.Unix(), int32(t.Nanosecond()))
	return o
}