How to use openFile method of lang Package

Best Gauge code snippet using lang.openFile

index.go

Source:index.go Github

copy

Full Screen

1package controllers23import (4 "bufio"5 "fmt"6 "github.com/astaxie/beego"7 "strings"8 // iconv "github.com/djimenez/iconv-go"9 "code.google.com/p/mahonia"10 "io"11 "io/ioutil"12 "os"13 "regexp"14 "strconv"15 "time"16)1718type IndexController struct {19 beego.Controller20}2122func (this *IndexController) Index() {23 this.TplNames = "index.html"24}2526func (this *IndexController) Left() {27 this.TplNames = "left.html"2829 //用户登陆状态30 vadmin := this.GetSession("adminUser")31 if admin_user, ok := vadmin.(string); ok && admin_user == beego.AppConfig.String("admin_user") {32 this.Data["IsLogin"] = true33 this.Data["IsAdmin"] = true3435 this.Data["UserName"] = beego.AppConfig.String("admin_realname")36 }3738 v := this.GetSession("currentUser")39 if current_user, ok := v.(string); ok {40 this.Data["IsLogin"] = true41 this.Data["IsUser"] = true4243 this.Data["UserName"] = current_user44 }4546 //比赛开始时间读取47 var durationSeconds, startTime int6448 if _, err := os.Stat("time.txt"); err == nil {49 ftime, err := os.OpenFile("time.txt", os.O_RDONLY, 0644)50 if err != nil {51 beego.Error(err)52 }53 defer ftime.Close()5455 fmt.Fscanf(ftime, "%d", &startTime)56 }5758 durationSeconds = time.Now().Unix() - startTime5960 if startTime > 0 {61 this.Data["IsMatchStart"] = true62 }63 this.Data["DurationSeconds"] = durationSeconds64}6566func (this *IndexController) Right() {67 this.TplNames = "right.html"6869 if _, err := os.Stat("time.txt"); err != nil {70 this.Data["MatchStop"] = true71 }72}7374func (this *IndexController) Check() {75 this.TplNames = "check.html"7677 username := this.GetString("username")78 //密码未加密79 password := this.GetString("password")80 encryptPassword := StrToMD5(password)8182 if username == "" || password == "" {83 this.Data["IsError"] = true84 this.Data["ErrorMsg"] = "用户名或密码为空"85 return86 }8788 //判断超级管理员登录89 if username == beego.AppConfig.String("admin_user") {90 if encryptPassword == beego.AppConfig.String("admin_pass") {91 this.SetSession("adminUser", username)92 // this.SetSession("adminRealname", beego.AppConfig.String("admin_realname"))9394 this.Data["UserName"] = beego.AppConfig.String("admin_realname")95 return96 }97 }9899 //判断普通用户登录100 //'teacher'=8d788385431273d11e8b43bb78f3aa41101 fuser, err := os.OpenFile("user.txt", os.O_RDONLY, 0644)102 if err != nil {103 beego.Error(err)104 this.Data["IsError"] = true105 this.Data["ErrorMsg"] = "无法打开 user.txt 用户数据文件"106 return107 }108 defer fuser.Close()109110 //'teacher'=8d788385431273d11e8b43bb78f3aa41111 reguserinfo := regexp.MustCompile(`\'` + username + `\'=.*\n`)112 var finduserinfo string113114 // bf := bufio.NewReader(fuser)115 userdata, err := ioutil.ReadAll(fuser)116 finduserinfo = reguserinfo.FindString(string(userdata))117118 uname := regexp.MustCompile(`\'([\p{Han}]|[0-9A-Za-z])*\'`).FindString(finduserinfo)119 uencpass := regexp.MustCompile(`\'=.*`).FindString(finduserinfo)120121 if "'"+username+"'" == uname {122 if "'="+encryptPassword == uencpass {123 this.SetSession("currentUser", username)124 // this.SetSession("adminRealname", beego.AppConfig.String("admin_realname"))125126 this.Data["UserName"] = username127 return128 }129 }130131 this.Data["IsError"] = true132 this.Data["ErrorMsg"] = "用户名或密码错误"133134}135136func (this *IndexController) Logout() {137 this.TplNames = "logout.html"138139 vadmin := this.GetSession("adminUser")140 if admin_user, ok := vadmin.(string); ok && admin_user == beego.AppConfig.String("admin_user") {141 this.DelSession("adminUser")142 this.DelSession("adminRealname")143144 this.Data["UserName"] = admin_user145 return146 }147148 v := this.GetSession("currentUser")149 if current_user, ok := v.(string); ok {150 this.DelSession("currentUser")151152 this.Data["UserName"] = current_user153 return154 }155}156157func (this *IndexController) Match() {158 this.TplNames = "match.html"159160 //用户登陆状态161 vadmin := this.GetSession("adminUser")162 if admin_user, ok := vadmin.(string); ok && admin_user == beego.AppConfig.String("admin_user") {163 this.Data["IsLogin"] = true164 this.Data["IsAdmin"] = true165166 // this.Data["UserName"] = admin_user167168 //判断time.txt文件是否存在,有就删除,没有就写入当前Unix时间169 if _, err := os.Stat("time.txt"); err == nil {170 if err := os.Remove("time.txt"); err != nil {171 beego.Error(err)172 }173 } else {174 ftime, err := os.OpenFile("time.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)175 if err != nil {176 beego.Error(err)177 }178 defer ftime.Close()179180 fmt.Fprintln(ftime, time.Now().Unix())181 }182 }183184}185186func (this *IndexController) Reg() {187 this.TplNames = "reg.html"188189 this.Data["AdminUserName"] = beego.AppConfig.String("admin_user")190 // beego.Info(this.Ctx.Request.Method)191 if this.Ctx.Request.Method == "GET" {192 this.Data["IsGet"] = true193 } else if this.Ctx.Request.Method == "POST" {194 this.Data["IsPost"] = true195 username := this.GetString("user")196 //密码未加密197 password := this.GetString("pass")198 encryptPassword := StrToMD5(password)199200 if username == beego.AppConfig.String("admin_user") {201 this.Data["IsError"] = true202 this.Data["ErrorMsg"] = "非法用户名"203204 return205 }206207 if len(username) < 4 {208 this.Data["IsError"] = true209 this.Data["ErrorMsg"] = "用户名太短。至少4个英文字符或2个中文字符。"210 return211 }212213 if ok, _ := regexp.Match(`^([\p{Han}]|[0-9A-Za-z])*$`, []byte(username)); !ok {214 this.Data["IsError"] = true215 this.Data["ErrorMsg"] = "用户名\"" + username + "\"含有非法字符。"216 return217 }218219 if len(password) < 6 {220 this.Data["IsError"] = true221 this.Data["ErrorMsg"] = "密码太短。至少6个英文字符。"222 return223 }224225 // curdir, _ := os.Getwd()226227 f, err := os.OpenFile("user.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)228 if err != nil {229 beego.Error(err)230 this.Data["IsError"] = true231 this.Data["ErrorMsg"] = "创建 user.txt 失败!"232 return233 }234 defer f.Close()235236 //'teacher'=8d788385431273d11e8b43bb78f3aa41237 bf := bufio.NewReader(f)238 reguserinfo := regexp.MustCompile(`\'([\p{Han}]|[0-9A-Za-z])*\'`)239 var finduser string240 for {241 //buf,err := r.ReadBytes('\n')242 buf, err := bf.ReadString('\n')243 if err == io.EOF {244 break245 }246247 finduser = reguserinfo.FindString(buf)248249 if finduser == `'`+username+`'` {250 this.Data["IsError"] = true251 this.Data["ErrorMsg"] = "用户名\"" + username + "\"已经存在,请更换用户名。"252 return253 }254 }255256 fmt.Fprintf(f, "'%s'=%s\n", username, encryptPassword)257258 this.Data["UserName"] = username259 }260261}262263func (this *IndexController) Problem() {264 this.TplNames = "problem.html"265266 vadmin := this.GetSession("adminUser")267 if admin_user, ok := vadmin.(string); ok && admin_user == beego.AppConfig.String("admin_user") {268 this.Data["IsLogin"] = true269 this.Data["IsAdmin"] = true270 this.Data["UserName"] = admin_user271 }272273 v := this.GetSession("currentUser")274 if current_user, ok := v.(string); ok {275 this.Data["IsLogin"] = true276 this.Data["IsUser"] = true277 this.Data["UserName"] = current_user278 }279280 //比赛开始时间读取281 var startTime int64282 if _, err := os.Stat("time.txt"); err == nil {283 ftime, err := os.OpenFile("time.txt", os.O_RDONLY, 0644)284 if err != nil {285 beego.Error(err)286 }287 defer ftime.Close()288289 fmt.Fscanf(ftime, "%d", &startTime)290 }291292 if startTime > 0 {293 this.Data["IsMatchStart"] = true294 } else {295 return296 }297298 probName := this.GetString("probname")299 if probName == "" {300 this.Data["IsProbList"] = true301 //读取题目列表302 if _, err := os.Stat("prob.txt"); err == nil {303 fprob, err := os.OpenFile("prob.txt", os.O_RDONLY, 0644)304 if err != nil {305 beego.Error(err)306 }307 defer fprob.Close()308309 var buf string310 n, _ := fmt.Fscanf(fprob, "%s\r", &buf)311 isWin := n > 0312 if isWin {313 fprob.Seek(0, os.SEEK_SET)314 }315316 var probnum int317 bfprob := bufio.NewReader(fprob)318 ret, _ := bfprob.ReadString('\n')319 if isWin {320 if n := strings.LastIndex(ret, "\r\n"); n >= 0 {321 ret = ret[:n]322 }323 }324 probnum, _ = strconv.Atoi(ret)325326 var hasProbset bool327 var fprobset *os.File328 if _, err := os.Stat("probset.txt"); err == nil {329 fprobset, err = os.OpenFile("probset.txt", os.O_RDONLY, 0644)330 if err != nil {331 beego.Error(err)332 }333 defer fprobset.Close()334335 hasProbset = true336 }337338 type ProbInfo struct {339 Id int340 Class int341 ProbName string342 AcTotal int343 SubTotal int344 CorrectPercent float32345 }346347 probInfos := make([]*ProbInfo, 0, probnum)348349 var pname string350 id := 0351 for {352 probinfo := new(ProbInfo)353354 //兼容WIN下的换行符号读入355 // fmt.Fscanf(fprob, "%d", &buf)356 // if buf != 0 {357 // fprob.Seek(-1, os.SEEK_CUR)358 // }359360 pname, err = bfprob.ReadString('\n')361 if err == io.EOF && len(pname) == 0 {362 break363 }364365 //转换WIN下gb18030 to utf-8366 if isWin {367 // pname=strings.TrimSpace(pname)368 if n := strings.LastIndex(pname, "\r\n"); n >= 0 {369 pname = pname[:n]370 }371 dec := mahonia.NewDecoder("gb18030")372 probinfo.ProbName = dec.ConvertString(pname)373 }374375 id++376 probinfo.Id = id377378 if hasProbset {379 _, err = fmt.Fscanf(fprobset, "%d %d\n", &probinfo.AcTotal, &probinfo.SubTotal)380 // beego.Info(probinfo.AcTotal, probinfo.SubTotal)381 }382383 if probinfo.SubTotal > 0 {384 probinfo.CorrectPercent = float32(probinfo.AcTotal * 100.0 / probinfo.SubTotal)385 }386387 probInfos = append(probInfos, probinfo)388 }389 // converter.Close()390391 this.Data["ProbInfos"] = probInfos392 }393 } else {394 this.Data["ProbName"] = probName395396 fprob, err := os.OpenFile("prob.txt", os.O_RDONLY, 0644)397 if err != nil {398 beego.Error(err)399 }400 defer fprob.Close()401 var buf string402 n, _ := fmt.Fscanf(fprob, "%s\r", &buf)403 isWin := n > 0404405 if _, err := os.Stat("prob/" + probName + "/prob.html"); err != nil {406 beego.Error(err)407 this.Data["ProbHtml"] = "找不到题目描述文件"408 return409 } else {410 fprobhtml, err := os.OpenFile("prob/"+probName+"/prob.html", os.O_RDONLY, 0644)411 if err != nil {412 beego.Error(err)413 this.Data["ProbHtml"] = "找不到题目描述文件"414 return415 }416 defer fprobhtml.Close()417418 var probhtml []byte419 probhtml, _ = ioutil.ReadAll(fprobhtml)420 //转换WIN下gb18030 to utf-8421 if isWin {422 dec := mahonia.NewDecoder("gb18030")423 this.Data["ProbHtml"] = dec.ConvertString(string(probhtml))424 } else {425 this.Data["ProbHtml"] = string(probhtml)426 }427428 }429 }430431}432433func (this *IndexController) Submit() {434 this.TplNames = "submit.html"435436 vadmin := this.GetSession("adminUser")437 if admin_user, ok := vadmin.(string); ok && admin_user == beego.AppConfig.String("admin_user") {438 this.Data["IsLogin"] = true439 this.Data["IsAdmin"] = true440 this.Data["UserName"] = admin_user441 }442443 v := this.GetSession("currentUser")444 if current_user, ok := v.(string); ok {445 this.Data["IsLogin"] = true446 this.Data["IsUser"] = true447 this.Data["UserName"] = current_user448 }449450 //比赛开始时间读取451 var startTime int64452 if _, err := os.Stat("time.txt"); err == nil {453 ftime, err := os.OpenFile("time.txt", os.O_RDONLY, 0644)454 if err != nil {455 beego.Error(err)456 }457 defer ftime.Close()458459 fmt.Fscanf(ftime, "%d", &startTime)460 }461462 if startTime > 0 {463 this.Data["IsMatchStart"] = true464 } else {465 return466 }467468 probName := this.GetString("probname")469 if probName == "" {470 this.Data["IsProbList"] = true471 //读取题目列表472 if _, err := os.Stat("prob.txt"); err == nil {473 fprob, err := os.OpenFile("prob.txt", os.O_RDONLY, 0644)474 if err != nil {475 beego.Error(err)476 this.Data["IsError"] = true477 this.Data["ErrorMsg"] = "找不到题目!"478 }479 defer fprob.Close()480 var buf string481 n, _ := fmt.Fscanf(fprob, "%s\r", &buf)482 isWin := n > 0483 if isWin {484 fprob.Seek(0, os.SEEK_SET)485 }486487 bfprob := bufio.NewReader(fprob)488 ret, _ := bfprob.ReadString('\n')489 probnum, _ := strconv.Atoi(ret)490491 type ProbInfo struct {492 Id int493 ProbName string494 }495496 probInfos := make([]*ProbInfo, 0, probnum)497498 var pname string499 id := 0500 for {501 probinfo := new(ProbInfo)502503 pname, err = bfprob.ReadString('\n')504 if err == io.EOF && len(pname) == 0 {505 break506 }507508 //转换WIN下gb18030 to utf-8509 if isWin {510 if n := strings.LastIndex(pname, "\r\n"); n >= 0 {511 pname = pname[:n]512 }513 dec := mahonia.NewDecoder("gb18030")514 probinfo.ProbName = dec.ConvertString(pname)515 }516517 id++518 probinfo.Id = id519520 probInfos = append(probInfos, probinfo)521 }522523 this.Data["ProbInfos"] = probInfos524 }525 } else if this.Ctx.Request.Method == "POST" {526 this.Data["ProbName"] = probName527528 if _, err := os.Stat("prob/" + probName + "/prob.html"); err != nil {529 beego.Error(err)530 this.Data["IsError"] = true531 this.Data["ErrorMsg"] = "找不到题目!"532 return533 }534535 lang := this.GetString("lang")536537 // file, fileHeader, err := this.GetFile("program")538 file, _, err := this.GetFile("program")539 if err != nil {540 beego.Error(err)541 this.Data["IsError"] = true542 this.Data["ErrorMsg"] = "没有上传文件!"543 return544 }545 defer file.Close()546547 //读入最后更新ID548 ftailr, err := os.OpenFile("tail.txt", os.O_RDONLY, 0644)549 if err != nil {550 beego.Error(err)551 this.Data["IsError"] = true552 this.Data["ErrorMsg"] = "找不到 tail.txt 文件!"553 return554 }555 defer ftailr.Close()556557 var tailid int558 fmt.Fscanf(ftailr, "%d", &tailid)559560 ftailw, err := os.OpenFile("tail.txt", os.O_WRONLY|os.O_TRUNC, 0644)561 if err != nil {562 beego.Error(err)563 this.Data["IsError"] = true564 this.Data["ErrorMsg"] = "找不到 tail.txt 文件!"565 return566 }567 defer ftailw.Close()568 tailid++569 fmt.Fprintf(ftailw, "%d", tailid)570571 // curdir, err := os.Getwd()572573 tofilepath := "submit/" + strconv.Itoa(tailid) + "/"574 err = os.MkdirAll(tofilepath, 0755)575 if err != nil {576 beego.Error(err)577 this.Data["IsError"] = true578 this.Data["ErrorMsg"] = "创建 " + tofilepath + " 失败!"579 return580 }581582 ftime, err := os.OpenFile("time.txt", os.O_RDONLY, 0644)583 if err != nil {584 beego.Error(err)585 this.Data["IsError"] = true586 this.Data["ErrorMsg"] = "找不到 time.txt 文件!"587 return588 }589 defer ftime.Close()590591 var startTime int592 fmt.Fscanf(ftime, "%d", &startTime)593594 ntime := (time.Now().Unix() - int64(startTime)) / 60595596 fsubtime, err := os.OpenFile(tofilepath+"time.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)597 if err != nil {598 beego.Error(err)599 this.Data["IsError"] = true600 this.Data["ErrorMsg"] = "无法创建 " + tofilepath + "time.txt 文件!"601 return602 }603 defer fsubtime.Close()604605 fmt.Fprintf(fsubtime, "%d", ntime)606607 fsubresult, err := os.OpenFile(tofilepath+"result.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)608 if err != nil {609 beego.Error(err)610 this.Data["IsError"] = true611 this.Data["ErrorMsg"] = "无法创建 " + tofilepath + "result.txt 文件!"612 return613 }614 defer fsubresult.Close()615616 fmt.Fprintf(fsubresult, "%s", "Waiting")617618 fsubuser, err := os.OpenFile(tofilepath+"user.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)619 if err != nil {620 beego.Error(err)621 this.Data["IsError"] = true622 this.Data["ErrorMsg"] = "无法创建 " + tofilepath + "user.txt 文件!"623 return624 }625 defer fsubuser.Close()626627 fmt.Fprintf(fsubuser, "%s", this.Data["UserName"])628629 fsubprob, err := os.OpenFile(tofilepath+"prob.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)630 if err != nil {631 beego.Error(err)632 this.Data["IsError"] = true633 this.Data["ErrorMsg"] = "无法创建 " + tofilepath + "prob.txt 文件!"634 return635 }636 defer fsubprob.Close()637638 fmt.Fprintf(fsubprob, "%s", probName)639640 fsubip, err := os.OpenFile(tofilepath+"ip.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)641 if err != nil {642 beego.Error(err)643 this.Data["IsError"] = true644 this.Data["ErrorMsg"] = "无法创建 " + tofilepath + "ip.txt 文件!"645 return646 }647 defer fsubip.Close()648649 fmt.Fprintf(fsubip, "%s", this.Ctx.Input.IP())650651 fsublang, err := os.OpenFile(tofilepath+"lang.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)652 if err != nil {653 beego.Error(err)654 this.Data["IsError"] = true655 this.Data["ErrorMsg"] = "无法创建 " + tofilepath + "lang.txt 文件!"656 return657 }658 defer fsublang.Close()659660 var tofile string661 if lang == "1" {662 tofile = tofilepath + "prog.cpp"663 fmt.Fprintf(fsublang, "%s", "C++")664 } else if lang == "2" {665 tofile = tofilepath + "prog.pas"666 fmt.Fprintf(fsublang, "%s", "PASCAL")667 }668669 f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)670 if err != nil {671 beego.Error(err)672 this.Data["IsError"] = true673 this.Data["ErrorMsg"] = "创建 " + tofile + " 失败!"674 return675 }676 defer f.Close()677678 io.Copy(f, file)679680 CopyFile(tofilepath+"test.bat", "prob/"+probName+"/test.bat")681 }682683}684685func (this *IndexController) AdminProblem() {686 this.TplNames = "adminproblem.html"687688 vadmin := this.GetSession("adminUser")689 if admin_user, ok := vadmin.(string); ok && admin_user == beego.AppConfig.String("admin_user") {690 this.Data["IsLogin"] = true691 this.Data["IsAdmin"] = true692 this.Data["UserName"] = admin_user693694 return695 } else {696 this.Data["IsError"] = true697 this.Data["ErrorMsg"] = "请使用管理员帐号登录"698699 return700 }701}702703func (this *IndexController) Status() {704 this.TplNames = "status.html"705706 vadmin := this.GetSession("adminUser")707 if admin_user, ok := vadmin.(string); ok && admin_user == beego.AppConfig.String("admin_user") {708 this.Data["IsLogin"] = true709 this.Data["IsAdmin"] = true710 this.Data["UserName"] = admin_user711 }712713 v := this.GetSession("currentUser")714 if current_user, ok := v.(string); ok {715 this.Data["IsLogin"] = true716 this.Data["IsUser"] = true717 this.Data["UserName"] = current_user718 }719720 //比赛开始时间读取721 var startTime int64722 if _, err := os.Stat("time.txt"); err == nil {723 ftime, err := os.OpenFile("time.txt", os.O_RDONLY, 0644)724 if err != nil {725 beego.Error(err)726 }727 defer ftime.Close()728729 fmt.Fscanf(ftime, "%d", &startTime)730 }731732 if startTime > 0 {733 this.Data["IsMatchStart"] = true734 } else {735 return736 }737738 if _, err := os.Stat("status.html"); err != nil {739 beego.Error(err)740 this.Data["StatusHtml"] = "找不到 status.html 文件"741 return742 } else {743 fstatushtml, err := os.OpenFile("status.html", os.O_RDONLY, 0644)744 if err != nil {745 beego.Error(err)746 this.Data["StatusHtml"] = "找不到 status.html 文件"747 return748 }749 defer fstatushtml.Close()750751 var statushtml []byte752 statushtml, _ = ioutil.ReadAll(fstatushtml)753 this.Data["StatusHtml"] = string(statushtml)754 }755}756757func (this *IndexController) Standing() {758 this.TplNames = "standing.html"759760 vadmin := this.GetSession("adminUser")761 if admin_user, ok := vadmin.(string); ok && admin_user == beego.AppConfig.String("admin_user") {762 this.Data["IsLogin"] = true763 this.Data["IsAdmin"] = true764 this.Data["UserName"] = admin_user765 }766767 v := this.GetSession("currentUser")768 if current_user, ok := v.(string); ok {769 this.Data["IsLogin"] = true770 this.Data["IsUser"] = true771 this.Data["UserName"] = current_user772 }773774 //比赛开始时间读取775 var startTime int64776 if _, err := os.Stat("time.txt"); err == nil {777 ftime, err := os.OpenFile("time.txt", os.O_RDONLY, 0644)778 if err != nil {779 beego.Error(err)780 }781 defer ftime.Close()782783 fmt.Fscanf(ftime, "%d", &startTime)784 }785786 if startTime > 0 {787 this.Data["IsMatchStart"] = true788 } else {789 return790 }791792 if _, err := os.Stat("rank.html"); err != nil {793 beego.Error(err)794 this.Data["RankHtml"] = "找不到 rank.html 文件"795 return796 } else {797 frankhtml, err := os.OpenFile("rank.html", os.O_RDONLY, 0644)798 if err != nil {799 beego.Error(err)800 this.Data["RankHtml"] = "找不到 rank.html 文件"801 return802 }803 defer frankhtml.Close()804805 var rankhtml []byte806 rankhtml, _ = ioutil.ReadAll(frankhtml)807 this.Data["RankHtml"] = string(rankhtml)808 }809810}811812func (this *IndexController) Faq() {813 this.TplNames = "faq.html"814815}816817func CopyFile(dstName, srcName string) (written int64, err error) {818 src, err := os.Open(srcName)819 if err != nil {820 return821 }822 defer src.Close()823 dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)824 if err != nil {825 return826 }827 defer dst.Close()828 return io.Copy(dst, src)829}830831//从指定的文件名中读出string832func readFile(filename string) string {833 f, err := os.OpenFile(filename, os.O_RDONLY, 0644)834 if err != nil {835 panic(err)836 }837 defer f.Close()838839 var str string840 bf := bufio.NewReader(f)841 str, _ = bf.ReadString('\n')842 // fmt.Fscanf(f, "%s\n", &str)843844 return str845}846847func (this *IndexController) ShowProg() {848 this.TplNames = "showprog.html"849850 vadmin := this.GetSession("adminUser")851852 if admin_user, ok := vadmin.(string); ok && admin_user == beego.AppConfig.String("admin_user") {853 this.Data["IsLogin"] = true854 this.Data["IsAdmin"] = true855 this.Data["UserName"] = admin_user856 } else {857 this.Data["IsError"] = true858 this.Data["ErrorMsg"] = "你不是老师,没有权限查看!"859 return860 }861862 progid := this.GetString("id")863864 progfilepath := "submit/" + progid + "/"865866 lang := readFile(progfilepath + "lang.txt")867868 var prog string869 if lang[:3] == "PAS" {870 prog = progfilepath + "prog.pas"871 } else if lang[:3] == "C++" {872 prog = progfilepath + "prog.cpp"873 }874875 // beego.Info(prog)876877 proguser := readFile(progfilepath + "user.txt")878879 progname := readFile(progfilepath + "prob.txt")880881 progip := readFile(progfilepath + "ip.txt")882883 fprog, err := os.OpenFile(prog, os.O_RDONLY, 0644)884 if err != nil {885 this.Data["IsError"] = true886 this.Data["ErrorMsg"] = "程序文件不存在!"887 return888 }889 defer fprog.Close()890891 var progcontent []byte892 progcontent, _ = ioutil.ReadAll(fprog)893894 this.Data["ProgUser"] = proguser895 this.Data["ProgName"] = progname896 this.Data["ProgIp"] = progip897 this.Data["ProgLang"] = lang898 this.Data["ProgId"] = progid899 this.Data["ProgContent"] = string(progcontent)900} ...

Full Screen

Full Screen

stat.go

Source:stat.go Github

copy

Full Screen

1package giashard2import (3 "compress/gzip"4 "bytes"5 "encoding/base64"6 "encoding/json"7 "errors"8 "io/ioutil"9 "log"10 "os"11 "path/filepath"12)13type LangStats struct {14 Lines map[string]int `json:"lines"`15 LinesPerDoc map[int]int `json:"linesperdoc"`16 TokensPerLine map[int]int `json:"tokensperline"`17}18type ShardStats struct {19 Shard string `json:"shard"`20 Bytes map[string]int64 `json:"bytes"`21 Records map[string]int `json:"records"`22 Native LangStats `json:"native"`23 English LangStats `json:"english"`24}25func (s *ShardStats)openfile(fname string) (ch chan []byte, err error) {26 s.Bytes[fname] = -127 s.Records[fname] = -128 fullpath := filepath.Join(s.Shard, fname)29 stat, err := os.Stat(fullpath)30 if err != nil {31 log.Printf("error reading %v", fullpath)32 return33 }34 s.Bytes[fname] = stat.Size()35 r, err := NewLineReader(fullpath)36 if err != nil {37 return38 }39 r.Fatal(false)40 41 ch = make(chan []byte)42 go func() {43 for doc := range r.Lines() {44 s.Records[fname] += 145 ch <- doc46 }47 close(ch)48 r.Close()49 }()50 return51}52func getLines(doc []byte) (lines [][]byte, err error) {53 buf := make([]byte, base64.StdEncoding.DecodedLen(len(doc)))54 n, err := base64.StdEncoding.Decode(buf, doc)55 if err != nil {56 return57 }58 buf = buf[:n]59 lines = bytes.Split(buf, []byte("\n"))60 return61}62func (ls LangStats)countLines(fname string, doc []byte) (lines [][]byte, err error) {63 lines, err = getLines(doc)64 if err != nil {65 return66 }67 n, _ := ls.Lines[fname]68 ls.Lines[fname] = n + len(lines)69 bucket := 5 * int(len(lines) / 5)70 p, _ := ls.LinesPerDoc[bucket]71 ls.LinesPerDoc[bucket] = p + 172 return73}74func (ls LangStats)countTokens(fname string, doc []byte) (lines [][]byte, err error) {75 lines, err = getLines(doc)76 if err != nil {77 return78 }79 n, _ := ls.Lines[fname]80 ls.Lines[fname] = n + len(lines)81 for _, line := range lines {82 toks := bytes.Split(line, []byte(" "))83 n, _ := ls.TokensPerLine[len(toks)]84 ls.TokensPerLine[len(toks)] = n + 185 }86 return87}88func NewStats(shard string) *ShardStats {89 s := ShardStats{}90 s.Shard = shard91 s.Bytes = make(map[string]int64)92 s.Records = make(map[string]int)93 s.Native.Lines = make(map[string]int)94 s.Native.LinesPerDoc = make(map[int]int)95 s.Native.TokensPerLine = make(map[int]int)96 s.English.Lines = make(map[string]int)97 s.English.LinesPerDoc = make(map[int]int)98 s.English.TokensPerLine = make(map[int]int)99 return &s100}101func ReadStats(shard string) (stats *ShardStats, err error) {102 fp, err := os.Open(filepath.Join(shard, "stats.json.gz"))103 if err != nil {104 return105 }106 defer fp.Close()107 r, err := gzip.NewReader(fp)108 if err != nil {109 return110 }111 defer r.Close()112 buf, err := ioutil.ReadAll(r)113 if err != nil {114 return115 }116 s := ShardStats{}117 err = json.Unmarshal(buf, &s)118 if err != nil {119 return120 }121 stats = &s122 return123}124func (s *ShardStats)Calc() {125 lines, err := s.openfile("mime.gz")126 if err == nil {127 for _ = range lines {128 //129 }130 }131 lines, err = s.openfile("source.gz")132 if err == nil {133 for _ = range lines {134 //135 }136 }137 lines, err = s.openfile("url.gz")138 if err == nil {139 for _ = range lines {140 //141 }142 }143 docs, err := s.openfile("plain_text.gz")144 if err == nil {145 for _ = range docs {146 //147 }148 }149 docs, err = s.openfile("sentences.gz")150 if err == nil {151 for doc := range docs {152 s.Native.countLines("sentences.gz", doc)153 }154 }155 docs, err = s.openfile("tokenised.gz")156 if err == nil {157 for doc := range docs {158 s.Native.countTokens("tokenised.gz", doc)159 }160 }161 docs, err = s.openfile("sentences_en.gz")162 if err == nil {163 for doc := range docs {164 s.English.countLines("sentences_en.gz", doc)165 }166 }167 docs, err = s.openfile("tokenised_en.gz")168 if err == nil {169 for doc := range docs {170 s.English.countTokens("tokenised_en.gz", doc)171 }172 }173}174func (s *ShardStats)Marshal() (buf []byte, err error) {175 return json.Marshal(s)176}177func (s *ShardStats)Write() (err error) {178 buf, err := s.Marshal()179 if err != nil {180 return181 }182 fullpath := filepath.Join(s.Shard, "stats.json.gz")183 fp, err := os.Create(fullpath)184 if err != nil {185 return186 }187 defer fp.Close()188 w, err := gzip.NewWriterLevel(fp, gzip.BestCompression)189 if err != nil {190 return191 }192 defer w.Close()193 w.Comment = "Written by giashard"194 n, err := w.Write(buf)195 if err == nil && n != len(buf) {196 err = errors.New("ShardStats.Save(): short write")197 }198 return199}...

Full Screen

Full Screen

stream-server.go

Source:stream-server.go Github

copy

Full Screen

1package main2import (3 "io"4 "io/ioutil"5 "log"6 "math/rand"7 "net/http"8 "os"9 // "strconv"10 "time"11 "github.com/nubunto/tts"12)13var chars = []rune("abcdefghijklmnopqrstuvwxyz0123456789")14func generateSessionID() string {15 id := make([]rune, 6)16 for i := range id {17 id[i] = chars[rand.Intn(len(chars))]18 }19 return string(id)20}21func speechText(text string, lang string) string {22 log.Printf("INFO: Speech text: " + text)23 s, err := tts.Speak(tts.Config{24 Speak: text,25 Language: lang,26 })27 if err != nil {28 log.Fatal(err)29 }30 now := time.Now()31 filename := now.Format("2006-01-02_") + generateSessionID() + ".mp3"32 err = ioutil.WriteFile("output/" + filename, s.Bytes(), os.ModePerm)33 if err != nil {34 log.Fatal(err)35 }36 return filename37}38func main() {39 log.Printf("INFO: Starting http stream server")40 http.HandleFunc("/", HandleClient)41 err := http.ListenAndServe(GetPort(), nil)42 if err != nil {43 log.Fatal(err)44 }45}46func GetPort() string {47 var port = os.Getenv("PORT")48 if port == "" {49 port = "4747"50 log.Printf("INFO: No PORT environment variable detected, defaulting to " + port)51 }52 return ":" + port53}54func HandleClient(writer http.ResponseWriter, request *http.Request) {55 text := request.URL.Query().Get("text")56 if text == "" {57 defaultMusic(writer, request)58 return59 }60 lang := request.URL.Query().Get("lang")61 if lang == "" {62 lang = "en"63 }64 c := make(chan string)65 go func() {66 c <- speechText(text, lang)67 }()68 var result string69 result = <-c70 Openfile, err := os.Open("output/" + result)71 defer Openfile.Close() // Close after function return72 if err != nil {73 http.Error(writer, "File not found.", 404)74 return75 }76 // Get the Content-Type of the file77 // Create a buffer to store the header of the file in78 FileHeader := make([]byte, 512)79 // Copy the headers into the FileHeader buffer80 Openfile.Read(FileHeader)81 // Get the file size82 // FileStat, _ := Openfile.Stat() // Get info from file83 // FileSize := strconv.FormatInt(FileStat.Size(), 10) // Get file size as a string84 // Send the headers85 // writer.Header().Set("Content-Length", FileSize)86 writer.Header().Set("Content-Type", "video/mp4")87 writer.Header().Set("Content-Type", "video/mpeg")88 writer.Header().Set("Content-Type", "application/octet-stream")89 writer.Header().Set("Content-Disposition", "inline")90 // Send the file91 // We read 512 bytes from the file already so we reset the offset back to 092 Openfile.Seek(0, 0)93 // 'Copy' the file to the client94 _, err = io.Copy(writer, Openfile)95 if err != nil {96 log.Print(err)97 }98}99func defaultMusic(writer http.ResponseWriter, request *http.Request) {100 // Check if file exists and open101 Openfile, err := os.Open("iloveyou.mp3")102 defer Openfile.Close() // Close after function return103 if err != nil {104 http.Error(writer, "File not found.", 404)105 return106 }107 // Get the Content-Type of the file108 // Create a buffer to store the header of the file in109 FileHeader := make([]byte, 512)110 // Copy the headers into the FileHeader buffer111 Openfile.Read(FileHeader)112 // Get the file size113 // FileStat, _ := Openfile.Stat() // Get info from file114 // FileSize := strconv.FormatInt(FileStat.Size(), 10) // Get file size as a string115 // Send the headers116 // writer.Header().Set("Content-Length", FileSize)117 writer.Header().Set("Content-Type", "video/mp4")118 writer.Header().Set("Content-Type", "video/mpeg")119 writer.Header().Set("Content-Type", "application/octet-stream")120 writer.Header().Set("Content-Disposition", "inline")121 // Send the file122 // We read 512 bytes from the file already so we reset the offset back to 0123 for {124 Openfile.Seek(0, 0)125 // 'Copy' the file to the client126 _, err = io.Copy(writer, Openfile)127 if err != nil {128 log.Print(err)129 return130 }131 log.Printf("INFO: Finish once")132 }133 return134}...

Full Screen

Full Screen

openFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f, err := os.OpenFile("test.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)4 if err != nil {5 fmt.Println(err)6 }7 defer f.Close()8 if _, err := f.WriteString("hello world9"); err != nil {10 fmt.Println(err)11 }12}

Full Screen

Full Screen

openFile

Using AI Code Generation

copy

Full Screen

1func main() {2 file, err := os.Open("1.txt")3 if err != nil {4 log.Fatal(err)5 }6 defer file.Close()7 scanner := bufio.NewScanner(file)8 for scanner.Scan() {9 fmt.Println(scanner.Text())10 }11 if err := scanner.Err(); err != nil {12 log.Fatal(err)13 }14}15func main() {16 b, err := ioutil.ReadFile("1.txt")17 if err != nil {18 fmt.Print(err)19 }20 str := string(b)21 fmt.Println(str)22}23func main() {24 file, err := os.Open("1.txt")25 if err != nil {26 fmt.Println(err)27 }28 defer file.Close()29 reader := bufio.NewReader(file)30 for {31 line, err := reader.ReadString('32 if err != nil {33 }34 fmt.Print(line)35 }36}37func main() {38 file, err := os.Open("1.txt")39 if err != nil {40 fmt.Println(err)41 }42 defer file.Close()43 reader := bufio.NewReader(file)44 for {45 line, _, err := reader.ReadLine()46 if err != nil {47 }48 fmt.Println(string(line))49 }50}51func main() {52 file, err := os.Open("1.txt")53 if err != nil {54 fmt.Println(err)55 }56 defer file.Close()57 reader := bufio.NewReader(file)58 for {59 line, _, err := reader.ReadLine()60 if err != nil {61 }62 fmt.Println(string(line))63 }64}65func main() {66 file, err := os.Open("1.txt")67 if err != nil {68 fmt.Println(err)69 }70 defer file.Close()71 reader := bufio.NewReader(file)72 for {73 line, _, err := reader.ReadLine()74 if err != nil {75 }76 fmt.Println(string(line))77 }78}

Full Screen

Full Screen

openFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0644)4 if err != nil {5 panic(err)6 }7 defer file.Close()8 if _, err = file.WriteString(text); err != nil {9 panic(err)10 }11}12import (13func main() {14 file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0644)15 if err != nil {16 panic(err)17 }18 defer file.Close()19 if _, err = file.WriteString(text); err != nil {20 panic(err)21 }22}23import (24func main() {25 file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0644)26 if err != nil {27 panic(err)28 }29 defer file.Close()30 if _, err = file.WriteString(text); err != nil {31 panic(err)32 }33}34import (35func main() {36 file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0644)37 if err != nil {38 panic(err)39 }40 defer file.Close()41 if _, err = file.WriteString(text); err != nil {42 panic(err)43 }44}45import (46func main() {47 file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0644)48 if err != nil {49 panic(err)50 }

Full Screen

Full Screen

openFile

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "os"3func main() {4 file, err := os.Open("1.go")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(file)9}10&{0xc0000a2000}11&{0xc0000a2000}

Full Screen

Full Screen

openFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := os.OpenFile("test.txt", os.O_CREATE|os.O_WRONLY, 0644)4 if err != nil {5 fmt.Println("Error creating file:", err)6 }7 defer file.Close()8 _, err = file.WriteString("Hello World!")9 if err != nil {10 fmt.Println("Error writing to file:", err)11 }12 err = file.Sync()13 if err != nil {14 fmt.Println(err)15 }16 fmt.Println("File created and contents written to file!")17}18import (19func main() {20 file, err := os.OpenFile("test.txt", os.O_RDONLY, 0644)21 if err != nil {22 fmt.Println("Error opening file:", err)23 }24 defer file.Close()25 stat, err := file.Stat()26 if err != nil {27 fmt.Println(err)28 }29 bs := make([]byte, stat.Size())30 _, err = file.Read(bs)31 if err != nil {32 fmt.Println(err)33 }34 str := string(bs)35 fmt.Println(str)36}37import (38func main() {39 file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0644)40 if err != nil {41 fmt.Println("Error opening file:", err)42 }43 defer file.Close()44 _, err = file.WriteString(" How are you?")45 if err != nil {46 fmt.Println("Error writing to file:", err)47 }

Full Screen

Full Screen

openFile

Using AI Code Generation

copy

Full Screen

1import java.io.*;2{3public static void main(String args[]) throws IOException4{5File f = new File("C:\\Users\\abc\\Desktop\\java\\java\\1.txt");6FileWriter fw = new FileWriter(f);7BufferedWriter bw = new BufferedWriter(fw);8bw.write("hello world");9bw.close();10}11}12import java.io.*;13{14public static void main(String args[]) throws IOException15{16File f = new File("C:\\Users\\abc\\Desktop\\java\\java\\1.txt");17FileWriter fw = new FileWriter(f);18BufferedWriter bw = new BufferedWriter(fw);19bw.write("hello world");20bw.newLine();21bw.write("welcome to java");22bw.close();23}24}25import java.io.*;26{27public static void main(String args[]) throws IOException28{29File f = new File("C:\\Users\\abc\\Desktop\\java\\java\\1.txt");30FileWriter fw = new FileWriter(f);31BufferedWriter bw = new BufferedWriter(fw);32bw.write("hello world");33bw.newLine();34bw.write("welcome to java");35bw.newLine();36bw.write("hello world");37bw.newLine()

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Gauge automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful