Example #1
0
File: data.go Project: bfix/gospel
// Write internal data structure to stream writer.
func (d *Data) writeData(wrt *bufio.Writer, level int) {

	// emit name (if defined)
	if len(d.Name) > 0 {
		wrt.WriteString(d.Name)
		wrt.WriteRune('=')
	}
	// handle value..
	if d.Len() == 0 {
		// .. as direct value
		wrt.WriteRune('"')
		wrt.WriteString(d.Value)
		wrt.WriteRune('"')
	} else {
		// .. as list of data
		if level > 0 {
			wrt.WriteRune('{')
		}
		// handle all list elements...
		count := d.Len()
		for n := 0; n < count; n++ {
			// emit delimiter
			if n > 0 {
				wrt.WriteRune(',')
			}
			// recursively write list element
			s := d.At(n).(*Data)
			s.writeData(wrt, level+1)
		}
		if level > 0 {
			wrt.WriteRune('}')
		}
	}
}
Example #2
0
func new_line(fw *bufio.Writer, email string, dest string) {
	pad := 40 - len(email)
	if pad <= 0 {
		pad = 1
	}
	fw.WriteString(email + strings.Repeat(" ", pad) + dest + "\n")
}
Example #3
0
func (r Resolver) outputResults(w *bufio.Writer, results gresults) {
	var zip, city, state, stateName, county, country, countryName string
	var latitude, longitude float32

	var comp addressComponent
	var err error
	for _, res := range results.Results {
		if comp, err = res.findAddressComponent(zipType); err == nil {
			zip = comp.LongName
		}
		if comp, err = res.findAddressComponent(cityType); err == nil {
			city = comp.LongName
		}
		if comp, err = res.findAddressComponent(countyType); err == nil {
			county = comp.LongName
		}
		if comp, err = res.findAddressComponent(stateType); err == nil {
			state = strings.ToUpper(comp.ShortName)
			stateName = comp.LongName
		}
		if comp, err = res.findAddressComponent(countryType); err == nil {
			country = strings.ToUpper(comp.ShortName)
			countryName = comp.LongName
		}
		latitude = res.Geometry.Location.Lat
		longitude = res.Geometry.Location.Lng
	}
	w.WriteString(fmt.Sprintf("%v,\"%v\",\"%v\",\"%v\",\"%v\",\"%v\",\"%v\",%v,%v\n", country, zip, city, state, stateName, county, countryName, latitude, longitude))
	w.Flush()
}
Example #4
0
//take input from srvChan and send to server
func writeToServer(w *bufio.Writer, srvChan chan string, wg *sync.WaitGroup, quit chan bool, quitChans chan chan bool) {
	defer wg.Done()
	defer fmt.Println("WTS") //debug

	_, err := w.WriteString("PING" + config.Nick + "\r\n") //test message. primarily to get to select loop
	if err == nil {
		err = w.Flush()
	}
	//send all lines in srvChan to server
	for err == nil {
		select {
		case <-quit: //exit if indicated
			return
		case str := <-srvChan:
			_, err = w.WriteString(str + "\r\n")
			if err == nil {
				err = w.Flush()
			}
		}
	}

	//print error and exit
	if err != nil {
		errOut(err, quitChans)
	}
}
Example #5
0
// writeTo serializes the element to the writer w.
func (e *Element) writeTo(w *bufio.Writer) {
	w.WriteByte('<')
	if e.Space != "" {
		w.WriteString(e.Space)
		w.WriteByte(':')
	}
	w.WriteString(e.Tag)
	for _, a := range e.Attr {
		w.WriteByte(' ')
		a.writeTo(w)
	}
	if len(e.Child) > 0 {
		w.WriteString(">")
		for _, c := range e.Child {
			c.writeTo(w)
		}
		w.Write([]byte{'<', '/'})
		if e.Space != "" {
			w.WriteString(e.Space)
			w.WriteByte(':')
		}
		w.WriteString(e.Tag)
		w.WriteByte('>')
	} else {
		w.Write([]byte{'/', '>'})
	}
}
Example #6
0
func createGroup(r *bufio.Reader, w *bufio.Writer, args []string, thisUser *utils.User) (err error) {

	if len(args) == 1 {
		fmt.Println("No arguments for call to create-group.")
		return nil
	}

	err = w.WriteByte(20)
	w.Flush()
	if err != nil {
		return err
	}

	// send the length of args
	err = w.WriteByte(uint8(len(args)))
	w.Flush()
	if err != nil {
		return err
	}

	for i := 1; i < len(args); i++ {

		// send group to create
		w.WriteString(args[i] + "\n")
		w.Flush()

		// get group id to display to user
		gid, _ := r.ReadString('\n')
		fmt.Println("Created group \"" + args[i] + "\" with id: " + strings.TrimSpace(gid))
	}
	// send the group to create

	return err
}
Example #7
0
func doWriteString(w *bufio.Writer) {
	if written, err := w.WriteString(", The Standard Library\n"); err != nil {
		log.Fatalf("failed writing string: %s", err)
	} else {
		log.Printf("Wrote string in %d bytes", written)
	}
}
Example #8
0
// Write embeddings to a binary file accepted by word2vec
func (e *Embeddings) Write(w *bufio.Writer) error {
	nWords := len(e.words)
	if nWords == 0 {
		return nil
	}

	if e.embedSize == 0 {
		return nil
	}

	if _, err := fmt.Fprintf(w, "%d %d\n", nWords, e.embedSize); err != nil {
		return err
	}

	for idx, word := range e.words {
		if _, err := w.WriteString(word + " "); err != nil {
			return err
		}

		if err := binary.Write(w, binary.LittleEndian, e.lookupIdx(idx)); err != nil {
			return err
		}

		w.WriteByte(0x0a)
	}

	return nil
}
Example #9
0
func (proto *LineProtoTriple) do(w *bufio.Writer, r *bufio.Reader) (err error) {
	var line string
	re := regexp.MustCompile(proto.GreetMatch)
	for {
		if line, err = r.ReadString('\n'); err != nil {
			return
		}
		line = strings.TrimRight(line, "\r")

		if re.MatchString(line) {
			break
		}
	}

	if _, err = w.WriteString(proto.AuthReq + "\r\n"); err != nil {
		return
	}
	if err = w.Flush(); err != nil {
		return
	}

	if line, err = r.ReadString('\n'); err != nil {
		return
	}
	line = strings.TrimRight(line, "\r")

	re = regexp.MustCompile(proto.ResponseMatch)
	if !re.MatchString(line) {
		return errors.New("Server does not support STARTTLS (" + strings.TrimSpace(line) + ")")
	}

	return
}
Example #10
0
/*
	Frame physical write.
*/
func (f *Frame) writeFrame(w *bufio.Writer, l string) error {
	// Write the frame Command
	if _, e := w.WriteString(f.Command + "\n"); e != nil {
		return e
	}
	// Content length - Always add it if client does not suppress it and
	// does not supply it.
	if _, ok := f.Headers.Contains("suppress-content-length"); !ok {
		if _, clok := f.Headers.Contains("content-length"); !clok {
			f.Headers = append(f.Headers, "content-length", strconv.Itoa(len(f.Body)))
		}
	}
	// Write the frame Headers
	for i := 0; i < len(f.Headers); i += 2 {
		if l > SPL_10 && f.Command != CONNECT {
			f.Headers[i] = encode(f.Headers[i])
			f.Headers[i+1] = encode(f.Headers[i+1])
		}
		_, e := w.WriteString(f.Headers[i] + ":" + f.Headers[i+1] + "\n")
		if e != nil {
			return e
		}
	}
	// Write the last Header LF
	if e := w.WriteByte('\n'); e != nil {
		return e
	}
	// Write the body
	if len(f.Body) != 0 { // Foolish to write 0 length data
		if _, e := w.Write(f.Body); e != nil {
			return e
		}
	}
	return nil
}
Example #11
0
// Write a FileAttr object to cache file.
func (me *FileAttr) SaveCache(writer *bufio.Writer) error {
	str := fmt.Sprintf("%v|%v|%v|%v\n",
		me.Path, me.ModTime, me.Size, &me.SHA256)

	_, err := writer.WriteString(str)
	return err
}
Example #12
0
/**
 * Write long data packet
 */
func (pkt *packetLongData) write(writer *bufio.Writer) (err os.Error) {
	// Construct packet header
	pkt.header = new(packetHeader)
	pkt.header.length = 7 + uint32(len(pkt.data))
	pkt.header.sequence = pkt.sequence
	err = pkt.header.write(writer)
	if err != nil {
		return
	}
	// Write command
	err = writer.WriteByte(byte(pkt.command))
	if err != nil {
		return
	}
	// Write statement id
	err = pkt.writeNumber(writer, uint64(pkt.statementId), 4)
	if err != nil {
		return
	}
	// Write param number
	err = pkt.writeNumber(writer, uint64(pkt.paramNumber), 2)
	if err != nil {
		return
	}
	// Write data
	_, err = writer.WriteString(pkt.data)
	if err != nil {
		return
	}
	// Flush
	err = writer.Flush()
	return
}
Example #13
0
func (r *AsyncResponse) WriteResponse(buf *bufio.Writer) error {
	_, err := buf.WriteString("+ASYNC ")
	_, err = buf.WriteString(r.asyncID)
	err = buf.WriteByte(' ')
	err = r.resp.WriteResponse(buf)
	return err
}
Example #14
0
func newlineStream(dst *bufio.Writer, prefix, indent string, depth int) {
	dst.WriteByte('\n')
	dst.WriteString(prefix)
	for i := 0; i < depth; i++ {
		dst.WriteString(indent)
	}
}
Example #15
0
func deleteGroup(r *bufio.Reader, w *bufio.Writer, args []string, thisUser *utils.User) (err error) {

	if len(args) < 2 {
		fmt.Println("Not enough arguments for call to group-remove:")
		fmt.Println("Format should be: delete-group GID")
		return nil
	}

	err = w.WriteByte(24)
	w.Flush()
	if err != nil {
		return err
	}

	w.WriteString(args[1] + "\n")
	w.Flush()

	// get success (1) or fail (2)
	success, _ := r.ReadByte()
	if success != 1 {
		fmt.Println("You cannot remove this group. Does it exist/are you the owner?")
		return err
	}

	fmt.Println("Removed: " + args[1])

	return err
}
Example #16
0
func (c *Config) write(buf *bufio.Writer, header string) (err error) {
	if header != "" {
		// Add comment character after of each new line.
		if i := strings.Index(header, "\n"); i != -1 {
			header = strings.Replace(header, "\n", "\n"+c.comment, -1)
		}

		if _, err = buf.WriteString(c.comment + header + "\n"); err != nil {
			return err
		}
	}

	for _, orderedSection := range c.Sections() {
		for section, sectionMap := range c.data {
			if section == orderedSection {

				// Skip default section if empty.
				if section == DEFAULT_SECTION && len(sectionMap) == 0 {
					continue
				}

				if _, err = buf.WriteString("\n[" + section + "]\n"); err != nil {
					return err
				}

				// Follow the input order in options.
				for i := 0; i < c.lastIdOption[section]; i++ {
					for option, tValue := range sectionMap {

						if tValue.position == i {

							if len(tValue.vMuti) > 0 {
								for _, realValue := range tValue.vMuti {
									if _, err = buf.WriteString(fmt.Sprint(
										"@", option, c.separator, realValue, "\n")); err != nil {
										return err
									}
								}
							} else {
								if _, err = buf.WriteString(fmt.Sprint(
									option, c.separator, tValue.v, "\n")); err != nil {
									return err
								}
							}

							c.RemoveOption(section, option)
							break
						}
					}
				}
			}
		}
	}

	if _, err = buf.WriteString("\n"); err != nil {
		return err
	}

	return nil
}
Example #17
0
func rm(r *bufio.Reader, w *bufio.Writer, currentDir string, args []string) (err error) {

	// START SENDCODE BLOCK
	err = w.WriteByte(7)
	w.Flush()
	if err != nil {
		panic(err)
	}
	// END SENDCODE BLOCK

	// Send current dir
	w.WriteString(currentDir + "\n")
	w.Flush()

	// send len args
	err = w.WriteByte(uint8(len(args)))
	w.Flush()
	if err != nil {
		panic(err)
	}

	// send each arg (if it exists)
	for i := 1; i < len(args); i++ {

		w.WriteString(args[i] + "\n")
		w.Flush()
	}

	return err
}
Example #18
0
func CSVWriteVal(cw *bufio.Writer, i interface{}) {
	sVal := fmt.Sprintf("%v", i)
	if len(sVal) <= 0 {
		return
	}

	bQuot := strings.IndexRune(sVal, ',') >= 0 || strings.IndexAny(sVal, "\"\r\n") >= 0
	if !bQuot {
		cw.WriteString(sVal)
		return
	}

	cw.WriteByte('"')
	for _, r1 := range sVal {
		switch r1 {
		case '"':
			cw.WriteString(`""`)
		case '\r':
			cw.WriteByte('\r')
		case '\n':
			cw.WriteByte('\n')
		default:
			cw.WriteRune(r1)
		}
	}
	cw.WriteByte('"')
}
Example #19
0
func groupLs(r *bufio.Reader, w *bufio.Writer, args []string, thisUser *utils.User) (err error) {

	if len(args) != 2 {
		fmt.Println("Wrong number of arguments for call to group-ls:")
		fmt.Println("Format should be: group-ls GID")
		return nil
	}

	err = w.WriteByte(23)
	w.Flush()
	if err != nil {
		return err
	}

	// send the group id
	w.WriteString(args[1] + "\n")
	w.Flush()

	// get success (1) or fail (2)
	success, _ := r.ReadByte()
	if success != 1 {
		fmt.Println("The group does not exist")
		return err
	}

	// get uuids of the group
	result, _ := r.ReadString('\n')
	result = strings.TrimSuffix(strings.TrimSpace(result), ",")

	fmt.Println("Members of Group " + args[1] + ": " + result)

	return err
}
Example #20
0
func WriteError(b *bufio.Writer, code int64, text string) error {
	_, err := b.WriteString("-ERR ")
	err = WriteInt64(b, code)
	err = b.WriteByte(' ')
	err = WriteString(b, text)
	return err
}
Example #21
0
// EncodeData encodes the entire data received so far into a JavaScript array format.
func (x *SeriesSweeper) EncodeData(w io.Writer) error {
	var bw *bufio.Writer = bufio.NewWriter(w)
	bw.WriteByte(byte('['))
	for e := x.chrono.Front(); e != nil; e = e.Next() {
		s := e.Value.(*sample)
		bw.WriteByte(byte('['))
		fmt.Fprintf(bw, "%0.3f,", s.Time)
		for i, series := range x.series {
			if series == s.Series {
				fmt.Fprintf(bw, "%0.3f", s.Value)
			} else {
				bw.WriteString("null")
			}
			if i < len(x.series)-1 {
				bw.WriteByte(byte(','))
			}
		}
		bw.WriteByte(']')
		if e.Next() != nil {
			bw.WriteByte(byte(','))
		}
		bw.WriteByte('\n')
	}
	bw.WriteByte(byte(']'))
	return bw.Flush()
}
Example #22
0
func WriteBytes(b *bufio.Writer, v []byte) error {
	err := b.WriteByte('$')
	_, err = b.WriteString(strconv.Itoa(len(v)))
	err = b.WriteByte(' ')
	_, err = b.Write(v)
	return err
}
Example #23
0
func tokenize(bf2 *bufio.Reader, bf3 *bufio.Writer) {
	for s, err := bf2.ReadString('\n'); err == nil; s, err = bf2.ReadString('\n') {
		fs := strings.Split(s, "\t")

		doc, _ := NewDocument(fs[0])
		doc.SetInput("T", fs[1])
		doc.SetInput("A", fs[2])
		doc.Tokenize()
		doc.AssembleSentences()

		var soffs []string
		sents := doc.SectionSentences("T")
		for _, sent := range sents {
			soffs = append(soffs, fmt.Sprintf("%d:%d", sent.Begin(), sent.End()))
		}
		bf3.WriteString(fmt.Sprintf("%s\t%s\t", fs[0], strings.Join(soffs, ",")))

		soffs = soffs[:0]
		sents = doc.SectionSentences("A")
		for _, sent := range sents {
			soffs = append(soffs, fmt.Sprintf("%d:%d", sent.Begin(), sent.End()))
		}
		bf3.WriteString(fmt.Sprintf("%s\n", strings.Join(soffs, ",")))
	}
}
Example #24
0
func addSRToffset(w *bufio.Writer, srt string, timeOff, idOff int) error {
	// Open SRT file
	file, err := os.Open(srt)
	defer file.Close()
	if err != nil {
		return err
	}
	// Create a reader
	reader := bufio.NewReader(file)
	for {
		// Read new line
		line, _, err := reader.ReadLine()
		if err != nil {
			break
		}
		switch {
		case regexpID.MatchString(string(line)):
			// Parse ID
			id, _ := parseID(string(line))
			line = []uint8(fmt.Sprintf("%d", id+idOff))
		case regexpTime.MatchString(string(line)):
			// Parse Times
			time := parseTime(string(line))
			time.Offset(timeOff)
			line = []uint8(time.String())
		default:
			// Do nothing
		}
		// Write to file
		if _, err := w.WriteString(string(line) + "\n"); err != nil {
			return err
		}
	}
	return nil
}
func writeToStderr(msg string, errWriter *bufio.Writer) {
	if !strings.HasSuffix(msg, "\n") {
		msg = msg + "\n"
	}
	errWriter.WriteString(msg)
	errWriter.Flush()
}
Example #26
0
func (l BList) renderBCode(w *bufio.Writer) {
	w.WriteString("l")
	for i := range l {
		l[i].renderBCode(w)
	}
	w.WriteString("e")
}
Example #27
0
func writeHeader(output *bufio.Writer) {
	if *verbose && !*dryRun {
		fmt.Println("Writing source header")
	}
	licensePath := pathutils.Join(*projectPath, "GPL3-header.txt")
	license, err := os.Open(licensePath)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := license.Close(); err != nil {
			panic(err)
		}
	}()

	reader := bufio.NewReader(license)
	for {
		if *verbose {
			fmt.Printf("Got line: '%s'\n")
		}
		line, err := reader.ReadString('\n')
		if err != nil {
			if err != io.EOF {
				panic(err)
			}
		}
		fmt.Fprintf(output, "// %s", line)
		if err == io.EOF {
			break
		}
	}

	output.WriteString("\n//\n")
	output.Flush()
}
Example #28
0
func writeln(w *bufio.Writer, s string) error {
	_, err := w.WriteString(s)
	if err != nil {
		return err
	}
	return newLine(w)
}
Example #29
0
func writeOne(bw *bufio.Writer, x interface{}) error {
	switch y := x.(type) {
	case bool:
		fmt.Fprintf(bw, "%t", y)
	case byte:
		fmt.Fprintf(bw, "'%c'", y)
	case string:
		fmt.Fprintf(bw, "\"%s\"", y)
	case int, int64:
		fmt.Fprintf(bw, "%d", y)
	case float32, float64:
		fmt.Fprintf(bw, "%f", y)
	default:
		slice := reflect.ValueOf(x)
		if slice.Kind() != reflect.Slice {
			return NewErrType(slice.Type())
		}
		bw.WriteByte('[')
		for i := 0; i < slice.Len(); i++ {
			if i != 0 {
				bw.WriteString(", ")
			}
			elem := slice.Index(i)
			if err := writeOne(bw, elem.Interface()); err != nil {
				return err
			}
		}
		bw.WriteByte(']')
	}
	return nil
}
Example #30
0
func (g *GVCFRefVar) _emit_ref_left_anchor(info GVCFRefVarInfo, out *bufio.Writer) {
	a_start := info.ref_start + 1
	a_len := info.ref_len
	a_r_seq := info.refseq
	a_ref_bp := byte('.')
	if len(a_r_seq) > 0 {
		a_ref_bp = a_r_seq[0]
	}
	a_gt_field := "0/0"

	a_filt_field := "PASS"
	//a_info_field := fmt.Sprintf("END=%d", a_start+a_len)
	a_info_field := fmt.Sprintf("END=%d", a_start+a_len-1)

	//                            0   1   2   3   4   5    6  7   8   9
	out.WriteString(fmt.Sprintf("%s\t%d\t%s\t%c\t%s\t%s\t%s\t%s\t%s\t%s\n",
		g.ChromStr,
		a_start,
		g.Id,
		a_ref_bp,
		".",
		g.Qual,
		a_filt_field,
		a_info_field,
		g.Format,
		a_gt_field))

}