// detectWebService returns the best matching webService given the list of path tokens.
// see also computeWebserviceScore
491669
func (c CurlyRouter) detectWebService(requestTokens []string, webServices []*WebService) *WebService {
	var best *WebService
	score := -1
	for _, each := range webServices {
		matches, eachScore := c.computeWebserviceScore(requestTokens, each.pathExpr.tokens)
		if matches && (eachScore > score) {
			best = each
			score = eachScore
		}
	}
	return best
}
4109
func (s *rootAPIsHandler) WebService() *restful.WebService {
	mediaTypes, _ := negotiation.MediaTypesForSerializer(s.serializer)
	ws := new(restful.WebService)
	ws.Path(APIGroupPrefix)
	ws.Doc("get available API versions")
	ws.Route(ws.GET("/").To(s.restfulHandle).
		Doc("get available API versions").
		Operation("getAPIVersions").
		Produces(mediaTypes...).
		Consumes(mediaTypes...).
		Writes(metav1.APIGroupList{}))
	return ws
}
778584
func (cln *Client) DiscoverIncludedServices(ss []ble.UUID, s *ble.Service) ([]*ble.Service, error) {
	rsp := cln.conn.sendReq(60, xpc.Dict{
		"kCBMsgArgDeviceUUID":         cln.id,
		"kCBMsgArgServiceStartHandle": s.Handle,
		"kCBMsgArgServiceEndHandle":   s.EndHandle,
		"kCBMsgArgUUIDs":              uuidSlice(ss),
	})
	if rsp.err() != nil {
		return nil, rsp.err()
	}
	return nil, ble.ErrNotImplemented
}
409610
func (environProviderCredentials) DetectCredentials() (*cloud.CloudCredential, error) {
	clientConfigFunc, err := clientconfig.NewClientConfigReader(CAASProviderType)
	if err != nil {
		return nil, errors.Trace(err)
	}
	caasConfig, err := clientConfigFunc(nil, "", "", nil)
	if err != nil {
		return nil, errors.Trace(err)
	}

	if len(caasConfig.Contexts) == 0 {
		return nil, errors.NotFoundf("k8s cluster definitions")
	}

	defaultContext := caasConfig.Contexts[caasConfig.CurrentContext]
	result := &cloud.CloudCredential{
		AuthCredentials:   caasConfig.Credentials,
		DefaultCredential: defaultContext.CredentialName,
	}
	return result, nil
}
973123
func (h *HAproxy) findIpForService(svcPort string, svc *service.Service) string {
	// We can turn off using IP addresses in the config, which is sometimes
	// necessary (e.g. w/Docker for Mac).
	if h.UseHostnames {
		return svc.Hostname
	}

	matchPort, err := strconv.ParseInt(svcPort, 10, 64)
	if err != nil {
		log.Errorf("Invalid value from template ('%s') can't parse as int64: %s", svcPort, err.Error())
		return "-1"
	}

	for _, port := range svc.Ports {
		if port.ServicePort == matchPort {
			return port.IP
		}
	}

	// This defaults to the previous behavior of templating the hostname
	// instead of the IP address. This relies on haproxy being able to
	// resolve the hostname (which means non-FQDN hostnames are a hazard).
	// Ideally this never happens for clusters that have IP addresses defined.
	return svc.Hostname
}
1144052
func (p *Client) DiscoverServices(filter []ble.UUID) ([]*ble.Service, error) {
	p.Lock()
	defer p.Unlock()
	if p.profile == nil {
		p.profile = &ble.Profile{}
	}
	start := uint16(0x0001)
	for {
		length, b, err := p.ac.ReadByGroupType(start, 0xFFFF, ble.PrimaryServiceUUID)
		if err == ble.ErrAttrNotFound {
			return p.profile.Services, nil
		}
		if err != nil {
			return nil, err
		}
		for len(b) != 0 {
			h := binary.LittleEndian.Uint16(b[:2])
			endh := binary.LittleEndian.Uint16(b[2:4])
			u := ble.UUID(b[4:length])
			if filter == nil || ble.Contains(filter, u) {
				s := &ble.Service{
					UUID:      u,
					Handle:    h,
					EndHandle: endh,
				}
				p.profile.Services = append(p.profile.Services, s)
			}
			if endh == 0xFFFF {
				return p.profile.Services, nil
			}
			start = endh + 1
			b = b[length:]
		}
	}
}
885343
func (e SourceRepositoryEnumerator) Detect(dir string, noSourceDetection bool) (*SourceRepositoryInfo, error) {
	info := &SourceRepositoryInfo{
		Path: dir,
	}

	// no point in doing source-type detection if the requested build strategy
	// is docker or pipeline
	if !noSourceDetection {
		for _, d := range e.Detectors {
			if detected := d(dir); detected != nil {
				info.Types = append(info.Types, SourceLanguageType{
					Platform: detected.Platform,
					Version:  detected.Version,
				})
			}
		}
	}
	if path, ok, err := e.DockerfileTester.Has(dir); err == nil && ok {
		dockerfile, err := NewDockerfileFromFile(path)
		if err != nil {
			return nil, err
		}
		info.Dockerfile = dockerfile
	}
	if _, ok, err := e.JenkinsfileTester.Has(dir); err == nil && ok {
		info.Jenkinsfile = true
	}

	return info, nil
}
397381
func (e environProviderCredentials) DetectCredentials() (*cloud.CloudCredential, error) {
	dir := credentialsDir()
	credsFile := filepath.Join(dir, "credentials")
	credInfo, err := ini.LooseLoad(credsFile)
	if err != nil {
		return nil, errors.Annotate(err, "loading AWS credentials file")
	}
	credInfo.NameMapper = ini.TitleUnderscore

	// There's always a section called "DEFAULT" for top level items.
	if len(credInfo.Sections()) == 1 {
		// No standard AWS credentials so try environment variables.
		return e.detectEnvCredentials()
	}

	type accessKeyValues struct {
		AwsAccessKeyId     string
		AwsSecretAccessKey string
	}
	result := cloud.CloudCredential{
		AuthCredentials: make(map[string]cloud.Credential),
	}
	for _, credName := range credInfo.SectionStrings() {
		if credName == ini.DEFAULT_SECTION {
			// No credentials at top level.
			continue
		}
		values := new(accessKeyValues)
		if err := credInfo.Section(credName).MapTo(values); err != nil {
			return nil, errors.Annotatef(err, "invalid credential attributes in section %q", credName)
		}
		// Basic validation check
		if values.AwsAccessKeyId == "" || values.AwsSecretAccessKey == "" {
			logger.Errorf("missing aws credential attributes in credentials file section %q", credName)
			continue
		}
		accessKeyCredential := cloud.NewCredential(
			cloud.AccessKeyAuthType,
			map[string]string{
				"access-key": values.AwsAccessKeyId,
				"secret-key": values.AwsSecretAccessKey,
			},
		)
		accessKeyCredential.Label = fmt.Sprintf("aws credential %q", credName)
		result.AuthCredentials[credName] = accessKeyCredential
	}

	// See if there's also a default region defined.
	configFile := filepath.Join(dir, "config")
	configInfo, err := ini.LooseLoad(configFile)
	if err != nil {
		return nil, errors.Annotate(err, "loading AWS config file")
	}
	result.DefaultRegion = configInfo.Section("default").Key("region").String()
	return &result, nil
}
287292
func (c CurlyRouter) computeWebserviceScore(requestTokens []string, tokens []string) (bool, int) {
	if len(tokens) > len(requestTokens) {
		return false, 0
	}
	score := 0
	for i := 0; i < len(tokens); i++ {
		each := requestTokens[i]
		other := tokens[i]
		if len(each) == 0 && len(other) == 0 {
			score++
			continue
		}
		if len(other) > 0 && strings.HasPrefix(other, "{") {
			// no empty match
			if len(each) == 0 {
				return false, score
			}
			score += 1
		} else {
			// not a parameter
			if each != other {
				return false, score
			}
			score += (len(tokens) - i) * 10 //fuzzy
		}
	}
	return true, score
}
37782
func detectContentType(body interface{}) string {
	contentType := "text/plain; charset=utf-8"
	kind := reflect.TypeOf(body).Kind()
	
	switch kind {
	case reflect.Struct, reflect.Map, reflect.Ptr:
		contentType = "application/json; charset=utf-8"
	case reflect.String:
		contentType = "text/plain; charset=utf-8"
	default:
		if b, ok := body.([]byte); ok {
			contentType = http.DetectContentType(b)
		} else if kind == reflect.Slice {
			contentType = "application/json; charset=utf-8"
		}
	}

	return contentType
}
1135798
func NewWebSocketService(c *Client) *WebSocketService {
	return &WebSocketService{
		client:     c,
		chanMap:    make(map[float64]chan []float64),
		subscribes: make([]subscribeToChannel, 0),
	}
}
1150918
func (c *Client) ResolveServicePath(path string, noprefix bool) ([]service.ServiceDetails, error) {
	resolveServiceRequest := ResolveServiceRequest{
		Path: path,
		NoPrefix: noprefix,
	}
	svcs := []service.ServiceDetails{}

	plog.WithFields(logrus.Fields{
                "path": path,
                "noprefix": noprefix,
        }).Info("Trying to find service")

	err := c.call("ResolveServicePath", resolveServiceRequest, &svcs)
        return svcs, err
}
220232
func (res *Response) DetectContentType(ct string) {
	// Autodetect if not passed a Content-Type header
	if ct == "" {
		ct = http.DetectContentType(res.Body)
	}

	// Content type (e.g. text/plain or text/html)
	mt, params, err := mime.ParseMediaType(ct)
	if err != nil {
		return
	}
	res.MediaType = mt

	// Character set (e.g. utf-8)
	cs, ok := params["charset"]
	if ok {
		res.Charset = cs
	}
	res.DetectCharset()
}
794690
func Detect(config backend.BuildConfig) (remote builder.Source, dockerfile *parser.Result, err error) {
	remoteURL := config.Options.RemoteContext
	dockerfilePath := config.Options.Dockerfile

	switch {
	case remoteURL == "":
		remote, dockerfile, err = newArchiveRemote(config.Source, dockerfilePath)
	case remoteURL == ClientSessionRemote:
		res, err := parser.Parse(config.Source)
		if err != nil {
			return nil, nil, errdefs.InvalidParameter(err)
		}

		return nil, res, nil
	case urlutil.IsGitURL(remoteURL):
		remote, dockerfile, err = newGitRemote(remoteURL, dockerfilePath)
	case urlutil.IsURL(remoteURL):
		remote, dockerfile, err = newURLRemote(remoteURL, dockerfilePath, config.ProgressWriter.ProgressReaderFunc)
	default:
		err = fmt.Errorf("remoteURL (%s) could not be recognized as URL", remoteURL)
	}
	return
}
756589
func (dns *dnsControl) detectChanges(oldObj, newObj interface{}) {
	// If both objects have the same resource version, they are identical.
	if newObj != nil && oldObj != nil && (oldObj.(meta.Object).GetResourceVersion() == newObj.(meta.Object).GetResourceVersion()) {
		return
	}
	obj := newObj
	if obj == nil {
		obj = oldObj
	}
	switch ob := obj.(type) {
	case *object.Service:
		dns.updateModifed()
	case *object.Endpoints:
		if newObj == nil || oldObj == nil {
			dns.updateModifed()
			return
		}
		p := oldObj.(*object.Endpoints)
		// endpoint updates can come frequently, make sure it's a change we care about
		if endpointsEquivalent(p, ob) {
			return
		}
		dns.updateModifed()
	case *object.Pod:
		dns.updateModifed()
	default:
		log.Warningf("Updates for %T not supported.", ob)
	}
}
67977
func (t *Template) GetAllAWSECSServiceResources() map[string]*resources.AWSECSService {
	results := map[string]*resources.AWSECSService{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSECSService:
			results[name] = resource
		}
	}
	return results
}
614688
func (b *UpdateService) DetectNoop(detectNoop bool) *UpdateService {
	b.detectNoop = &detectNoop
	return b
}