Esempio n. 1
0
func main() {

	Repo := [6]string{"https://github.com/EgeBalci/ARCANUS/blob/master/SOURCE/ARCANUS.go", "https://github.com/EgeBalci/ARCANUS/raw/master/ARCANUS_x64", "https://github.com/EgeBalci/ARCANUS/raw/master/ARCANUS_x64.exe", "https://github.com/EgeBalci/ARCANUS/raw/master/ARCANUS_x86", "https://github.com/EgeBalci/ARCANUS/raw/master/ARCANUS_x86.exe", "https://github.com/EgeBalci/ARCANUS/raw/master/README.md"}

	if runtime.GOOS == "windows" {
		exec.Command("cmd", "/C", "msg ARCANUS Update Started...").Run()
		exec.Command("cmd", "/C", "del ARCANUS.go").Run()
		exec.Command("cmd", "/C", "del ARCANUS_x64.exe").Run()
		exec.Command("cmd", "/C", "del ARCANUS_x86.exe").Run()
		exec.Command("cmd", "/C", "del ARCANUS_x64").Run()
		exec.Command("cmd", "/C", "del ARCANUS_x86").Run()
		color.Blue("[*] Updating ARCANUS...\n\n")
		for i := 0; i < len(Repo); i++ {
			response, _ := http.Get(Repo[i])
			defer response.Body.Close()
			body, _ := ioutil.ReadAll(response.Body)

			Name := strings.Split(Repo[i], "/")
			color.Green("#	" + string(Name[(len(Name)-1)]) + "		[OK]")
			file, _ := os.Create(string(Name[(len(Name) - 1)]))

			file.WriteString(string(body))
		}
		/*ARC, _ := exec.Command("cmd", "/C", "echo %PROCESSOR_ARCHITECTURE%").Output()
		if strings.Contains(string(ARC), "x86") || strings.Contains(string(ARC), "X86") {
			exec.Command("cmd", "/C", "ARCANUS_x86.exe").Start()
		}else if strings.Contains(string(ARC), "AMD64") {
			exec.Command("cmd", "/C", "ARCANUS_x64.exe").Start()
		}*/
		exec.Command("cmd", "/C", "msg * ARCANUS Updated Succesfuly !").Run()
	} else if runtime.GOOS == "linux" {
		exec.Command("sh", "-c", "zenity --info --text=\"ARCANUS Update Started... \"").Run()
		exec.Command("sh", "-c", "rm ARCANUS.go").Run()
		exec.Command("sh", "-c", "rm ARCANUS_x64.exe").Run()
		exec.Command("sh", "-c", "rm ARCANUS_x86.exe").Run()
		exec.Command("sh", "-c", "rm ARCANUS_x64").Run()
		exec.Command("sh", "-c", "rm ARCANUS_x86").Run()
		color.Blue("[*] Updating ARCANUS...\n\n")
		for i := 0; i < len(Repo); i++ {
			response, _ := http.Get(Repo[i])
			defer response.Body.Close()
			body, _ := ioutil.ReadAll(response.Body)

			Name := strings.Split(Repo[i], "/")
			color.Green("#	" + string(Name[(len(Name)-1)]) + "		[OK]")
			file, _ := os.Create(string(Name[(len(Name) - 1)]))

			file.WriteString(string(body))
		}
		exec.Command("sh", "-c", "zenity --info --text=\"ARCANUS Updated Succesfuly !\"").Run()
		/*ARC, _ := exec.Command("sh", "-c", "uname -a").Output()
		if strings.Contains(string(ARC), "x86") || strings.Contains(string(ARC), "X86") {
			exec.Command("sh", "-c", "./ARCANUS_x86").Start()
		}else if strings.Contains(string(ARC), "amd64") {
			exec.Command("sh", "-c", "./ARCANUS_x64").Start()
		}*/

	}

}
Esempio n. 2
0
func userInputFrequency(reader *bufio.Reader) time.Duration {
	color.Blue("Backup Frequency, use a short string like: 30m or 2h43m10s")
	color.Blue("Valid time units are: h, m, s")
	fmt.Println("")
	fmt.Print("Backup Every: ")
	text, _ := reader.ReadString('\n')
	text = strings.TrimSpace(text)
	d, err := time.ParseDuration(text)
	if err != nil {
		color.Red("Error parsing frequency, try again")
		return userInputFrequency(reader)
	}
	return d
}
Esempio n. 3
0
func main() {
	if all_ssh.ArgsInfo.IP != "" {
		color.Yellow("开始登录:%s\n", all_ssh.ArgsInfo.IP)
		var v all_ssh.ConnetctionInfo
		for _, v = range all_ssh.ServerList {
			if v.IP == all_ssh.ArgsInfo.IP {
				break
			}
		}
		v.IP = all_ssh.ArgsInfo.IP
		client := all_ssh.Connection(v)
		if client == nil {
			return
		}
		err := all_ssh.TtyClient(client)
		if err != nil {
			println(err.Error())
		}
		if len(all_ssh.ErrorList) >= 1 {
			color.Red(all_ssh.ErrorList[0])
		}
		return
	}
	if all_ssh.ArgsInfo.File != "" {
		copyfile()
		return
	}
	if all_ssh.ArgsInfo.Cmd != "" {
		runcmd()
		return
	}
	color.Blue("使用%s -h查看帮助.\n", os.Args[0])
}
Esempio n. 4
0
func copyfile() {
	color.Yellow("开始执行文件发送:")
	info, err := os.Lstat(all_ssh.ArgsInfo.File)
	if err != nil || info.IsDir() {
		color.Blue("检查要发送的文件.")
		return
	}
	for _, v := range all_ssh.ServerList {
		go func() {
			client := all_ssh.Connection(v)
			if client != nil {
				all_ssh.CopyFile(client, all_ssh.ArgsInfo.File, all_ssh.ArgsInfo.Dir)
			}
		}()
	}
	var num int
	var Over chan os.Signal = make(chan os.Signal, 1)
	go signal.Notify(Over, os.Interrupt, os.Kill)
	go result(&num, Over)
	<-Over
	color.Yellow("一共有%d条错误.\n", len(all_ssh.ErrorList))
	for _, v := range all_ssh.ErrorList {
		color.Red(v)
	}
	color.Red("收到结果:%d条\n", num)
}
Esempio n. 5
0
File: main.go Progetto: jordic/tenv
// TEST="asdf,asdf,asdf" ./main template.tpl
func main() {

	if len(os.Args) != 2 {
		color.Red("tenv: v.01")
		color.Blue("------------------------")
		color.Cyan("Prepopulates to stdin given template with information stored in env variables")
		color.Cyan("variables should follow go template syntax {{.VAR_NAME}}")
		color.Cyan("and must be declared on the environment")
		color.Cyan("Usage : tenv filename")
		os.Exit(1)
	}
	var funcMap template.FuncMap
	funcMap = template.FuncMap{
		"split": strings.Split,
	}

	file := filepath.Base(os.Args[1])

	t, err := template.New(file).Funcs(funcMap).ParseFiles(os.Args[1])
	if err != nil {
		log.Fatalf("Error: %s", err)
	}

	context := make(map[string]string)
	for _, v := range os.Environ() {
		p := strings.Split(v, "=")
		context[p[0]] = p[1]
	}

	err = t.ExecuteTemplate(os.Stdout, file, context)
	if err != nil {
		log.Fatal(err)
	}

}
Esempio n. 6
0
func main() {
	checkArgs()
	url := os.Args[1]
	directory := os.Args[2]

	r, err := git.NewFilesystemRepository(directory)
	checkIfError(err)

	// Clone the given repository, using depth we create a shallow clone :
	// > git clone <url> --depth 1
	color.Blue("git clone %s --depth 1 %s", url, directory)

	err = r.Clone(&git.CloneOptions{
		URL: url,
	})
	checkIfError(err)

	// ... retrieving the branch being pointed by HEAD
	ref, err := r.Head()
	checkIfError(err)
	// ... retrieving the commit object
	commit, err := r.Commit(ref.Hash())
	checkIfError(err)

	fmt.Println(commit)
	os.Exit(0)

	// ... we get all the files from the commit
	files, err := commit.Files()
	checkIfError(err)

	// ... now we iterate the files to save to disk
	err = files.ForEach(func(f *git.File) error {
		abs := filepath.Join(directory, f.Name)
		dir := filepath.Dir(abs)

		os.MkdirAll(dir, 0777)
		file, err := os.Create(abs)
		if err != nil {
			return err
		}

		defer file.Close()
		r, err := f.Reader()
		if err != nil {
			return err
		}

		defer r.Close()

		if err := file.Chmod(f.Mode); err != nil {
			return err
		}

		_, err = io.Copy(file, r)
		return err
	})
	checkIfError(err)
}
Esempio n. 7
0
func main() {
	r, _ := git.NewFilesystemRepository(".git")

	// Clone the given repository, creating the remote, the local branches
	// and fetching the objects, exactly as:
	// > git clone https://github.com/git-fixtures/basic.git
	color.Blue("git clone https://github.com/git-fixtures/basic.git")

	r.Clone(&git.CloneOptions{
		URL: "https://github.com/git-fixtures/basic.git",
	})

	// Getting the latest commit on the current branch
	// > git log -1
	color.Blue("git log -1")

	// ... retrieving the branch being pointed by HEAD
	ref, _ := r.Head()
	// ... retrieving the commit object
	commit, err := r.Commit(ref.Hash())
	fmt.Println(commit, err)

	// List the tree from HEAD
	// > git ls-tree -r HEAD
	color.Blue("git ls-tree -r HEAD")

	// ... retrieve the tree from the commit
	tree, _ := commit.Tree()
	// ... get the files iterator and print the file
	tree.Files().ForEach(func(f *git.File) error {
		fmt.Printf("100644 blob %s    %s\n", f.Hash, f.Name)
		return nil
	})

	// List the history of the repository
	// > git log --oneline
	color.Blue("git log --oneline")

	commits, _ := commit.History()
	for _, c := range commits {
		hash := c.Hash.String()
		line := strings.Split(c.Message, "\n")
		fmt.Println(hash[:7], line[0])
	}

}
Esempio n. 8
0
func clone(r *git.Repository, url string) {
	// Clone the given repository, all the objects, references and
	// configuration sush as remotes, are save into the Aerospike database.
	// > git clone <url>
	color.Blue("git clone %s", url)
	err := r.Clone(&git.CloneOptions{URL: url})
	checkIfError(err)
}
Esempio n. 9
0
func userInputType(reader *bufio.Reader) string {
	color.Blue("Which type of backup destination would you like to add?")
	color.Blue("	1. Amazon (S3 or Glacier)")
	color.Blue("	2. Google Cloud")
	fmt.Println("")
	fmt.Print("Choose an option [1-2]: ")
	text, _ := reader.ReadString('\n')
	destType := strings.TrimSpace(text)
	switch destType {
	case "1":
		destType = "amazon"
	case "2":
		destType = "google"
	default:
		os.Exit(1)
	}
	return destType
}
Esempio n. 10
0
// verifyPlatform should in the future verify that your {arch, platform,
// os, etc.} match for the given file
func (lib Lib) verifyPlatform() bool {
	out, err := execShellCmd("strings " + lib.Fname + " | grep " + runtime.GOOS)
	if err != nil {
		log.Println(err)
	}

	color.Blue(string(out))

	return true
}
Esempio n. 11
0
func show(dict Dict) {
	for _, ps := range dict.Ps {
		color.Green(ps)
	}
	for index, pos := range dict.Pos {
		color.Red(strings.TrimSpace(pos))
		color.Yellow(strings.TrimSpace(dict.Acceptation[index]))
	}
	for _, sent := range dict.SentList {
		color.Blue("ex. %s", strings.TrimSpace(sent.Orig))
		color.Cyan("    %s", strings.TrimSpace(sent.Trans))
	}
}
Esempio n. 12
0
func main() {
	var configFileContents []byte
	var conf Config
	var changedFiles []string
	var tests []string
	var err error

	if configFileContents, err = ioutil.ReadFile("testdiff.toml"); err != nil {
		color.Red("Loading configuration failed!")
		return
	}

	if _, err := toml.Decode(string(configFileContents), &conf); err != nil {
		color.Red("Loading configuration failed!")
		return
	}

	color.Blue("Scanning for changed files...")
	if changedFiles, err = findChangedFiles(conf); err != nil {
		color.Red("Diffing failed!")
		return
	}

	color.Blue("Determining what tests to run...")
	if tests, err = determineTestsToExecute(conf, changedFiles); err != nil {
		color.Red("Test locating failed!")
		return
	}

	color.Blue("Executing tests.")
	if err = executeTests(conf, tests); err != nil {
		color.Red("Running tests failed!")
		return
	}

	color.Green("All done!")
}
Esempio n. 13
0
// This SIFT app will randomly alter any detected lights
func ghostInTheCircuits(server *sift.Server, minMS, maxMS int) {
	for {
		// Wait for a random amount of time
		<-time.After(randTime(minMS, maxMS))

		// Get all lights connected to the system
		lightsQuery := `
			SELECT c.name, c.device_id FROM component c
				JOIN device d ON c.device_id=d.id
				WHERE is_online=1 AND type=?`
		lights := []db.Component{}
		db, err := server.DB()
		if err != nil {
			color.Red("could not open DB: %v", err)
		}
		// run the query
		if err = db.Select(&lights, lightsQuery, types.LightEmitter{}.Type()); err != nil {
			color.Red("could not run query to get light ids: %v", err)
		}

		if len(lights) == 0 {
			color.Red("no lights found for the circuit ghosts to play with...")
		} else {
			// For each light found...
			for _, light := range lights {
				// ...assemble a component ID...
				lightID := types.ComponentID{
					Name:     light.Name,
					DeviceID: types.DeviceID(light.DeviceID),
				}

				// ...generate a random brightness value (0-100)...
				randBrightness := uint8(rand.Intn(100))

				// ...then create and submit an intent
				newLightIntent := types.SetLightEmitterIntent{
					BrightnessInPercent: randBrightness,
				}
				if err := server.EnactIntent(lightID, newLightIntent); err != nil {
					color.Red("could not enact intent: %v", err)
				} else {
					color.Blue("set light %v to %v", lightID, randBrightness)
				}
			}
		}
	}
}
Esempio n. 14
0
// main starts a sift server and listens for updates, printing any to console.
func repeatUpdatesToConsole(server *sift.Server) {
	myToken := server.Login()
	updateChan := server.Listen(myToken) // without specifying filters, this will listen to everything

	fmt.Println("listening to SIFT server and printing updates to console...")
	for {
		update := <-updateChan //TODO: uncaught panic if updateChan is closed
		switch typed := update.(type) {
		case notif.ComponentNotification:
			color.Blue("component %+v %v: %+v\n", typed.ID, typed.Action, typed.Component)
		//case notif.DriverNotification:
		//	fmt.Printf("driver %v: %v", typed.NotificationType, typed.Component)
		default:
			color.Red("unhandled update type from updateChan: %T (%v)\n", update, update)
		}
	}
}
Esempio n. 15
0
func runDelete(args []string) {
	config := stash.NewConfig()
	reader := bufio.NewReader(os.Stdin)
	color.Red("WARNING! Deleted entries cannot be recovered")
	color.Blue("Please choose one of the following entries: ")
	for _, entry := range config.Entries {
		color.Magenta("	%s", entry.Name)
	}
	fmt.Println()
	fmt.Print("Entry to delete (case-sensitive): ")
	text, _ := reader.ReadString('\n')
	text = strings.TrimSpace(text)
	err := config.DeleteEntry(text)
	if err != nil {
		color.Red("Fatal error deleting an entry: %s", err)
		os.Exit(1)
	}
}
Esempio n. 16
0
func main() {
	// Create a new repository
	color.Blue("git init")
	r := git.NewMemoryRepository()

	// Add a new remote, with the default fetch refspec
	// > git remote add example https://github.com/git-fixtures/basic.git
	color.Blue("git remote add example https://github.com/git-fixtures/basic.git")

	r.CreateRemote(&config.RemoteConfig{
		Name: "example",
		URL:  "https://github.com/git-fixtures/basic.git",
	})

	// List remotes from a repository
	// > git remotes -v
	color.Blue("git remotes -v")

	list, _ := r.Remotes()
	for _, r := range list {
		fmt.Println(r)
	}

	// Pull using the create repository
	// > git pull example
	color.Blue("git pull example")

	r.Pull(&git.PullOptions{
		RemoteName: "example",
	})

	// List the branches
	// > git show-ref
	color.Blue("git show-ref")

	refs, _ := r.Refs()
	refs.ForEach(func(ref *plumbing.Reference) error {
		// The HEAD is ommitted in a `git show-ref` so we ignore the symbolic
		// references, the HEAD
		if ref.Type() == plumbing.SymbolicReference {
			return nil
		}

		fmt.Println(ref)
		return nil
	})

	// Delete the example remote
	// > git remote rm example
	color.Blue("git remote rm example")
	r.DeleteRemote("example")
}
Esempio n. 17
0
func strike_create(c *cli.Context) error {
	url := c.GlobalString("url")
	if url == "" {
		return cli.NewExitError("A URL must be provided with the SCALE_URL environment variable or the --url argument", 1)
	}
	data_file := c.String("data")
	var strike_data scalecli.StrikeData
	err := Parse_json_or_yaml(data_file, &strike_data)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	strike_process_id, err := scalecli.CreateStrikeProcess(url, strike_data)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	color.Blue(fmt.Sprintf("Strike process %d created.", strike_process_id))
	return nil
}
Esempio n. 18
0
func log(r *git.Repository) {
	// Prints the history of the repository starting in the current HEAD, the
	// objects are retrieved from Aerospike database.
	// > git log --oneline
	color.Blue("git log --oneline")

	ref, err := r.Head()
	checkIfError(err)
	commit, err := r.Commit(ref.Hash())
	checkIfError(err)
	commits, err := commit.History()
	checkIfError(err)

	for _, c := range commits {
		hash := c.Hash.String()
		line := strings.Split(c.Message, "\n")
		fmt.Println(hash[:7], line[0])
	}
}
Esempio n. 19
0
func printIssueDetails(body []byte) {
	issue := Issue{}
	err := json.Unmarshal(body, &issue)
	if err != nil {
		color.Red(err.Error())
		return
	}

	if issue.Title != "" {
		color.Green("[ #" + issue.Path() + "] " + issue.Title)
		fmt.Println(issue.Body)
		color.Blue(issue.URL)
		fmt.Println(issue.Status)
	} else {
		err := Error{}
		json.Unmarshal(body, &err)
		color.Red("ERROR: " + err.Message)

	}
}
Esempio n. 20
0
func CloseChildren(cfg Config) {
	parent := GetBug(strconv.Itoa(cfg.Bugzilla.Parent), cfg)
	if parent.Id == cfg.Bugzilla.Parent {
		for _, alias := range cfg.Bugzilla.Child {
			child := GetBug(alias, cfg)
			if child.Alias == alias {
				fmt.Printf("bug %v found for %v\n", child.Id, child.Alias)
				if ContainsInt(cfg.Bugzilla.Parent, child.DependsOn) {
					color.Blue(" - is linked to parent %v", cfg.Bugzilla.Parent)
					if child.IsOpen {
						if Resolve(parent.Id, child.Id, fmt.Sprint("deallocated from bug ", parent.Id), cfg) {
							color.Green(" - resolved %v (%v) and deallocated from parent %v", child.Id, child.Alias, parent.Id)
						}
					}
				} else {
					color.Yellow(" - not linked to parent %v", cfg.Bugzilla.Parent)
				}
			}
		}
	}
}
// Usage: giphy-to-clipboard url
// url should be a resource at i.giphy.com, though theoretically this program
// can copy an arbitrary resource into a file named giphy.gif. This is probably
// insecure and most likely should be avoided
func main() {
	flag.Parse()
	args := flag.Args()
	if len(args) == 0 {
		color.Blue("Usage: giphy-to-clipboard <giphy url>")
		return
	}
	url := args[0]
	_, err := downloadFromFile(url)
	if err != nil {
		color.Red(fmt.Sprintf("Error copying %s", url))
		return
	}
	fmt.Println("Copying", url, " to clipboard")
	err = copyToClipboard()
	if err != nil {
		errString := fmt.Sprintf("Copying %s, to clipboard failed. Encountered error: %s", url, err)
		color.Red(errString)
		return
	}
	color.Green("Your GIF has been copied!")
}
Esempio n. 22
0
func colorLineDiff(a, b string) {
	aLines := strings.Split(a, "\n")
	bLines := strings.Split(b, "\n")

	fmt.Print("Overlapping portion of reassembled TCP Stream:\n")
	for i := 0; i < len(aLines); i++ {
		if aLines[i] == bLines[i] {
			color.Blue(aLines[i])
		} else {
			color.Green(aLines[i])
		}
	}

	fmt.Print("Injection packet whose contents did not coalesce into the TCP Stream:\n")
	for i := 0; i < len(aLines); i++ {
		if aLines[i] == bLines[i] {
			color.Cyan(bLines[i])
		} else {
			color.Red(bLines[i])
		}
	}

}
Esempio n. 23
0
func OpenChildren(cfg Config) {
	parent := GetBug(strconv.Itoa(cfg.Bugzilla.Parent), cfg)
	if parent.Id == cfg.Bugzilla.Parent {
		for _, alias := range cfg.Bugzilla.Child {
			child := GetBug(alias, cfg)
			if child.Alias == alias {
				fmt.Printf("bug %v found for %v\n", child.Id, child.Alias)
				if ContainsInt(cfg.Bugzilla.Parent, child.DependsOn) {
					color.Blue(" - is linked to parent %v", cfg.Bugzilla.Parent)
				} else {
					color.Yellow(" - not linked to parent %v", cfg.Bugzilla.Parent)
				}
				if !child.IsOpen {
					if SetDepends(parent.Id, child.Id, fmt.Sprint("allocated to bug ", parent.Id), cfg) {
						color.Green(" - reopened %v (%v) and linked to parent %v", child.Id, child.Alias, parent.Id)
					}
				}
			} else {
				color.Yellow("no bug found for %v", alias)
				//todo: create the bug
			}
		}
	}
}
Esempio n. 24
0
func printIssuesList(body []byte) error {
	issues := Issues{}
	err := json.Unmarshal(body, &issues)
	if err != nil {
		return err
	}

	prev := ""
	for _, issue := range issues {
		if issue.Repo != prev {
			repo := strings.Replace(issue.Repo, "\n", "", 1)
			if prev != "" {
				fmt.Println("\n")
			}
			color.Blue("\nRepo: " + issue.Owner + "/" + repo + ":")
			prev = issue.Repo
		}
		title := color.YellowString(issue.Title)
		fmt.Printf("\n - " + title + " - [#" + issue.Path() + "]")
	}
	fmt.Printf("\n\n")

	return nil
}
Esempio n. 25
0
func (j GroupsImport) Run() {
	start := time.Now()
	fmt.Println("------------------------------")
	fmt.Printf("| Starting import at %s\n", start.Format("2006-01-02 15:04:05.000"))
	db := controllers.Gdb
	file := OpenExcelFile("/home/kolan/Documents/ONR_FITIS.xlsx")
	fmt.Println("------------------------------")

	rowCount := 0
	successCount := 0
	alreadyExist := 0
	wrongYear := 0
	wrongNumberOfStudents := 0

	for _, row := range file.Sheets[1].Rows[10:] {
		group := models.Groups{}

		re := regexp.MustCompile("[^\\S]+")
		re2 := regexp.MustCompile("([^\x00-\x7F])i")
		re3 := regexp.MustCompile("i([^\x00-\x7F])")

		groupYear, err := strconv.Atoi(strings.TrimSpace(row.Cells[7].Value))
		if err != nil {
			group.Year = 0
			wrongYear += 1
		} else {
			group.Year = groupYear
		}

		groupName := strings.TrimSpace(row.Cells[27].Value)
		groupName = re.ReplaceAllString(groupName, " ")
		groupName = re2.ReplaceAllString(groupName, "${1}і")
		groupName = re3.ReplaceAllString(groupName, "i${1}")
		group.Name = groupName

		groupStudents, err := strconv.Atoi(strings.TrimSpace(row.Cells[11].Value))
		if err != nil {
			group.NumOfStudents = 0
			wrongNumberOfStudents += 1
		} else {
			group.NumOfStudents = groupStudents
		}

		group.FacultyId = 1

		result := db.Where(&group).First(&group)

		if result.Error != nil {
			if result.RecordNotFound() {
				db.NewRecord(group)
				err = db.Save(&group).Error
				if err != nil {
					if regexp.MustCompile(`^Error 1062:`).MatchString(err.Error()) == true {
						alreadyExist += 1
						color.Cyan("| \"%s\" - is already exist", groupName)
					} else {
						color.Red("| Saving error for - \"%s\"", groupName)
					}
				} else {
					successCount += 1
					color.Green("| \"%s\" - added", groupName)
				}
			}
		} else {
			alreadyExist += 1
			color.Cyan("| \"%s\" - is already exist", groupName)
		}

		rowCount += 1
	}
	elapsed := time.Since(start)
	fmt.Println("------------------------------")
	fmt.Printf("| Import finished at %s\n", time.Now().Format("2006-01-02 15:04:05.000"))
	fmt.Printf("| Importing time %s\n", elapsed)
	color.Blue("------------------------------------------")
	color.Blue("| Groups in file                  : %d", rowCount)
	color.Blue("| Imported groups                 : %d", successCount)
	color.Blue("| Already exist groups            : %d", alreadyExist)
	color.Blue("| Groups without year             : %d", wrongYear)
	color.Blue("| Groups without students count   : %d", wrongNumberOfStudents)
	color.Blue("------------------------------------------")
}
Esempio n. 26
0
func (j SubjectsImport) Run() {
	start := time.Now()
	fmt.Println("------------------------------")
	fmt.Printf("| Starting import at %s\n", start.Format("2006-01-02 15:04:05.000"))
	db := controllers.Gdb
	db.LogMode(false)
	file := OpenExcelFile("/home/kolan/Documents/ONR_FITIS.xlsx")
	fmt.Println("------------------------------")

	rowCount := 0
	successCount := 0
	alreadyExist := 0

	for _, row := range file.Sheets[1].Rows[10:] {
		var subject models.Subjects

		re := regexp.MustCompile("[^\\S]+")
		re2 := regexp.MustCompile("([^\x00-\x7F])i")
		re3 := regexp.MustCompile("i([^\x00-\x7F])")

		subjectName := strings.TrimSpace(row.Cells[1].Value)
		subjectName = re.ReplaceAllString(subjectName, " ")
		subjectName = re2.ReplaceAllString(subjectName, "${1}і")
		subjectName = re3.ReplaceAllString(subjectName, "i${1}")

		subject.Subject = subjectName

		result := db.Where(&subject).First(&subject)

		if result.Error != nil {
			if result.RecordNotFound() {
				db.NewRecord(subject)
				err := db.Save(&subject).Error
				if err != nil {
					if regexp.MustCompile(`^Error 1062:`).MatchString(err.Error()) == true {
						alreadyExist += 1
						color.Cyan("| \"%s\" - is already exist", subjectName)
					} else {
						color.Red("| Saving error for - \"%s\"", subjectName)
					}
				} else {
					successCount += 1
					color.Green("| \"%s\" - added", subjectName)
				}
			}
		} else {
			alreadyExist += 1
			color.Cyan("| \"%s\" - is already exist", subjectName)
		}

		rowCount += 1
	}
	elapsed := time.Since(start)
	fmt.Println("------------------------------")
	fmt.Printf("| Import finished at %s\n", time.Now().Format("2006-01-02 15:04:05.000"))
	fmt.Printf("| Importing time %s\n", elapsed)
	color.Blue("------------------------------")
	color.Blue("| Subjects in file          : %d", rowCount)
	color.Blue("| Imported subjects         : %d", successCount)
	color.Blue("| Already exist subjects    : %d", alreadyExist)
	color.Blue("------------------------------")
}
Esempio n. 27
0
func TestWebSocketProxy(t *testing.T) {
	color.Blue("====> Starting WebSocket test")
	conf := config.New()
	conf.Username = "******"
	conf.KontrolURL = "http://localhost:5555/kite"
	conf.KontrolKey = testkeys.Public
	conf.KontrolUser = "******"
	conf.KiteKey = testutil.NewKiteKey().Raw
	conf.ReadEnvironmentVariables()

	// start kontrol
	color.Green("Starting kontrol")
	kontrol.DefaultPort = 5555
	kon := kontrol.New(conf.Copy(), "0.1.0")

	switch os.Getenv("KONTROL_STORAGE") {
	case "etcd":
		kon.SetStorage(kontrol.NewEtcd(nil, kon.Kite.Log))
	case "postgres":
		p := kontrol.NewPostgres(nil, kon.Kite.Log)
		kon.SetStorage(p)
		kon.SetKeyPairStorage(p)
	default:
		kon.SetStorage(kontrol.NewEtcd(nil, kon.Kite.Log))
	}

	kon.AddKeyPair("", testkeys.Public, testkeys.Private)

	go kon.Run()
	<-kon.Kite.ServerReadyNotify()

	// start proxy
	color.Green("Starting Proxy and registering to Kontrol")
	proxyConf := conf.Copy()
	proxyConf.Port = 4999
	proxy := New(proxyConf)
	proxy.PublicHost = "localhost"
	proxy.PublicPort = proxyConf.Port
	proxy.Scheme = "http"
	go proxy.Run()
	<-proxy.ReadyNotify()

	proxyRegisterURL := &url.URL{
		Scheme: proxy.Scheme,
		Host:   proxy.PublicHost + ":" + strconv.Itoa(proxy.PublicPort),
		Path:   "/kite",
	}

	fmt.Printf("proxyRegisterURL %+v\n", proxyRegisterURL)

	_, err := proxy.Kite.Register(proxyRegisterURL)
	if err != nil {
		t.Error(err)
	}

	// start now backend kite
	color.Green("Starting BackendKite")
	backendKite := kite.New("backendKite", "1.0.0")
	backendKite.Config = conf.Copy()
	backendKite.HandleFunc("foo", func(r *kite.Request) (interface{}, error) {
		return "bar", nil
	})

	backendKite.Config.Port = 7777
	kiteUrl := &url.URL{Scheme: "http", Host: "localhost:7777", Path: "/kite"}

	go backendKite.Run()
	<-backendKite.ServerReadyNotify()

	// now search for a proxy from kontrol
	color.Green("BackendKite is searching proxy from kontrol")
	kites, err := backendKite.GetKites(&protocol.KontrolQuery{
		Username:    "******",
		Environment: config.DefaultConfig.Environment,
		Name:        Name,
	})
	if err != nil {
		t.Fatal(err)
	}

	proxyKite := kites[0]
	err = proxyKite.Dial()
	if err != nil {
		t.Fatal(err)
	}

	// backendKite is connected to proxy, now let us register to proxy and get
	// a proxy url. We send our url to proxy, it needs it in order to proxy us
	color.Green("Backendkite found proxy, now registering to it")
	result, err := proxyKite.TellWithTimeout("register", 4*time.Second, kiteUrl.String())
	if err != nil {
		t.Fatal(err)
	}

	proxyURL := result.MustString()
	if !strings.Contains(proxyURL, "/proxy") {
		t.Fatalf("Invalid proxy URL: %s", proxyURL)
	}

	registerURL, err := url.Parse(proxyURL)
	if err != nil {
		t.Fatal(err)
	}

	// register ourself to kontrol with this proxyUrl
	color.Green("BackendKite is registering to Kontrol with the result from proxy")
	go backendKite.RegisterForever(registerURL)
	<-backendKite.KontrolReadyNotify()

	// now another completely foreign kite and will search for our backend
	// kite, connect to it and execute the "foo" method
	color.Green("Foreign kite started")
	foreignKite := kite.New("foreignKite", "1.0.0")
	foreignKite.Config = conf.Copy()

	color.Green("Querying backendKite now")
	backendKites, err := foreignKite.GetKites(&protocol.KontrolQuery{
		Username:    "******",
		Environment: config.DefaultConfig.Environment,
		Name:        "backendKite",
	})

	remoteBackendKite := backendKites[0]
	color.Green("Dialing BackendKite")
	err = remoteBackendKite.Dial()
	if err != nil {
		t.Fatal(err)
	}

	// foreignKite is connected to backendKite via proxy kite, fire our call...
	color.Green("Calling BackendKite's foo method")
	result, err = remoteBackendKite.TellWithTimeout("foo", 4*time.Second)
	if err != nil {
		t.Fatal(err)
	}

	s := result.MustString()
	if s != "bar" {
		t.Fatalf("Wrong reply: %s", s)
	}
}
Esempio n. 28
0
func recipes_run(c *cli.Context) error {
	url := c.GlobalString("url")
	if url == "" {
		return cli.NewExitError("A URL must be provided with the SCALE_URL environment variable or the --url argument", 1)
	}
	if c.NArg() != 1 && c.NArg() != 2 {
		return cli.NewExitError("Must specify a single recipe type name or id.", 1)
	}
	var recipe_type scalecli.RecipeType
	found := false
	id, err := strconv.Atoi(c.Args()[0])
	if err == nil {
		var resp_code int
		recipe_type, resp_code, err = scalecli.GetRecipeTypeDetails(url, id)
		if err != nil && resp_code != 404 {
			return cli.NewExitError(err.Error(), 1)
		} else if err == nil {
			found = true
		}
	}
	if !found {
		name := c.Args()[0]
		recipe_types, err := scalecli.GetRecipeTypes(url)
		if err != nil {
			return cli.NewExitError(err.Error(), 1)
		}
		var version string
		if c.NArg() == 2 {
			version = c.Args()[1]
		}
		switch len(recipe_types) {
		case 0:
			return cli.NewExitError("Recipe type not found.", 1)
		case 1:
			recipe_type = recipe_types[0]
			found = true
			break
		default:
			for _, rt := range recipe_types {
				if rt.Name == name && rt.Version == version {
					recipe_type = rt
					found = true
					break
				}
			}
			if !found {
				for _, rt := range recipe_types {
					fmt.Printf("%4d %8s [%25s] - %s\n", rt.Id, rt.Version, rt.Name, rt.Title)
				}
				return cli.NewExitError("Multiple recipe types found", 1)
			}
		}
	}
	data_file := c.String("data")
	var recipe_data scalecli.RecipeData
	err = Parse_json_or_yaml(data_file, &recipe_data)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	update_location, err := scalecli.RunRecipe(url, recipe_type.Id, recipe_data)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	color.Blue(fmt.Sprintf("Recipe submited, updates available at %s", update_location))
	return nil
}
Esempio n. 29
0
File: logging.go Progetto: jonasi/pg
func (l *logger) Debugf(fmt string, params ...interface{}) {
	if l.debug {
		color.Blue("[DEBUG] "+fmt, params...)
	}
}
Esempio n. 30
0
func (j AudiencesImport) Run() {
	start := time.Now()
	fmt.Println("------------------------------")
	fmt.Printf("| Starting import at %s\n", start.Format("2006-01-02 15:04:05.000"))
	db := controllers.Gdb
	file := OpenExcelFile("/home/kolan/Documents/a.xlsx")
	fmt.Println("------------------------------")

	rowCount := 0
	successCount := 0
	alreadyExist := 0
	withoutSets := 0
	wrongType := 0

	var audienceTypes = map[string]func() string{
		"Л": func() string {
			return "лекційна"
		},
		"ПР": func() string {
			return "практична"
		},
		"ЛАБ": func() string {
			return "лабораторія"
		},
		"МК": func() string {
			return "методичний кабінет"
		},
		"КК": func() string {
			return "комп'ютерний клас"
		},
	}

	for _, row := range file.Sheets[0].Rows {
		audienceType := row.Cells[2].Value

		if audienceType != "НВНП" && audienceType != "" && audienceType != "Спорт. зал" && audienceType != "ФПФ" {
			var audience models.Audiences

			housingId, err := strconv.Atoi(row.Cells[1].Value)
			if err != nil {
				housingId = 0
			}

			sets, err := strconv.Atoi(row.Cells[3].Value)
			if err != nil {
				sets = 0
			}
			if sets == 0 {
				withoutSets += 1
			}

			audienceTypeFunction, found := audienceTypes[audienceType]
			if found {
				audienceType = audienceTypeFunction()
			} else {
				audienceType = "Невідомо"
				wrongType += 1
			}

			audience.Number = row.Cells[0].Value
			audience.HousingId = int64(housingId)
			audience.Sets = sets
			audience.Note = row.Cells[7].Value
			audience.Type = audienceType

			result := db.Where(&audience).First(&audience)

			if result.Error != nil {
				if result.RecordNotFound() {
					db.NewRecord(audience)
					err = db.Save(&audience).Error
					if err != nil {
						if regexp.MustCompile(`^Error 1062:`).MatchString(err.Error()) == true {
							alreadyExist += 1
							color.Cyan("| \"%s\" - is already exist", row.Cells[0].Value)
						} else {
							color.Red("| Saving error for - \"%s\"", row.Cells[0].Value)
						}
					} else {
						successCount += 1
						color.Green("| \"%s\" - added", row.Cells[0].Value)
					}
				}
			} else {
				alreadyExist += 1
				color.Cyan("| \"%s\" - is already exist", row.Cells[0].Value)
			}
		}
		rowCount += 1
	}
	elapsed := time.Since(start)
	fmt.Println("------------------------------")
	fmt.Printf("| Import finished at %s\n", time.Now().Format("2006-01-02 15:04:05.000"))
	fmt.Printf("| Importing time %s\n", elapsed)
	color.Blue("------------------------------")
	color.Blue("| Audiences in file         : %d", rowCount)
	color.Blue("| Imported audiences        : %d", successCount)
	color.Blue("| Already exist audiences   : %d", alreadyExist)
	color.Blue("| Audiences without sets    : %d", withoutSets)
	color.Blue("| Audiences with wrong type : %d", wrongType)
	color.Blue("------------------------------")
}