// printDocumentIds is a convenience method to print readable log entries for arrays of pointers
// to couch document IDs
436980
func printDocumentIds(documentPointers []*CouchDoc) (string, error) {

	documentIds := []string{}

	for _, documentPointer := range documentPointers {
		docMetadata := &DocMetadata{}
		err := json.Unmarshal(documentPointer.JSONValue, &docMetadata)
		if err != nil {
			return "", errors.Wrap(err, "error unmarshalling json data")
		}
		documentIds = append(documentIds, docMetadata.ID)
	}
	return strings.Join(documentIds, ","), nil
}
360546
func (r *logRun) printLogs(ctx context.Context, logs []*pb.Step_Log) error {
	if len(logs) == 0 {
		return nil
	}

	// Parse Log URLs.
	addrs := make([]*types.StreamAddr, len(logs))
	for i, l := range logs {
		var err error
		addrs[i], err = types.ParseURL(l.Url)
		if err != nil {
			return fmt.Errorf("log %q has unsupported URL %q", l.Name, l.Url)
		}

		if addrs[0].Host != addrs[i].Host {
			// unrealistic
			return fmt.Errorf("multiple different logdog hosts are not supported")
		}
	}

	// Create a client.
	client := coordinator.NewClient(&prpc.Client{
		C:    r.httpClient,
		Host: addrs[0].Host,
	})

	// Fetch descriptors and create fetchers.
	fetchers := make([]*fetcher.Fetcher, len(addrs))
	m := logMultiplexer{Chans: make([]logChan, len(addrs))}
	err := parallel.FanOutIn(func(work chan<- func() error) {
		for i, addr := range addrs {
			i := i
			stream := client.Stream(addr.Project, addr.Path)
			fetchers[i] = stream.Fetcher(ctx, nil)
			work <- func() error {
				s, err := stream.State(ctx)
				if err != nil {
					return err
				}
				if s.Desc.StreamType != logpb.StreamType_TEXT {
					return fmt.Errorf("log %q is not a text stream; only text streams are currently supported", logs[i].Name)
				}
				m.Chans[i].start, err = ptypes.Timestamp(s.Desc.Timestamp)
				return err
			}
		}
	})
	if err != nil {
		return err
	}

	// Start fetching.
	for i := range m.Chans {
		i := i
		c := make(chan logAndErr, 256)
		m.Chans[i].c = c
		go func() {
			defer close(c)
			for {
				log, err := fetchers[i].NextLogEntry()
				c <- logAndErr{log, err}
				if err != nil {
					break
				}
			}
		}()
	}

	stdout, stderr := newStdioPrinters(r.noColor)
	for {
		chanIndex, entry, err := m.Next()
		out := stdout
		switch {
		case err == io.EOF:
			return nil
		case err != nil:
			return err
		case logs[chanIndex].Name == "stderr":
			out = stderr
		}

		for _, line := range entry.GetText().GetLines() {
			out.f("%s%s", line.Value, line.Delimiter)
		}
		if out.Err != nil {
			return out.Err
		}
	}
}
368027
func printMethod(method *Methodx, out *os.File, serviceName string, methodName string, objectFuncToObject map[string]string) {

	actualResponses := filterResponses(method.Responses, methodName)
	// Generate Description
	if method.Description != "" {
		fmt.Fprintln(out, formatComment("", method.Description, method.Parameters))
	}
	fmt.Fprint(out, "func (obj *", serviceName, ") ", methodName, "(ctx context.Context")

	// Generate Parameters
	for _, param := range method.Parameters {
		fmt.Fprint(out, ", ", "", toParamName(param.Name), " ", getTypeName(param))
	}
	fmt.Fprint(out, ") ")

	// Generate Return Types
	if len(actualResponses) > 0 {
		fmt.Fprint(out, "(")
	}
	for _, response := range actualResponses {
		typeName := getTypeName(response)
		if typeName == "*ObjectInterface" {
			// Replace the generic ObjectInterface pointer with the right Remote Object API struct
			objectTypeName := objectFuncToObject[serviceName+"."+methodName]
			if objectTypeName == "" {
				panic("Unknown remote object type for " + serviceName + "." + methodName)
			}
			fmt.Fprint(out, "*"+objectTypeName, ", ")
		} else {
			fmt.Fprint(out, getTypeName(response), ", ")
		}

	}
	fmt.Fprint(out, "error")
	if len(actualResponses) > 0 {
		fmt.Fprint(out, ")")
	}

	// Generate Start of Function body
	fmt.Fprintln(out, " {")

	// Generate an anonymous result container struct
	var resultParamName string
	if len(method.Responses) > 0 {
		fmt.Fprintln(out, "\tresult := &struct {")
		for _, response := range method.Responses {
			fmt.Fprintln(out, "\t\t"+toPublicMemberName(response.Name), getTypeName(response)+"\t`json:\""+response.Name+"\"`")
		}
		fmt.Fprintln(out, "\t} {}")
		resultParamName = "result"
	} else {
		resultParamName = "nil"
	}

	// Generate the actual call down to the RPC machinery
	fmt.Fprint(out, "\terr := obj.rpc(ctx, \"", methodName, "\", ", resultParamName)
	for _, param := range method.Parameters {
		// Fill in the parameters in the parameter array
		fmt.Fprint(out, ", ", toParamName(param.Name))
	}
	fmt.Fprintln(out, ")")

	// If there is at least one Remote Object that will be created then check for nil and return early
	if atLeastOneObjectInterface(method) {
		fmt.Fprintln(out, "\tif err != nil {")
		fmt.Fprint(out, "\t\treturn ")
		for _, response := range actualResponses {
			fmt.Fprint(out, nilNameInEarlyReturnAfterError(response.Type)+", ")
		}
		fmt.Fprintln(out, "err")
		fmt.Fprintln(out, "\t}")
	}

	fmt.Fprint(out, getExtraCrossAssignmentLine(methodName))

	// Return the result including creating a new Remote Object if needed
	fmt.Fprint(out, "\treturn ")
	for _, response := range actualResponses {
		if getTypeName(response) == "*ObjectInterface" {
			objectAPITypeName := objectFuncToObject[serviceName+"."+methodName]
			fmt.Fprint(out, "&"+objectAPITypeName+"{obj.session.getRemoteObject(result."+response.Name[1:]+")}, ")
		} else {
			fmt.Fprint(out, "result."+toPublicMemberName(response.Name)+", ")
		}
	}
	fmt.Fprintln(out, "err ")
	fmt.Fprintln(out, "}")
	fmt.Fprintln(out, "")
}
1180409
func (i *DocumentIndex) AddDocumentLabel(docID, labelID influxdb.ID) error {
	m := &influxdb.LabelMapping{
		LabelID:      labelID,
		ResourceType: influxdb.DocumentsResourceType,
		ResourceID:   docID,
	}
	if err := i.service.createLabelMapping(i.ctx, i.tx, m); err != nil {
		return err
	}

	return nil
}
1052087
func (jlf *jsonLedgerFactory) ChainIDs() []string {
	jlf.mutex.Lock()
	defer jlf.mutex.Unlock()
	ids := make([]string, len(jlf.ledgers))

	i := 0
	for key := range jlf.ledgers {
		ids[i] = key
		i++
	}

	return ids
}
713059
func (s *SegmentBase) DocNumbers(ids []string) (*roaring.Bitmap, error) {
	rv := roaring.New()

	if len(s.fieldsMap) > 0 {
		idDict, err := s.dictionary("_id")
		if err != nil {
			return nil, err
		}

		postingsList := emptyPostingsList

		sMax, err := idDict.fst.GetMaxKey()
		if err != nil {
			return nil, err
		}
		sMaxStr := string(sMax)
		filteredIds := make([]string, 0, len(ids))
		for _, id := range ids {
			if id <= sMaxStr {
				filteredIds = append(filteredIds, id)
			}
		}

		for _, id := range filteredIds {
			postingsList, err = idDict.postingsList([]byte(id), nil, postingsList)
			if err != nil {
				return nil, err
			}
			postingsList.OrInto(rv)
		}
	}

	return rv, nil
}
144710
func NewPaperDocumentLogInfo(DocId string, DocTitle string) *PaperDocumentLogInfo {
	s := new(PaperDocumentLogInfo)
	s.DocId = DocId
	s.DocTitle = DocTitle
	return s
}
440020
func (tc *ToolsConstraint) IndexIds() []string {
	if tc.Stream == "" {
		return nil
	}
	return []string{ToolsContentId(tc.Stream)}
}
412330
func printDocumentV3(code *printer.Code, document *openapiv3.Document) {
	code.Print("OpenAPI: %+v", document.Openapi)
	code.Print("Servers: %+v", document.Servers)
	if document.Info != nil {
		code.Print("Info:")
		code.Indent()
		if document.Info.Title != "" {
			code.Print("Title: %s", document.Info.Title)
		}
		if document.Info.Description != "" {
			code.Print("Description: %s", document.Info.Description)
		}
		if document.Info.Version != "" {
			code.Print("Version: %s", document.Info.Version)
		}
		code.Outdent()
	}
	code.Print("Paths:")
	code.Indent()
	for _, pair := range document.Paths.Path {
		v := pair.Value
		if v.Get != nil {
			code.Print("GET %+v", pair.Name)
		}
		if v.Post != nil {
			code.Print("POST %+v", pair.Name)
		}
	}
	code.Outdent()
}
78619
func printFilesIfDryRunning(data InitData) error {
	if !data.DryRun() {
		return nil
	}
	manifestDir := data.ManifestDir()

	fmt.Printf("[dryrun] Wrote certificates, kubeconfig files and control plane manifests to the %q directory\n", manifestDir)
	fmt.Println("[dryrun] The certificates or kubeconfig files would not be printed due to their sensitive nature")
	fmt.Printf("[dryrun] Please examine the %q directory for details about what would be written\n", manifestDir)

	// Print the contents of the upgraded manifests and pretend like they were in /etc/kubernetes/manifests
	files := []dryrunutil.FileToPrint{}
	// Print static pod manifests
	for _, component := range kubeadmconstants.ControlPlaneComponents {
		realPath := kubeadmconstants.GetStaticPodFilepath(component, manifestDir)
		outputPath := kubeadmconstants.GetStaticPodFilepath(component, kubeadmconstants.GetStaticPodDirectory())
		files = append(files, dryrunutil.NewFileToPrint(realPath, outputPath))
	}
	// Print kubelet config manifests
	kubeletConfigFiles := []string{kubeadmconstants.KubeletConfigurationFileName, kubeadmconstants.KubeletEnvFileName}
	for _, filename := range kubeletConfigFiles {
		realPath := filepath.Join(manifestDir, filename)
		outputPath := filepath.Join(kubeadmconstants.KubeletRunDirectory, filename)
		files = append(files, dryrunutil.NewFileToPrint(realPath, outputPath))
	}

	return dryrunutil.PrintDryRunFiles(files, data.OutputWriter())
}
1106900
func (c *FleetClient) printUnits(states []*schema.UnitState) {
	cols := strings.Split(defaultListUnitsFields, ",")
	fmt.Fprintln(c.out, strings.ToUpper(strings.Join(cols, "\t")))
	for _, us := range states {
		var f []string
		for _, col := range cols {
			f = append(f, listUnitsFields[col](c, us, false))
		}
		fmt.Fprintln(c.out, strings.Join(f, "\t"))
	}
	c.out.Flush()
}
802860
func getParentIDs(root, id string) ([]string, error) {
	f, err := os.Open(path.Join(root, "layers", id))
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var out []string
	s := bufio.NewScanner(f)

	for s.Scan() {
		if t := s.Text(); t != "" {
			out = append(out, s.Text())
		}
	}
	return out, s.Err()
}
1251448
func (dbclient *CouchDatabase) ReadDoc(id string) (*CouchDoc, string, error) {
	var couchDoc CouchDoc
	attachments := []*AttachmentInfo{}
	dbName := dbclient.DBName

	logger.Debugf("[%s] Entering ReadDoc()  id=[%s]", dbName, id)
	if !utf8.ValidString(id) {
		return nil, "", errors.Errorf("doc id [%x] not a valid utf8 string", id)
	}

	readURL, err := url.Parse(dbclient.CouchInstance.conf.URL)
	if err != nil {
		logger.Errorf("URL parse error: %s", err)
		return nil, "", errors.Wrapf(err, "error parsing CouchDB URL: %s", dbclient.CouchInstance.conf.URL)
	}

	query := readURL.Query()
	query.Add("attachments", "true")

	//get the number of retries
	maxRetries := dbclient.CouchInstance.conf.MaxRetries

	resp, couchDBReturn, err := dbclient.handleRequest(http.MethodGet, "ReadDoc", readURL, nil, "", "", maxRetries, true, &query, id)
	if err != nil {
		if couchDBReturn != nil && couchDBReturn.StatusCode == 404 {
			logger.Debugf("[%s] Document not found (404), returning nil value instead of 404 error", dbclient.DBName)
			// non-existent document should return nil value instead of a 404 error
			// for details see https://github.com/hyperledger-archives/fabric/issues/936
			return nil, "", nil
		}
		logger.Debugf("[%s] couchDBReturn=%v\n", dbclient.DBName, couchDBReturn)
		return nil, "", err
	}
	defer closeResponseBody(resp)

	//Get the media type from the Content-Type header
	mediaType, params, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
	if err != nil {
		log.Fatal(err)
	}

	//Get the revision from header
	revision, err := getRevisionHeader(resp)
	if err != nil {
		return nil, "", err
	}

	//check to see if the is multipart,  handle as attachment if multipart is detected
	if strings.HasPrefix(mediaType, "multipart/") {
		//Set up the multipart reader based on the boundary
		multipartReader := multipart.NewReader(resp.Body, params["boundary"])
		for {
			p, err := multipartReader.NextPart()
			if err == io.EOF {
				break // processed all parts
			}
			if err != nil {
				return nil, "", errors.Wrap(err, "error reading next multipart")
			}

			defer p.Close()

			logger.Debugf("[%s] part header=%s", dbclient.DBName, p.Header)
			switch p.Header.Get("Content-Type") {
			case "application/json":
				partdata, err := ioutil.ReadAll(p)
				if err != nil {
					return nil, "", errors.Wrap(err, "error reading multipart data")
				}
				couchDoc.JSONValue = partdata
			default:

				//Create an attachment structure and load it
				attachment := &AttachmentInfo{}
				attachment.ContentType = p.Header.Get("Content-Type")
				contentDispositionParts := strings.Split(p.Header.Get("Content-Disposition"), ";")
				if strings.TrimSpace(contentDispositionParts[0]) == "attachment" {
					switch p.Header.Get("Content-Encoding") {
					case "gzip": //See if the part is gzip encoded

						var respBody []byte

						gr, err := gzip.NewReader(p)
						if err != nil {
							return nil, "", errors.Wrap(err, "error creating gzip reader")
						}
						respBody, err = ioutil.ReadAll(gr)
						if err != nil {
							return nil, "", errors.Wrap(err, "error reading gzip data")
						}

						logger.Debugf("[%s] Retrieved attachment data", dbclient.DBName)
						attachment.AttachmentBytes = respBody
						attachment.Length = uint64(len(attachment.AttachmentBytes))
						attachment.Name = p.FileName()
						attachments = append(attachments, attachment)

					default:

						//retrieve the data,  this is not gzip
						partdata, err := ioutil.ReadAll(p)
						if err != nil {
							return nil, "", errors.Wrap(err, "error reading multipart data")
						}
						logger.Debugf("[%s] Retrieved attachment data", dbclient.DBName)
						attachment.AttachmentBytes = partdata
						attachment.Length = uint64(len(attachment.AttachmentBytes))
						attachment.Name = p.FileName()
						attachments = append(attachments, attachment)

					} // end content-encoding switch
				} // end if attachment
			} // end content-type switch
		} // for all multiparts

		couchDoc.Attachments = attachments

		return &couchDoc, revision, nil
	}

	//handle as JSON document
	couchDoc.JSONValue, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, "", errors.Wrap(err, "error reading response body")
	}

	logger.Debugf("[%s] Exiting ReadDoc()", dbclient.DBName)
	return &couchDoc, revision, nil
}
433198
func printSignatures(out io.Writer, signatureRows []trustTagRow) error {
	trustTagCtx := formatter.Context{
		Output: out,
		Format: NewTrustTagFormat(),
	}
	// convert the formatted type before printing
	formattedTags := []SignedTagInfo{}
	for _, sigRow := range signatureRows {
		formattedSigners := sigRow.Signers
		if len(formattedSigners) == 0 {
			formattedSigners = append(formattedSigners, fmt.Sprintf("(%s)", releasedRoleName))
		}
		formattedTags = append(formattedTags, SignedTagInfo{
			Name:    sigRow.SignedTag,
			Digest:  sigRow.Digest,
			Signers: formattedSigners,
		})
	}
	return TagWrite(trustTagCtx, formattedTags)
}
941732
func (addr *Address) DocID() string {
	return addr.st.docID(addr.doc.DocID)
}
616161
func (i *IndexReader) DumpDoc(id string) chan interface{} {
	idBytes := []byte(id)

	rv := make(chan interface{})

	go func() {
		defer close(rv)

		back, err := backIndexRowForDoc(i.kvreader, []byte(id))
		if err != nil {
			rv <- err
			return
		}

		// no such doc
		if back == nil {
			return
		}
		// build sorted list of term keys
		keys := make(keyset, 0)
		for _, entry := range back.termsEntries {
			for i := range entry.Terms {
				tfr := NewTermFrequencyRow([]byte(entry.Terms[i]), uint16(*entry.Field), idBytes, 0, 0)
				key := tfr.Key()
				keys = append(keys, key)
			}
		}
		sort.Sort(keys)

		// first add all the stored rows
		storedRowPrefix := NewStoredRow(idBytes, 0, []uint64{}, 'x', []byte{}).ScanPrefixForDoc()
		dumpPrefix(i.kvreader, rv, storedRowPrefix)

		// now walk term keys in order and add them as well
		if len(keys) > 0 {
			it := i.kvreader.RangeIterator(keys[0], nil)
			defer func() {
				cerr := it.Close()
				if cerr != nil {
					rv <- cerr
				}
			}()

			for _, key := range keys {
				it.Seek(key)
				rkey, rval, valid := it.Current()
				if !valid {
					break
				}
				rck := make([]byte, len(rkey))
				copy(rck, key)
				rcv := make([]byte, len(rval))
				copy(rcv, rval)
				row, err := ParseFromKeyValue(rck, rcv)
				if err != nil {
					rv <- err
					return
				}
				rv <- row
			}
		}
	}()

	return rv
}
355959
func (rm *RoleManager) PrintRoles() error {
	line := ""
	rm.allRoles.Range(func(_, value interface{}) bool {
		if text := value.(*Role).toString(); text != "" {
			if line == "" {
				line = text
			} else {
				line += ", " + text
			}
		}
		return true
	})
	log.LogPrint(line)
	return nil
}