示例#1
0
func main() {

	var placeNames []string
	var placeName string

	color.Println("@M Note: @m Use an empty string to begin the war!")

	for i := 0; ; i++ {

		placeName = ""

		// Prompt the user to enter their place name.
		fmt.Printf("Place: ")
		fmt.Scanf("%s", &placeName)

		if len(placeName) == 0 {

			// We've got all of the places we need to begin the process of comparing
			// the weather!
			break

		}

		// Voila! We have another place name so let's add it to the array of strings for later.
		placeNames = append(placeNames, placeName)

	}

	// At this point we're ready to begin the whole process.
	color.Println("@gPreparing the war with " + strconv.Itoa(len(placeNames)) + " places...")

}
示例#2
0
文件: main.go 项目: hisayosh/isucon3
func showResult(r *BenchmarkResult) {
	if r.Score == 0.0 {
		color.Println("@{r}Result:   FAIL")
	} else {
		color.Println("@{g}Result:   SUCCESS")
	}
	fmt.Printf("RawScore: %.1f\n", r.RawScore)
	fmt.Printf("Fails:    %d\n", r.Fails)
	fmt.Printf("Score:    %.1f\n", r.Score)
}
示例#3
0
文件: main.go 项目: ashora/talk
func main() {
	reader := bufio.NewReader(os.Stdin)

	for {
		color.Print("@b>> ")
		words, _ := reader.ReadString('\n')
		text, err := request(strings.TrimSpace(words))
		if err != nil {
			color.Println("@rERROR : ", err)
		}

		color.Println("@r>> ", text)
	}

}
示例#4
0
func getFuncNames(filecontent []string) ([]string, []string) {
	r := make([]string, 0)
	r2 := make([]string, 0)
	var funcCounter int64
	functionRx := regexp.MustCompile(FUNCTION_NAME_REGEX)
	functionDefRx := regexp.MustCompile(FUNCTION_DEFINITION_REGEX)
	for lineno, line := range filecontent {
		if functionRx.MatchString(line) {
			funcnameB := functionRx.FindSubmatch([]byte(line))
			funcname := string(funcnameB[1])
			funcCounter = funcCounter + 1
			fmt.Printf("%v %d ", funcCounter, lineno)
			color.Print("@g", funcname)
			color.Println("@y|", line)
			r = append(r, funcname)

			if functionDefRx.MatchString(line) {
				funcdefB := functionDefRx.FindSubmatch([]byte(line))
				funcdef := string(funcdefB[1])
				r2 = append(r2, funcdef)
			} else {
				log.Fatal("Can detect the funciton name but not the function definition! That is not acceptable")
			}
		}
	}
	return r, r2
}
示例#5
0
// Display project details
// http://docs.gemnasium.apiary.io/#get-%2Fprojects%2F%7Bslug%7D
func (p *Project) Show() error {
	err := p.Fetch()
	if err != nil {
		return err
	}
	if config.RawFormat {
		return nil
	}

	color.Println(fmt.Sprintf("%s: %s\n", p.Name, utils.StatusDots(p.Color)))
	table := tablewriter.NewWriter(os.Stdout)
	table.SetRowLine(true)

	table.Append([]string{"Slug", p.Slug})
	table.Append([]string{"Description", p.Description})
	table.Append([]string{"Origin", p.Origin})
	table.Append([]string{"Private", strconv.FormatBool(p.Private)})
	table.Append([]string{"Monitored", strconv.FormatBool(p.Monitored)})
	if !p.Monitored {
		table.Append([]string{"Unmonitored reason", p.UnmonitoredReason})
	}

	table.Render()
	return nil
}
示例#6
0
文件: main.go 项目: hisayosh/isucon3
func register(newApiKey string) {
	if err := ioutil.WriteFile(apiKeyFile, []byte(newApiKey), 0600); err != nil {
		log.Fatal(err)
		os.Exit(1)
	}
	apiKey = newApiKey
	apiRes := callAPI("register", url.Values{"api_key": {newApiKey}})
	if !apiRes.Ok {
		if apiRes.StatusCode == http.StatusNotFound {
			color.Println(messageInvalidAPIKey)
		} else {
			color.Println(messageAPIError)
			color.Println(apiRes.Message)
		}
		os.Exit(1)
	}
	log.Printf("OK: %s", apiRes.Message)
}
示例#7
0
文件: jira.go 项目: johntdyer/jira
// uses color if availible
func smartPrintln(str string) (cnt int, err error) {
	pattern := regexp.MustCompile(`@.`)
	if useColor {
		cnt, err = color.Println(str)
	} else {
		rawStr := pattern.ReplaceAll([]byte(str), []byte(""))
		cnt, err = fmt.Println(string(rawStr))
	}
	return
}
示例#8
0
/**
* Central function for printing
 */
func print(level int, message string) {

	if !beenhere {
		startTime = time.Now()
		beenhere = true
	}

	if _level >= level {

		//
		// Escape newlines and carriage returns
		//
		message = strings.Replace(message, "\n", "\\n", -1)
		message = strings.Replace(message, "\r", "\\r", -1)

		//
		// Escape anything else that is below ASCII 32 (space)
		// This is done because backspace (ASCII 8) is especially evil,
		// as an attrack could inject backspaces to hide their tracks
		//
		re, _ := regexp.Compile("([\x00-\x1f])")
		message = re.ReplaceAllStringFunc(message, func(in string) string {
			return (fmt.Sprintf("[0x%x]", in))
		})

		//
		// If displayTime is uninitialized, default to true
		//
		if displayTime == 0 || displayTime == 2 {
			now := time.Now()
			elapsed := now.Sub(startTime)
			if UseColor() {
				color_string := getColor(level)
				color.Printf(color_string+"[%s] %s\n", elapsed, message)
			} else {
				fmt.Printf("[%s] %s\n", elapsed, message)
			}

		} else {
			if UseColor() {
				color_string := getColor(level)
				color.Println(color_string + message)
			} else {
				fmt.Println(message)
			}

		}

	}

} // End of print()
示例#9
0
文件: main.go 项目: hisayosh/isucon3
func initializeData(initScript string) {
	log.Printf("initialize data...\n")
	sh := []string{
		"#!/bin/sh",
		"set -e",
		"cd " + initialDataDir,
		"md5sum -c checksum",
		"pigz -dc init.sql.gz | mysql -uisucon isucon",
	}
	defer os.Remove(initialLoader)
	if err := ioutil.WriteFile(initialLoader, []byte(strings.Join(sh, "\n")), 0700); err != nil {
		color.Println(fmt.Sprintf("%s %v", messageInitFailed, err))
		os.Exit(1)
	}
	checksum := initialDataDir + "/checksum"
	defer os.Remove(checksum)
	if err := ioutil.WriteFile(checksum, []byte(initialDataMD5), 0600); err != nil {
		color.Println(fmt.Sprintf("%s %v", messageInitFailed, err))
		os.Exit(1)
	}
	loader := exec.Command(initialLoader)
	if err := loader.Run(); err != nil {
		color.Println(fmt.Sprintf("%s %v", messageInitFailed, err))
		os.Exit(1)
	}
	if initScript == "" {
		return
	}

	log.Printf("run %s timeout %s sec...\n", initScript, userInitTimeout)
	userInit := exec.Command("timeout", userInitTimeout, initScript)
	if err := userInit.Run(); err != nil {
		color.Println(fmt.Sprintf("%s %v", messageUserInitFailed, err))
		os.Exit(1)
	}
	log.Println("done")
}
示例#10
0
// checkLocalPackages warns if there are local (pip or easy_install) versions of
// Python packages and returns how many were found.
func checkLocalPackages() int {
	localPkgs := findLocalPackages()
	if len(localPkgs) > 0 {
		for _, p := range localPkgs {
			warn("Found a local version of", p.name, "in", p.dir)
		}
		names := []string{}
		for _, p := range localPkgs {
			names = append(names, p.name)
		}
		cmd := ("@{c}while sudo pip uninstall " +
			strings.Join(names, " ") +
			"; do echo Continuing; done@{|}")
		color.Println("You may want to run", cmd)
	}
	return len(localPkgs)
}
示例#11
0
func (c *ListItemCommand) Run() error {

	// find category by title
	category := &models.Category{}
	if c.CategoryTitle != "" {
		err := category.FindByParams(map[string]interface{}{"title": c.CategoryTitle}).Error
		if err == nil {
			return errors.New("Undefine Category")
		}
	}

	// find all items
	items := []models.Item{}
	params := map[string]interface{}{"type": c.ItemType, "user_id": db.USERID}
	if category.Id != 0 {
		params["category_id"] = category.Id
	}
	db.Connection().Find(&items, params)

	// prepare table view
	data := [][]string{}
	for _, item := range items {
		data = append(data, []string{
			strconv.Itoa(item.Id), strconv.FormatFloat(item.Amount, 'f', 2, 64),
			item.GetCategoryTitle(), item.Comment,
		})
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Id", "Amount", "Category", "Comments"})
	table.SetAlignment(tablewriter.ALIGN_LEFT)
	for _, v := range data {
		table.Append(v)
	}

	// render table views
	color.Println("@gSpent items:")
	table.Render()
	return nil
}
示例#12
0
// Create a project config gile (.gemnasium.yml)
func (p *Project) Configure(slug string, r io.Reader, w io.Writer) error {
	if slug == "" {
		fmt.Printf("Enter project slug: ")
		_, err := fmt.Scanln(&slug)
		if err != nil {
			return err
		}
	}

	// We just create a file with project_config for now.
	projectConfig := &map[string]string{"project_slug": slug}
	body, err := yaml.Marshal(&projectConfig)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	// write content to the file
	_, err = w.Write(body)
	if err != nil {
		return err
	}
	color.Println("@gYour .gemnasium.yml was created!")
	return nil
}
示例#13
0
文件: main.go 项目: hisayosh/isucon3
func main() {
	rand.Seed(time.Now().UnixNano())
	runtime.GOMAXPROCS(runtime.NumCPU())
	if DEBUG {
		log.Println("<<<DEBUG build>>>")
		instanceType = "m3.xlarge"
		instanceId = "i-isucondebug"
		amiId = "ami-isucondebug"
		cpuInfo = "dummy"
	} else {
		instanceType = getMetaData("instance-type")
		instanceId = getMetaData("instance-id")
		amiId = getMetaData("ami-id")
		cpuInfo = getCpuInfo()
	}

	if instanceType != instanceTypeRequired {
		color.Printf(messageInvalidInstanceType, instanceTypeRequired, instanceType)
		os.Exit(1)
	}

	var newApiKey *string = flag.String("register", "", "register a new API key")
	flag.Parse()

	if *newApiKey != "" {
		register(*newApiKey)
		os.Exit(0)
	}
	apiKey = loadApiKey()
	if apiKey == "" {
		color.Println(messagePleaseRegister)
		os.Exit(1)
	}

	if len(flag.Args()) == 0 {
		showUsageAndExit()
	}
	command := flag.Args()[0]
	if command == "test" {
		var testWorkload *int = flag.Int("workload", 1, "benchmark workload")
		var testEndpoint *string = flag.String("endpoint", endpoint, "debugging endpoint")
		var testSeconds *int = flag.Int("seconds", 60, "running seconds")
		var accessLog *bool = flag.Bool("accesslog", false, "show access log")
		if DEBUG {
			os.Args = flag.Args()
			flag.Parse()
		}
		workload := *testWorkload
		endpoint = *testEndpoint
		seconds = *testSeconds
		bench.AccessLog = *accessLog
		log.Println("test mode")
		result := runBenchmark(workload)
		showResult(result)
	} else if command == "benchmark" {
		var workload *int = flag.Int("workload", 1, "benchmark workload")
		var initScript *string = flag.String("init", "", "init script")
		os.Args = flag.Args()
		flag.Parse()
		if *workload < 1 {
			*workload = 1
		}
		log.Println("benchmark mode")
		apiRes := callAPI("start", url.Values{})
		if !apiRes.Ok {
			color.Println(messageAPIError)
			os.Exit(1)
		}
		initializeData(*initScript)

		log.Printf("sleeping %d sec...", 5)
		time.Sleep(time.Duration(5) * time.Second)

		result := runBenchmark(*workload)
		showResult(result)
		if result.Score == 0.0 {
			os.Exit(0)
		}
		if DEBUG {
			os.Exit(0)
		}
		apiRes = callAPI("result", url.Values{
			"score":   {fmt.Sprintf("%.1f", result.Score)},
			"cpuinfo": {cpuInfo},
			"log":     {strings.Join(*result.Logs, "\n")},
		})
		if apiRes.Ok {
			color.Println(messageResultOk)
		} else {
			color.Println(messageAPIError)
			os.Exit(1)
		}
	} else {
		showUsageAndExit()
	}
}
示例#14
0
func main() {
	//originalFile := "./OriginalPlotClusters.m"
	//className := "PC"

	originalFile := "./OriginalAllVPCs.m"
	className := "AllV"

	b, err := ioutil.ReadFile(originalFile)
	if err != nil {
		log.Fatal("Cant read the original,", err)
	}

	lines := strings.Split(string(b), "\n")

	funcnames, funcdefs := getFuncNames(lines)
	//revese the funcnames, to reduce the change of collision, like a funcname being embded inside another function name
	funcnames = reversSortStringSlice(funcnames)

	//TODO: in all the function declaration lines, replace `=([A-z])` with '= \1'
	functionRx := regexp.MustCompile(FUNCTION_NAME_REGEX)

	var funcCounter int64
	//insidefunc := false
	//TODO: the assuption is the original file STARTS with a function declaration line, no comments of white space before it
	funclines := make([]string, 0)
	funcname := ""
	lineno := 0
	line := ""
	for lineno, line = range lines {
		if functionRx.MatchString(line) {
			if len(funclines) != 0 {
				patchedfunclines := renameFuncs(className, funclines, funcnames)
				color.Println("@rWriting: ", funcname)
				err = ioutil.WriteFile(funcname+".m", []byte(strings.Join(patchedfunclines, "")), os.ModePerm)
				if err != nil {
					log.Fatal("Error writing the file", err)
				}
				funclines = make([]string, 0)
			}
			funcnameB := functionRx.FindSubmatch([]byte(line))
			funcname = string(funcnameB[1])
			funcCounter = funcCounter + 1
			fmt.Printf("%v %d ", funcCounter, lineno)
			color.Print("@g", funcname)
			color.Println("@y|", line)
		}
		funclines = append(funclines, line)
	}
	//write the last function
	if len(funclines) != 0 {
		patchedfunclines := renameFuncs(className, funclines, funcnames)
		color.Println("@rWriting: ", funcname)
		err = ioutil.WriteFile(funcname+".m", []byte(strings.Join(patchedfunclines, "")), os.ModePerm)
		if err != nil {
			log.Fatal("Error writing the file", err)
		}
		funclines = make([]string, 0)
	}

	//TODO: do the main class def file
	classdeflines := ""
	classdeflines = classdeflines + "classdef " + className + "\r"
	classdeflines = classdeflines + `properties
        Version = '1'
    end
    methods (Static)        
`
	classdeflines = classdeflines + strings.Join(funcdefs, "\r")
	classdeflines = classdeflines + `

    end
end
`
	err = ioutil.WriteFile(className+".m", []byte(classdeflines), os.ModePerm)
	if err != nil {
		log.Fatal("Error writing the Classdefninition file", err)
	}
}
示例#15
0
func warn(args ...string) {
	color.Println("@{r}Warning@{|}:", strings.Join(args, " "))
}
示例#16
0
// Live evaluation of dependency files Several files can be sent, not only from
// the same language (ie: package.json + Gemfile + Gemfile.lock) LiveEvaluation
// will return 2 stases (color for Runtime / Dev.) and the list of deps with
// their color.
func LiveEvaluation(files []string) error {

	dfiles, err := models.LookupDependencyFiles(files)
	if err != nil {
		return err
	}

	requestDeps := map[string][]*models.DependencyFile{"dependency_files": dfiles}
	var jsonResp map[string]interface{}

	opts := &gemnasium.APIRequestOptions{
		Method: "POST",
		URI:    LIVE_EVAL_PATH,
		Body:   requestDeps,
		Result: &jsonResp,
	}
	err = gemnasium.APIRequest(opts)
	if err != nil {
		return err
	}

	// Wait until job is done
	url := fmt.Sprintf("%s%s/%s", config.APIEndpoint, LIVE_EVAL_PATH, jsonResp["job_id"])
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return err
	}
	req.SetBasicAuth("x", config.APIKey)
	req.Header.Add("Content-Type", "application/json")
	var response struct {
		Status string `json:"status"`
		Result struct {
			RuntimeStatus     string              `json:"runtime_status"`
			DevelopmentStatus string              `json:"development_status"`
			Dependencies      []models.Dependency `json:"dependencies"`
		} `json:"result"`
	}
	var iter int // used to display the little dots for each loop bellow
	client := &http.Client{}
	for {
		// use the same request again and again
		resp, err := client.Do(req)
		if err != nil {
			return err
		}
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}

		if resp.StatusCode != http.StatusOK {
			response.Status = "error"
		}

		if err = json.Unmarshal(body, &response); err != nil {
			return err
		}

		if !config.RawFormat { // don't display status if RawFormat
			iter += 1
			fmt.Printf("\rJob Status: %s%s", response.Status, strings.Repeat(".", iter))
		}
		if response.Status != "working" && response.Status != "queued" { // Job has completed or failed or whatever
			if config.RawFormat {
				fmt.Printf("%s\n", body)
				return nil
			}
			break
		}
		// Wait 1s before trying again
		time.Sleep(time.Second * 1)
	}

	color.Println(fmt.Sprintf("\n\n%-12.12s %s", "Run. Status", utils.StatusDots(response.Result.RuntimeStatus)))
	color.Println(fmt.Sprintf("%-12.12s %s\n\n", "Dev. Status", utils.StatusDots(response.Result.DevelopmentStatus)))

	// Display deps in an ascii table
	models.RenderDepsAsTable(response.Result.Dependencies, os.Stdout)

	if response.Result.RuntimeStatus == "red" {
		return fmt.Errorf("There are important updates available.\n")
	}

	return nil
}
示例#17
0
func ExitWithError(err error) {
	color.Println("@{r!}" + err.Error())
	os.Exit(1)
}