text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>JGProgressHUDRingIndicatorView Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1333)">

				JGProgressHUD

				Jonas Gessner

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Properties">

		<option value="//api/name/ringBackgroundColor">ringBackgroundColor</option>

		<option value="//api/name/ringColor">ringColor</option>

		<option value="//api/name/ringWidth">ringWidth</option>

		<option value="//api/name/roundProgressLine">roundProgressLine</option>

	</optgroup>

	<optgroup label="Instance Methods">

		<option value="//api/name/initWithContentView:">- initWithContentView:</option>

		<option value="//api/name/setProgress:animated:">- setProgress:animated:</option>

		<option value="//api/name/setUpForHUDStyle:vibrancyEnabled:">- setUpForHUDStyle:vibrancyEnabled:</option>

	</optgroup>

</select>

JGProgressHUDRingIndicatorView Class Reference

	Inherits from
	JGProgressHUDIndicatorView : UIView

	Declared in
	JGProgressHUDRingIndicatorView.h
JGProgressHUDRingIndicatorView.m

Overview

A ring shaped determinate progress indicator.

Other Methods

– initWithContentView:

Designated initializer for this class.

- (instancetype)initWithContentView:(UIView *)contentView

Parameters

						contentView

The content view to place on the container view (the container is the JGProgressHUDIndicatorView).

Discussion

Designated initializer for this class.

Declared In

JGProgressHUDIndicatorView.h

– setProgress:animated:

Adjusts the current progress shown by the receiver, optionally animating the change.

- (void)setProgress:(float)progress animated:(BOOL)animated

Parameters

						progress

The new progress value.

						animated

YES if the change should be animated, NO if the change should happen immediately.

Discussion

Adjusts the current progress shown by the receiver, optionally animating the change.

The current progress is represented by a floating-point value between 0.0 and 1.0, inclusive, where 1.0 indicates the completion of the task. The default value is 0.0. Values less than 0.0 and greater than 1.0 are pinned to those limits.

Declared In

JGProgressHUDIndicatorView.h

– setUpForHUDStyle:vibrancyEnabled:

Use this method to set up the indicator view to fit the HUD style and vibrancy setting. This method is called by @c JGProgressHUD when the indicator view is added to the HUD and when the HUD’s @c vibrancyEnabled property changes. This method may be called multiple times with different values. The default implementation does nothing.

- (void)setUpForHUDStyle:(JGProgressHUDStyle)style vibrancyEnabled:(BOOL)vibrancyEnabled

Discussion

Use this method to set up the indicator view to fit the HUD style and vibrancy setting. This method is called by @c JGProgressHUD when the indicator view is added to the HUD and when the HUD’s @c vibrancyEnabled property changes. This method may be called multiple times with different values. The default implementation does nothing.

Declared In

JGProgressHUDIndicatorView.h

Other Methods

  ringBackgroundColor

Background color of the ring.
@attention Custom values need to be set after assigning the indicator view to @c JGProgressHUD’s @c indicatorView property.

@property (nonatomic, strong, nonnull) UIColor *ringBackgroundColor

Discussion

Background color of the ring.
@attention Custom values need to be set after assigning the indicator view to @c JGProgressHUD’s @c indicatorView property.

@b Default: Black for JGProgressHUDStyleDark, light gray otherwise.

Declared In

JGProgressHUDRingIndicatorView.h

  ringColor

Progress color of the progress ring.
@attention Custom values need to be set after assigning the indicator view to @c JGProgressHUD’s @c indicatorView property.

@property (nonatomic, strong, nonnull) UIColor *ringColor

Discussion

Progress color of the progress ring.
@attention Custom values need to be set after assigning the indicator view to @c JGProgressHUD’s @c indicatorView property.

@b Default: White for JGProgressHUDStyleDark, otherwise black.

Declared In

JGProgressHUDRingIndicatorView.h

  roundProgressLine

Sets if the progress ring should have a rounded line cap.

@property (nonatomic, assign) BOOL roundProgressLine

Discussion

Sets if the progress ring should have a rounded line cap.

@b Default: NO.

Declared In

JGProgressHUDRingIndicatorView.h

  ringWidth

Width of the ring.

@property (nonatomic, assign) CGFloat ringWidth

Discussion

Width of the ring.

@b Default: 3.0.

Declared In

JGProgressHUDRingIndicatorView.h

Copyright © 2020 Jonas Gessner. All rights reserved. Updated: 2020-10-16

Generated by appledoc 2.2.1 (build 1333).


text:
{% extends 'neuropy/base.html' %}
{% block content %}

Home Page

{% endblock content %}

redpajama_set_name: RedPajamaGithub


text:
package policy

import (
	"fmt"
	"strings"

	"github.com/cilium/cilium/pkg/identity"
	slim_metav1 "github.com/cilium/cilium/pkg/k8s/slim/k8s/apis/meta/v1"
	"github.com/cilium/cilium/pkg/labels"
	"github.com/cilium/cilium/pkg/lock"
	"github.com/cilium/cilium/pkg/option"
	"github.com/cilium/cilium/pkg/policy/api"
	"github.com/cilium/cilium/pkg/policy/api/kafka"
)

type rule struct {
	api.Rule

	metadata *ruleMetadata
}

type ruleMetadata struct {
	// mutex protects all fields in this type.
	Mutex lock.RWMutex

	// IdentitySelected is a cache that maps from an identity to whether
	// this rule selects that identity.
	IdentitySelected map[identity.NumericIdentity]bool
}

func newRuleMetadata() *ruleMetadata {
	return &ruleMetadata{
		IdentitySelected: make(map[identity.NumericIdentity]bool),
	}
}

func (m *ruleMetadata) delete(identity *identity.Identity) {
	m.Mutex.Lock()
	defer m.Mutex.Unlock()
	delete(m.IdentitySelected, identity.ID)
}

func (r *rule) String() string {
	return fmt.Sprintf("%v", r.EndpointSelector)
}

func (r *rule) getSelector() *api.EndpointSelector {
	if r.NodeSelector.LabelSelector != nil {
		return &r.NodeSelector
	}
	return &r.EndpointSelector
}

func (epd *PerSelectorPolicy) appendL7WildcardRule(ctx *SearchContext) *PerSelectorPolicy {
	// Wildcard rule only needs to be appended if some rules already exist
	switch {
	case len(epd.L7Rules.HTTP) > 0:
		rule := api.PortRuleHTTP{}
		if !rule.Exists(epd.L7Rules) {
			ctx.PolicyTrace("   Merging HTTP wildcard rule: %+v\n", rule)
			epd.L7Rules.HTTP = append(epd.L7Rules.HTTP, rule)
		} else {
			ctx.PolicyTrace("   Merging HTTP wildcard rule, equal rule already exists: %+v\n", rule)
		}
	case len(epd.L7Rules.Kafka) > 0:
		rule := kafka.PortRule{}
		rule.Sanitize()
		if !rule.Exists(epd.L7Rules.Kafka) {
			ctx.PolicyTrace("   Merging Kafka wildcard rule: %+v\n", rule)
			epd.L7Rules.Kafka = append(epd.L7Rules.Kafka, rule)
		} else {
			ctx.PolicyTrace("   Merging Kafka wildcard rule, equal rule already exists: %+v\n", rule)
		}
	case len(epd.L7Rules.DNS) > 0:
		// Wildcarding at L7 for DNS is specified via allowing all via
		// MatchPattern!
		rule := api.PortRuleDNS{MatchPattern: "*"}
		rule.Sanitize()
		if !rule.Exists(epd.L7Rules) {
			ctx.PolicyTrace("   Merging DNS wildcard rule: %+v\n", rule)
			epd.L7Rules.DNS = append(epd.L7Rules.DNS, rule)
		} else {
			ctx.PolicyTrace("   Merging DNS wildcard rule, equal rule already exists: %+v\n", rule)
		}
	case epd.L7Rules.L7Proto != "" && len(epd.L7Rules.L7) > 0:
		rule := api.PortRuleL7{}
		if !rule.Exists(epd.L7Rules) {
			ctx.PolicyTrace("   Merging L7 wildcard rule: %+v\n", rule)
			epd.L7Rules.L7 = append(epd.L7Rules.L7, rule)
		} else {
			ctx.PolicyTrace("   Merging L7 wildcard rule, equal rule already exists: %+v\n", rule)
		}
	}
	return epd
}

func mergePortProto(ctx *SearchContext, existingFilter, filterToMerge *L4Filter, selectorCache *SelectorCache) error {
	// Merge the L7-related data from the filter to merge
	// with the L7-related data already in the existing filter.
	if filterToMerge.L7Parser != ParserTypeNone {
		if existingFilter.L7Parser == ParserTypeNone {
			existingFilter.L7Parser = filterToMerge.L7Parser
		} else if filterToMerge.L7Parser != existingFilter.L7Parser {
			ctx.PolicyTrace("   Merge conflict: mismatching parsers %s/%s\n", filterToMerge.L7Parser, existingFilter.L7Parser)
			return fmt.Errorf("cannot merge conflicting L7 parsers (%s/%s)", filterToMerge.L7Parser, existingFilter.L7Parser)
		}
	}

	for cs, newL7Rules := range filterToMerge.L7RulesPerSelector {
		// 'cs' will be merged or moved (see below), either way it needs
		// to be removed from the map it is in now.
		delete(filterToMerge.L7RulesPerSelector, cs)

		if l7Rules, ok := existingFilter.L7RulesPerSelector[cs]; ok {
			// existing filter already has 'cs', release and merge L7 rules
			selectorCache.RemoveSelector(cs, filterToMerge)

			// skip merging for reserved:none, as it is never
			// selected, and toFQDN rules currently translate to
			// reserved:none as an endpoint selector, causing a
			// merge conflict for different toFQDN destinations
			// with different TLS contexts.
			if cs.IsNone() {
				continue
			}

			if l7Rules.Equal(newL7Rules) {
				continue // identical rules need no merging
			}

			// Merge two non-identical sets of non-nil rules
			if l7Rules != nil && l7Rules.IsDeny {
				// If existing rule is deny then it's a no-op
				// Denies takes priority over any rule.
				continue
			} else if newL7Rules != nil && newL7Rules.IsDeny {
				// Overwrite existing filter if the new rule is a deny case
				// Denies takes priority over any rule.
				existingFilter.L7RulesPerSelector[cs] = newL7Rules
				continue
			}

			// nil L7 rules wildcard L7. When merging with a non-nil rule, the nil must be expanded
			// to an actual wildcard rule for the specific L7
			if l7Rules.IsEmpty() && !newL7Rules.IsEmpty() {
				existingFilter.L7RulesPerSelector[cs] = newL7Rules.appendL7WildcardRule(ctx)
				continue
			}
			if !l7Rules.IsEmpty() && newL7Rules.IsEmpty() {
				existingFilter.L7RulesPerSelector[cs] = l7Rules.appendL7WildcardRule(ctx)
				continue
			}

			if !newL7Rules.TerminatingTLS.Equal(l7Rules.TerminatingTLS) {
				ctx.PolicyTrace("   Merge conflict: mismatching terminating TLS contexts %v/%v\n", newL7Rules.TerminatingTLS, l7Rules.TerminatingTLS)
				return fmt.Errorf("cannot merge conflicting terminating TLS contexts for cached selector %s: (%v/%v)", cs.String(), newL7Rules.TerminatingTLS, l7Rules.TerminatingTLS)
			}
			if !newL7Rules.OriginatingTLS.Equal(l7Rules.OriginatingTLS) {
				ctx.PolicyTrace("   Merge conflict: mismatching originating TLS contexts %v/%v\n", newL7Rules.OriginatingTLS, l7Rules.OriginatingTLS)
				return fmt.Errorf("cannot merge conflicting originating TLS contexts for cached selector %s: (%v/%v)", cs.String(), newL7Rules.OriginatingTLS, l7Rules.OriginatingTLS)
			}

			switch {
			case len(newL7Rules.HTTP) > 0:
				if len(l7Rules.Kafka) > 0 || len(l7Rules.DNS) > 0 || l7Rules.L7Proto != "" {
					ctx.PolicyTrace("   Merge conflict: mismatching L7 rule types.\n")
					return fmt.Errorf("cannot merge conflicting L7 rule types")
				}

				for _, newRule := range newL7Rules.HTTP {
					if !newRule.Exists(l7Rules.L7Rules) {
						l7Rules.HTTP = append(l7Rules.HTTP, newRule)
					}
				}
			case len(newL7Rules.Kafka) > 0:
				if len(l7Rules.HTTP) > 0 || len(l7Rules.DNS) > 0 || l7Rules.L7Proto != "" {
					ctx.PolicyTrace("   Merge conflict: mismatching L7 rule types.\n")
					return fmt.Errorf("cannot merge conflicting L7 rule types")
				}

				for _, newRule := range newL7Rules.Kafka {
					if !newRule.Exists(l7Rules.L7Rules.Kafka) {
						l7Rules.Kafka = append(l7Rules.Kafka, newRule)
					}
				}
			case newL7Rules.L7Proto != "":
				if len(l7Rules.Kafka) > 0 || len(l7Rules.HTTP) > 0 || len(l7Rules.DNS) > 0 || (l7Rules.L7Proto != "" && l7Rules.L7Proto != newL7Rules.L7Proto) {
					ctx.PolicyTrace("   Merge conflict: mismatching L7 rule types.\n")
					return fmt.Errorf("cannot merge conflicting L7 rule types")
				}
				if l7Rules.L7Proto == "" {
					l7Rules.L7Proto = newL7Rules.L7Proto
				}

				for _, newRule := range newL7Rules.L7 {
					if !newRule.Exists(l7Rules.L7Rules) {
						l7Rules.L7 = append(l7Rules.L7, newRule)
					}
				}
			case len(newL7Rules.DNS) > 0:
				if len(l7Rules.HTTP) > 0 || len(l7Rules.Kafka) > 0 || len(l7Rules.L7) > 0 {
					ctx.PolicyTrace("   Merge conflict: mismatching L7 rule types.\n")
					return fmt.Errorf("cannot merge conflicting L7 rule types")
				}

				for _, newRule := range newL7Rules.DNS {
					if !newRule.Exists(l7Rules.L7Rules) {
						l7Rules.DNS = append(l7Rules.DNS, newRule)
					}
				}

			default:
				ctx.PolicyTrace("   No L7 rules to merge.\n")
			}
			existingFilter.L7RulesPerSelector[cs] = l7Rules
		} else { // 'cs' is not in the existing filter yet
			// Update selector owner to the existing filter
			selectorCache.ChangeUser(cs, filterToMerge, existingFilter)

			// Move L7 rules over.
			existingFilter.L7RulesPerSelector[cs] = newL7Rules

			if cs.IsWildcard() {
				existingFilter.wildcard = cs
			}
		}
	}

	return nil
}

// mergeIngressPortProto merges all rules which share the same port & protocol that
// select a given set of endpoints. It updates the L4Filter mapped to by the specified
// port and protocol with the contents of the provided PortRule. If the rule
// being merged has conflicting L7 rules with those already in the provided
// L4PolicyMap for the specified port-protocol tuple, it returns an error.
//
// If any rules contain L7 rules that select Host or Remote Node and we should
// accept all traffic from host, the L7 rules will be translated into L7
// wildcards via 'hostWildcardL7'. That is to say, traffic will be
// forwarded to the proxy for endpoints matching those labels, but the proxy
// will allow all such traffic.
func mergeIngressPortProto(policyCtx PolicyContext, ctx *SearchContext, endpoints api.EndpointSelectorSlice, hostWildcardL7 []string,
	r api.Ports, p api.PortProtocol, proto api.L4Proto, ruleLabels labels.LabelArray, resMap L4PolicyMap) (int, error) {
	// Create a new L4Filter
	filterToMerge, err := createL4IngressFilter(policyCtx, endpoints, hostWildcardL7, r, p, proto, ruleLabels)
	if err != nil {
		return 0, err
	}

	err = addL4Filter(policyCtx, ctx, resMap, p, proto, filterToMerge, ruleLabels)
	if err != nil {
		return 0, err
	}
	return 1, err
}

func traceL3(ctx *SearchContext, peerEndpoints api.EndpointSelectorSlice, direction string, isDeny bool) {
	var result strings.Builder

	// Requirements will be cloned into every selector, only trace them once.
	if len(peerEndpoints[0].MatchExpressions) > 0 {
		sel := peerEndpoints[0]
		result.WriteString("    Enforcing requirements ")
		result.WriteString(fmt.Sprintf("%+v", sel.MatchExpressions))
		result.WriteString("\n")
	}
	// EndpointSelector
	for _, sel := range peerEndpoints {
		if len(sel.MatchLabels) > 0 {
			if !isDeny {
				result.WriteString("    Allows ")
			} else {
				result.WriteString("    Denies ")
			}
			result.WriteString(direction)
			result.WriteString(" labels ")
			result.WriteString(sel.String())
			result.WriteString("\n")
		}
	}
	ctx.PolicyTrace(result.String())
}

// portRulesCoverContext determines whether L4 portions of rules cover the
// specified port models.
//
// Returns true if the list of ports is 0, or the rules match the ports.
func rulePortsCoverSearchContext(ports []api.PortProtocol, ctx *SearchContext) bool {
	if len(ctx.DPorts) == 0 {
		return true
	}
	for _, p := range ports {
		for _, dp := range ctx.DPorts {
			tracePort := api.PortProtocol{
				Protocol: api.L4Proto(dp.Protocol),
			}
			if dp.Name != "" {
				tracePort.Port = dp.Name
			} else {
				tracePort.Port = fmt.Sprintf("%d", dp.Port)
			}
			if p.Covers(tracePort) {
				return true
			}
		}
	}
	return false
}

func mergeIngress(policyCtx PolicyContext, ctx *SearchContext, fromEndpoints api.EndpointSelectorSlice, toPorts api.PortsIterator, ruleLabels labels.LabelArray, resMap L4PolicyMap) (int, error) {
	found := 0

	if ctx.From != nil && len(fromEndpoints) > 0 {
		if ctx.TraceEnabled() {
			traceL3(ctx, fromEndpoints, "from", policyCtx.IsDeny())
		}
		if !fromEndpoints.Matches(ctx.From) {
			ctx.PolicyTrace("      No label match for %s", ctx.From)
			return 0, nil
		}
		ctx.PolicyTrace("      Found all required labels")
	}

	// Daemon options may induce L3 allows for host/world. In this case, if
	// we find any L7 rules matching host/world then we need to turn any L7
	// restrictions on these endpoints into L7 allow-all so that the
	// traffic is always allowed, but is also always redirected through the
	// proxy
	hostWildcardL7 := make([]string, 0, 2)
	if option.Config.AlwaysAllowLocalhost() {
		hostWildcardL7 = append(hostWildcardL7, labels.IDNameHost)
		if !option.Config.EnableRemoteNodeIdentity {
			hostWildcardL7 = append(hostWildcardL7, labels.IDNameRemoteNode)
		}
	}

	var (
		cnt int
		err error
	)

	// L3-only rule (with requirements folded into fromEndpoints).
	if toPorts.Len() == 0 && len(fromEndpoints) > 0 {
		cnt, err = mergeIngressPortProto(policyCtx, ctx, fromEndpoints, hostWildcardL7, &api.PortRule{}, api.PortProtocol{Port: "0", Protocol: api.ProtoAny}, api.ProtoAny, ruleLabels, resMap)
		if err != nil {
			return found, err
		}
	}

	found += cnt

	err = toPorts.Iterate(func(r api.Ports) error {
		// For L4 Policy, an empty slice of EndpointSelector indicates that the
		// rule allows all at L3 - explicitly specify this by creating a slice
		// with the WildcardEndpointSelector.
		if len(fromEndpoints) == 0 {
			fromEndpoints = api.EndpointSelectorSlice{api.WildcardEndpointSelector}
		}
		if !policyCtx.IsDeny() {
			ctx.PolicyTrace("      Allows port %v\n", r.GetPortProtocols())
		} else {
			ctx.PolicyTrace("      Denies port %v\n", r.GetPortProtocols())
		}
		if !rulePortsCoverSearchContext(r.GetPortProtocols(), ctx) {
			ctx.PolicyTrace("        No port match found\n")
			return nil
		}
		pr := r.GetPortRule()
		if pr != nil {
			if pr.Rules != nil && pr.Rules.L7Proto != "" {
				ctx.PolicyTrace("        l7proto: \"%s\"\n", pr.Rules.L7Proto)
			}
			if !pr.Rules.IsEmpty() {
				for _, l7 := range pr.Rules.HTTP {
					ctx.PolicyTrace("          %+v\n", l7)
				}
				for _, l7 := range pr.Rules.Kafka {
					ctx.PolicyTrace("          %+v\n", l7)
				}
				for _, l7 := range pr.Rules.L7 {
					ctx.PolicyTrace("          %+v\n", l7)
				}
			}
		}

		for _, p := range r.GetPortProtocols() {
			if p.Protocol != api.ProtoAny {
				cnt, err := mergeIngressPortProto(policyCtx, ctx, fromEndpoints, hostWildcardL7, r, p, p.Protocol, ruleLabels, resMap)
				if err != nil {
					return err
				}
				found += cnt
			} else {
				cnt, err := mergeIngressPortProto(policyCtx, ctx, fromEndpoints, hostWildcardL7, r, p, api.ProtoTCP, ruleLabels, resMap)
				if err != nil {
					return err
				}
				found += cnt

				cnt, err = mergeIngressPortProto(policyCtx, ctx, fromEndpoints, hostWildcardL7, r, p, api.ProtoUDP, ruleLabels, resMap)
				if err != nil {
					return err
				}
				found += cnt
			}
		}
		return nil
	})

	return found, err
}

func (state *traceState) selectRule(ctx *SearchContext, r *rule) {
	ctx.PolicyTrace("* Rule %s: selected\n", r)
	state.selectedRules++
}

func (state *traceState) unSelectRule(ctx *SearchContext, labels labels.LabelArray, r *rule) {
	ctx.PolicyTraceVerbose("  Rule %s: did not select %+v\n", r, labels)
}

// resolveIngressPolicy analyzes the rule against the given SearchContext, and
// merges it with any prior-generated policy within the provided L4Policy.
// Requirements based off of all Ingress requirements (set in FromRequires) in
// other rules are stored in the specified slice of LabelSelectorRequirement.
// These requirements are dynamically inserted into a copy of the receiver rule,
// as requirements form conjunctions across all rules.
func (r *rule) resolveIngressPolicy(
	policyCtx PolicyContext,
	ctx *SearchContext,
	state *traceState,
	result L4PolicyMap,
	requirements, requirementsDeny []slim_metav1.LabelSelectorRequirement,
) (
	L4PolicyMap, error,
) {
	if !ctx.rulesSelect {
		if !r.getSelector().Matches(ctx.To) {
			state.unSelectRule(ctx, ctx.To, r)
			return nil, nil
		}
	}

	state.selectRule(ctx, r)
	found, foundDeny := 0, 0

	if len(r.Ingress) == 0 && len(r.IngressDeny) == 0 {
		ctx.PolicyTrace("    No ingress rules\n")
	}
	for _, ingressRule := range r.Ingress {
		fromEndpoints := ingressRule.GetSourceEndpointSelectorsWithRequirements(requirements)
		cnt, err := mergeIngress(policyCtx, ctx, fromEndpoints, ingressRule.ToPorts, r.Rule.Labels.DeepCopy(), result)
		if err != nil {
			return nil, err
		}
		if cnt > 0 {
			found += cnt
		}
	}

	oldDeny := policyCtx.SetDeny(true)
	defer func() {
		policyCtx.SetDeny(oldDeny)
	}()
	for _, ingressRule := range r.IngressDeny {
		fromEndpoints := ingressRule.GetSourceEndpointSelectorsWithRequirements(requirementsDeny)
		cnt, err := mergeIngress(policyCtx, ctx, fromEndpoints, ingressRule.ToPorts, r.Rule.Labels.DeepCopy(), result)
		if err != nil {
			return nil, err
		}
		if cnt > 0 {
			foundDeny += cnt
		}
	}

	if found+foundDeny > 0 {
		if found != 0 {
			state.matchedRules++
		}
		if foundDeny != 0 {
			state.matchedDenyRules++
		}
		return result, nil
	}

	return nil, nil
}

// ********************** CIDR POLICY **********************

// mergeCIDR inserts all of the CIDRs in ipRules to resMap. Returns the number
// of CIDRs added to resMap.
func mergeCIDR(ctx *SearchContext, isDeny bool, dir string, ipRules []api.CIDR, ruleLabels labels.LabelArray, resMap *CIDRPolicyMap) int {
	found := 0

	for _, r := range ipRules {
		strCIDR := string(r)
		if !isDeny {
			ctx.PolicyTrace("  Allows %s IP %s\n", dir, strCIDR)
		} else {
			ctx.PolicyTrace("  Denies %s IP %s\n", dir, strCIDR)
		}

		found += resMap.Insert(strCIDR, ruleLabels)
	}

	return found
}

// resolveCIDRPolicy inserts the CIDRs from the specified rule into result if
// the rule corresponds to the current SearchContext. It returns the resultant
// CIDRPolicy containing the added ingress and egress CIDRs. If no CIDRs are
// added to result, a nil CIDRPolicy is returned.
func (r *rule) resolveCIDRPolicy(ctx *SearchContext, state *traceState, result *CIDRPolicy) *CIDRPolicy {
	// Don't select rule if it doesn't apply to the given context.
	if !ctx.rulesSelect {
		if !r.getSelector().Matches(ctx.To) {
			state.unSelectRule(ctx, ctx.To, r)
			return nil
		}
	}

	state.selectRule(ctx, r)
	found := 0

	for _, ingressRule := range r.Ingress {
		// TODO (ianvernon): GH-1658
		allCIDRs := make([]api.CIDR, 0, len(ingressRule.FromCIDR))
		allCIDRs = append(allCIDRs, ingressRule.FromCIDR...)
		allCIDRs = append(allCIDRs, api.ComputeResultantCIDRSet(ingressRule.FromCIDRSet)...)

		// CIDR + L4 rules are handled via mergeIngress(),
		// skip them here.
		if len(allCIDRs) > 0 && len(ingressRule.ToPorts) > 0 {
			continue
		}

		if cnt := mergeCIDR(ctx, false, "Ingress", allCIDRs, r.Labels, &result.Ingress); cnt > 0 {
			found += cnt
		}
	}

	for _, ingressRule := range r.IngressDeny {
		// TODO (ianvernon): GH-1658
		allCIDRs := make([]api.CIDR, 0, len(ingressRule.FromCIDR))
		allCIDRs = append(allCIDRs, ingressRule.FromCIDR...)
		allCIDRs = append(allCIDRs, api.ComputeResultantCIDRSet(ingressRule.FromCIDRSet)...)

		// CIDR + L4 rules are handled via mergeIngress(),
		// skip them here.
		if len(allCIDRs) > 0 && len(ingressRule.ToPorts) > 0 {
			continue
		}

		if cnt := mergeCIDR(ctx, true, "Ingress", allCIDRs, r.Labels, &result.Ingress); cnt > 0 {
			found += cnt
		}
	}

	// CIDR egress policy is used for visibility of desired state in
	// the API and for determining which prefix lengths are available,
	// however it does not determine the actual CIDRs in the BPF maps
	// for allowing traffic by CIDR!
	for _, egressRule := range r.Egress {
		allCIDRs := make([]api.CIDR, 0, len(egressRule.ToCIDR))
		allCIDRs = append(allCIDRs, egressRule.ToCIDR...)
		allCIDRs = append(allCIDRs, api.ComputeResultantCIDRSet(egressRule.ToCIDRSet)...)

		// Unlike the Ingress policy which only counts L3 policy in
		// this function, we count the CIDR+L4 policy in the
		// desired egress CIDR policy here as well. This ensures
		// proper computation of IPcache prefix lengths.
		if cnt := mergeCIDR(ctx, false, "Egress", allCIDRs, r.Labels, &result.Egress); cnt > 0 {
			found += cnt
		}
	}

	for _, egressRule := range r.EgressDeny {
		allCIDRs := make([]api.CIDR, 0, len(egressRule.ToCIDR))
		allCIDRs = append(allCIDRs, egressRule.ToCIDR...)
		allCIDRs = append(allCIDRs, api.ComputeResultantCIDRSet(egressRule.ToCIDRSet)...)

		// Unlike the Ingress policy which only counts L3 policy in
		// this function, we count the CIDR+L4 policy in the
		// desired egress CIDR policy here as well. This ensures
		// proper computation of IPcache prefix lengths.
		if cnt := mergeCIDR(ctx, true, "Egress", allCIDRs, r.Labels, &result.Egress); cnt > 0 {
			found += cnt
		}
	}

	if found > 0 {
		return result
	}

	ctx.PolicyTrace("    No L3 rules\n")
	return nil
}

func (r *rule) matches(securityIdentity *identity.Identity) bool {
	r.metadata.Mutex.Lock()
	defer r.metadata.Mutex.Unlock()
	var ruleMatches bool

	if ruleMatches, cached := r.metadata.IdentitySelected[securityIdentity.ID]; cached {
		return ruleMatches
	}
	isNode := securityIdentity.ID == identity.ReservedIdentityHost
	if (r.NodeSelector.LabelSelector != nil) != isNode {
		r.metadata.IdentitySelected[securityIdentity.ID] = false
		return ruleMatches
	}
	// Fall back to costly matching.
	if ruleMatches = r.getSelector().Matches(securityIdentity.LabelArray); ruleMatches {
		// Update cache so we don't have to do costly matching again.
		r.metadata.IdentitySelected[securityIdentity.ID] = true
	} else {
		r.metadata.IdentitySelected[securityIdentity.ID] = false
	}

	return ruleMatches
}

// ****************** EGRESS POLICY ******************

func mergeEgress(policyCtx PolicyContext, ctx *SearchContext, toEndpoints api.EndpointSelectorSlice, toPorts api.PortsIterator, ruleLabels labels.LabelArray, resMap L4PolicyMap, fqdns api.FQDNSelectorSlice) (int, error) {
	found := 0

	if ctx.To != nil && len(toEndpoints) > 0 {
		if ctx.TraceEnabled() {
			traceL3(ctx, toEndpoints, "to", policyCtx.IsDeny())
		}
		if !toEndpoints.Matches(ctx.To) {
			ctx.PolicyTrace("      No label match for %s", ctx.To)
			return 0, nil
		}
		ctx.PolicyTrace("      Found all required labels")
	}

	var (
		cnt int
		err error
	)

	// L3-only rule (with requirements folded into toEndpoints).
	if toPorts.Len() == 0 && len(toEndpoints) > 0 {
		cnt, err = mergeEgressPortProto(policyCtx, ctx, toEndpoints, &api.PortRule{}, api.PortProtocol{Port: "0", Protocol: api.ProtoAny}, api.ProtoAny, ruleLabels, resMap, fqdns)
		if err != nil {
			return found, err
		}
	}

	found += cnt

	err = toPorts.Iterate(func(r api.Ports) error {
		// For L4 Policy, an empty slice of EndpointSelector indicates that the
		// rule allows all at L3 - explicitly specify this by creating a slice
		// with the WildcardEndpointSelector.
		if len(toEndpoints) == 0 {
			toEndpoints = api.EndpointSelectorSlice{api.WildcardEndpointSelector}
		}
		if !policyCtx.IsDeny() {
			ctx.PolicyTrace("      Allows port %v\n", r.GetPortProtocols())
		} else {
			ctx.PolicyTrace("      Denies port %v\n", r.GetPortProtocols())
		}

		pr := r.GetPortRule()
		if pr != nil {
			if !pr.Rules.IsEmpty() {
				for _, l7 := range pr.Rules.HTTP {
					ctx.PolicyTrace("          %+v\n", l7)
				}
				for _, l7 := range pr.Rules.Kafka {
					ctx.PolicyTrace("          %+v\n", l7)
				}
				for _, l7 := range pr.Rules.L7 {
					ctx.PolicyTrace("          %+v\n", l7)
				}
			}
		}

		for _, p := range r.GetPortProtocols() {
			if p.Protocol != api.ProtoAny {
				cnt, err := mergeEgressPortProto(policyCtx, ctx, toEndpoints, r, p, p.Protocol, ruleLabels, resMap, fqdns)
				if err != nil {
					return err
				}
				found += cnt
			} else {
				cnt, err := mergeEgressPortProto(policyCtx, ctx, toEndpoints, r, p, api.ProtoTCP, ruleLabels, resMap, fqdns)
				if err != nil {
					return err
				}
				found += cnt

				cnt, err = mergeEgressPortProto(policyCtx, ctx, toEndpoints, r, p, api.ProtoUDP, ruleLabels, resMap, fqdns)
				if err != nil {
					return err
				}
				found += cnt
			}
		}
		return nil
	},
	)

	return found, err
}

// mergeEgressPortProto merges all rules which share the same port & protocol that
// select a given set of endpoints. It updates the L4Filter mapped to by the specified
// port and protocol with the contents of the provided PortRule. If the rule
// being merged has conflicting L7 rules with those already in the provided
// L4PolicyMap for the specified port-protocol tuple, it returns an error.
func mergeEgressPortProto(policyCtx PolicyContext, ctx *SearchContext, endpoints api.EndpointSelectorSlice, r api.Ports, p api.PortProtocol,
	proto api.L4Proto, ruleLabels labels.LabelArray, resMap L4PolicyMap, fqdns api.FQDNSelectorSlice) (int, error) {
	// Create a new L4Filter
	filterToMerge, err := createL4EgressFilter(policyCtx, endpoints, r, p, proto, ruleLabels, fqdns)
	if err != nil {
		return 0, err
	}

	err = addL4Filter(policyCtx, ctx, resMap, p, proto, filterToMerge, ruleLabels)
	if err != nil {
		return 0, err
	}
	return 1, err
}

func (r *rule) resolveEgressPolicy(
	policyCtx PolicyContext,
	ctx *SearchContext,
	state *traceState,
	result L4PolicyMap,
	requirements, requirementsDeny []slim_metav1.LabelSelectorRequirement,
) (
	L4PolicyMap, error,
) {
	if !ctx.rulesSelect {
		if !r.getSelector().Matches(ctx.From) {
			state.unSelectRule(ctx, ctx.From, r)
			return nil, nil
		}
	}

	state.selectRule(ctx, r)
	found, foundDeny := 0, 0

	if len(r.Egress) == 0 && len(r.EgressDeny) == 0 {
		ctx.PolicyTrace("    No egress rules\n")
	}
	for _, egressRule := range r.Egress {
		toEndpoints := egressRule.GetDestinationEndpointSelectorsWithRequirements(requirements)
		cnt, err := mergeEgress(policyCtx, ctx, toEndpoints, egressRule.ToPorts, r.Rule.Labels.DeepCopy(), result, egressRule.ToFQDNs)
		if err != nil {
			return nil, err
		}
		if cnt > 0 {
			found += cnt
		}
	}

	oldDeny := policyCtx.SetDeny(true)
	defer func() {
		policyCtx.SetDeny(oldDeny)
	}()
	for _, egressRule := range r.EgressDeny {
		toEndpoints := egressRule.GetDestinationEndpointSelectorsWithRequirements(requirementsDeny)
		cnt, err := mergeEgress(policyCtx, ctx, toEndpoints, egressRule.ToPorts, r.Rule.Labels.DeepCopy(), result, nil)
		if err != nil {
			return nil, err
		}
		if cnt > 0 {
			foundDeny += cnt
		}
	}

	if found+foundDeny > 0 {
		if found != 0 {
			state.matchedRules++
		}
		if foundDeny != 0 {
			state.matchedDenyRules++
		}
		return result, nil
	}

	return nil, nil
}


text:
package io.cattle.platform.spring.web;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

import org.springframework.web.context.support.WebApplicationContextUtils;

public abstract class SpringFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        WebApplicationContextUtils
            .getRequiredWebApplicationContext(filterConfig.getServletContext())
            .getAutowireCapableBeanFactory()
            .autowireBean(this);
    }

    @Override
    public void destroy() {
    }

}


text:
from myMiddleware import MyMiddleware, MyHandler

urls = [(r"^/.*$", MyMiddleware, MyHandler, "pos-arg-value",
                                 {"named_arg": "named-arg-value"})]


text:
using base::ASCIIToUTF16;

namespace views {
class InkDropDelegate;

namespace test {

// A MenuButton subclass that provides access to some MenuButton internals.
class TestMenuButton : public MenuButton {
 public:
  explicit TestMenuButton(MenuButtonListener* menu_button_listener)
      : MenuButton(base::string16(ASCIIToUTF16("button")),
                   menu_button_listener,
                   false) {}

  ~TestMenuButton() override {}

  // Accessors to protected MenuButton methods.
  void set_ink_drop_delegate(InkDropDelegate* ink_drop_delegate) {
    MenuButton::set_ink_drop_delegate(ink_drop_delegate);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(TestMenuButton);
};

class MenuButtonTest : public ViewsTestBase {
 public:
  MenuButtonTest() : widget_(nullptr), button_(nullptr) {}
  ~MenuButtonTest() override {}

  void TearDown() override {
    generator_.reset();
    if (widget_ && !widget_->IsClosed())
      widget_->Close();

    ViewsTestBase::TearDown();
  }

  Widget* widget() { return widget_; }
  TestMenuButton* button() { return button_; }
  ui::test::EventGenerator* generator() { return generator_.get(); }

 protected:
  // Creates a MenuButton with no button listener.
  void CreateMenuButtonWithNoListener() { CreateMenuButton(nullptr); }

  // Creates a MenuButton with a MenuButtonListener. In this case, when the
  // MenuButton is pushed, it notifies the MenuButtonListener to open a
  // drop-down menu.
  void CreateMenuButtonWithMenuButtonListener(
      MenuButtonListener* menu_button_listener) {
    CreateMenuButton(menu_button_listener);
  }

 private:
  void CreateMenuButton(MenuButtonListener* menu_button_listener) {
    CreateWidget();
    generator_.reset(new ui::test::EventGenerator(GetContext(),
        widget_->GetNativeWindow()));
    // Set initial mouse location in a consistent way so that the menu button we
    // are about to create initializes its hover state in a consistent manner.
    generator_->set_current_location(gfx::Point(10, 10));

    button_ = new TestMenuButton(menu_button_listener);
    button_->SetBoundsRect(gfx::Rect(0, 0, 200, 20));
    widget_->SetContentsView(button_);

    widget_->Show();
  }

  void CreateWidget() {
    DCHECK(!widget_);

    widget_ = new Widget;
    Widget::InitParams params =
        CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
    params.bounds = gfx::Rect(0, 0, 200, 200);
    widget_->Init(params);
  }

  Widget* widget_;
  TestMenuButton* button_;
  std::unique_ptr<ui::test::EventGenerator> generator_;

  DISALLOW_COPY_AND_ASSIGN(MenuButtonTest);
};

class TestButtonListener : public ButtonListener {
 public:
  TestButtonListener()
      : last_sender_(nullptr),
        last_sender_state_(Button::STATE_NORMAL),
        last_event_type_(ui::ET_UNKNOWN) {}
  ~TestButtonListener() override {}

  void ButtonPressed(Button* sender, const ui::Event& event) override {
    last_sender_ = sender;
    CustomButton* custom_button = CustomButton::AsCustomButton(sender);
    DCHECK(custom_button);
    last_sender_state_ = custom_button->state();
    last_event_type_ = event.type();
  }

  Button* last_sender() { return last_sender_; }
  Button::ButtonState last_sender_state() { return last_sender_state_; }
  ui::EventType last_event_type() { return last_event_type_; }

 private:
  Button* last_sender_;
  Button::ButtonState last_sender_state_;
  ui::EventType last_event_type_;

  DISALLOW_COPY_AND_ASSIGN(TestButtonListener);
};

class TestMenuButtonListener : public MenuButtonListener {
 public:
  TestMenuButtonListener()
      : last_source_(nullptr), last_source_state_(Button::STATE_NORMAL) {}
  ~TestMenuButtonListener() override {}

  void OnMenuButtonClicked(MenuButton* source,
                           const gfx::Point& point,
                           const ui::Event* event) override {
    last_source_ = source;
    CustomButton* custom_button = CustomButton::AsCustomButton(source);
    DCHECK(custom_button);
    last_source_state_ = custom_button->state();
  }

  View* last_source() { return last_source_; }
  Button::ButtonState last_source_state() { return last_source_state_; }

 private:
  View* last_source_;
  Button::ButtonState last_source_state_;

  DISALLOW_COPY_AND_ASSIGN(TestMenuButtonListener);
};

// A MenuButtonListener that will acquire a PressedLock in the
// OnMenuButtonClicked() method and optionally release it as well.
class PressStateMenuButtonListener : public MenuButtonListener {
 public:
  explicit PressStateMenuButtonListener(bool release_lock)
      : menu_button_(nullptr), release_lock_(release_lock) {}

  ~PressStateMenuButtonListener() override {}

  void set_menu_button(MenuButton* menu_button) { menu_button_ = menu_button; }

  void OnMenuButtonClicked(MenuButton* source,
                           const gfx::Point& point,
                           const ui::Event* event) override {
    pressed_lock_.reset(new MenuButton::PressedLock(menu_button_));
    if (release_lock_)
      pressed_lock_.reset();
  }

 private:
  MenuButton* menu_button_;

  std::unique_ptr<MenuButton::PressedLock> pressed_lock_;

  // The |pressed_lock_| will be released when true.
  bool release_lock_;

  DISALLOW_COPY_AND_ASSIGN(PressStateMenuButtonListener);
};

// Basic implementation of a DragController, to test input behaviour for
// MenuButtons that can be dragged.
class TestDragController : public DragController {
 public:
  TestDragController() {}
  ~TestDragController() override {}

  void WriteDragDataForView(View* sender,
                            const gfx::Point& press_pt,
                            ui::OSExchangeData* data) override {}

  int GetDragOperationsForView(View* sender, const gfx::Point& p) override {
    return ui::DragDropTypes::DRAG_MOVE;
  }

  bool CanStartDragForView(View* sender,
                           const gfx::Point& press_pt,
                           const gfx::Point& p) override {
    return true;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(TestDragController);
};

#if defined(USE_AURA)
// Basic implementation of a DragDropClient, tracking the state of the drag
// operation. While dragging addition mouse events are consumed, preventing the
// target view from receiving them.
class TestDragDropClient : public aura::client::DragDropClient,
                           public ui::EventHandler {
 public:
  TestDragDropClient();
  ~TestDragDropClient() override;

  // aura::client::DragDropClient:
  int StartDragAndDrop(const ui::OSExchangeData& data,
                       aura::Window* root_window,
                       aura::Window* source_window,
                       const gfx::Point& screen_location,
                       int operation,
                       ui::DragDropTypes::DragEventSource source) override;
  void DragUpdate(aura::Window* target, const ui::LocatedEvent& event) override;
  void Drop(aura::Window* target, const ui::LocatedEvent& event) override;
  void DragCancel() override;
  bool IsDragDropInProgress() override;

  // ui::EventHandler:
  void OnMouseEvent(ui::MouseEvent* event) override;

 private:
  // True while receiving ui::LocatedEvents for drag operations.
  bool drag_in_progress_;

  // Target window where drag operations are occuring.
  aura::Window* target_;

  DISALLOW_COPY_AND_ASSIGN(TestDragDropClient);
};

TestDragDropClient::TestDragDropClient()
    : drag_in_progress_(false), target_(nullptr) {
}

TestDragDropClient::~TestDragDropClient() {
}

int TestDragDropClient::StartDragAndDrop(
    const ui::OSExchangeData& data,
    aura::Window* root_window,
    aura::Window* source_window,
    const gfx::Point& screen_location,
    int operation,
    ui::DragDropTypes::DragEventSource source) {
  if (IsDragDropInProgress())
    return ui::DragDropTypes::DRAG_NONE;
  drag_in_progress_ = true;
  target_ = root_window;
  return operation;
}

void TestDragDropClient::DragUpdate(aura::Window* target,
                                    const ui::LocatedEvent& event) {
}

void TestDragDropClient::Drop(aura::Window* target,
                              const ui::LocatedEvent& event) {
  drag_in_progress_ = false;
}

void TestDragDropClient::DragCancel() {
  drag_in_progress_ = false;
}

bool TestDragDropClient::IsDragDropInProgress() {
  return drag_in_progress_;
}

void TestDragDropClient::OnMouseEvent(ui::MouseEvent* event) {
  if (!IsDragDropInProgress())
    return;
  switch (event->type()) {
    case ui::ET_MOUSE_DRAGGED:
      DragUpdate(target_, *event);
      event->StopPropagation();
      break;
    case ui::ET_MOUSE_RELEASED:
      Drop(target_, *event);
      event->StopPropagation();
      break;
    default:
      break;
  }
}
#endif  // defined(USE_AURA)

class TestShowSiblingButtonListener : public MenuButtonListener {
 public:
  TestShowSiblingButtonListener() {}
  ~TestShowSiblingButtonListener() override {}

  void OnMenuButtonClicked(MenuButton* source,
                           const gfx::Point& point,
                           const ui::Event* event) override {
    // The MenuButton itself doesn't set the PRESSED state during Activate() or
    // OnMenuButtonClicked(). That should be handled by the MenuController or,
    // if no menu is shown, the listener.
    EXPECT_EQ(Button::STATE_HOVERED, static_cast<MenuButton*>(source)->state());
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(TestShowSiblingButtonListener);
};

// Tests if the listener is notified correctly when a mouse click happens on a
// MenuButton that has a MenuButtonListener.
TEST_F(MenuButtonTest, ActivateDropDownOnMouseClick) {
  TestMenuButtonListener menu_button_listener;
  CreateMenuButtonWithMenuButtonListener(&menu_button_listener);

  generator()->ClickLeftButton();

  // Check that MenuButton has notified the listener, while it was in pressed
  // state.
  EXPECT_EQ(button(), menu_button_listener.last_source());
  EXPECT_EQ(Button::STATE_HOVERED, menu_button_listener.last_source_state());
}

// Test that the MenuButton stays pressed while there are any PressedLocks.
TEST_F(MenuButtonTest, ButtonStateForMenuButtonsWithPressedLocks) {
  CreateMenuButtonWithNoListener();

  // Move the mouse over the button; the button should be in a hovered state.
  generator()->MoveMouseTo(gfx::Point(10, 10));
  EXPECT_EQ(Button::STATE_HOVERED, button()->state());

  // Introduce a PressedLock, which should make the button pressed.
  std::unique_ptr<MenuButton::PressedLock> pressed_lock1(
      new MenuButton::PressedLock(button()));
  EXPECT_EQ(Button::STATE_PRESSED, button()->state());

  // Even if we move the mouse outside of the button, it should remain pressed.
  generator()->MoveMouseTo(gfx::Point(300, 10));
  EXPECT_EQ(Button::STATE_PRESSED, button()->state());

  // Creating a new lock should obviously keep the button pressed.
  std::unique_ptr<MenuButton::PressedLock> pressed_lock2(
      new MenuButton::PressedLock(button()));
  EXPECT_EQ(Button::STATE_PRESSED, button()->state());

  // The button should remain pressed while any locks are active.
  pressed_lock1.reset();
  EXPECT_EQ(Button::STATE_PRESSED, button()->state());

  // Reseting the final lock should return the button's state to normal...
  pressed_lock2.reset();
  EXPECT_EQ(Button::STATE_NORMAL, button()->state());

  // ...And it should respond to mouse movement again.
  generator()->MoveMouseTo(gfx::Point(10, 10));
  EXPECT_EQ(Button::STATE_HOVERED, button()->state());

  // Test that the button returns to the appropriate state after the press; if
  // the mouse ends over the button, the button should be hovered.
  pressed_lock1.reset(new MenuButton::PressedLock(button()));
  EXPECT_EQ(Button::STATE_PRESSED, button()->state());
  pressed_lock1.reset();
  EXPECT_EQ(Button::STATE_HOVERED, button()->state());

  // If the button is disabled before the pressed lock, it should be disabled
  // after the pressed lock.
  button()->SetState(Button::STATE_DISABLED);
  pressed_lock1.reset(new MenuButton::PressedLock(button()));
  EXPECT_EQ(Button::STATE_PRESSED, button()->state());
  pressed_lock1.reset();
  EXPECT_EQ(Button::STATE_DISABLED, button()->state());

  generator()->MoveMouseTo(gfx::Point(300, 10));

  // Edge case: the button is disabled, a pressed lock is added, and then the
  // button is re-enabled. It should be enabled after the lock is removed.
  pressed_lock1.reset(new MenuButton::PressedLock(button()));
  EXPECT_EQ(Button::STATE_PRESSED, button()->state());
  button()->SetState(Button::STATE_NORMAL);
  pressed_lock1.reset();
  EXPECT_EQ(Button::STATE_NORMAL, button()->state());
}

// Test that if a sibling menu is shown, the original menu button releases its
// PressedLock.
TEST_F(MenuButtonTest, PressedStateWithSiblingMenu) {
  TestShowSiblingButtonListener listener;
  CreateMenuButtonWithMenuButtonListener(&listener);

  // Move the mouse over the button; the button should be in a hovered state.
  generator()->MoveMouseTo(gfx::Point(10, 10));
  EXPECT_EQ(Button::STATE_HOVERED, button()->state());
  generator()->ClickLeftButton();
  // Test is continued in TestShowSiblingButtonListener::OnMenuButtonClicked().
}

// Test that the MenuButton does not become pressed if it can be dragged, until
// a release occurs.
TEST_F(MenuButtonTest, DraggableMenuButtonActivatesOnRelease) {
  TestMenuButtonListener menu_button_listener;
  CreateMenuButtonWithMenuButtonListener(&menu_button_listener);
  TestDragController drag_controller;
  button()->set_drag_controller(&drag_controller);

  generator()->PressLeftButton();
  EXPECT_EQ(nullptr, menu_button_listener.last_source());

  generator()->ReleaseLeftButton();
  EXPECT_EQ(button(), menu_button_listener.last_source());
  EXPECT_EQ(Button::STATE_HOVERED, menu_button_listener.last_source_state());
}

TEST_F(MenuButtonTest, InkDropStateForMenuButtonActivationsWithoutListener) {
  CreateMenuButtonWithNoListener();
  TestInkDropDelegate ink_drop_delegate;
  ink_drop_delegate.OnAction(InkDropState::ACTION_PENDING);
  button()->set_ink_drop_delegate(&ink_drop_delegate);
  button()->Activate(nullptr);

  EXPECT_EQ(InkDropState::HIDDEN, ink_drop_delegate.GetTargetInkDropState());
}

TEST_F(MenuButtonTest,
       InkDropStateForMenuButtonActivationsWithListenerThatDoesntAcquireALock) {
  TestMenuButtonListener menu_button_listener;
  CreateMenuButtonWithMenuButtonListener(&menu_button_listener);
  TestInkDropDelegate ink_drop_delegate;
  button()->set_ink_drop_delegate(&ink_drop_delegate);
  button()->Activate(nullptr);

  EXPECT_EQ(InkDropState::ACTION_TRIGGERED,
            ink_drop_delegate.GetTargetInkDropState());
}

TEST_F(
    MenuButtonTest,
    InkDropStateForMenuButtonActivationsWithListenerThatDontReleaseAllLocks) {
  PressStateMenuButtonListener menu_button_listener(false);
  CreateMenuButtonWithMenuButtonListener(&menu_button_listener);
  menu_button_listener.set_menu_button(button());
  TestInkDropDelegate ink_drop_delegate;
  button()->set_ink_drop_delegate(&ink_drop_delegate);
  button()->Activate(nullptr);

  EXPECT_EQ(InkDropState::ACTIVATED, ink_drop_delegate.GetTargetInkDropState());

  // Prevent the button from accessing invalid memory during clean up.
  button()->set_ink_drop_delegate(nullptr);
}

TEST_F(MenuButtonTest,
       InkDropStateForMenuButtonActivationsWithListenerThatReleaseAllLocks) {
  PressStateMenuButtonListener menu_button_listener(true);
  CreateMenuButtonWithMenuButtonListener(&menu_button_listener);
  menu_button_listener.set_menu_button(button());
  TestInkDropDelegate ink_drop_delegate;
  button()->set_ink_drop_delegate(&ink_drop_delegate);
  button()->Activate(nullptr);

  EXPECT_EQ(InkDropState::DEACTIVATED,
            ink_drop_delegate.GetTargetInkDropState());
}

TEST_F(MenuButtonTest, InkDropStateForMenuButtonsWithPressedLocks) {
  CreateMenuButtonWithNoListener();
  TestInkDropDelegate ink_drop_delegate;
  button()->set_ink_drop_delegate(&ink_drop_delegate);

  std::unique_ptr<MenuButton::PressedLock> pressed_lock1(
      new MenuButton::PressedLock(button()));

  EXPECT_EQ(InkDropState::ACTIVATED, ink_drop_delegate.GetTargetInkDropState());

  std::unique_ptr<MenuButton::PressedLock> pressed_lock2(
      new MenuButton::PressedLock(button()));

  EXPECT_EQ(InkDropState::ACTIVATED, ink_drop_delegate.GetTargetInkDropState());

  pressed_lock1.reset();
  EXPECT_EQ(InkDropState::ACTIVATED, ink_drop_delegate.GetTargetInkDropState());

  pressed_lock2.reset();
  EXPECT_EQ(InkDropState::DEACTIVATED,
            ink_drop_delegate.GetTargetInkDropState());
}

// Verifies only one ink drop animation is triggered when multiple PressedLocks
// are attached to a MenuButton.
TEST_F(MenuButtonTest, OneInkDropAnimationForReentrantPressedLocks) {
  CreateMenuButtonWithNoListener();
  TestInkDropDelegate ink_drop_delegate;
  button()->set_ink_drop_delegate(&ink_drop_delegate);

  std::unique_ptr<MenuButton::PressedLock> pressed_lock1(
      new MenuButton::PressedLock(button()));

  EXPECT_EQ(InkDropState::ACTIVATED, ink_drop_delegate.GetTargetInkDropState());
  ink_drop_delegate.OnAction(InkDropState::ACTION_PENDING);

  std::unique_ptr<MenuButton::PressedLock> pressed_lock2(
      new MenuButton::PressedLock(button()));

  EXPECT_EQ(InkDropState::ACTION_PENDING,
            ink_drop_delegate.GetTargetInkDropState());
}

// Verifies the InkDropState is left as ACTIVATED if a PressedLock is active
// before another Activation occurs.
TEST_F(MenuButtonTest,
       InkDropStateForMenuButtonWithPressedLockBeforeActivation) {
  TestMenuButtonListener menu_button_listener;
  CreateMenuButtonWithMenuButtonListener(&menu_button_listener);
  TestInkDropDelegate ink_drop_delegate;
  button()->set_ink_drop_delegate(&ink_drop_delegate);
  MenuButton::PressedLock lock(button());

  button()->Activate(nullptr);

  EXPECT_EQ(InkDropState::ACTIVATED, ink_drop_delegate.GetTargetInkDropState());
}

#if defined(USE_AURA)

// Tests that the MenuButton does not become pressed if it can be dragged, and a
// DragDropClient is processing the events.
TEST_F(MenuButtonTest, DraggableMenuButtonDoesNotActivateOnDrag) {
  TestMenuButtonListener menu_button_listener;
  CreateMenuButtonWithMenuButtonListener(&menu_button_listener);
  TestDragController drag_controller;
  button()->set_drag_controller(&drag_controller);

  TestDragDropClient drag_client;
  SetDragDropClient(GetContext(), &drag_client);
  button()->PrependPreTargetHandler(&drag_client);

  generator()->DragMouseBy(10, 0);
  EXPECT_EQ(nullptr, menu_button_listener.last_source());
  EXPECT_EQ(Button::STATE_NORMAL, menu_button_listener.last_source_state());
}

#endif  // USE_AURA

// No touch on desktop Mac. Tracked in http://crbug.com/445520.
#if !defined(OS_MACOSX) || defined(USE_AURA)

// Tests if the listener is notified correctly when a gesture tap happens on a
// MenuButton that has a MenuButtonListener.
TEST_F(MenuButtonTest, ActivateDropDownOnGestureTap) {
  TestMenuButtonListener menu_button_listener;
  CreateMenuButtonWithMenuButtonListener(&menu_button_listener);

  // Move the mouse outside the menu button so that it doesn't impact the
  // button state.
  generator()->MoveMouseTo(400, 400);
  EXPECT_FALSE(button()->IsMouseHovered());

  generator()->GestureTapAt(gfx::Point(10, 10));

  // Check that MenuButton has notified the listener, while it was in pressed
  // state.
  EXPECT_EQ(button(), menu_button_listener.last_source());
  EXPECT_EQ(Button::STATE_HOVERED, menu_button_listener.last_source_state());

  // The button should go back to it's normal state since the gesture ended.
  EXPECT_EQ(Button::STATE_NORMAL, button()->state());
}

// Tests that the button enters a hovered state upon a tap down, before becoming
// pressed at activation.
TEST_F(MenuButtonTest, TouchFeedbackDuringTap) {
  TestMenuButtonListener menu_button_listener;
  CreateMenuButtonWithMenuButtonListener(&menu_button_listener);
  generator()->PressTouch();
  EXPECT_EQ(Button::STATE_HOVERED, button()->state());

  generator()->ReleaseTouch();
  EXPECT_EQ(Button::STATE_HOVERED, menu_button_listener.last_source_state());
}

// Tests that a move event that exits the button returns it to the normal state,
// and that the button did not activate the listener.
TEST_F(MenuButtonTest, TouchFeedbackDuringTapCancel) {
  TestMenuButtonListener menu_button_listener;
  CreateMenuButtonWithMenuButtonListener(&menu_button_listener);
  generator()->PressTouch();
  EXPECT_EQ(Button::STATE_HOVERED, button()->state());

  generator()->MoveTouch(gfx::Point(10, 30));
  generator()->ReleaseTouch();
  EXPECT_EQ(Button::STATE_NORMAL, button()->state());
  EXPECT_EQ(nullptr, menu_button_listener.last_source());
}

#endif  // !defined(OS_MACOSX) || defined(USE_AURA)

}  // namespace views
}  // namespace test


text:
<?php

namespace Frigg\KeeprBundle\Elastica;

use FOS\ElasticaBundle\Elastica\Client as BaseClient;
use Elastica\Exception\ExceptionInterface;
use Elastica\Response;
use Elastica\Request;

/**
 * Override to suppress exceptions.
 */
class ElasticaClient extends BaseClient
{
    /**
     * @param string $path
     * @param string $method
     * @param array  $data
     * @param array  $query
     *
     * @return Response
     */
    public function request($path, $method = Request::GET, $data = [], array $query = [])
    {
        try {
            return parent::request($path, $method, $data, $query);
        } catch (ExceptionInterface $e) {
            return new Response('{"took":0,"timed_out":false,"hits":{"total":0,"max_score":0,"hits":[]}}');
        }
    }
}


text:
package runner

import (
	"bytes"
	"context"
	"fmt"
	"hello-compsci/code-runner/common"
	"io/ioutil"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

const runtimeLimit = 2 // seconds
var ReadyToBuildChan chan bool

// will be called right after package variables are instantiated
func init() {
	ReadyToBuildChan = make(chan bool, 1) // can hold 1
	ReadyToBuildChan <- true
}

//Code runs code files and stores output
type Code struct {
	OutputFile      string
	CompilerErrFile string
	buildCMD        string
	buildARGs       []string
	runCMD          string
	runARGs         []string
}

//NewCode returns a new Code with runCMD and buildCMD properly set
func NewCode(codeFile string) (*Code, error) {
	runCMD, runARGs := getRunCMD(codeFile)
	buildCMD, buildARGs := getBuildCMD(codeFile)

	if runCMD == "" && buildCMD == "" {
		return nil, fmt.Errorf("NewCode/Invalid filetype")
	}

	return &Code{
		CompilerErrFile: "output/cErr.txt",
		OutputFile:      "output/output.txt",
		buildCMD:        buildCMD,
		buildARGs:       buildARGs,
		runCMD:          runCMD,
		runARGs:         runARGs,
	}, nil
}
func getBuildCMD(codeFile string) (cmd string, args []string) {
	switch filepath.Ext(codeFile) {
	case ".go":
		cmd = "go"
		args = []string{"build", "-o", codeFile[:len(codeFile)-3], codeFile}
	case ".c":
		cmd = "gcc"
		args = []string{codeFile}
	case ".cpp":
		cmd = "g++"
		args = []string{codeFile}
	case ".java":
		cmd = "javac"
		args = []string{codeFile}
	}
	return
}

func getRunCMD(codeFile string) (cmd string, args []string) {
	switch filepath.Ext(codeFile) {
	case ".go":
		cmd = "./" + codeFile[:len(codeFile)-3]
		removePrevExecutable("./" + codeFile[:len(codeFile)-3])
	case ".c":
		cmd = "./a.out"
		removePrevExecutable("a.out")
	case ".cpp":
		cmd = "./a.out"
		removePrevExecutable("a.out")
	case ".java":
		cmd = "java"
		args = getJavaRunArgs(codeFile)
		removePrevExecutable(args[1] + args[2] + ".class")
	case ".py":
		cmd = "python3"
		args = []string{codeFile}
	}
	return
}

func removePrevExecutable(name string) {
	exec.Command("rm", name).Run()
}

func getJavaRunArgs(codeFile string) []string {
	tokens := strings.Split(codeFile, "/")
	var dir string
	for _, tok := range tokens[:len(tokens)-1] {
		dir += tok + "/"
	}
	fName := tokens[len(tokens)-1]
	return []string{"-cp", dir, fName[:len(fName)-5]}
}

//BuildRun builds and runs the saved code.
func (c *Code) BuildRun() (err error) {
	defer func() { ReadyToBuildChan <- true }()

	//build
	buildCMD := exec.Command(c.buildCMD, c.buildARGs...)
	var buildOut bytes.Buffer
	buildCMD.Stderr = &buildOut
	buildCMD.Run()

	//write output to file
	if err = ioutil.WriteFile(c.CompilerErrFile, buildOut.Bytes(), 0644); err != nil {
		return common.GetError("BuildRun", err)
	}

	return c.run(buildOut)
}

// accepts the output buffer for the build process in case it needs to be written to a file
func (c *Code) run(buildOut bytes.Buffer) (err error) {
	runContext, cancel := context.WithTimeout(context.Background(), time.Second*runtimeLimit)
	defer cancel()
	runCMD := exec.CommandContext(runContext, c.runCMD, c.runARGs...)
	var out bytes.Buffer
	runCMD.Stdout = &out //store output in out
	runCMD.Stderr = &out
	doneChan := make(chan bool)
	errChan := make(chan bool)
	go func() {
		if err = runCMD.Run(); err != nil {
			errChan <- true
		} else {
			doneChan <- true
		}
	}()

	select {
	case <-doneChan:
		if err = ioutil.WriteFile(c.OutputFile, out.Bytes(), 0644); err != nil {
			err = common.GetError("BuildRun", err)
		}
	case <-runContext.Done():
		// write the timeout error the the err file
		ioutil.WriteFile(c.CompilerErrFile, []byte("TIMEOUT: Process took too long to complete"), 0644)
		err = fmt.Errorf("BuildRun/TIMEOUT: Process took too long to complete")
	case <-errChan:
		ioutil.WriteFile(c.CompilerErrFile, buildOut.Bytes(), 0644)
	}
	return
}


text:
'use strict';

module.exports = moduleName => {
  const SampleModel = LUKEE.model.get(moduleName);
  const logger = new LUKEE.Logger();

  return new LUKEE.Controller(SampleModel, logger);
};


text:
"""
Example of a wordpress environment that creates a prod build.
"""

from fabric.state import env
from fabric.decorators import task
from fabrik.utils import get_stage_var

@task
def prod():
    from fabrik.recipes import wordpress
    wordpress.register()

    env.stage = "prod"
    env.branch = "master"

    # SSH info are not needed on local deployment.
    env.hosts = [get_stage_var("HOST")]
    env.user = get_stage_var("USER")
    env.password = get_stage_var("PASSWORD")
    env.app_path = get_stage_var("APP_PATH")
    env.source_path = get_stage_var("APP_SOURCE_PATH", "src")

    # (Optional) Public path (example: var/www/yourproject)
    env.public_path = get_stage_var("PUBLIC_PATH")


text:
<?php

echo'
';
echo'
';
echo'

Nhân Viên

			<form method="post" action="'.base_url().'admin.php/quanglynhanvien/employee_save" enctype="multipart/form-data">

Tên đăng nhập*	<input type="text" name="name" class="form-control" required>

Phân quyền	<select name="level">';
foreach ($chucvus as $cv) {
	echo '<option value="'.$cv["id"].'">'.$cv['title'].'</option>';
}
echo '			</select>

Mật khẩu*	<input id="pass1" type="password" name="pass" class="form-control" required>

Xác nhận mật khẩu*	<input id="pass2" type="password" name="pass1" class="form-control" required;">

Email*	<input type="text" name="email" class="form-control" required>

Tên Đầy Đủ*	<input type="text" name="fullname" class="form-control" required>

Ngày sinh	<input type="date" name="birthday" class="form-control" required>

Giới tính	<select name="sex">
					<option value="0">Nam</option>
					<option value="1">Nữ</option>
				</select>

Ngày vào làm	<input type="date" name="datein" class="form-control" required>

Ngày nghỉ việc	<input type="date" name="dateout" class="form-control">

Địa chỉ	<input type="text" name="address" class="form-control" required>

Điện thoại	<input type="number" name="phone" class="form-control" required>

Số chứng minh thư	<input type="number" name="CMND" class="form-control" required>

Kích hoạt
					<input name="active" type="radio" class="no-uniform" value="0" checked="checked" />Active
      				<input name="active" type="radio" class="no-uniform" value="1" />Unactive

Hình đại diện	<input type="file" name="icon" accept="image/*">

<input type="submit" value="Upload" class="btn btn-success">

				<input class="btn btn-success" value="Cancel">

			</form>

';
echo'
';
echo'
';

?>


text:
// Header for C3PaneCalendarAccount class

#ifndef __C3PANECALENDARACCOUNT__MULBERRY__
#define __C3PANECALENDARACCOUNT__MULBERRY__

#include "C3PaneViewPanel.h"

// Constants
const	PaneIDT		paneid_3PaneCalendarAccount = 1713;

// Messages

// Resources

// Classes
class CCalendarStoreView;

class C3PaneCalendarAccount : public C3PaneViewPanel
{
public:
	enum { class_ID = '3PND' };

					C3PaneCalendarAccount();
					C3PaneCalendarAccount(LStream *inStream);
	virtual 		~C3PaneCalendarAccount();

	virtual CBaseView*	GetBaseView() const;
	CCalendarStoreView*	GetCalendarStoreView() const
		{ return mCalendarStoreView; }

protected:
	CCalendarStoreView*	mCalendarStoreView;

	virtual void	FinishCreateSelf(void);
};

#endif


text:
"""

Animation of propagating plane wave wavefronts.
March 2, 2015
G. Nordin

"""

from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import pyqtgraph as pg
import numpy as np

app = QtGui.QApplication([])
w = gl.GLViewWidget()
w.opts['distance'] = 20
w.resize(800,600)
w.show()
w.setWindowTitle('Propagating plane wave')

g = gl.GLGridItem()
#g.rotate(90,1,0,0)
w.addItem(g)

linewidth = 2.0

# Add lines to visually define axes
x_length = 1.1
y_length = 1.1
z_length = 10
## make z-axis
zaxis = np.linspace(-z_length,z_length,10)
x_zaxis = np.zeros(10)
y_zaxis = np.zeros(10)
pts_zaxis = np.vstack([x_zaxis,zaxis,y_zaxis]).transpose()
plt_zaxis = gl.GLLinePlotItem(pos=pts_zaxis, width=linewidth, antialias=True)
w.addItem(plt_zaxis)
## make y-axis
yaxis = np.linspace(-y_length,y_length,10)
x_yaxis = np.zeros(10)
z_yaxis = np.zeros(10)
pts_yaxis = np.vstack([yaxis,z_yaxis,x_yaxis]).transpose()
plt_yaxis = gl.GLLinePlotItem(pos=pts_yaxis, width=linewidth, antialias=True)
w.addItem(plt_yaxis)
## make x-axis
xaxis = np.linspace(-x_length,x_length,10)
y_xaxis = np.zeros(10)
z_xaxis = np.zeros(10)
pts_xaxis = np.vstack([y_xaxis,z_xaxis,xaxis]).transpose()
plt_xaxis = gl.GLLinePlotItem(pos=pts_xaxis, width=linewidth, antialias=True)
w.addItem(plt_xaxis)

## make images
image_shape = (8,8)
uniform_values = np.ones(image_shape, dtype=np.int) * 255
uniform_image_transparent = pg.makeARGB(uniform_values)[0]
uniform_image_transparent[:,:,:] = 255
uniform_image_transparent[:,:,3] = 65
v1 = gl.GLImageItem(uniform_image_transparent)
v1.translate(-image_shape[0]/2, -image_shape[1]/2, 0)
v1.rotate(90, 1,0,0)
#w.addItem(v1)
v = []
for i in range(0,20):
    vtemp = gl.GLImageItem(uniform_image_transparent)
    vtemp.translate(-image_shape[0]/2, -image_shape[1]/2, 0)
    vtemp.rotate(90, 1,0,0)
    dz = float(i - 10)
    vtemp.translate(0, dz, 0)
    v.append(vtemp)
    w.addItem(v[i])

# Set up some animation parameters
frametime = 40 # frame refresh time in ms
inv_frametime = 1./frametime
counter = 0

# Function to update scene for each frame
def update():
    global inv_frametime, counter, amplitude
    counter +=1
    time = float(counter)/frametime % 1
    if counter != 1:
        if time != 0:
            dz = inv_frametime
        else:
            dz = -1.0
    else:
        dz = inv_frametime
    #v1.translate(0, dz, 0)
    for vtemp in v:
        vtemp.translate(0, dz, 0)

# Set up timer for animation
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(50)

## Start Qt event loop unless running in interactive mode.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Bracatinga</logradouro><bairro>Limoeiro</bairro><cidade>Timóteo</cidade><uf>MG</uf><cep>35181516</cep></feed>


text:
package tests

import (
	"log"
	"reflect"
	"time"

	"github.com/nytlabs/streamtools/st/blocks"
	"github.com/nytlabs/streamtools/test_utils"
	. "launchpad.net/gocheck"
)

type HistogramSuite struct{}

var histogramSuite = Suite(&HistogramSuite{})

func (s *HistogramSuite) TestHistogram(c *C) {
	log.Println("testing Histogram")
	b, ch := test_utils.NewBlock("testingHistogram", "histogram")
	go blocks.BlockRoutine(b)
	outChan := make(chan *blocks.Msg)
	ch.AddChan <- &blocks.AddChanMsg{
		Route:   "out",
		Channel: outChan,
	}

	ruleMsg := map[string]interface{}{"Window": "10s", "Path": ".data"}
	toRule := &blocks.Msg{Msg: ruleMsg, Route: "rule"}
	ch.InChan <- toRule

	queryOutChan := make(blocks.MsgChan)
	time.AfterFunc(time.Duration(1)*time.Second, func() {
		ch.QueryChan <- &blocks.QueryMsg{MsgChan: queryOutChan, Route: "rule"}
	})

	time.AfterFunc(time.Duration(5)*time.Second, func() {
		ch.QuitChan <- true
	})
	for {
		select {
		case messageI := <-queryOutChan:
			if !reflect.DeepEqual(messageI, ruleMsg) {
				c.Fail()
			}

		case err := <-ch.ErrChan:
			if err != nil {
				c.Errorf(err.Error())
			} else {
				return
			}
		case <-outChan:
		}
	}
}


text:
import { Meteor } from 'meteor/meteor';
import { Blaze } from 'meteor/blaze';
import { Session } from 'meteor/session';

import { isSetNotNull } from './function-isSet';
import { RoomManager } from '../../../ui-utils/client';
import { emoji, EmojiPicker } from '../../../emoji/client';
import { CachedCollectionManager } from '../../../ui-cached-collection/client';
import { APIClient } from '../../../utils/client';

export const getEmojiUrlFromName = function(name, extension) {
	Session.get;

	const key = `emoji_random_${ name }`;

	let random = 0;
	if (isSetNotNull(() => Session.keys[key])) {
		random = Session.keys[key];
	}

	if (name == null) {
		return;
	}
	const path = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || '';
	return `${ path }/emoji-custom/${ encodeURIComponent(name) }.${ extension }?_dc=${ random }`;
};

Blaze.registerHelper('emojiUrlFromName', getEmojiUrlFromName);

export const deleteEmojiCustom = function(emojiData) {
	delete emoji.list[`:${ emojiData.name }:`];
	const arrayIndex = emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(emojiData.name);
	if (arrayIndex !== -1) {
		emoji.packages.emojiCustom.emojisByCategory.rocket.splice(arrayIndex, 1);
	}
	const arrayIndexList = emoji.packages.emojiCustom.list.indexOf(`:${ emojiData.name }:`);
	if (arrayIndexList !== -1) {
		emoji.packages.emojiCustom.list.splice(arrayIndexList, 1);
	}
	if (isSetNotNull(() => emojiData.aliases)) {
		for (const alias of emojiData.aliases) {
			delete emoji.list[`:${ alias }:`];
			const aliasIndex = emoji.packages.emojiCustom.list.indexOf(`:${ alias }:`);
			if (aliasIndex !== -1) {
				emoji.packages.emojiCustom.list.splice(aliasIndex, 1);
			}
		}
	}
	EmojiPicker.updateRecent('rocket');
};

export const updateEmojiCustom = function(emojiData) {
	let key = `emoji_random_${ emojiData.name }`;
	Session.set(key, Math.round(Math.random() * 1000));

	const previousExists = isSetNotNull(() => emojiData.previousName);
	const currentAliases = isSetNotNull(() => emojiData.aliases);

	if (previousExists && isSetNotNull(() => emoji.list[`:${ emojiData.previousName }:`].aliases)) {
		for (const alias of emoji.list[`:${ emojiData.previousName }:`].aliases) {
			delete emoji.list[`:${ alias }:`];
			const aliasIndex = emoji.packages.emojiCustom.list.indexOf(`:${ alias }:`);
			if (aliasIndex !== -1) {
				emoji.packages.emojiCustom.list.splice(aliasIndex, 1);
			}
		}
	}

	if (previousExists && emojiData.name !== emojiData.previousName) {
		const arrayIndex = emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(emojiData.previousName);
		if (arrayIndex !== -1) {
			emoji.packages.emojiCustom.emojisByCategory.rocket.splice(arrayIndex, 1);
		}
		const arrayIndexList = emoji.packages.emojiCustom.list.indexOf(`:${ emojiData.previousName }:`);
		if (arrayIndexList !== -1) {
			emoji.packages.emojiCustom.list.splice(arrayIndexList, 1);
		}
		delete emoji.list[`:${ emojiData.previousName }:`];
	}

	const categoryIndex = emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(`${ emojiData.name }`);
	if (categoryIndex === -1) {
		emoji.packages.emojiCustom.emojisByCategory.rocket.push(`${ emojiData.name }`);
		emoji.packages.emojiCustom.list.push(`:${ emojiData.name }:`);
	}
	emoji.list[`:${ emojiData.name }:`] = Object.assign({ emojiPackage: 'emojiCustom' }, emoji.list[`:${ emojiData.name }:`], emojiData);
	if (currentAliases) {
		for (const alias of emojiData.aliases) {
			emoji.packages.emojiCustom.list.push(`:${ alias }:`);
			emoji.list[`:${ alias }:`] = {};
			emoji.list[`:${ alias }:`].emojiPackage = 'emojiCustom';
			emoji.list[`:${ alias }:`].aliasOf = emojiData.name;
		}
	}

	const url = getEmojiUrlFromName(emojiData.name, emojiData.extension);

	// update in admin interface
	if (previousExists && emojiData.name !== emojiData.previousName) {
		$(document).find(`.emojiAdminPreview-image[data-emoji='${ emojiData.previousName }']`).css('background-image', `url('${ url })'`).attr('data-emoji', `${ emojiData.name }`);
	} else {
		$(document).find(`.emojiAdminPreview-image[data-emoji='${ emojiData.name }']`).css('background-image', `url('${ url }')`);
	}

	// update in picker
	if (previousExists && emojiData.name !== emojiData.previousName) {
		$(document).find(`li[data-emoji='${ emojiData.previousName }'] span`).css('background-image', `url('${ url }')`).attr('data-emoji', `${ emojiData.name }`);
		$(document).find(`li[data-emoji='${ emojiData.previousName }']`).attr('data-emoji', `${ emojiData.name }`).attr('class', `emoji-${ emojiData.name }`);
	} else {
		$(document).find(`li[data-emoji='${ emojiData.name }'] span`).css('background-image', `url('${ url }')`);
	}

	// update in picker and opened rooms
	for (key in RoomManager.openedRooms) {
		if (RoomManager.openedRooms.hasOwnProperty(key)) {
			const room = RoomManager.openedRooms[key];
			if (previousExists && emojiData.name !== emojiData.previousName) {
				$(room.dom).find(`span[data-emoji='${ emojiData.previousName }']`).css('background-image', `url('${ url }')`).attr('data-emoji', `${ emojiData.name }`);
			} else {
				$(room.dom).find(`span[data-emoji='${ emojiData.name }']`).css('background-image', `url('${ url }')`);
			}
		}
	}

	EmojiPicker.updateRecent('rocket');
};

const customRender = (html) => {
	const emojisMatchGroup = emoji.packages.emojiCustom.list.map(RegExp.escape).join('|');
	if (emojisMatchGroup !== emoji.packages.emojiCustom._regexpSignature) {
		emoji.packages.emojiCustom._regexpSignature = emojisMatchGroup;
		emoji.packages.emojiCustom._regexp = new RegExp(`<object[^>]*>.*?<\/object>|<span[^>]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|(${ emojisMatchGroup })`, 'gi');
	}

	html = html.replace(emoji.packages.emojiCustom._regexp, (shortname) => {
		if ((typeof shortname === 'undefined') || (shortname === '') || (emoji.packages.emojiCustom.list.indexOf(shortname) === -1)) {
			return shortname;
		}

		let emojiAlias = shortname.replace(/:/g, '');

		let dataCheck = emoji.list[shortname];
		if (dataCheck.hasOwnProperty('aliasOf')) {
			emojiAlias = dataCheck.aliasOf;
			dataCheck = emoji.list[`:${ emojiAlias }:`];
		}

		return `<span class="emoji" style="background-image:url(${ getEmojiUrlFromName(emojiAlias, dataCheck.extension) });" data-emoji="${ emojiAlias }" title="${ shortname }">${ shortname }</span>`;
	});

	return html;
};

emoji.packages.emojiCustom = {
	emojiCategories: [{ key: 'rocket', i18n: 'Custom' }],
	categoryIndex: 1,
	toneList: {},
	list: [],
	_regexpSignature: null,
	_regexp: null,

	render: customRender,
	renderPicker: customRender,
};

Meteor.startup(() =>
	CachedCollectionManager.onLogin(async () => {
		try {
			const { emojis: { update: emojis } } = await APIClient.v1.get('emoji-custom.list');

			emoji.packages.emojiCustom.emojisByCategory = { rocket: [] };
			for (const currentEmoji of emojis) {
				emoji.packages.emojiCustom.emojisByCategory.rocket.push(currentEmoji.name);
				emoji.packages.emojiCustom.list.push(`:${ currentEmoji.name }:`);
				emoji.list[`:${ currentEmoji.name }:`] = currentEmoji;
				emoji.list[`:${ currentEmoji.name }:`].emojiPackage = 'emojiCustom';
				for (const alias of currentEmoji.aliases) {
					emoji.packages.emojiCustom.list.push(`:${ alias }:`);
					emoji.list[`:${ alias }:`] = {
						emojiPackage: 'emojiCustom',
						aliasOf: currentEmoji.name,
					};
				}
			}

			EmojiPicker.updateRecent('rocket');
		} catch (e) {
			console.error('Error getting custom emoji', e);
		}
	}),
);


text:
'use strict';

var fs = require('fs');
var chalk = require('chalk');
var extend = require('mixin-deep');
var hasAny = require('has-any');
var hasAnyDeep = require('has-any-deep');
var isObject = require('is-plain-object');
var omit = require('omit-keys');
var mapFiles = require('map-files');
var matter = require('gray-matter');
var omitEmpty = require('omit-empty');
var reduce = require('reduce-object');
var utils = require('./lib/utils');

/**
 * Set heuristics to speed up normalization decisions.
 *
 * @type {Array}
 */

var heuristics = [
  '_mappedFile',
  '_normalizedFile',
  '_s1',
  '_s1s2',
  '_s1s2o1',
  '_s1s2o1o2',
  '_o1',
  '_o1o2',
  '_o1o2o3'
];

/**
 * If we detected a `path` property directly on the object
 * that was passed, this means that the object is not
 * formatted with a key (as expected).
 *
 * ```js
 * // before
 * normalize({path: 'a/b/c.md', content: 'this is foo'});
 *
 * // after
 * normalize('a/b/c.md': {path: 'a/b/c.md', content: 'this is foo'});
 * ```
 *
 * @param  {String} `path`
 * @param  {Object} `value`
 * @return {Object}
 */

function createKeyFromPath(filepath, value) {
  var o = {};
  o[filepath] = value;
  return o;
}

/**
 * Create the `path` property from the string
 * passed in the first arg. This is only used
 * when the second arg is a string.
 *
 * ```js
 * normalize('abc', {content: 'this is content'});
 * //=> normalize('abc', {path: 'abc', content: 'this is content'});
 * ```
 *
 * @param  {Object} a
 * @return {Object}
 */

function createPathFromStringKey(o) {
  for (var key in o) {
    if (o.hasOwnProperty(key)) {
      o[key].path = o[key].path || key;
    }
  }
  return o;
}

/**
 * Create the `path` property from a singular object key.
 *
 * ```js
 * normalize({'a/b/d.md': {content: 'this is content'}})
 * ```
 *
 * @param  {String} `key`
 * @param  {Object} `value`
 * @return {String}
 */

function createPathFromObjectKey(key, value) {
  var o = {};
  value.path = value.path || key;
  o[key] = value;
  return o;
}

/**
 * Default function for reading any files resolved.
 *
 * Pass a custom `parseFn` function on the options to change
 * how files are parsed.
 *
 * @param  {String} `filepath`
 * @param  {Object} `options`
 * @return {Object}
 */

function readFn(filepath, options) {
  var opts = extend({ enc: 'utf8' }, options);

  if (opts.readFn) {
    return opts.readFn(filepath, options);
  }

  return fs.readFileSync(filepath, opts.enc);
}

/**
 * Default function for parsing any files resolved.
 *
 * Pass a custom `parseFn` function on the options to change
 * how files are parsed.
 *
 * @param  {String} `filepath`
 * @param  {Object} `options`
 * @return {Object}
 */

function parseFn(str, options) {
  var opts = extend({ autodetect: true }, options);

  if (opts.parseFn) {
    return opts.parseFn(str, options);
  }

  return matter(str, opts);
}

/**
 * [parseContent description]
 *
 * @param  {[type]} value
 * @param  {[type]} options
 * @return {[type]}
 */

function parseContent(obj, options) {
  var o = extend({}, obj);

  if (o.data != null) {
    return o;
  }

  if (utils.isString(o.content)) {
    var parsed = parseFn(o.content, options);
    o = extend({}, o, parsed);
  }

  return o;
}

/**
 * Rename the key of a template object.
 *
 * Pass a custom `renameKey` function on the options to change
 * how keys are renamed.
 *
 * @param  {String} `key`
 * @param  {Object} `options`
 * @return {Object}
 */

function renameKey(key, options) {
  var opts = options || {};
  if (opts.renameKey) {
    return opts.renameKey(key, options);
  }
  return key;
}

/**
 * Map files resolved from glob patterns or file paths.
 *
 *
 * @param  {String|Array} `patterns`
 * @param  {Object} `options`
 * @return {Object}
 */

function mapFilesFn(patterns, options) {
  var files = mapFiles(patterns, extend({
    rename: renameKey,
    parse: readFn
  }, options));

  return reduce(files, function (acc, value, key) {
    if (utils.isString(value)) {
      value = parseFn(value);
      value.path = key;
    }

    value._mappedFile = true;
    acc[key] = value;
    return acc;
  }, {})
}

/**
 * First arg is a file path or glob pattern.
 *
 * ```js
 * normalize('a/b/c.md', ...);
 * normalize('a/b/*.md', ...);
 * ```
 *
 * @param  {String} `key`
 * @param  {Object} `value`
 * @return {Object}
 */

function normalizeFiles(patterns, locals, options) {
  var files = mapFilesFn(patterns, options);

  options = extend({}, options);
  locals = extend({}, locals);

  if (files && Object.keys(files).length === 0) {
    return utils.generateKey(patterns, locals, options);
  }

  return reduce(files, function (acc, value, key) {
    var locs = utils.pickLocals(locals);
    var opts = utils.pickOptions(locals);
    extend(opts, options);

    value.options = utils.flattenOptions(opts);
    value.locals = utils.flattenLocals(locs);

    value._normalizedFile = true;
    acc[key] = value;
    return acc;
  }, {});
}

/**
 * First value is a string, second value is a string or
 * an object.
 *
 *   - first arg can be a file-path
 *   - first arg can be a non-file-path string
 *   - first arg can be a glob pattern
 *   - second arg can a string
 *   - when the second arg is a string, the first arg cannot be a file path
 *   - the second can be an object
 *   - when the second arg is an object, it may _be_ locals
 *   - when the second arg is an object, it may _have_ an `options` property
 *   - the second can be an object
 *   - in this pattern, when a third arg exists, it _must be_ the options object.
 *   - when a third arg exists, the second arg may still have an options property
 *   - when a third arg exists, `options` and `locals.options` are merged.
 *
 * **Examples:**
 *
 * ```js
 * template.normalize('a/b/c.md');
 * template.normalize('a/b/c.md', 'this is content');
 * template.normalize('a/b/c.md', {content: 'this is content'});
 * template.normalize('a/b/c.md', {path: 'a/b/c.md'});
 * template.normalize('a/b/c.md', {path: 'a/b/c.md', content: 'this is content'});
 * template.normalize('a/b/c.md', {path: 'a/b/c.md'}, {a: 'b'});
 * template.normalize('a/b/c.md', {path: 'a/b/c.md'}, {a: 'b'}, {c: 'd'});
 * template.normalize('a/b/c.md', {path: 'a/b/c.md'}, {a: 'b', options: {c: 'd'}});
 * template.normalize('a/b/c.md', {path: 'a/b/c.md', locals: {a: 'b'}, options: {c: 'd'}});
 * ```
 *
 * @param  {Object} `value` Always an object.
 * @param  {Object} `locals` Always an object.
 * @param  {Object} `options` Always an object.
 * @return {Object} Returns a normalized object.
 */

function normalizeString(key, value, locals, options) {
  var args = [].slice.call(arguments, 1);

  var objects = utils.argsOfType('object', arguments);
  var strings = utils.argsOfType('string', arguments);

  var props = utils.siftProps.apply(utils.siftProps, args);
  var opts = options || props.options;
  var locs = props.locals;
  var val = {};

  var o = {};
  o[key] = {};

  if (strings) {
    if (strings.length === 1) {
      var content = (value && value.content) || value;

      o[key].path = key;
      o[key].content = content;
      o[key].locals = locs;
      o[key].options = opts;
      o[key]._s1 = true;
    }

    if (strings.length === 2) {
      o[key] = {path: key, content: value, locals: locs, options: opts};
    }
  }

  if (objects == null) {
    // console.log(chalk.gray('zero objects'));
  } else {
    if (objects.length === 1) {
      // console.log(chalk.magenta('one: %j'), objects);
    }

    if (objects.length === 2) {
      // console.log(chalk.magenta.bold('two: %j'), objects);
    }

    if (isObject(value) && hasAny(value, ['path', 'content'])) {
      value = utils.siftLocals(value);
      value.options = opts;
      return createPathFromObjectKey(key, value);
    }
  }

  opts = utils.flattenOptions(opts);

  // Second value === 'string'
  if (utils.isString(value)) {
    o[key].options = opts;
    return o;
  }

  return normalizeFiles(key, value, locals, opts);
}

/**
 * Normalize objects that have `rootKeys` directly on
 * the root of the object.
 *
 * **Example**
 *
 * ```js
 * {path: 'a/b/c.md', content: 'this is content.'}
 * ```
 *
 * @param  {Object} `value` Always an object.
 * @param  {Object} `locals` Always an object.
 * @param  {Object} `options` Always an object.
 * @return {Object} Returns a normalized object.
 */

function normalizeShallowObject(value, locals, options) {
  var o = utils.siftLocals(value);
  o.options = extend({}, options, o.options);
  o.locals = extend({}, locals, o.locals);
  return o;
}

/**
 * Normalize nested templates that have the following pattern:
 *
 * ```js
 * => {'a/b/c.md': {path: 'a/b/c.md', content: 'this is content.'}}
 * ```
 * or:
 *
 * ```js
 * { 'a/b/a.md': {path: 'a/b/a.md', content: 'this is content.'},
 *   'a/b/b.md': {path: 'a/b/b.md', content: 'this is content.'},
 *   'a/b/c.md': {path: 'a/b/c.md', content: 'this is content.'} }
 *```
 */

function normalizeDeepObject(obj, locals, options) {
  return reduce(obj, function (acc, value, key) {
    acc[key] = normalizeShallowObject(value, locals, options);
    return acc;
  }, {});
}

/**
 * When the first arg is an object, all arguments
 * should be objects.
 *
 * ```js
 * normalize({'a/b/c.md', ...});
 *
 * // or
 * normalize({path: 'a/b/c.md', ...});
 * ```
 *
 * @param  {Object} `object` Template object
 * @param  {Object} `locals` Possibly locals, with `options` property
 * @return {Object} `options` Possibly options
 */

function normalizeObject(o) {
  var args = [].slice.call(arguments);
  var locals1 = utils.pickLocals(args[1]);
  var locals2 = utils.pickLocals(args[2]);
  var val;

  var opts = args.length === 3 ? locals2 : {};

  if (hasAny(o, ['path', 'content'])) {
    val = normalizeShallowObject(o, locals1, opts);
    return createKeyFromPath(val.path, val);
  }

  if (hasAnyDeep(o, ['path', 'content'])) {
    val = normalizeDeepObject(o, locals1, opts);
    return createPathFromStringKey(val);
  }

  throw new Error('Invalid template object. Must' +
    'have a `path` or `content` property.');
}

/**
 * When the first arg is an array, assume it's glob
 * patterns or file paths.
 *
 * ```js
 * normalize(['a/b/c.md', 'a/b/*.md']);
 * ```
 *
 * @param  {Object} `patterns` Template object
 * @param  {Object} `locals` Possibly locals, with `options` property
 * @return {Object} `options` Possibly options
 */

function normalizeArray(patterns, locals, options) {
  var opts = extend({}, locals && locals.options, options);
  return normalizeFiles(patterns, locals, opts);
}

/**
 * When the first arg is an array, assume it's glob
 * patterns or file paths.
 *
 * ```js
 * normalize(['a/b/c.md', 'a/b/*.md']);
 * ```
 *
 * @param  {Object} `patterns` Template object
 * @param  {Object} `locals` Possibly locals, with `options` property
 * @return {Object} `options` Possibly options
 */

function normalizeFn(fn, options) {
  var file = fn.call(null, options);
  return file;
}

/**
 * Normalize base template formats.
 */

function normalizeFormat() {
  var args = [].slice.call(arguments);

  switch (utils.typeOf(args[0])) {
  case 'string':
    return normalizeString.apply(null, args);
  case 'object':
    return normalizeObject.apply(null, args);
  case 'array':
    return normalizeArray.apply(null, args);
  case 'function':
    return normalizeFn.apply(null, args);
  default:
    return args;
  }
}

/**
 * Final normalization step to remove empty values and rename
 * the object key. By now the template should be _mostly_
 * normalized.
 *
 * @param  {Object} `object` Template object
 * @return {Object}
 */

module.exports = function (options) {
  return function(o) {
    o = normalizeFormat.apply(null, arguments);

    return reduce(o, function (acc, value, key) {
      if (Object.keys(value).length === 0) {
        return acc;
      }

      var opts = {};
      var str = (value && value.content);

      extend(opts, options, value.options);
      value = parseContent(value, options);
      if (value.data != null && value.content === str) {
        value = omit(value, 'orig');
      }

      value = omit(value, heuristics);
      value = omitEmpty(value);

      acc[renameKey(key, opts)] = value;
      return acc;
    }, {});
  };
};


text:
package com.example.seecloud;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.seecloud.database.Attribute;
import com.example.seecloud.database.InitAttribute;
import com.jaygoo.widget.RangeSeekBar;
import com.stepstone.stepper.Step;
import com.stepstone.stepper.VerificationError;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;

/**
 * Created by monkeysmac on 2017/4/2.
 */

public class StepFragment extends Fragment implements Step{

    private TextView type;

    private TextView attribute_name;

    private TextView attribute_intro;

    private SeekBar seekBar1;

    private TextView value;

    private int position;

    private List<Attribute> attributes = new ArrayList<>();

    private Attribute attribute;

    private int weight;

    private SharedPreferences preferences;

    private SharedPreferences.Editor editor;

    private boolean commit;

    public static StepFragment newInstance(@LayoutRes int layoutResId) {
        //attribute = a;
        Bundle args = new Bundle();
        args.putInt("messageResourceId", layoutResId);
        StepFragment stepFragment = new StepFragment();
        stepFragment.setArguments(args);
        return stepFragment;
    }
    public StepFragment setAttribute(Attribute attribute) {
        this.attribute = attribute;
        return this;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.weight_setting_area, container, false);

        preferences = PreferenceManager.getDefaultSharedPreferences(this.getContext());
        //UI初始化
        type = (TextView) view.findViewById(R.id.type_name);
        attribute_name = (TextView) view.findViewById(R.id.attr_name);
        attribute_intro = (TextView) view.findViewById(R.id.attr_intro);
        seekBar1 = (SeekBar) view.findViewById(R.id.seek_bar_1);
        value = (TextView) view.findViewById(R.id.text_value);

        //position = getArguments().getInt("weight_position");
        if (position <= 8) {
            type.setText("客观指标");
        } else if (position <= 17) {
            type.setText("主观指标");
        } else if (position == 18) {
            type.setText("综合可信度客观占比");
        } else if (position == 19) {
            type.setText("综合可信度主观占比");
        }
        InitAttribute initAttribute = new InitAttribute();
        if (position < 18) {
            attribute_name.setText(attribute.getName());
            attribute_intro.setText(attribute.getInstruction());
        }
        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 当拖动条的滑块位置发生改变时触发该方法,在这里直接使用参数progress,即当前滑块代表的进度值
                value.setText("Value:" + Integer.toString(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //取得滑块停止时的值作为权重
                weight = Integer.parseInt(String.valueOf(seekBar1.getProgress()));
                editor = preferences.edit();
                editor.putInt(Integer.toString(position), weight);
                Log.e(Integer.toString(position), Integer.toString(weight));
                commit = editor.commit();
                if (!commit) {
                     dialog();
                }
            }
        });
        return view;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    protected void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
        builder.setMessage("权重未成功提交");
        builder.setTitle("提示");
        builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    /*@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        attribute_name = (TextView) view.findViewById(R.id.attr_name);
        attribute_intro = (TextView) view.findViewById(R.id.attr_intro);
        seekBar1 = (SeekBar) view.findViewById(R.id.seek_bar_1);
        value = (TextView) view.findViewById(R.id.text_value);

        position = getArguments().getInt("weight_position");
        InitAttribute initAttribute = new InitAttribute();
        attributes.addAll(initAttribute.getAttributes());
        attribute_name.setText(attributes.get(position).getName());
        attribute_intro.setText(attributes.get(position).getInstruction());

        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 当拖动条的滑块位置发生改变时触发该方法,在这里直接使用参数progress,即当前滑块代表的进度值
                value.setText("Value:" + Integer.toString(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //取得滑块停止时的值作为权重
                weight = Integer.parseInt(String.valueOf(seekBar1.getProgress()));
            }
        });
    }*/

   /* @Override
    public void onStart() {
        super.onStart();
        if (isAdded()) {
            position = getArguments().getInt("weight_position");
            InitAttribute initAttribute = new InitAttribute();
            attributes.addAll(initAttribute.getAttributes());
            attribute_name.setText(attributes.get(position).getName());
            attribute_intro.setText(attributes.get(position).getInstruction());
        }
    }*/

    @Override
    public VerificationError verifyStep() {
        //return null if the user can go to the next step, create a new VerificationError instance otherwise
        return null;
    }

    @Override
    public void onSelected() {
        //update UI when selected

    }

    @Override
    public void onError(@NonNull VerificationError error) {
        //handle error inside of the fragment, e.g. show error on EditText
    }

    public int getWeight() {
        return weight;
    }
}