本文整理匯總了Golang中github.com/cheggaaa/pb.ProgressBar類的典型用法代碼示例。如果您正苦於以下問題:Golang ProgressBar類的具體用法?Golang ProgressBar怎麽用?Golang ProgressBar使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了ProgressBar類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: StartClient
func StartClient(c chan string, bar *pb.ProgressBar) {
readClient, writeClient := http.Client{}, http.Client{}
for file := range c {
file = escapeFile(file)
read := readUrl + file
write := writeUrl + file
// get
resp, err := readClient.Get(read)
if err != nil {
panic(err)
}
getMd5 := resp.Header.Get("X-Ae-Md5")
length := resp.ContentLength
// put
req, err := http.NewRequest(*method, write, resp.Body)
if err != nil {
panic(err)
}
req.ContentLength = length
wres, err := writeClient.Do(req)
if err != nil {
panic(err)
}
if wres.StatusCode != http.StatusConflict {
putMd5 := wres.Header.Get("X-Ae-Md5")
if putMd5 != getMd5 {
fmt.Printf("ERROR! MD5 not equals: %s vs %s (%s)\n", getMd5, putMd5, file)
}
}
wres.Body.Close()
resp.Body.Close()
bar.Increment()
}
}
示例2: httpWorker
func httpWorker(jobs <-chan int, hosts []host, bar *pb.ProgressBar) {
for job := range jobs {
h := &hosts[job]
timeout, err := time.ParseDuration(*httpClientTimeout)
if err != nil {
log.Fatal(err)
}
client := http.Client{
Timeout: timeout,
}
url := fmt.Sprintf("%s://%s:%d/xmldata?item=All", *scheme, hosts[job].ip.String(), *port)
// Anon function for proper wg.Done() call
func() {
defer bar.Increment()
defer wg.Done()
res, err := client.Get(url)
if err != nil {
h.Err += err.Error()
return
}
xmldata, err := ioutil.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
h.Err += err.Error()
return
}
h.XMLErr = xml.Unmarshal(xmldata, h)
}()
}
}
示例3: getInitTweets
func (g *Game) getInitTweets(aliveNum int) {
var progress *pb.ProgressBar
if !g.debug {
progress = pb.StartNew(aliveNum)
}
for y := 0; y < g.field.SizeY; y++ {
for x := 0; x < g.field.SizeX; x++ {
if g.field.Points[y][x].IsAlive {
tweet := <-g.tweetCh
if g.debug {
emoji.Printf(":bird:Points[%v][%v]: %v\n", x, y, tweet)
}
g.field.Points[y][x].Str = tweet
if !g.debug {
progress.Increment()
}
}
}
}
if g.debug {
emoji.Println(":smile::smile::smile:Collected initial tweets:smile::smile::smile:")
} else {
e := emoji.Sprint(":smile::smile::smile:")
progress.FinishPrint(e + "Collected initial tweets" + e)
}
}
示例4: work
func work(wg *sync.WaitGroup, bar *pb.ProgressBar, queue chan *Track) {
defer wg.Done()
for track := range queue {
track.Download()
bar.Increment()
}
}
示例5: main
func main() {
var progress *pb.ProgressBar
page := 0
category := "bugs"
for {
printf("Get page: %d", page)
tickets, _, err := sfClient.Tracker.Info(category)
if err != nil {
log.Fatal(err)
}
if ghMilestones == nil {
createMilestones(tickets)
getMilestones()
}
if progress == nil {
log.Println("Creating tickets")
progress = pb.StartNew(tickets.Count)
}
if len(tickets.Tickets) == 0 {
break
}
for _, ticket := range tickets.Tickets {
ticket, _, err := sfClient.Tracker.Get(category, ticket.TicketNum)
if err != nil {
log.Fatal(err)
}
sfTicketToGhIssue(ticket, category)
progress.Increment()
time.Sleep(time.Millisecond * sleepTime)
}
page += 1
}
progress.FinishPrint("All tickets imported")
}
示例6: HostMerge
func HostMerge(List []Host, ShowBar bool) []string {
count := 0
filterList := []string{""}
length := len(List)
var bar *pb.ProgressBar
if ShowBar == true {
bar = pb.StartNew(length)
bar.SetMaxWidth(80)
}
for _, Host := range List {
length = len(filterList[count])
if length == 0 {
filterList[count] = Host.Hostname
} else if length+Host.length() <= 255 && length != 0 {
filterList[count] += "|"
filterList[count] += Host.Hostname
} else {
count++
filterList = append(filterList, Host.Hostname)
// filterList[count] = Ref.Referrer
}
if ShowBar == true {
bar.Increment()
time.Sleep(time.Millisecond * 50)
}
}
if ShowBar == true {
bar.Finish()
}
return filterList
}
示例7: customizeBar
func customizeBar(bar *pb.ProgressBar) {
bar.ShowCounters = true
bar.ShowTimeLeft = false
bar.ShowSpeed = true
bar.SetMaxWidth(80)
bar.SetUnits(pb.U_BYTES)
}
示例8: main
func main() {
opts, args := parseFlags()
conv := cbconvert.NewConvertor(opts)
var bar *pb.ProgressBar
c := make(chan os.Signal, 3)
signal.Notify(c, os.Interrupt, syscall.SIGHUP, syscall.SIGTERM)
go func() {
for _ = range c {
fmt.Fprintf(os.Stderr, "Aborting\n")
os.RemoveAll(conv.Workdir)
os.Exit(1)
}
}()
if _, err := os.Stat(opts.Outdir); err != nil {
os.MkdirAll(opts.Outdir, 0777)
}
files := conv.GetFiles(args)
if opts.Cover || opts.Thumbnail {
if !opts.Quiet {
bar = pb.New(conv.Nfiles)
bar.ShowTimeLeft = false
bar.Start()
}
}
for _, file := range files {
stat, err := os.Stat(file)
if err != nil {
fmt.Fprintf(os.Stderr, "Error Stat: %v\n", err.Error())
continue
}
if opts.Cover {
conv.ExtractCover(file, stat)
if !opts.Quiet {
bar.Increment()
}
continue
} else if opts.Thumbnail {
conv.ExtractThumbnail(file, stat)
if !opts.Quiet {
bar.Increment()
}
continue
}
conv.ConvertComic(file, stat)
}
}
示例9: download
// download a file with the HTTP/HTTPS protocol showing a progress bar. The destination file is
// always overwritten.
func download(rawurl string, destinationPath string) {
tempDestinationPath := destinationPath + ".tmp"
destination, err := os.Create(tempDestinationPath)
if err != nil {
log.Fatalf("Unable to open the destination file: %s", tempDestinationPath)
}
defer destination.Close()
response, err := customGet(rawurl)
if err != nil {
log.Fatalf("Unable to open a connection to %s", rawurl)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
log.Fatalf("Unexpected HTTP response code. Wanted 200 but got %d", response.StatusCode)
}
var progressBar *pb.ProgressBar
contentLength, err := strconv.Atoi(response.Header.Get("Content-Length"))
if err == nil {
progressBar = pb.New(int(contentLength))
} else {
progressBar = pb.New(0)
}
defer progressBar.Finish()
progressBar.ShowSpeed = true
progressBar.SetRefreshRate(time.Millisecond * 1000)
progressBar.SetUnits(pb.U_BYTES)
progressBar.Start()
writer := io.MultiWriter(destination, progressBar)
io.Copy(writer, response.Body)
destination.Close()
os.Rename(tempDestinationPath, destinationPath)
}
示例10: runClusterBackup
func runClusterBackup(args *docopt.Args) error {
client, err := getClusterClient()
if err != nil {
return err
}
var bar *pb.ProgressBar
var progress backup.ProgressBar
if term.IsTerminal(os.Stderr.Fd()) {
bar = pb.New(0)
bar.SetUnits(pb.U_BYTES)
bar.ShowBar = false
bar.ShowSpeed = true
bar.Output = os.Stderr
bar.Start()
progress = bar
}
var dest io.Writer = os.Stdout
if filename := args.String["--file"]; filename != "" {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
dest = f
}
fmt.Fprintln(os.Stderr, "Creating cluster backup...")
if err := backup.Run(client, dest, progress); err != nil {
return err
}
if bar != nil {
bar.Finish()
}
fmt.Fprintln(os.Stderr, "Backup complete.")
return nil
}
示例11: scan
func scan(ips []string, out chan ILOInfo, bar *pb.ProgressBar, wg *sync.WaitGroup) {
for _, host := range ips {
if IsOpen(host, iloPort) {
srvName := ""
iloName := ""
info, err := requestInfo(host)
if err != nil {
fmt.Println(err)
}
if match, _ := regexp.MatchString("iLO (3|4|5)", info.HW); match {
srvName, iloName, _ = requestServerName(host)
} else {
srvName, iloName, _ = requestServerNameV2(host)
}
info.ServerName = srvName
info.IloName = iloName
out <- *info
}
bar.Increment()
}
wg.Done()
}
示例12: processSystemArchives
// processSystemArchives processes archives for given system
func (h *Harvester) processSystemArchives(s *system.System, archives []string) error {
var bar *pb.ProgressBar
nb := len(archives)
// extract archives
if !s.Options.Quiet {
fmt.Printf("[%s] Extracting %v archive(s)\n", s.Infos.Name, nb)
if !s.Options.Debug {
bar = pb.StartNew(nb)
bar.ShowCounters = true
bar.ShowPercent = false
bar.ShowTimeLeft = true
bar.SetMaxWidth(80)
}
}
for _, archive := range archives {
if !s.Options.Quiet && !s.Options.Debug {
bar.Increment()
}
if err := s.ProcessArchive(archive, h.Options.Output); err != nil {
return err
}
}
if !s.Options.Quiet && !s.Options.Debug {
bar.Finish()
fmt.Printf("[%s] Processed %v files (skipped: %v)\n", s.Infos.Name, s.Processed, s.Skipped)
}
fmt.Printf("[%s] Selected %v games\n", s.Infos.Name, len(s.Games))
return nil
}
示例13: uploadItem
func uploadItem(c *cli.Context, hash string, item client.IndexItem, bar *pb.ProgressBar, ch chan error) {
data, err := ioutil.ReadFile(item.Name)
if err != nil {
ch <- err
return
}
for i := 0; i < 3; i++ {
err = rackClient(c).IndexUpload(hash, data)
if err != nil {
continue
}
bar.Add(item.Size)
ch <- nil
return
}
ch <- fmt.Errorf("max 3 retries on upload")
return
}
示例14: indexAndSaveHits
func indexAndSaveHits(ts *index.TokenSetSearcher, hits []HitInfo, idxs []int, saveFullHit func(*HitInfo) error) error {
rank := 0
var bar *pb.ProgressBar
if terminal.IsTerminal(int(os.Stdout.Fd())) {
bar = pb.New(len(idxs))
bar.Start()
}
for i := range idxs {
hit := &hits[idxs[i]]
if i > 0 && hit.StaticScore < hits[idxs[i-1]].StaticScore {
rank = i
}
hit.StaticRank = rank
if err := saveFullHit(hit); err != nil {
return err
}
var desc, readme string
desc, hit.Description = hit.Description, ""
readme, hit.ReadmeData = hit.ReadmeData, ""
hit.Imported = nil
hit.TestImported = nil
var nameTokens stringsp.Set
nameTokens = AppendTokens(nameTokens, []byte(hit.Name))
var tokens stringsp.Set
tokens.Add(nameTokens.Elements()...)
tokens = AppendTokens(tokens, []byte(hit.Package))
tokens = AppendTokens(tokens, []byte(desc))
tokens = AppendTokens(tokens, []byte(readme))
tokens = AppendTokens(tokens, []byte(hit.Author))
for _, word := range hit.Exported {
AppendTokens(tokens, []byte(word))
}
ts.AddDoc(map[string]stringsp.Set{
IndexTextField: tokens,
IndexNameField: nameTokens,
IndexPkgField: stringsp.NewSet(hit.Package),
}, *hit)
if bar != nil {
bar.Increment()
}
}
if bar != nil {
bar.FinishPrint("Indexing finished!")
}
DumpMemStats()
return nil
}
示例15: StoreRedirects
func StoreRedirects(db *sql.DB, redirs []wikidump.Redirect,
bar *pb.ProgressBar) error {
counts := make([]linkCount, 0)
var titleId, old, del, delTitle, insTitle, ins, update *sql.Stmt
tx, err := db.Begin()
if err == nil {
titleId, err = tx.Prepare(`select id from titles where title = ?`)
}
if err == nil {
old, err = tx.Prepare(
`select ngramhash, count from linkstats where targetid = ?`)
}
if err == nil {
del, err = tx.Prepare(`delete from linkstats where targetid = ?`)
}
if err == nil {
delTitle, err = tx.Prepare(`delete from titles where id = ?`)
}
if err == nil {
insTitle, err = tx.Prepare(
`insert or ignore into titles values (NULL, ?)`)
}
if err == nil {
ins, err = tx.Prepare(
`insert or ignore into linkstats values
(?, (select id from titles where title = ?), 0)`)
}
if err == nil {
update, err = tx.Prepare(
`update linkstats set count = count + ?
where targetid = (select id from titles where title = ?)
and ngramhash = ?`)
}
if err != nil {
return err
}
for _, r := range redirs {
if bar != nil {
bar.Increment()
}
var fromId int
err := titleId.QueryRow(r.Title).Scan(&fromId)
if err == sql.ErrNoRows { // No links to this redirect.
continue
} else if err != nil {
return err
}
rows, err := old.Query(fromId)
if err != nil {
return err
}
// SQLite won't let us INSERT or UPDATE while doing a SELECT.
for counts = counts[:0]; rows.Next(); {
var count float64
var hash int64
rows.Scan(&hash, &count)
counts = append(counts, linkCount{hash, count})
}
rows.Close()
err = rows.Err()
if err == nil {
_, err = del.Exec(fromId)
}
if err == nil {
_, err = delTitle.Exec(fromId)
}
if err != nil {
return err
}
for _, c := range counts {
if err == nil {
_, err = insTitle.Exec(r.Target)
}
if err == nil {
_, err = ins.Exec(c.hash, r.Target)
}
if err == nil {
_, err = update.Exec(c.count, r.Target, c.hash)
}
}
if err != nil {
return err
}
}
err = tx.Commit()
return err
}