コード例 #1
0
ファイル: έντομο.go プロジェクト: droundy/entomonitor
func (b *Bug) Comments() (out []Comment, err os.Error) {
	d, err := os.Open(".entomon/" + string(b.Type) + "/" + b.Id)
	defer d.Close()
	if err != nil {
		return out, nil
	}
	ns, err := d.Readdirnames(-1)
	d.Close()
	if err != nil {
		return
	}
	sort.Strings(ns)
	for _, n := range ns {
		dateauthor := strings.SplitN(n, "--", 2)
		// Now let's put the date into the current timezone...
		date, err := time.Parse(time.RFC3339, dateauthor[0])
		if err == nil {
			dateauthor[0] = time.SecondsToLocalTime(date.Seconds()).Format(
				"January 2, 2006 3:04PM")
		}
		if len(dateauthor) == 2 {
			c := Comment{dateauthor[1], dateauthor[0], ""}
			x, err := ioutil.ReadFile(".entomon/" + b.String() + "/" + n)
			if err != nil {
				return out, err
			}
			c.Text = string(x)
			c = b.stripAttributes(c)
			out = append(out, c)
		}
	}
	return
}
コード例 #2
0
ファイル: searchpanelhandler.go プロジェクト: Chouia/Chrall
func (h *SearchPanelHandler) getSearchPanelHtml(hr *http.Request) string {
	fmt.Println("\n=== SearchPanelHandler : Requete reçue ====================")
	fmt.Println(" URL : " + hr.RawURL)
	hr.ParseForm()

	askerId := GetFormValueAsInt(hr, "asker")
	mdpr := GetFormValue(hr, "mdpr") // mot de passe restreint
	tok := GetFormValue(hr, "tok")
	compteOk := false
	var compte *Compte

	db, err := h.store.Connect()
	if err != nil {
		fmt.Printf("Erreur ouverture connexion BD dans makeBestiaryExtractHtml : %s\n", err.String())
		return err.String()
	}
	defer db.Close()

	if askerId > 0 && mdpr != "" {
		compteOk, compte, err = h.store.CheckCompte(db, uint(askerId), mdpr)
	}
	if !compteOk {
		return "Compte non authentifié"
	}
	if tok == "" {
		return "Demande non comprise"
	}
	amis, err := h.store.GetPartageurs(db, askerId)
	if err != nil {
		return fmt.Sprintf("Erreur récupération amis : %s\n", err.String())
	}
	observations, err := h.store.SearchObservations(db, tok, askerId, amis)
	if err != nil {
		return fmt.Sprintf("Erreur recherche : %s\n", err.String())
	}
	if len(observations) == 0 {
		return "Rien trouvé"
	}
	html := fmt.Sprintf("%d résultats :", len(observations))
	html += "<table border='0' cellspacing='1' cellpadding='2' class='mh_tdborder' align='center'>"
	html += "<tr class=mh_tdtitre><td class=mh_tdpage><b>Dist.</b></td><td class=mh_tdpage><b>Réf.</b></td><td class=mh_tdpage><b>Nom</b></td>"
	html += "<td class=mh_tdpage><b>Position</b></td>"
	html += "<td class=mh_tdpage><b>Vu par</b></td><td class=mh_tdpage><b>Le</b></td></tr>"
	for _, o := range observations {
		t := time.SecondsToLocalTime(o.Date)
		var lien string
		if o.Type == "troll" {
			lien = fmt.Sprintf("<a href='javascript:EPV(%d)' class=mh_trolls_1 id=%d>%s</a>", o.Num, o.Num, o.Nom)
		} else if o.Type == "monstre" {
			lien = fmt.Sprintf("<a href='javascript:EMV(%d, 750, 550)' class=mh_monstres id=%d>%s</a>", o.Num, o.Num, o.Nom)
		} else {
			lien = o.Nom
		}
		dist := dist(compte.Troll.X, o.X, compte.Troll.Y, o.Y, compte.Troll.Z, o.Z)
		btnVoir := fmt.Sprintf("<a x=%d y=%d z=%d class=gogo name=zoom>%d  %d  %d</a>", o.X, o.Y, o.Z, o.X, o.Y, o.Z)
		html += fmt.Sprintf("<tr class=mh_tdpage><td>%d</td><td>%d</td><td>%s</td><td>%s</td><td>%d</td><td>%s</td></tr>", dist, o.Num, lien, btnVoir, o.Auteur, t.Format("02/01 à 15h04"))
	}
	html += "</table>"
	return html
}
コード例 #3
0
ファイル: show.go プロジェクト: ghostnotes/HelloGo
func show(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)
    q := datastore.NewQuery("Guest").Order("Date")
    count, err := q.Count(c)
    if err != nil {
        http.Error(w, err.String(), http.StatusInternalServerError)
        return
    }

    guests := make([]Guest, 0, count)
    guest_views :=([]Guest_View, count)
    if keys, err := q.GetAll(c, &guests); err != nil {
        http.Error(w, errString(), http.StatusInternalServerError)
        return
    } else {
        for pos, guest := range guests {
            guest_views[pos].Id = keys[pos].IntID()
            guest_views[pos].Name = guest.Name
            localTime := time.SecondsToLocalTime(int64(guest.Date) / 1000000)
            guest_views[pos].Date = fmt.Sprintf("%04d/%02d/%02d %02d:%02d:%02d", localTime.Year, localTime.Month, localTime.Day, localTime.Hour, localTime.Minute, localTime.Second)
        }
    }

    if err := showHTMLTemplate.Execute(w, guest_views); err != nil {
        http.Error(w, err.String(), http.StatusInternalServerError)
    }
}
コード例 #4
0
ファイル: tick1.go プロジェクト: kawaz/go-example
func main() {
	ticker := time.NewTicker(1000 * 1000 * 1000)
	for {
		ns := <-ticker.C
		t := time.SecondsToLocalTime(ns / 1000 / 1000 / 1000)
		fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", t.Year, t.Month, t.Day, t.Hour, t.Minute, t.Second)
	}
}
コード例 #5
0
ファイル: time.go プロジェクト: Qyrus/graphpaper
func FormatTime(nanoSeconds int64, utc bool, format string) string {
	seconds := nanoSeconds / 1000000000
	if utc {
		return time.SecondsToUTC(seconds).Format(format)
	} else {
		return time.SecondsToLocalTime(seconds).Format(format)
	}
	panic("unreachable code")
}
コード例 #6
0
ファイル: jtime.go プロジェクト: hokapoka/gostack
func (jt *jTime) UnmarshalJSON(data []byte) os.Error {
	var n int64
	if err := json.Unmarshal(data, &n); err != nil {
		return err
	}
	t := time.SecondsToLocalTime(n)
	*jt = (jTime)(*t)
	return nil
}
コード例 #7
0
ファイル: epoch2time.go プロジェクト: andrewrjones/epoch2time
func main() {
	os.Setenv("TZ", "GMT")
	flag.Parse()

	arg, _ := strconv.Atoi64(flag.Arg(0))
	t := time.SecondsToLocalTime(arg)
	out := t.Format(time.RFC850)

	os.Stdout.WriteString(out + "\n")
}
コード例 #8
0
ファイル: db.go プロジェクト: toddcblank/gobook
func getTimeOfDay(when int64) (tod int, utc_time *time.Time) {
	utc_time = time.SecondsToLocalTime(when)
	tod = 0 // default to morning (midnight to noon)
	switch {
	case utc_time.Hour < 4:
		tod = 3 // night, shift day back 1
	case utc_time.Hour < 12:
		tod = 0 // morning
	case utc_time.Hour < 17:
		tod = 1 // afternoon
	default:
		tod = 2 // evening
	}
	if tod == 3 {
		// Quick hack to mark night time as part of the previous day
		utc_time = time.SecondsToLocalTime(when - 86400)
	}
	return
}
コード例 #9
0
ファイル: index.go プロジェクト: kybernetyk/fettemama
// renders /
func index(ctx *web.Context) string {
	css, ok := ctx.Params["css"]
	if ok {
		SetCSS(ctx, css)
		ctx.Redirect(302, "/")
		return "ok"
	}
	//posts := postsForMonth(time.LocalTime()) //Db.GetLastNPosts(10)

	//	posts := lastPosts(0xff)
	posts := postsForLastNDays(4)
	if len(posts) <= 0 {
		posts = lastPosts(23)
	}
	//fmt.Printf("posts: %#v\n", posts)
	//embedded struct - our mustache templates need a NumOfComments field to render
	//but we don't want to put that field into the BlogPost Struct so it won't get stored
	//into the DB
	type MyPost struct {
		BlogPost
		NumOfComments int
	}

	//posts ordered by date. this is ugly. TODO: look up if mustache hase something to handle this situation
	type Date struct {
		Date  string
		Posts []MyPost
	}
	Db := DBGet()
	defer Db.Close()

	//loop through our posts and put them into the appropriate date structure
	dates := []Date{}
	var cur_date time.Time
	var date *Date
	for _, p := range posts {
		post_date := time.SecondsToLocalTime(p.Timestamp)
		if !(cur_date.Day == post_date.Day && cur_date.Month == post_date.Month && cur_date.Year == post_date.Year) {
			cur_date = *post_date
			dates = append(dates, Date{Date: cur_date.Format("Mon Jan _2 2006")})
			date = &dates[len(dates)-1]
		}
		p.Comments, _ = Db.GetComments(p.Id)
		mp := MyPost{p, len(p.Comments)}
		date.Posts = append(date.Posts, mp)
	}
	m := map[string]interface{}{
		"Dates": dates,
	}

	tmpl, _ := mustache.ParseFile("templ/index.mustache")
	s := tmpl.Render(&m, getCSS(ctx))
	return s
}
コード例 #10
0
ファイル: filemon.go プロジェクト: anvie/Anscdn
func GetLastModif(file *os.File) (rv string, err os.Error) {
	rv = ""
	st, err := file.Stat()
	if err != nil {
		return rv, err
	}

	t := time.SecondsToLocalTime(st.Mtime_ns / 1e9)
	rv = t.Format(time.RFC1123)
	return rv, err
}
コード例 #11
0
ファイル: logger.go プロジェクト: alangenfeld/cs639
func String(thisTask TaskId) string {
	var ret string
	info := taskMap[thisTask]
	if info.EndTime == 0 {
		return ""
	}
	timeSpent := info.EndTime - info.StartTime
	niceTimeSpent := float64(timeSpent) / float64(1000000000)
	timeStamp := time.SecondsToLocalTime(time.Seconds())
	ret = "\n" + timeStamp.String() + ": " + info.TaskName + ": " + fmt.Sprintf("%f", niceTimeSpent) + " seconds\n"
	return ret
}
コード例 #12
0
ファイル: dateedit.go プロジェクト: wiloe/walk
func (de *DateEdit) Value() *time.Time {
	st, err := de.systemTime()
	if err != nil {
		return nil
	}

	if st == nil {
		return nil
	}

	return time.SecondsToLocalTime(systemTimeToTime(st).Seconds())
}
コード例 #13
0
ファイル: godoc.go プロジェクト: WXB506/golang
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if redirect(w, r) {
		return
	}

	relpath := r.URL.Path[len(h.pattern):]
	abspath := absolutePath(relpath, h.fsRoot)
	var mode PageInfoMode
	if relpath != builtinPkgPath {
		mode = exportsOnly
	}
	if r.FormValue("m") != "src" {
		mode |= genDoc
	}
	info := h.getPageInfo(abspath, relpath, r.FormValue("p"), mode)
	if info.Err != nil {
		log.Print(info.Err)
		serveError(w, r, relpath, info.Err)
		return
	}

	if r.FormValue("f") == "text" {
		contents := applyTemplate(packageText, "packageText", info)
		serveText(w, contents)
		return
	}

	var title, subtitle string
	switch {
	case info.PAst != nil:
		title = "Package " + info.PAst.Name.Name
	case info.PDoc != nil:
		switch {
		case info.IsPkg:
			title = "Package " + info.PDoc.PackageName
		case info.PDoc.PackageName == fakePkgName:
			// assume that the directory name is the command name
			_, pkgname := path.Split(path.Clean(relpath))
			title = "Command " + pkgname
		default:
			title = "Command " + info.PDoc.PackageName
		}
	default:
		title = "Directory " + relativeURL(info.Dirname)
		if *showTimestamps {
			subtitle = "Last update: " + time.SecondsToLocalTime(info.DirTime).String()
		}
	}

	contents := applyTemplate(packageHTML, "packageHTML", info)
	servePage(w, title, subtitle, "", contents)
}
コード例 #14
0
ファイル: types.go プロジェクト: hpcorona/gowt
func GwtDate(reg *Registry, strtable, payload []string, partype string, idxv int) (interface{}, int, os.Error) {
	vb64 := payload[idxv+1]
	datab, err := ToLong(vb64)
	if err != nil {
		return nil, 2, err
	}

	//milli := datab % 1000 (maybe when GAE supports Nanoseconds)
	datab = datab / 1000
	t := time.SecondsToLocalTime(datab)

	return t, 2, nil
}
コード例 #15
0
ファイル: time_test.go プロジェクト: sankark/golang-stuff
func TestRoundDown(t *testing.T) {
	tf := "2006-01-02 15:04:05 MST"
	samples := []struct {
		date, expected string
		delta          TimeDelta
	}{
		// Simple cases
		{"2011-07-04 16:43:23 CEST", "2011-07-04 16:43:00 CEST", Minute{1}},
		{"2011-07-04 16:43:23 CEST", "2011-07-04 16:40:00 CEST", Minute{5}},
		{"2011-07-04 16:43:23 CEST", "2011-07-04 16:40:00 CEST", Minute{10}},
		{"2011-07-04 16:43:23 CEST", "2011-07-04 16:30:00 CEST", Minute{15}},
		{"2011-07-04 16:43:23 CEST", "2011-07-04 16:00:00 CEST", Hour{1}},
		{"2011-07-04 16:43:23 CEST", "2011-07-04 12:00:00 CEST", Hour{6}},

		// Around daylight saving switch
		{"2011-03-27 04:15:16 CEST", "2011-03-27 04:00:00 CEST", Hour{1}},
		{"2011-03-27 04:15:16 CEST", "2011-03-27 00:00:00 CET", Hour{5}},

		{"2011-07-04 16:43:23 CEST", "2011-01-01 00:00:00 CET", Year{1}},
		{"2011-07-04 16:43:23 CEST", "2010-01-01 00:00:00 CET", Year{10}},
	}

	for _, sample := range samples {
		date, e1 := time.Parse(tf, sample.date)
		expected, e2 := time.Parse(tf, sample.expected)
		if e1 != nil || e2 != nil {
			t.FailNow()
		}
		date = time.SecondsToLocalTime(date.Seconds())
		expected = time.SecondsToLocalTime(expected.Seconds())
		sample.delta.RoundDown(date)
		if date.Seconds() != expected.Seconds() {
			t.Errorf("RoundDown %s to %s != %s, was %s", sample.date, sample.delta,
				sample.expected, date.Format(tf))
		}
	}

}
コード例 #16
0
ファイル: posts.go プロジェクト: Quasimo/bloody.go
func (post *PostModel) FrontPage() []map[string]string {
	var result *Post
	results := []map[string]string{}
	err := post.c.Find(nil).Sort(bson.M{"timestamp": -1}).Limit(10).For(&result, func() os.Error {
		t := time.SecondsToLocalTime(result.Created)
		results = append(results, map[string]string{"Title": result.Title, "Content": result.Content, "Date": t.Format("2006 Jan 02 15:04"), "Id": objectIdHex(result.Id.String())})
		return nil
	})
	if err != nil {
		panic(err)
	}

	return results
}
コード例 #17
0
ファイル: s3.go プロジェクト: russross/propolis
func (p *Propolis) SetRequestMetaData(req *http.Request, info *os.FileInfo) {
	// file permissions: grant "public-read" if the file grants world read permission
	if info.Permission()&s_iroth != 0 {
		req.Header.Set("X-Amz-Acl", acl_public)
	} else {
		req.Header.Set("X-Amz-Acl", acl_private)
	}

	// user id: store the numeric and symbolic names
	user, err := user.LookupId(info.Uid)
	if err != nil {
		req.Header.Set("X-Amz-Meta-Uid", fmt.Sprintf("%d", info.Uid))
	} else {
		req.Header.Set("X-Amz-Meta-Uid", fmt.Sprintf("%d (%s)", info.Uid, user.Username))
	}

	// group id: just store the numeric id for now until Go supports looking up group names
	req.Header.Set("X-Amz-Meta-Gid", fmt.Sprintf("%d", info.Gid))

	// store the permissions as an octal number
	req.Header.Set("X-Amz-Meta-Mode", fmt.Sprintf("0%o", info.Mode))

	// store the modified date in a nice format
	sec := info.Mtime_ns / 1e9
	ns := info.Mtime_ns % 1e9
	date := time.SecondsToLocalTime(sec).String()
	if ns == 0 {
		req.Header.Set("X-Amz-Meta-Mtime", fmt.Sprintf("%d (%s)", sec, date))
	} else {
		req.Header.Set("X-Amz-Meta-Mtime", fmt.Sprintf("%d.%09d (%s)", sec, ns, date))
	}

	// set the content-type by looking up the MIME type
	mimetype := default_mime_type
	switch {
	case info.IsDirectory():
		mimetype = directory_mime_type
	case info.IsSymlink():
		mimetype = symlink_mime_type
	default:
		if dot := strings.LastIndex(info.Name, "."); dot >= 0 && dot+1 < len(info.Name) {
			extension := strings.ToLower(info.Name[dot:])
			if kind := mime.TypeByExtension(extension); kind != "" {
				mimetype = kind
			}
		}
	}
	req.Header.Set("Content-Type", mimetype)
}
コード例 #18
0
ファイル: log.go プロジェクト: GNA-SERVICES-INC/MoNGate
func (l *Logger) formatHeader(buf *bytes.Buffer, ns int64, calldepth int) {
	buf.WriteString(l.prefix)
	if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
		t := time.SecondsToLocalTime(ns / 1e9)
		if l.flag&Ldate != 0 {
			itoa(buf, int(t.Year), 4)
			buf.WriteByte('/')
			itoa(buf, int(t.Month), 2)
			buf.WriteByte('/')
			itoa(buf, int(t.Day), 2)
			buf.WriteByte(' ')
		}
		if l.flag&(Ltime|Lmicroseconds) != 0 {
			itoa(buf, int(t.Hour), 2)
			buf.WriteByte(':')
			itoa(buf, int(t.Minute), 2)
			buf.WriteByte(':')
			itoa(buf, int(t.Second), 2)
			if l.flag&Lmicroseconds != 0 {
				buf.WriteByte('.')
				itoa(buf, int(ns%1e9)/1e3, 6)
			}
			buf.WriteByte(' ')
		}
	}
	if l.flag&(Lshortfile|Llongfile) != 0 {
		_, file, line, ok := runtime.Caller(calldepth)
		if ok {
			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
			}
		} else {
			file = "???"
			line = 0
		}
		buf.WriteString(file)
		buf.WriteByte(':')
		itoa(buf, line, -1)
		buf.WriteString(": ")
	}
}
コード例 #19
0
ファイル: time_test.go プロジェクト: sankark/golang-stuff
func TextCalendarWeek(t *testing.T) {
	for _, u := range [][4]int{
		[4]int{2011, 1, 1, 52},
		[4]int{2011, 1, 2, 52},
		[4]int{2011, 1, 3, 1},
		[4]int{2011, 1, 4, 1},
		[4]int{2011, 1, 5, 1},
		[4]int{2011, 1, 6, 1},
		[4]int{2011, 1, 7, 1},
		[4]int{2011, 1, 8, 1},
		[4]int{2011, 1, 9, 1},
		[4]int{2011, 1, 10, 2},
		[4]int{2011, 12, 25, 51},
		[4]int{2011, 12, 26, 52},
		[4]int{2011, 12, 27, 52},
		[4]int{2011, 12, 28, 52},
		[4]int{2011, 12, 29, 52},
		[4]int{2011, 12, 30, 52},
		[4]int{2011, 12, 31, 52},
		[4]int{1995, 1, 1, 52},
		[4]int{1995, 1, 2, 1},
		[4]int{1996, 1, 1, 1},
		[4]int{1996, 1, 7, 1},
		[4]int{1996, 1, 8, 2},
		[4]int{1997, 1, 1, 1},
		[4]int{1998, 1, 1, 1},
		[4]int{1999, 1, 1, 53},
		[4]int{2000, 1, 1, 52},
		[4]int{2001, 1, 1, 1},
		[4]int{2002, 1, 1, 1},
		[4]int{2003, 1, 1, 1},
		[4]int{2004, 1, 1, 1},
		[4]int{2005, 1, 1, 53},
		[4]int{2006, 1, 1, 52},
		[4]int{2007, 1, 1, 1},
		[4]int{2008, 1, 1, 1},
		[4]int{2009, 1, 1, 1},
		[4]int{2010, 1, 1, 53},
	} {
		dt := &time.Time{Year: int64(u[0]), Month: u[1], Day: u[2]}
		dt = time.SecondsToLocalTime(dt.Seconds())
		w := calendarWeek(dt)
		if w != u[3] {
			t.Errorf("Failed on %d-%d-%d. Got %d, expected %d.", u[0], u[1], u[2], w, u[3])
		}
	}

}
コード例 #20
0
ファイル: filebrowser.go プロジェクト: wiloe/walk
func (m *FileInfoModel) Value(row, col int) interface{} {
	item := m.items[row]

	switch col {
	case 0:
		return item.Name

	case 1:
		return item.Size

	case 2:
		return time.SecondsToLocalTime(item.Modified)
	}

	panic("unexpected col")
}
コード例 #21
0
ファイル: arbit.go プロジェクト: sergshabal/ArBit
func dashboard(w http.ResponseWriter, r *http.Request) { // Simple monitoring dashboard
	//var err os.Error
	c := appengine.NewContext(r)

	fmt.Fprintln(w, "<table>")
	fmt.Fprintln(w, "<tr><th>Exchange</th><th>Updated</th><th>Highest Buy</th><th>Lowest Sell</th><th>Last Trade</th></tr>")

	// Read ticker data from datastore
	var ticker [numExchanges][]datastore.Map
	for i := int8(0); i < numExchanges; i++ {
		ticker[i], _ = appdb.Query(c, "Ticker_"+exchangeName[i], "", nil, "-Date", 0, 1) // Get the last ticker only
		fmt.Fprintln(w, "<tr><td>", exchangeName[i], "</td><td>", time.SecondsToLocalTime(int64(ticker[i][0]["Date"].(datastore.Time))/1e6),
			"</td><td>", ticker[i][0]["HighestBuy"], "</td><td>", ticker[i][0]["LowestSell"], "</td><td>", ticker[i][0]["Last"], "</td></tr>")
	}
	fmt.Fprintln(w, "</table>")
}
コード例 #22
0
ファイル: jsongethandler.go プロジェクト: Chouia/Chrall
func (h *JsonGetHandler) makeBestiaryExtractHtml(hr *http.Request) string {
	askerId := GetFormValueAsInt(hr, "asker")
	mdpr := GetFormValue(hr, "mdpr") // mot de passe restreint, optionnel, permet d'authentifier la requête en cas d'existence de compte Chrall
	compteOk := false
	monsterId := GetFormValueAsUint(hr, "monsterId")

	db, err := h.store.Connect()
	if err != nil {
		fmt.Printf("Erreur ouverture connexion BD dans makeBestiaryExtractHtml : %s\n", err.String())
		return err.String()
	}
	defer db.Close()
	html := ""

	var amis []int
	if askerId > 0 && mdpr != "" && monsterId > 0 {
		compteOk, _, err = h.store.CheckCompte(db, uint(askerId), mdpr)
		if compteOk {
			amis, err = h.store.GetPartageurs(db, askerId)
			if err != nil {
				fmt.Printf("Erreur récupération amis dans makeBestiaryExtractHtml : %s\n", err.String())
			}
			blessure, auteurCDM, dateCDM, _ := h.store.GetBlessure(db, monsterId, askerId, amis)
			if auteurCDM != 0 {
				nomAuteur, _, _ := h.tksManager.GetNomRaceNiveauTroll(auteurCDM)
				t := time.SecondsToLocalTime(dateCDM)
				html += fmt.Sprintf("Blessure: <b>%d %%</b> (CDM de %s le %s)<br>", blessure, nomAuteur, t.Format("02/01 à 15h04")) // oui les gars de Google ont fumé lorsqu'ils ont fait leur bibliothèque de formatage de date
			}
		}
	}

	fmt.Println(" demande bestiaire  authentification =", compteOk)

	monsterCompleteName := GetFormValue(hr, "name")
	if monsterCompleteName == "" {
		fmt.Println(" no monster complete name in request")
		return "Hein ?"
	}
	be, err := h.store.ComputeMonsterStats(db, monsterCompleteName, monsterId)
	if err != nil {
		fmt.Println(" Erreur : " + err.String())
		return "Erreur : " + err.String()
	}

	html += be.Html(monsterId, askerId, h.tksManager, 0 /* pourcentage blessure */)
	return html
}
コード例 #23
0
ファイル: servefile.go プロジェクト: ality/web.go
func serveFile(ctx *Context, name string) {
	f, err := os.Open(name, os.O_RDONLY, 0)

	if err != nil {
		ctx.Abort(404, "Invalid file")
		return
	}

	defer f.Close()

	info, _ := f.Stat()
	size := strconv.Itoa64(info.Size)
	mtime := strconv.Itoa64(info.Mtime_ns)

	//set content-length
	ctx.SetHeader("Content-Length", size, true)

	//set the last-modified header
	lm := time.SecondsToLocalTime(info.Mtime_ns / 1e9)
	ctx.SetHeader("Last-Modified", webTime(lm), true)

	//generate a simple etag with heuristic MD5(filename, size, lastmod)
	etagparts := []string{name, size, mtime}
	etag := fmt.Sprintf(`"%s"`, getmd5(strings.Join(etagparts, "|")))
	ctx.SetHeader("ETag", etag, true)

	ext := path.Ext(name)
	if ctype := mime.TypeByExtension(ext); ctype != "" {
		ctx.SetHeader("Content-Type", ctype, true)
	} else {
		// read first chunk to decide between utf-8 text and binary
		buf := make([]byte, 1024)
		n, _ := io.ReadFull(f, buf)
		b := buf[0:n]
		if isText(b) {
			ctx.SetHeader("Content-Type", "text-plain; charset=utf-8", true)
		} else {
			ctx.SetHeader("Content-Type", "application/octet-stream", true) // generic binary
		}
		if ctx.Request.Method != "HEAD" {
			ctx.Write(b)
		}
	}
	if ctx.Request.Method != "HEAD" {
		io.Copy(ctx, f)
	}
}
コード例 #24
0
ファイル: posts.go プロジェクト: Quasimo/bloody.go
func (post *PostModel) PostListing(page int) []map[string]string {
	var result *Post
	results := []map[string]string{}
	callback := func() os.Error {
		t := time.SecondsToLocalTime(result.Created)
		results = append(results, map[string]string{"Title": result.Title, "Date": t.Format("2006 Jan 02 15:04"), "Id": objectIdHex(result.Id.String())})
		return nil
	}
	var err os.Error
	if page == 0 {
		err = post.c.Find(nil).Sort(bson.M{"timestamp": -1}).For(&result, callback)
	} else {
		err = post.c.Find(nil).Sort(bson.M{"timestamp": -1}).Skip(10*(page-1)).Limit(10).For(&result, callback)
	}
	if err != nil {
		panic(err)
	}
	return results
}
コード例 #25
0
ファイル: tableview.go プロジェクト: wiloe/walk
// Called by the TableView when it needs the text to display for a given cell.
func (m *FooModel) Value(row, col int) interface{} {
	item := m.items[row]

	switch col {
	case 0:
		return row

	case 1:
		return item.Bar

	case 2:
		return item.Baz

	case 3:
		return time.SecondsToLocalTime(item.Quux)
	}

	panic("unexpected col")
}
コード例 #26
0
ファイル: seen.go プロジェクト: gnuvince/profbot
func (s *t) seen(conn *irc.Connection, msg *irc.Message) {
	if msg.Command != "PRIVMSG" {
		return
	}

	fs := flag.NewFlagSet("seen", flag.ContinueOnError)
	fs.Usage = func() {
		conn.Privmsg(*msg.Target(), "usage: seen <nick>")
	}

	parts := msg.Split()
	if fs.Parse(parts[1:]) != nil {
		return
	}

	if fs.NArg() == 0 {
		fs.Usage()
		return
	}

	target := fs.Arg(0)
	stmt, err := s.db.Prepare(
		fmt.Sprintf("SELECT datetime, message FROM %s WHERE nick LIKE ? ORDER BY datetime desc LIMIT 1", tableName))
	defer stmt.Finalize()
	if err != nil {
		log.Printf("seen.seen(): sql error: %s", err)
		return
	}

	stmt.Exec(target)
	found := stmt.Next()
	if found {
		var datetime int64
		var rawmessage string
		stmt.Scan(&datetime, &rawmessage)
		t := time.SecondsToLocalTime(datetime)
		str := t.Format(time.UnixDate)
		conn.Privmsg(*msg.Target(), str+": "+rawmessage)
	} else {
		conn.Privmsg(*msg.Target(), "I haven't seen "+target)
	}
}
コード例 #27
0
ファイル: blog.go プロジェクト: moritzpein/fettemama
func (bf *TelnetBlogFormatter) FormatPost(post *BlogPost, withComments bool) string {
	t := time.SecondsToLocalTime(post.Timestamp)
	s := fmt.Sprintf("Post #%d, %s\n", post.Id, t.String())

	lines := strings.Split(post.Content, "\n", -1)
	for _, line := range lines {
		line = htmlstrip(line)
		s += fmt.Sprintf("\t%s\n", line)
	}

	if !withComments {
		return s
	}

	s += fmt.Sprintf("\nComments for post #%d:\n", post.Id)
	for _, c := range post.Comments {
		s += bf.FormatComment(&c)
	}
	return s
}
コード例 #28
0
ファイル: mongo_db.go プロジェクト: kybernetyk/fettemama
func (md *MongoDB) GetPostsForLastNDays(num_of_days int64) (posts []BlogPost, err os.Error) {
	today := time.LocalTime()
	s := today.Seconds()
	i := 0
	for {
		if num_of_days <= 0 || i >= 30 {
			break
		}
		fmt.Printf("i: %d - s: %d\n", i, s)
		d := time.SecondsToLocalTime(s)
		p, e := md.GetPostsForDate(*d)
		if e == nil && len(p) > 0 {
			posts = append(posts, p...)
			num_of_days--
		}
		i++
		s -= 86400
	}
	return
}
コード例 #29
0
ファイル: godoc.go プロジェクト: 8l/go-learn
func servePage(c *http.Conn, title, query string, content []byte) {
	type Data struct {
		Title     string
		Timestamp string
		Query     string
		Content   []byte
	}

	_, ts := fsTree.get()
	d := Data{
		Title:     title,
		Timestamp: time.SecondsToLocalTime(ts).String(),
		Query:     query,
		Content:   content,
	}

	if err := godocHtml.Execute(&d, c); err != nil {
		log.Stderrf("godocHtml.Execute: %s", err)
	}
}
コード例 #30
0
ファイル: log.go プロジェクト: lougxing/golang-china
func (l *Logger) formatHeader(ns int64, calldepth int) string {
	h := l.prefix
	if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
		t := time.SecondsToLocalTime(ns / 1e9)
		if l.flag&(Ldate) != 0 {
			h += itoa(int(t.Year), 4) + "/" + itoa(t.Month, 2) + "/" + itoa(t.Day, 2) + " "
		}
		if l.flag&(Ltime|Lmicroseconds) != 0 {
			h += itoa(t.Hour, 2) + ":" + itoa(t.Minute, 2) + ":" + itoa(t.Second, 2)
			if l.flag&Lmicroseconds != 0 {
				h += "." + itoa(int(ns%1e9)/1e3, 6)
			}
			h += " "
		}
	}
	if l.flag&(Lshortfile|Llongfile) != 0 {
		_, file, line, ok := runtime.Caller(calldepth)
		if ok {
			if l.flag&Lshortfile != 0 {
				short, ok := shortnames[file]
				if !ok {
					short = file
					for i := len(file) - 1; i > 0; i-- {
						if file[i] == '/' {
							short = file[i+1:]
							break
						}
					}
					shortnames[file] = short
				}
				file = short
			}
		} else {
			file = "???"
			line = 0
		}
		h += file + ":" + itoa(line, -1) + ": "
	}
	return h
}