text:
<!-- toc -->
- [Release Signoff Checklist](#release-signoff-checklist)
- [Summary](#summary)
- [Motivation](#motivation)
  - [Goals](#goals)
  - [Non-Goals](#non-goals)
- [Proposal](#proposal)
  - [Risks and Mitigations](#risks-and-mitigations)
- [Design Details](#design-details)
  - [Assumptions](#assumptions)
  - [Identifying Zones](#identifying-zones)
  - [Excluding Control Plane Nodes](#excluding-control-plane-nodes)
  - [Configuration](#configuration)
    - [Interoperability](#interoperability)
    - [Feature Gate](#feature-gate)
  - [API](#api)
    - [Future API Expansion](#future-api-expansion)
  - [Kube-Proxy](#kube-proxy)
  - [EndpointSlice Controller](#endpointslice-controller)
    - [Example](#example)
    - [Overload](#overload)
    - [Handling Node Updates](#handling-node-updates)
  - [Future Expansion](#future-expansion)
  - [Test Plan](#test-plan)
    - [Unit tests](#unit-tests)
      - [Controller Unit Tests](#controller-unit-tests)
      - [Kube-Proxy Unit Tests](#kube-proxy-unit-tests)
    - [Integration tests](#integration-tests)
    - [e2e tests](#e2e-tests)
  - [Observability](#observability)
  - [Events](#events)
    - [Logic](#logic)
    - [Sample Events](#sample-events)
    - [Documentation](#documentation)
    - [Limitations](#limitations)
  - [Graduation Criteria](#graduation-criteria)
  - [Version Skew Strategy](#version-skew-strategy)
- [Production Readiness Review Questionnaire](#production-readiness-review-questionnaire)
  - [Feature Enablement and Rollback](#feature-enablement-and-rollback)
  - [Rollout, Upgrade and Rollback Planning](#rollout-upgrade-and-rollback-planning)
  - [Monitoring Requirements](#monitoring-requirements)
  - [Dependencies](#dependencies)
  - [Scalability](#scalability)
  - [Troubleshooting](#troubleshooting)
- [Implementation History](#implementation-history)
- [Drawbacks](#drawbacks)
- [Alternatives](#alternatives)
<!-- /toc -->

## Release Signoff Checklist

Items marked with (R) are required *prior to targeting to a milestone / release*.

- [x] (R) Enhancement issue in release milestone, which links to KEP dir in [kubernetes/enhancements] (not the initial KEP PR)
- [x] (R) KEP approvers have approved the KEP status as `implementable`
- [x] (R) Design details are appropriately documented
- [x] (R) Test plan is in place, giving consideration to SIG Architecture and SIG Testing input
- [x] (R) Graduation criteria is in place
- [x] (R) Production readiness review completed
- [x] (R) Production readiness review approved
- [ ] "Implementation History" section is up-to-date for milestone
- [ ] User-facing documentation has been created in [kubernetes/website], for publication to [kubernetes.io]
- [ ] Supporting documentation—e.g., additional design documents, links to mailing list discussions/SIG meetings, relevant PRs/issues, release notes

[kubernetes.io]: https://kubernetes.io/
[kubernetes/enhancements]: https://git.k8s.io/enhancements
[kubernetes/kubernetes]: https://git.k8s.io/kubernetes
[kubernetes/website]: https://git.k8s.io/website

## Summary

Kubernetes clusters are increasingly deployed in multi-zone environments but
unfortunately network routing has not caught up with that. This KEP proposes an
automatic topology aware hinting mechanism that would provide a way for
EndpointSlice producers to indicate where consumers should use specific
endpoints. Even in scenarios where endpoints are not balanced evenly across
zones, EndpointSlice producers could use these hints to allocate endpoints
from zones with extra endpoints to zones with insufficient endpoints.

This would enable EndpointSlice consumers such as Kube-Proxy to implement simple
topology aware routing. This proposal is currently focused on topology aware
routing at zone level but could be expanded to include region.

In the short term, this is taking the place of two closely related KEPs that
were never implemented. These KEPs relate to EndpointSlice subsetting and are
still relevant, just deferred to a later point in time. This
[doc](https://docs.google.com/document/d/1ZzUoFY1SrdjVefl7gVOJZJLt1I1LHttw8pcX95nlgMY/edit)
has more info on this transition.

## Motivation

Kubernetes clusters are increasingly deployed in multi-zone environments.
Network traffic is routed randomly to any endpoint matching a Service. Some
users might want the traffic to stay in the same zone for the following
reasons:
- Cost savings: Keeping traffic within a zone can limit cross-zone networking
  costs.
- Performance: Traffic within a zone usually has less latency and bandwidth
  constraints, having a better performance than traffic leaving the zone.

In this KEP we are going to focus on avoiding cross-zone traffic when in-zone
endpoints would suffice. We're attempting to provide a simple and more automatic
approach to topology aware routing. This API will still allow users to indicate
that they prefer to keep traffic in the same zone if there's sufficient
capacity. With this approach users won't have to configure anything by default
for most use cases.

### Goals
- Provide a simple way for users to indicate their preference for keeping
  traffic in zone.
- Use the standard topology label `topology.kubernetes.io/zone` to derive the
  zones of nodes and endpoints.
- Use EndpointSlice hints as the primary mechanism for topology aware routing.
- Minimize churn of EndpointSlices while doing topology aware distribution.
- Minimize the number of new EndpointSlices required.
- Provide a simple API that requires minimal configuration for most users.

### Non-Goals
- Real-time distribution rebalancing based on traffic load or distribution
  feedback or metrics.
- Multi-cluster topology aware routing (this same pattern may be useful there
  though).
- Region based topology aware routing (this may come later).
- Ensuring that Pods are distributed evenly across zones.

## Proposal

When this feature is enabled, the EndpointSlice controller will be updated to
provide hints for each endpoint. These hints will initially be limited to a
single zone per-endpoint. Kube-Proxy will then use these hints to filter the
endpoints they should route to.

For example, for a Service with 3 endpoints, the EndpointSlice controller may
create an EndpointSlice with endpoints that look like this:

```
- addresses: ["10.1.2.3"]
  zone: "zone-a"
  hints:
    zone: "zone-a"
- addresses: ["10.1.2.4"]
  zone: "zone-b"
  hints:
    zone: "zone-b"
- addresses: ["10.1.2.5"]
  zone: "zone-a"
  hints:
    zone: "zone-c"
```

In the above example, 2 endpoints are in zone-a and 1 endpoint is in zone-b. The
hints help ensure that each zone will have a single endpoint to consume by
adding a hint to the third endpoint that it should be consumed by "zone-c".

This functionality will be enabled by a `TopologyAwareHints` feature gate along
with a new Service annotation.

### Risks and Mitigations

- In a scenario where all traffic originates from a single zone there is a
  chance that endpoints in that zone will be overloaded while endpoints in other
  zones receive little to no traffic. Without some sort of feedback (out of
  scope) this will not self-rectify.
- Autoscaling will not behave well if only a single zone is receiving large
  amounts of traffic. This could potentially be mitigated by separating
  deployments and HPAs per zone.
- Services with ExternalTrafficPolicy=local will need special treatment here.
  This approach could result in a situation where an endpoint on a Node is
  delivered to a separate underprovisioned zone. The simplest approach would be
  to disable this functionality altogether.
- When this feature is transitioning between enabled and disabled states, there
  will be a brief point in time where only some EndpointSlices have hints. That
  could temporarily result in traffic being routed to a small subset of
  endpoints. To avoid this, we only filter out endpoints that have a hint set
  to a different zone. If a hint is not set for an endpoint, it will be included
  by all instances of kube-proxy.

## Design Details

### Assumptions

- Incoming traffic is proportional to the number of allocatable CPU cores in a
  zone. Although this is an imperfect metric, it is the best available way of
  predicting how much traffic will be received in a zone. If we are unable to
  derive the number of allocatable cores in a zone we will fall back to the
  number of nodes in that zone.
- Service capacity is proportional to the number of endpoints in a zone. This
  assumes that each endpoint has equivalent capacity. Although this is not
  always true, it usually is. We can explore ways to deal with variable capacity
  endpoints in the future.

### Identifying Zones

The EndpointSlice controller reads the standard `topology.kubernetes.io/zone`
label on Nodes to determine which zone a Pod is running in. Kube-Proxy would be
updated to read the same information to identify which zone it is running in.

### Excluding Control Plane Nodes

Any Nodes with the following labels (set to any value) will be excluded when
calculating allocatable cores in a zone:

* `node-role.kubernetes.io/control-plane`
* `node-role.kubernetes.io/master`

### Configuration

A new `service.kubernetes.io/topology-aware-routing` annotation  can be used to
enable or disable Topology Aware Routing (and by extension, hints) for a
Service. This may be set to "Auto" or "Disabled". Any other value is treated as
"Disabled".

The previous `service.kubernetes.io/topology-aware-hints` annotation will
continue to be supported as a means of configuring this feature.

#### Interoperability

Topology hints will be ignored if the TopologyKeys field has at least one entry.
This field is deprecated and will be removed soon.

Both ExternalTrafficPolicy and InternalTrafficPolicy will be given precedence
over topology aware routing. For example, if `ExternalTrafficPolicy=Local` and
topology was enabled, external traffic would be routed using the
ExternalTrafficPolicy configuration while internal traffic would be routed with
topology.

#### Feature Gate

This functionality will be guarded by the `TopologyAwareHints` feature gate.
This gate also interacts with 2 other feature gates:
- It is dependent on the `ServiceTrafficPolicy` feature gate.
- It is not compatible with the deprecated `ServiceTopology` feature gate.

### API

A new `EndpointHints` struct would be added to the `EndpointSlice.Endpoint`
struct:

```go
type Endpoint struct {
  ...
  // hints contains information associated with how an endpoint should be
  // consumed.
  // +optional
  Hints EndpointHints `json:"hints,omitempty" protobuf:"bytes,7,opt,name=hints"`
}
```

```go
// EndpointHints provides hints describing how an endpoint should be consumed.
type EndpointHints struct {
  // forZones indicates the zone(s) this endpoint should be consumed by to
  // enable topology aware routing.
  forZones []ForZone `json:"forZone,omitempty" protobuf:"bytes,1,name=forZones"`
}
```

```go
// ForZone provides information about which zones should consume this endpoint.
type ForZone struct {
  // name represents the name of the zone.
  name string `json:"name" protobuf:"bytes,1,name=name"`
}
```

#### Future API Expansion
This approach would allow for future API expansion that enabled specifying
multiple zones per endpoint with weights. That level of complexity may never be
necessary, but it will be possible. For example:

```yaml
hints:
  forZones:
  - name: example-1a
    weight: 50
  - name: example-2a
    weight: 50
```

Additionally we could easily expand this API to include support for region
hints. Although it is unclear if either expansion will be necessary, the API is
designed in a way to make expansions straightforward.

### Kube-Proxy

When the `TopologyAwareHints` feature gate is enabled, Kube-Proxy will be
updated to filter endpoints based on topology hints when the following
conditions are true:

- Kube-Proxy is able to determine the zone it is running within (likely based
  on node labels).
- The annotation is set to `Auto`.
- At least one endpoint for the Service has a hint pointing to the zone
  Kube-Proxy is running within.
- All endpoints for the Service have zone hints.

When the above conditions are true, kube-proxy will only route traffic to
endpoints with a hint referring to the zone Kube-Proxy is running within.

This means that if any endpoints for a Service do not have a hint, kube-proxy
will ignore all hints. This is to provide safer transitions between enabled
and disabled states. Without this fallback, endpoints could easily get
overloaded as hints were being added or removed from some EndpointSlices but
had not yet propagated to all of them.

### EndpointSlice Controller

When the `TopologyAwareHints` feature gate is enabled and the annotation is set
to `Auto` for a Service, the EndpointSlice controller will add hints to
EndpointSlices. These hints will indicate where an endpoint should be consumed
by proxy implementations to enable topology aware routing.

The EndpointSlice controller will determine how many endpoints should be
available for each zone based on the proportion of CPU cores in each zone. If
it is not possible to determine the number CPU cores, 1 core per node will be
assumed for calculations.

#### Example

zone-a: 20 CPU cores
zone-b: 16 CPU cores
zone-c: 14 CPU cores

In this scenario, the following proportion of endpoints would be allocated for
each Service:

zone-a: 40%
zone-b: 32%
zone-c: 28%

When allocating endpoints to meet this distribution, keeping endpoints in the
same zone will be prioritized. When same-zone endpoints are exhausted, endpoints
will be taken from zones that have excess capacity.

#### Overload

Overload is a key concept for this proposal. This occurs when there are less
endpoints for a zone than a perfect distribution would result in. For example,
in a 3-zone cluster where each zone has an equivalent size, an EndpointSlice for
a 4 endpoint service would not receive any zone hints. The expected number of
endpoints per zone would be 1.33, and 2 of the 3 zones would only have 1
endpoint allocated. This means that endpoints for these zones would be likely to
receive 33% more traffic than a perfectly balanced scenario. In this case, the
"Overload" for those zones would be 33%.

Overload Threshold represents the maximum acceptable overload for this algorithm
before changes are required. If the overload threshold is reached, the
controller will attempt to redistribute endpoints to get below this threshold.
If this is impossible, hints will be removed from the endpoints.

As a starting point, an Overload Threshold of 30% will be used. Hints will not
be added for a Service unless the expected initial overload is below 20%. This
difference exists to prevent flapping between approaches.

#### Handling Node Updates

This approach results in a new potential reason to update EndpointSlices. As
nodes are added or removed, the proportion of endpoints that should be allocated
to each zone will change. This will be especially common in autoscaling
scenarios.

To mitigate the number of changes resulting from these events, EndpointSlices
will only be updated if a Node addition or removal results in a transition above
or below the overload threshold. For example, syncs would be triggered in either
of the following scenarios:

1. A deleted Node results in a Service exceeding the overload threshold.
2. A new Node results in a Service that is able to achieve an endpoint
   distribution below 20% for the first time.

### Future Expansion

In the future we may expand this functionality if needed. This could include:

- A new `RequireZone` algorithm that would keep endpoints in EndpointSlices for
  the same zone they are in.
- A new option to specify a minimum threshold for the `Auto` (PreferZone)
  approach.
- Support for region based hints.

### Test Plan

[x] I/we understand the owners of the involved components may require updates to
existing tests to make this code solid enough prior to committing the changes necessary
to implement this enhancement.

#### Unit tests

- `k8s.io/pkg/controller/endpointslice`: `2022-10-05` - `73.1`
- `k8s.io/pkg/controller/endpointslice/topologycache`: `2022-10-05` - `75.4`

##### Controller Unit Tests
| Test Description | Expected Result |
| :--- | :--- |
| Feature On, 2+ zones | Hints set |
| Feature Off, 2+ zones | No hints |
| Feature On, 1 zone | No hints set |
| Feature On, ExternalTrafficPolicy == 'Local', 2+ zones | No hints |
| 2 endpoints, 3 zones | No hints |
| 3 endpoints, 3 zones | Hints set |
| 4 endpoints, 3 zones | No hints |
| 4 endpoints, 2 zones | Hints set |
| 4 endpoints all from 1 zone, 2 zones | Hints set |
| 4 endpoints, 3 zones, 1 zone with 2x cores | Hints set |
| 400 endpoints, 4 zones with slightly different cores | Hints set |
| Node removal that does not trigger threshold transition | No EndpointSlice changes |
| Node removal that triggers threshold transition | EndpointSlice updates |
| Node without way to determine cores | All Nodes treated equally |
| Endpoint additions that require redistribution | Hints updated |
| Endpoint removals that require redistribution | Hints updated |

##### Kube-Proxy Unit Tests
| Test Description | Expected Result |
| :--- | :--- |
| Feature On, hints matching zone | Endpoints filtered |
| Feature On, ExternalTrafficPolicy == 'Local', hints matching zone | Endpoints not filtered |
| Feature Off, hints matching zone | Endpoints not filtered |
| Feature On, no hints matching zone | Endpoints not filtered |

#### Integration tests

N/A

#### e2e tests

This feature has e2e test coverage with the ["Topology Hints"
test](https://github.com/kubernetes/kubernetes/blob/fbb6ccc0c62d2431dc3a18a4130d7fbae5c05acd/test/e2e/network/topology_hints.go#L43).
This is currently limited to a periodic run due to the nature of requiring a
multizone cluster to run. It has been [remarkably
stable](https://testgrid.k8s.io/sig-network-kind#sig-network-kind,%20multizone)
with 100% green runs.

As a prerequisite for GA, we will ensure that this test runs as a presubmit
if any code changes in kube-proxy or the EndpointSlice controller.

### Observability
We can reuse some of the metrics of EndpointSlice Controller that we already
have in the current version to observe the changes of endpoints (addition,
deletion and update). Meanwhile we can add more metrics to have a glimpse of
different approaches.

- `endpoint_slice_controller/endpointslices_changed_per_sync`
- `endpoint_slice_controller/syncs`

```
const SubSystem = "endpoint_slice_controller"

// This metric observes churn of EndpointSlices per sync
EPSChangedPerSync = metrics.NewHistogramVec(
  &metrics.HistogramOpts{
	  Subsystem: Subsystem,
    Name: "endpointslices_changed_per_sync",
    Help: "Number of EndpointSlices be changed on each Service sync",
  },
  []string{"approach"}, // either "random" or "auto"
)

// EndpointSliceSyncs tracks the number of sync operations the controller runs along with their result.
EndpointSliceSyncs = metrics.NewCounterVec(
  &metrics.CounterOpts{
    Subsystem:      EndpointSliceSubsystem,
    Name:           "syncs",
    Help:           "Number of EndpointSlice syncs",
    StabilityLevel: metrics.ALPHA,
  },
  []string{"result"}, // either "success" or "failure"
)

```

### Events
A common point of frustration among initial users of this feature was how
difficult it was to tell if this feature was enabled and working as intended.
Due to the nature of this design, even when a user opts in to the `Auto` mode
that is no guarantee that the controller logic will determine that there are
a sufficient number of endpoints to allocate them proportionally to each zone
in the cluster.

To make this feature easier to understand and use, the EndpointSlice controller
will publish events for a Service to describe if the feature has been enabled,
and if not, why not.

#### Logic

The EndpointSlice controller will track the known state of this feature for
each Service. When that state or the reason for it changes, the EndpointSlice
controller will publish a new Event to reflect the updated status of this
feature.

#### Sample Events

| Type | Reason | Message |
|-|-|-|
| Normal | TopologyAwareRoutingEnabled | Topology Aware Routing has been enabled |
| Normal | TopologyAwareRoutingDisabled | Topology Aware Routing configuration was removed |
| Warning | TopologyAwareRoutingDisabled | Insufficient number of Endpoints (n), impossible to safely allocate proportionally |
| Warning | TopologyAwareRoutingDisabled | 1 or more Endpoints do not have a Zone specified |
| Warning | TopologyAwareRoutingDisabled | 1 or more Nodes do not have allocatable CPU specified |
| Warning | TopologyAwareRoutingDisabled | Nodes only ready in 1 zone |

#### Documentation

The Topology Aware Hints documentation will be updated to describe the reason
each of these events may have been triggered, along with steps that can be taken
to recover from that state.

#### Limitations

Although the events described above should dramatically simplify the use of this
feature, there is a tiny edge case that will not be covered. If any
EndpointSlices for a Service do not include Hints, Kube-Proxy will not implement
this feature. This would happen if a user created custom EndpointSlices _and_
enabled Topology Aware Hints _and_ failed to set Hints on their custom
EndpointSlices. This seems very unlikely, but is mentioned here for the sake of
completeness.

### Graduation Criteria
**Alpha:**
- Basic functionality covered with unit tests described above.

**Beta:**
- Tests expanded to include e2e coverage described above.

**GA:**
- Feedback from real world usage shows that feature is working as intended
- Events are triggered on each Service to provide users with clear information
  on when the feature transitioned between enabled and disabled states.
- Test coverage in EndpointSlice strategy to ensure that the Hints field is
  dropped when the feature gate is not enabled.
- Test coverage in EndpointSlice controller for the transition from enabled to
  disabled.
- Ensure that existing Topology Hints e2e test runs as a presubmit if any code
  changes in kube-proxy or the EndpointSlice controller.
- Topology Hints e2e tests will graduate to conformance tests.
- Autoscaling and Scheduling SIGs have a plan to provide zone aware autoscaling
  (and scheduling) that allows users to proportionally distribute endpoints
  across zones.

### Version Skew Strategy
This KEP requires updates to both the EndpointSlice Controller and kube-proxy.
Thus there could be two potential version skew scenarios:
1. EndpointSlice Controller falls back to current behavior that does not
   support labeling EndpointSlices. In this case, kube-proxy will still work
   because EndpointSlices will not include topology hints.
2. Kube-Proxy falls back to current behavior that does not support topology
   hints in EndpointSlices. In this case, kube-proxy will continue to consume
   all endpoints. This will not be an issue, it simply won't be taking advantage
   of the new controller functionality.

Each scenario described above will end up behaving as if this feature is not
enabled even if the annotation has been set on the Service.

## Production Readiness Review Questionnaire

### Feature Enablement and Rollback

* **How can this feature be enabled / disabled in a live cluster?**
  - [x] Feature gate (also fill in values in `kep.yaml`)
    - Feature gate name: TopologyAwareHints
    - Components depending on the feature gate:
      - kube-controller-manager
      - kube-proxy

* **Does enabling the feature change any default behavior?**
  No.

* **Can the feature be disabled once it has been enabled (i.e. can we roll back
  the enablement)?**
  Yes. It can easily be disabled universally by turning off the feature gate or
  setting the annotation to some other value for a Service.

* **What happens if we reenable the feature if it was previously rolled back?**
  EndpointSlices hints will be added again resulting in changes to existing
  EndpointSlices for Services that have this feature enabled.

* **Are there any tests for feature enablement/disablement?**
  Per Service enablement and disablement is covered in depth by unit tests. As a
  prerequisite for graduation to GA, we will also add the following:

  - Test coverage in EndpointSlice strategy to ensure that the Hints field is
    dropped when the feature gate is not enabled.
  - Test coverage in EndpointSlice controller for the transition from enabled to
    disabled.

### Rollout, Upgrade and Rollback Planning

* **How can a rollout fail? Can it impact already running workloads?**
  The biggest risk here is that EndpointSlices may be created with hints some
  but not all zones. This will be covered by kube-proxy falling back to all
  endpoints if none have hints.

* **What specific metrics should inform a rollback?**
  If the proportion of `endpoint_slice_controller/syncs` with a "failure" result
  is greater than 10%, a rollback may be considered. It is worth noting that
  other issues can cause sync failures such as an out of date informer cache.
  The key indicator should be a significantly elevated error rate when compared
  with before the feature was enabled.

* **Were upgrade and rollback tested? Was the upgrade->downgrade->upgrade path tested?**
  Per-Service enablement/disablement is covered in depth and feature gate
  enablement and disablement will be covered before the feature graduates to GA.
  In addition, manual testing covering combinations of
  upgrade->downgrade->upgrade cycles will be completed prior to GA graduation.

* **Is the rollout accompanied by any deprecations and/or removals of features,
  APIs, fields of API types, flags, etc.?**
  Yes, this represents a replacement to the approach tracked with KEP 536. This
  KEP included an alpha implementation but did not graduate beyond that.

### Monitoring Requirements

* **How can an operator determine if the feature is in use by workloads?**
  If the `endpointslices_changed_per_sync` metric has a non-zero value for the
  `auto` approach, this feature is in use.

* **What are the SLIs (Service Level Indicators) an operator can use to
  determine the health of the service?**
  - [x] Metrics
    - Metric name: `endpoint_slice_controller/syncs`
    - [Optional] Aggregation method: Counter
    - Components exposing the metric: EndpointSlice Controller
    - The relative failure rate over time can be used to track the health of
      this controller.

* **What are the reasonable SLOs (Service Level Objectives) for the above SLIs?**
  As a starting point, it is likely reasonable for the EndpointSlice controller
  to experience up to a 10% sync failure rate. This is largely related to it
  trying to update stale EndpointSlices. When we are able to find a solution for
  that issue the expected sync failure rate should be significantly lower. This
  specific problem is most notable for large Services that have rapidly updating
  endpoints.

* **Are there any missing metrics that would be useful to have to improve
  observability of this feature?**
  None that I can think of.

### Dependencies

* **Does this feature depend on any specific services running in the cluster?**
  No new dependencies.

### Scalability

* **Will enabling / using this feature result in any new API calls?**
  Kube-Proxy will include a Node informer when this feature is enabled. This is
  also the case for a couple other Kube-Proxy features, including the previous
  `ServiceTopology` feature gate. This would also require a watch that was
  covering the node the instance is running on. This may result in some
  additional calls to the EndpointSlice API, but expect the increase to be
  minimal.

  The EndpointSlice controller will begin publishing Events for each Service
  that has opted in to this feature when this transitions between enablement
  states.

* **Will enabling / using this feature result in introducing new API types?**
  No.

* **Will enabling / using this feature result in any new calls to the cloud
  provider?**
  No.

* **Will enabling / using this feature result in increasing size or count of the
  existing API objects?**
  Yes, a new EndpointHints field will be added to the EndpointSlice API. This
  could add 20 bytes for each endpoint.

* **Will enabling / using this feature result in increasing time taken by any
  operations covered by [existing SLIs/SLOs]?**
  Although the EndpointSlice controller may take slightly longer to create
  EndpointSlices, kube-proxy performance should also be slightly improved. I do
  not anticipate any impact on existing SLIs or SLOs.

* **Will enabling / using this feature result in non-negligible increase of
  resource usage (CPU, RAM, disk, IO, ...) in any components?**
  This could result in increased CPU utilization for kube-controller-manager
  (specifically  the EndpointSlice controller). Profiling will be performed to
  ensure that this increase is minimal.

### Troubleshooting

* **How does this feature react if the API server and/or etcd is unavailable?**
  The EndpointSlice controller will stop functioning.

* **What are other known failure modes?**
  - The API server is unavailable. This is not specific to this controller and
    detections and mitigations are likely already widely covered.

* **What steps should be taken if SLOs are not being met to determine the problem?**
  This feature should be disabled. It is easy to leave this enabled for a single
  Service for debugging, but if SLOs are not being met the fastest solution is
  likely to disable this feature for any critical Services.

[supported limits]: https://git.k8s.io/community//sig-scalability/configs-and-limits/thresholds.md
[existing SLIs/SLOs]: https://git.k8s.io/community/sig-scalability/slos/slos.md#kubernetes-slisslos

## Implementation History

- KEP Merged: February 2021
- Alpha release: Kubernetes 1.21
- Beta Release: Kubernetes 1.23[^1]
- Feature Gate on-by default, feature available by default: 1.24

[^1]: This was intended to also flip the feature gate to enabled by default, but
    unfortunately that part was missed in 1.23. See
    [#108747](https://github.com/kubernetes/kubernetes/pull/108747) for more
    information.

## Drawbacks
1. Increased complexity in EndpointSlice controller
2. No immediate plans to support region

## Alternatives
1. Conduct topology aware routing at node level with specified topology keys,
   refer to the previous [Topology Aware Routing
   KEP](https://github.com/kubernetes/enhancements/blob/master/keps/sig-network/20181024-service-topology.md).
   As drawbacks described above, we could do some improvement i.e. fix the
   topology keys. But it still requires API and controller additions which
   introduces more complexity meanwhile cannot offer an easy policy decision at
   service level.
2. Implement this proposal with EndpointSlice subsetting. This was the original
   plan here but it resulted in too many compromises on both sides. We ended up
   with weaker approaches for subsetting and topology aware routing than if we
   separated them.


text:
#ifndef __SYS_RTXC_H__
#define __SYS_RTXC_H__

#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"

#define SYS_MBOX_NULL (xQueueHandle)0
#define SYS_SEM_NULL  (xSemaphoreHandle)0

typedef xSemaphoreHandle sys_sem_t;
typedef xQueueHandle sys_mbox_t;
typedef xTaskHandle sys_thread_t;

/* Message queue constants. */
#define archMESG_QUEUE_LENGTH	( 6 )
#define archPOST_BLOCK_TIME_MS	( ( unsigned long ) 10000 )

#endif

redpajama_set_name: RedPajamaGithub


text:
/*	$NetBSD: openssl_hostname_validation.h,v 1.2.2.2 2014/12/24 00:05:26 riz Exp $	*/

/* Obtained from: https://github.com/iSECPartners/ssl-conservatory */

/*
Copyright (C) 2012, iSEC Partners.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 */

/*
 * Helper functions to perform basic hostname validation using OpenSSL.
 *
 * Please read "everything-you-wanted-to-know-about-openssl.pdf" before
 * attempting to use this code. This whitepaper describes how the code works,
 * how it should be used, and what its limitations are.
 *
 * Author:  Alban Diquet
 * License: See LICENSE
 *
 */

typedef enum {
        MatchFound,
        MatchNotFound,
        NoSANPresent,
        MalformedCertificate,
        Error
} HostnameValidationResult;

/**
* Validates the server's identity by looking for the expected hostname in the
* server's certificate. As described in RFC 6125, it first tries to find a match
* in the Subject Alternative Name extension. If the extension is not present in
* the certificate, it checks the Common Name instead.
*
* Returns MatchFound if a match was found.
* Returns MatchNotFound if no matches were found.
* Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it.
* Returns Error if there was an error.
*/
HostnameValidationResult validate_hostname(const char *hostname, const X509 *server_cert);


text:
package guava.Order;

import com.google.common.collect.Ordering;

/**
 * @author yujianjian
 * @CreateTime 2017-03-27 下午5:29
 * @Description OrderDemo1.java
 * guava的排序器
 */
public class OrderDemo1 {

  public static void main(String[] args) {
    Integer min = Ordering.natural().min(1, 2, 3, 4);
    System.out.println(min);
    Integer max = Ordering.natural().max(2, 5, 8, 79);
    System.out.println(max);
  }

}


text:
class User < ApplicationRecord
    has_secure_password
    has_many :sessions
    has_many :join_sessions

    validates :nickname,
              presence: true,
              uniqueness: true,
              allow_blank: false
    validates :email,
              presence: true,
              uniqueness: true,
              allow_blank: false,
              format: {with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i}
    validates :password,
              length: { minimum: 8 },
              presence: true,
              allow_blank: false
    validates :phone_number,
              presence: true,
              allow_blank: false
end


text:
package org.elasticsearch.xpack.core.ml.job.results;

import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.xpack.core.ml.datafeed.ChunkingConfig;
import org.elasticsearch.xpack.core.ml.datafeed.DatafeedConfig;
import org.elasticsearch.xpack.core.ml.datafeed.DatafeedTimingStats;
import org.elasticsearch.xpack.core.ml.datafeed.DelayedDataCheckConfig;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsConfig;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsDest;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsSource;
import org.elasticsearch.xpack.core.ml.dataframe.analyses.BoostedTreeParams;
import org.elasticsearch.xpack.core.ml.dataframe.analyses.Classification;
import org.elasticsearch.xpack.core.ml.dataframe.analyses.OutlierDetection;
import org.elasticsearch.xpack.core.ml.dataframe.analyses.Regression;
import org.elasticsearch.xpack.core.ml.job.config.AnalysisConfig;
import org.elasticsearch.xpack.core.ml.job.config.AnalysisLimits;
import org.elasticsearch.xpack.core.ml.job.config.DataDescription;
import org.elasticsearch.xpack.core.ml.job.config.DetectionRule;
import org.elasticsearch.xpack.core.ml.job.config.Detector;
import org.elasticsearch.xpack.core.ml.job.config.Job;
import org.elasticsearch.xpack.core.ml.job.config.ModelPlotConfig;
import org.elasticsearch.xpack.core.ml.job.config.Operator;
import org.elasticsearch.xpack.core.ml.job.config.PerPartitionCategorizationConfig;
import org.elasticsearch.xpack.core.ml.job.config.RuleCondition;
import org.elasticsearch.xpack.core.ml.job.persistence.ElasticsearchMappings;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.DataCounts;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.ModelSizeStats;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.ModelSnapshot;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.ModelSnapshotField;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.TimingStats;
import org.elasticsearch.xpack.core.ml.utils.ExponentialAverageCalculationContext;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * Defines the field names that we use for our results.
 * Fields from the raw data with these names are not added to any result.  Even
 * different types of results will not have raw data fields with reserved names
 * added to them, as it could create confusion if in some results a given field
 * contains raw data and in others it contains some aspect of our output.
 */
public final class ReservedFieldNames {
    private static final Pattern DOT_PATTERN = Pattern.compile("\\.");

    /**
     * This array should be updated to contain all the field names that appear
     * in any documents we store in our results index.  (The reason it's any
     * documents we store and not just results documents is that Elasticsearch
     * 2.x requires mappings for given fields be consistent across all types
     * in a given index.)
     */
    private static final String[] RESERVED_RESULT_FIELD_NAME_ARRAY = {
            ElasticsearchMappings.ALL_FIELD_VALUES,

            Job.ID.getPreferredName(),

            AnomalyCause.PROBABILITY.getPreferredName(),
            AnomalyCause.OVER_FIELD_NAME.getPreferredName(),
            AnomalyCause.OVER_FIELD_VALUE.getPreferredName(),
            AnomalyCause.BY_FIELD_NAME.getPreferredName(),
            AnomalyCause.BY_FIELD_VALUE.getPreferredName(),
            AnomalyCause.CORRELATED_BY_FIELD_VALUE.getPreferredName(),
            AnomalyCause.PARTITION_FIELD_NAME.getPreferredName(),
            AnomalyCause.PARTITION_FIELD_VALUE.getPreferredName(),
            AnomalyCause.FUNCTION.getPreferredName(),
            AnomalyCause.FUNCTION_DESCRIPTION.getPreferredName(),
            AnomalyCause.TYPICAL.getPreferredName(),
            AnomalyCause.ACTUAL.getPreferredName(),
            AnomalyCause.GEO_RESULTS.getPreferredName(),
            AnomalyCause.INFLUENCERS.getPreferredName(),
            AnomalyCause.FIELD_NAME.getPreferredName(),

            AnomalyRecord.PROBABILITY.getPreferredName(),
            AnomalyRecord.MULTI_BUCKET_IMPACT.getPreferredName(),
            AnomalyRecord.BY_FIELD_NAME.getPreferredName(),
            AnomalyRecord.BY_FIELD_VALUE.getPreferredName(),
            AnomalyRecord.CORRELATED_BY_FIELD_VALUE.getPreferredName(),
            AnomalyRecord.PARTITION_FIELD_NAME.getPreferredName(),
            AnomalyRecord.PARTITION_FIELD_VALUE.getPreferredName(),
            AnomalyRecord.FUNCTION.getPreferredName(),
            AnomalyRecord.FUNCTION_DESCRIPTION.getPreferredName(),
            AnomalyRecord.TYPICAL.getPreferredName(),
            AnomalyRecord.ACTUAL.getPreferredName(),
            AnomalyRecord.GEO_RESULTS.getPreferredName(),
            AnomalyRecord.INFLUENCERS.getPreferredName(),
            AnomalyRecord.FIELD_NAME.getPreferredName(),
            AnomalyRecord.OVER_FIELD_NAME.getPreferredName(),
            AnomalyRecord.OVER_FIELD_VALUE.getPreferredName(),
            AnomalyRecord.CAUSES.getPreferredName(),
            AnomalyRecord.RECORD_SCORE.getPreferredName(),
            AnomalyRecord.INITIAL_RECORD_SCORE.getPreferredName(),
            AnomalyRecord.BUCKET_SPAN.getPreferredName(),

            GeoResults.TYPICAL_POINT.getPreferredName(),
            GeoResults.ACTUAL_POINT.getPreferredName(),

            Bucket.ANOMALY_SCORE.getPreferredName(),
            Bucket.BUCKET_INFLUENCERS.getPreferredName(),
            Bucket.BUCKET_SPAN.getPreferredName(),
            Bucket.EVENT_COUNT.getPreferredName(),
            Bucket.INITIAL_ANOMALY_SCORE.getPreferredName(),
            Bucket.PROCESSING_TIME_MS.getPreferredName(),
            Bucket.SCHEDULED_EVENTS.getPreferredName(),

            BucketInfluencer.INITIAL_ANOMALY_SCORE.getPreferredName(), BucketInfluencer.ANOMALY_SCORE.getPreferredName(),
            BucketInfluencer.RAW_ANOMALY_SCORE.getPreferredName(), BucketInfluencer.PROBABILITY.getPreferredName(),

            CategoryDefinition.CATEGORY_ID.getPreferredName(),
            CategoryDefinition.TERMS.getPreferredName(),
            CategoryDefinition.REGEX.getPreferredName(),
            CategoryDefinition.MAX_MATCHING_LENGTH.getPreferredName(),
            CategoryDefinition.EXAMPLES.getPreferredName(),
            CategoryDefinition.NUM_MATCHES.getPreferredName(),
            CategoryDefinition.PREFERRED_TO_CATEGORIES.getPreferredName(),

            DataCounts.PROCESSED_RECORD_COUNT.getPreferredName(),
            DataCounts.PROCESSED_FIELD_COUNT.getPreferredName(),
            DataCounts.INPUT_BYTES.getPreferredName(),
            DataCounts.INPUT_RECORD_COUNT.getPreferredName(),
            DataCounts.INPUT_FIELD_COUNT.getPreferredName(),
            DataCounts.INVALID_DATE_COUNT.getPreferredName(),
            DataCounts.MISSING_FIELD_COUNT.getPreferredName(),
            DataCounts.OUT_OF_ORDER_TIME_COUNT.getPreferredName(),
            DataCounts.EMPTY_BUCKET_COUNT.getPreferredName(),
            DataCounts.SPARSE_BUCKET_COUNT.getPreferredName(),
            DataCounts.BUCKET_COUNT.getPreferredName(),
            DataCounts.LATEST_RECORD_TIME.getPreferredName(),
            DataCounts.EARLIEST_RECORD_TIME.getPreferredName(),
            DataCounts.LAST_DATA_TIME.getPreferredName(),
            DataCounts.LATEST_EMPTY_BUCKET_TIME.getPreferredName(),
            DataCounts.LATEST_SPARSE_BUCKET_TIME.getPreferredName(),

            Detector.DETECTOR_INDEX.getPreferredName(),

            Influence.INFLUENCER_FIELD_NAME.getPreferredName(),
            Influence.INFLUENCER_FIELD_VALUES.getPreferredName(),

            Influencer.PROBABILITY.getPreferredName(),
            Influencer.INFLUENCER_FIELD_NAME.getPreferredName(),
            Influencer.INFLUENCER_FIELD_VALUE.getPreferredName(),
            Influencer.INITIAL_INFLUENCER_SCORE.getPreferredName(),
            Influencer.INFLUENCER_SCORE.getPreferredName(),
            Influencer.BUCKET_SPAN.getPreferredName(),

            ModelPlot.PARTITION_FIELD_NAME.getPreferredName(), ModelPlot.PARTITION_FIELD_VALUE.getPreferredName(),
            ModelPlot.OVER_FIELD_NAME.getPreferredName(), ModelPlot.OVER_FIELD_VALUE.getPreferredName(),
            ModelPlot.BY_FIELD_NAME.getPreferredName(), ModelPlot.BY_FIELD_VALUE.getPreferredName(),
            ModelPlot.MODEL_FEATURE.getPreferredName(), ModelPlot.MODEL_LOWER.getPreferredName(),
            ModelPlot.MODEL_UPPER.getPreferredName(), ModelPlot.MODEL_MEDIAN.getPreferredName(),
            ModelPlot.ACTUAL.getPreferredName(),

            Forecast.FORECAST_LOWER.getPreferredName(), Forecast.FORECAST_UPPER.getPreferredName(),
            Forecast.FORECAST_PREDICTION.getPreferredName(),
            Forecast.FORECAST_ID.getPreferredName(),

            //re-use: TIMESTAMP
            ForecastRequestStats.START_TIME.getPreferredName(),
            ForecastRequestStats.END_TIME.getPreferredName(),
            ForecastRequestStats.CREATE_TIME.getPreferredName(),
            ForecastRequestStats.EXPIRY_TIME.getPreferredName(),
            ForecastRequestStats.MESSAGES.getPreferredName(),
            ForecastRequestStats.PROGRESS.getPreferredName(),
            ForecastRequestStats.STATUS.getPreferredName(),
            ForecastRequestStats.MEMORY_USAGE.getPreferredName(),

            ModelSizeStats.MODEL_BYTES_FIELD.getPreferredName(),
            ModelSizeStats.PEAK_MODEL_BYTES_FIELD.getPreferredName(),
            ModelSizeStats.TOTAL_BY_FIELD_COUNT_FIELD.getPreferredName(),
            ModelSizeStats.TOTAL_OVER_FIELD_COUNT_FIELD.getPreferredName(),
            ModelSizeStats.TOTAL_PARTITION_FIELD_COUNT_FIELD.getPreferredName(),
            ModelSizeStats.BUCKET_ALLOCATION_FAILURES_COUNT_FIELD.getPreferredName(),
            ModelSizeStats.MEMORY_STATUS_FIELD.getPreferredName(),
            ModelSizeStats.LOG_TIME_FIELD.getPreferredName(),

            ModelSnapshot.DESCRIPTION.getPreferredName(),
            ModelSnapshotField.SNAPSHOT_ID.getPreferredName(),
            ModelSnapshot.SNAPSHOT_DOC_COUNT.getPreferredName(),
            ModelSnapshot.LATEST_RECORD_TIME.getPreferredName(),
            ModelSnapshot.LATEST_RESULT_TIME.getPreferredName(),
            ModelSnapshot.RETAIN.getPreferredName(),
            ModelSnapshot.MIN_VERSION.getPreferredName(),

            Result.RESULT_TYPE.getPreferredName(),
            Result.TIMESTAMP.getPreferredName(),
            Result.IS_INTERIM.getPreferredName(),

            TimingStats.BUCKET_COUNT.getPreferredName(),
            TimingStats.MIN_BUCKET_PROCESSING_TIME_MS.getPreferredName(),
            TimingStats.MAX_BUCKET_PROCESSING_TIME_MS.getPreferredName(),
            TimingStats.AVG_BUCKET_PROCESSING_TIME_MS.getPreferredName(),
            TimingStats.EXPONENTIAL_AVG_BUCKET_PROCESSING_TIME_MS.getPreferredName(),
            TimingStats.EXPONENTIAL_AVG_CALCULATION_CONTEXT.getPreferredName(),

            DatafeedTimingStats.SEARCH_COUNT.getPreferredName(),
            DatafeedTimingStats.BUCKET_COUNT.getPreferredName(),
            DatafeedTimingStats.TOTAL_SEARCH_TIME_MS.getPreferredName(),
            DatafeedTimingStats.EXPONENTIAL_AVG_CALCULATION_CONTEXT.getPreferredName(),

            ExponentialAverageCalculationContext.INCREMENTAL_METRIC_VALUE_MS.getPreferredName(),
            ExponentialAverageCalculationContext.LATEST_TIMESTAMP.getPreferredName(),
            ExponentialAverageCalculationContext.PREVIOUS_EXPONENTIAL_AVERAGE_MS.getPreferredName(),

            GetResult._ID,
            GetResult._INDEX
   };

    /**
     * This array should be updated to contain all the field names that appear
     * in any documents we store in our config index.
     */
    private static final String[] RESERVED_CONFIG_FIELD_NAME_ARRAY = {
            Job.ID.getPreferredName(),
            Job.JOB_TYPE.getPreferredName(),
            Job.JOB_VERSION.getPreferredName(),
            Job.GROUPS.getPreferredName(),
            Job.ANALYSIS_CONFIG.getPreferredName(),
            Job.ANALYSIS_LIMITS.getPreferredName(),
            Job.CREATE_TIME.getPreferredName(),
            Job.CUSTOM_SETTINGS.getPreferredName(),
            Job.DATA_DESCRIPTION.getPreferredName(),
            Job.DESCRIPTION.getPreferredName(),
            Job.FINISHED_TIME.getPreferredName(),
            Job.MODEL_PLOT_CONFIG.getPreferredName(),
            Job.RENORMALIZATION_WINDOW_DAYS.getPreferredName(),
            Job.BACKGROUND_PERSIST_INTERVAL.getPreferredName(),
            Job.MODEL_SNAPSHOT_RETENTION_DAYS.getPreferredName(),
            Job.DAILY_MODEL_SNAPSHOT_RETENTION_AFTER_DAYS.getPreferredName(),
            Job.RESULTS_RETENTION_DAYS.getPreferredName(),
            Job.MODEL_SNAPSHOT_ID.getPreferredName(),
            Job.MODEL_SNAPSHOT_MIN_VERSION.getPreferredName(),
            Job.RESULTS_INDEX_NAME.getPreferredName(),
            Job.ALLOW_LAZY_OPEN.getPreferredName(),

            AnalysisConfig.BUCKET_SPAN.getPreferredName(),
            AnalysisConfig.CATEGORIZATION_FIELD_NAME.getPreferredName(),
            AnalysisConfig.CATEGORIZATION_FILTERS.getPreferredName(),
            AnalysisConfig.CATEGORIZATION_ANALYZER.getPreferredName(),
            AnalysisConfig.PER_PARTITION_CATEGORIZATION.getPreferredName(),
            AnalysisConfig.LATENCY.getPreferredName(),
            AnalysisConfig.SUMMARY_COUNT_FIELD_NAME.getPreferredName(),
            AnalysisConfig.DETECTORS.getPreferredName(),
            AnalysisConfig.INFLUENCERS.getPreferredName(),
            AnalysisConfig.MULTIVARIATE_BY_FIELDS.getPreferredName(),

            AnalysisLimits.MODEL_MEMORY_LIMIT.getPreferredName(),
            AnalysisLimits.CATEGORIZATION_EXAMPLES_LIMIT.getPreferredName(),

            Detector.DETECTOR_DESCRIPTION_FIELD.getPreferredName(),
            Detector.FUNCTION_FIELD.getPreferredName(),
            Detector.FIELD_NAME_FIELD.getPreferredName(),
            Detector.BY_FIELD_NAME_FIELD.getPreferredName(),
            Detector.OVER_FIELD_NAME_FIELD.getPreferredName(),
            Detector.PARTITION_FIELD_NAME_FIELD.getPreferredName(),
            Detector.USE_NULL_FIELD.getPreferredName(),
            Detector.EXCLUDE_FREQUENT_FIELD.getPreferredName(),
            Detector.CUSTOM_RULES_FIELD.getPreferredName(),
            Detector.DETECTOR_INDEX.getPreferredName(),

            DetectionRule.ACTIONS_FIELD.getPreferredName(),
            DetectionRule.CONDITIONS_FIELD.getPreferredName(),
            DetectionRule.SCOPE_FIELD.getPreferredName(),
            RuleCondition.APPLIES_TO_FIELD.getPreferredName(),
            RuleCondition.VALUE_FIELD.getPreferredName(),
            Operator.OPERATOR_FIELD.getPreferredName(),

            DataDescription.FORMAT_FIELD.getPreferredName(),
            DataDescription.TIME_FIELD_NAME_FIELD.getPreferredName(),
            DataDescription.TIME_FORMAT_FIELD.getPreferredName(),
            DataDescription.FIELD_DELIMITER_FIELD.getPreferredName(),
            DataDescription.QUOTE_CHARACTER_FIELD.getPreferredName(),

            ModelPlotConfig.ENABLED_FIELD.getPreferredName(),
            ModelPlotConfig.TERMS_FIELD.getPreferredName(),
            ModelPlotConfig.ANNOTATIONS_ENABLED_FIELD.getPreferredName(),

            PerPartitionCategorizationConfig.STOP_ON_WARN.getPreferredName(),

            DatafeedConfig.ID.getPreferredName(),
            DatafeedConfig.QUERY_DELAY.getPreferredName(),
            DatafeedConfig.FREQUENCY.getPreferredName(),
            DatafeedConfig.INDICES.getPreferredName(),
            DatafeedConfig.QUERY.getPreferredName(),
            DatafeedConfig.SCROLL_SIZE.getPreferredName(),
            DatafeedConfig.AGGREGATIONS.getPreferredName(),
            DatafeedConfig.SCRIPT_FIELDS.getPreferredName(),
            DatafeedConfig.CHUNKING_CONFIG.getPreferredName(),
            DatafeedConfig.HEADERS.getPreferredName(),
            DatafeedConfig.DELAYED_DATA_CHECK_CONFIG.getPreferredName(),
            DatafeedConfig.INDICES_OPTIONS.getPreferredName(),
            DelayedDataCheckConfig.ENABLED.getPreferredName(),
            DelayedDataCheckConfig.CHECK_WINDOW.getPreferredName(),

            ChunkingConfig.MODE_FIELD.getPreferredName(),
            ChunkingConfig.TIME_SPAN_FIELD.getPreferredName(),

            DataFrameAnalyticsConfig.ID.getPreferredName(),
            DataFrameAnalyticsConfig.DESCRIPTION.getPreferredName(),
            DataFrameAnalyticsConfig.SOURCE.getPreferredName(),
            DataFrameAnalyticsConfig.DEST.getPreferredName(),
            DataFrameAnalyticsConfig.ANALYSIS.getPreferredName(),
            DataFrameAnalyticsConfig.ANALYZED_FIELDS.getPreferredName(),
            DataFrameAnalyticsConfig.CREATE_TIME.getPreferredName(),
            DataFrameAnalyticsConfig.VERSION.getPreferredName(),
            DataFrameAnalyticsConfig.MAX_NUM_THREADS.getPreferredName(),
            DataFrameAnalyticsDest.INDEX.getPreferredName(),
            DataFrameAnalyticsDest.RESULTS_FIELD.getPreferredName(),
            DataFrameAnalyticsSource.INDEX.getPreferredName(),
            DataFrameAnalyticsSource.QUERY.getPreferredName(),
            DataFrameAnalyticsSource._SOURCE.getPreferredName(),
            OutlierDetection.NAME.getPreferredName(),
            OutlierDetection.N_NEIGHBORS.getPreferredName(),
            OutlierDetection.METHOD.getPreferredName(),
            OutlierDetection.FEATURE_INFLUENCE_THRESHOLD.getPreferredName(),
            Regression.NAME.getPreferredName(),
            Regression.DEPENDENT_VARIABLE.getPreferredName(),
            Regression.LOSS_FUNCTION.getPreferredName(),
            Regression.LOSS_FUNCTION_PARAMETER.getPreferredName(),
            Regression.PREDICTION_FIELD_NAME.getPreferredName(),
            Regression.TRAINING_PERCENT.getPreferredName(),
            Regression.FEATURE_PROCESSORS.getPreferredName(),
            Classification.NAME.getPreferredName(),
            Classification.DEPENDENT_VARIABLE.getPreferredName(),
            Classification.PREDICTION_FIELD_NAME.getPreferredName(),
            Classification.CLASS_ASSIGNMENT_OBJECTIVE.getPreferredName(),
            Classification.NUM_TOP_CLASSES.getPreferredName(),
            Classification.TRAINING_PERCENT.getPreferredName(),
            Classification.FEATURE_PROCESSORS.getPreferredName(),
            BoostedTreeParams.LAMBDA.getPreferredName(),
            BoostedTreeParams.GAMMA.getPreferredName(),
            BoostedTreeParams.ETA.getPreferredName(),
            BoostedTreeParams.MAX_TREES.getPreferredName(),
            BoostedTreeParams.FEATURE_BAG_FRACTION.getPreferredName(),
            BoostedTreeParams.NUM_TOP_FEATURE_IMPORTANCE_VALUES.getPreferredName(),

            ElasticsearchMappings.CONFIG_TYPE,

            GetResult._ID,
            GetResult._INDEX,
    };

    /**
     * Test if fieldName is one of the reserved result fieldnames or if it contains
     * dots then that the segment before the first dot is not a reserved results
     * fieldname. A fieldName containing dots represents nested fields in which
     * case we only care about the top level.
     *
     * @param fieldName Document field name. This may contain dots '.'
     * @return True if fieldName is not a reserved results fieldname or the top level segment
     * is not a reserved name.
     */
    public static boolean isValidFieldName(String fieldName) {
        String[] segments = DOT_PATTERN.split(fieldName);
        return RESERVED_RESULT_FIELD_NAMES.contains(segments[0]) == false;
    }

    /**
     * A set of all reserved field names in our results.  Fields from the raw
     * data with these names are not added to any result.
     */
    public static final Set<String> RESERVED_RESULT_FIELD_NAMES = new HashSet<>(Arrays.asList(RESERVED_RESULT_FIELD_NAME_ARRAY));

    /**
     * A set of all reserved field names in our config.
     */
    public static final Set<String> RESERVED_CONFIG_FIELD_NAMES = new HashSet<>(Arrays.asList(RESERVED_CONFIG_FIELD_NAME_ARRAY));

    private ReservedFieldNames() {
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2022 The Chromium Authors. All rights reserved.
     Use of this source code is governed by a BSD-style license that can be
     found in the LICENSE file. -->

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <LinearLayout
            android:id="@+id/welcome_main_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:animateLayoutChanges="true"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/image"
                android:layout_marginVertical="32dp"
                android:layout_height="@dimen/privacy_review_illustration_height"
                android:layout_width="@dimen/privacy_review_illustration_width"
                android:src="@drawable/privacy_review_done_image"
                android:importantForAccessibility="no" />

            <TextView
                android:id="@+id/done_title"
                android:layout_gravity="start"
                android:layout_marginHorizontal="16dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/privacy_review_done_title"
                style="@style/TextAppearance.Headline.Primary" />

            <TextView
                android:id="@+id/done_description"
                android:layout_gravity="start"
                android:layout_marginHorizontal="16dp"
                android:layout_marginBottom="8dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/privacy_review_done_description"
                style="@style/TextAppearance.TextLarge.Secondary" />

            <org.chromium.chrome.browser.privacy_review.PrivacyReviewExplanationHeading
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:titleText="@string/privacy_review_privacy_sandbox_heading" />

            <TextView
                android:id="@+id/privacy_sandbox_description"
                android:layout_marginHorizontal="16dp"
                android:layout_marginBottom="8dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/privacy_review_privacy_sandbox_description"
                style="@style/TextAppearance.TextMedium.Secondary" />

            <org.chromium.chrome.browser.privacy_review.PrivacyReviewExplanationHeading
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:titleText="@string/privacy_review_web_app_activity_heading" />

            <TextView
                android:id="@+id/web_app_activity_description"
                android:layout_marginHorizontal="16dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/privacy_review_web_app_activity_description"
                style="@style/TextAppearance.TextMedium.Secondary" />

        </LinearLayout>

    </ScrollView>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom|center">

        <org.chromium.ui.widget.ButtonCompat
            android:id="@+id/done_button"
            android:focusable="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:text="@string/done"
            style="@style/FilledButton.Flat" />
    </LinearLayout>

</LinearLayout>


text:
package org.zeromq.czmq;

public class Zuuid {
    public native void create ();
    public native void destroy ();
    public native void print ();
    public native Zuuid newFrom (byte [] Source);
    public native void set (byte [] Source);
    public native int setStr (String Source);
    public native byte [] data ();
    public native long size ();
    public native String str ();
    public native String strCanonical ();
    public native void export (byte [] Target);
    public native boolean eq (byte [] Compare);
    public native boolean neq (byte [] Compare);
    public native Zuuid dup ();
    public native void test (boolean Verbose);
}


text:
import json

from lxml import etree

from tempest.common.rest_client import RestClientXML
from tempest import config
from tempest import exceptions
from tempest.services.compute.xml.common import Document
from tempest.services.compute.xml.common import Element
from tempest.services.compute.xml.common import xml_to_json

CONF = config.CONF

XMLNS = "http://docs.openstack.org/identity/api/v2.0"

class IdentityClientXML(RestClientXML):

    def __init__(self, auth_provider):
        super(IdentityClientXML, self).__init__(auth_provider)
        self.service = CONF.identity.catalog_type
        self.endpoint_url = 'adminURL'

    def _parse_array(self, node):
        array = []
        for child in node.getchildren():
            array.append(xml_to_json(child))
        return array

    def _parse_body(self, body):
        data = xml_to_json(body)
        return data

    def has_admin_extensions(self):
        """
        Returns True if the KSADM Admin Extensions are supported
        False otherwise
        """
        if hasattr(self, '_has_admin_extensions'):
            return self._has_admin_extensions
        resp, body = self.list_roles()
        self._has_admin_extensions = ('status' in resp and resp.status != 503)
        return self._has_admin_extensions

    def create_role(self, name):
        """Create a role."""
        create_role = Element("role", xmlns=XMLNS, name=name)
        resp, body = self.post('OS-KSADM/roles', str(Document(create_role)),
                               self.headers)
        body = self._parse_body(etree.fromstring(body))
        return resp, body

    def create_tenant(self, name, **kwargs):
        """
        Create a tenant
        name (required): New tenant name
        description: Description of new tenant (default is none)
        enabled <true|false>: Initial tenant status (default is true)
        """
        en = kwargs.get('enabled', 'true')
        create_tenant = Element("tenant",
                                xmlns=XMLNS,
                                name=name,
                                description=kwargs.get('description', ''),
                                enabled=str(en).lower())
        resp, body = self.post('tenants', str(Document(create_tenant)),
                               self.headers)
        body = self._parse_body(etree.fromstring(body))
        return resp, body

    def delete_role(self, role_id):
        """Delete a role."""
        resp, body = self.delete('OS-KSADM/roles/%s' % str(role_id),
                                 self.headers)
        return resp, body

    def list_user_roles(self, tenant_id, user_id):
        """Returns a list of roles assigned to a user for a tenant."""
        url = '/tenants/%s/users/%s/roles' % (tenant_id, user_id)
        resp, body = self.get(url, self.headers)
        body = self._parse_array(etree.fromstring(body))
        return resp, body

    def assign_user_role(self, tenant_id, user_id, role_id):
        """Add roles to a user on a tenant."""
        resp, body = self.put('/tenants/%s/users/%s/roles/OS-KSADM/%s' %
                              (tenant_id, user_id, role_id), '', self.headers)
        body = self._parse_body(etree.fromstring(body))
        return resp, body

    def remove_user_role(self, tenant_id, user_id, role_id):
        """Removes a role assignment for a user on a tenant."""
        return self.delete('/tenants/%s/users/%s/roles/OS-KSADM/%s' %
                           (tenant_id, user_id, role_id), self.headers)

    def delete_tenant(self, tenant_id):
        """Delete a tenant."""
        resp, body = self.delete('tenants/%s' % str(tenant_id), self.headers)
        return resp, body

    def get_tenant(self, tenant_id):
        """Get tenant details."""
        resp, body = self.get('tenants/%s' % str(tenant_id), self.headers)
        body = self._parse_body(etree.fromstring(body))
        return resp, body

    def list_roles(self):
        """Returns roles."""
        resp, body = self.get('OS-KSADM/roles', self.headers)
        body = self._parse_array(etree.fromstring(body))
        return resp, body

    def list_tenants(self):
        """Returns tenants."""
        resp, body = self.get('tenants', self.headers)
        body = self._parse_array(etree.fromstring(body))
        return resp, body

    def get_tenant_by_name(self, tenant_name):
        resp, tenants = self.list_tenants()
        for tenant in tenants:
            if tenant['name'] == tenant_name:
                return tenant
        raise exceptions.NotFound('No such tenant')

    def update_tenant(self, tenant_id, **kwargs):
        """Updates a tenant."""
        resp, body = self.get_tenant(tenant_id)
        name = kwargs.get('name', body['name'])
        desc = kwargs.get('description', body['description'])
        en = kwargs.get('enabled', body['enabled'])
        update_tenant = Element("tenant",
                                xmlns=XMLNS,
                                id=tenant_id,
                                name=name,
                                description=desc,
                                enabled=str(en).lower())

        resp, body = self.post('tenants/%s' % tenant_id,
                               str(Document(update_tenant)),
                               self.headers)
        body = self._parse_body(etree.fromstring(body))
        return resp, body

    def create_user(self, name, password, tenant_id, email, **kwargs):
        """Create a user."""
        create_user = Element("user",
                              xmlns=XMLNS,
                              name=name,
                              password=password,
                              tenantId=tenant_id,
                              email=email)
        if 'enabled' in kwargs:
            create_user.add_attr('enabled', str(kwargs['enabled']).lower())

        resp, body = self.post('users', str(Document(create_user)),
                               self.headers)
        body = self._parse_body(etree.fromstring(body))
        return resp, body

    def update_user(self, user_id, **kwargs):
        """Updates a user."""
        if 'enabled' in kwargs:
            kwargs['enabled'] = str(kwargs['enabled']).lower()
        update_user = Element("user", xmlns=XMLNS, **kwargs)

        resp, body = self.put('users/%s' % user_id,
                              str(Document(update_user)),
                              self.headers)
        body = self._parse_body(etree.fromstring(body))
        return resp, body

    def get_user(self, user_id):
        """GET a user."""
        resp, body = self.get("users/%s" % user_id, self.headers)
        body = self._parse_body(etree.fromstring(body))
        return resp, body

    def delete_user(self, user_id):
        """Delete a user."""
        resp, body = self.delete("users/%s" % user_id, self.headers)
        return resp, body

    def get_users(self):
        """Get the list of users."""
        resp, body = self.get("users", self.headers)
        body = self._parse_array(etree.fromstring(body))
        return resp, body

    def enable_disable_user(self, user_id, enabled):
        """Enables or disables a user."""
        enable_user = Element("user", enabled=str(enabled).lower())
        resp, body = self.put('users/%s/enabled' % user_id,
                              str(Document(enable_user)), self.headers)
        body = self._parse_array(etree.fromstring(body))
        return resp, body

    def delete_token(self, token_id):
        """Delete a token."""
        resp, body = self.delete("tokens/%s" % token_id, self.headers)
        return resp, body

    def list_users_for_tenant(self, tenant_id):
        """List users for a Tenant."""
        resp, body = self.get('/tenants/%s/users' % tenant_id, self.headers)
        body = self._parse_array(etree.fromstring(body))
        return resp, body

    def get_user_by_username(self, tenant_id, username):
        resp, users = self.list_users_for_tenant(tenant_id)
        for user in users:
            if user['name'] == username:
                return user
        raise exceptions.NotFound('No such user')

    def create_service(self, name, type, **kwargs):
        """Create a service."""
        OS_KSADM = "http://docs.openstack.org/identity/api/ext/OS-KSADM/v1.0"
        create_service = Element("service",
                                 xmlns=OS_KSADM,
                                 name=name,
                                 type=type,
                                 description=kwargs.get('description'))
        resp, body = self.post('OS-KSADM/services',
                               str(Document(create_service)),
                               self.headers)
        body = self._parse_body(etree.fromstring(body))
        return resp, body

    def list_services(self):
        """Returns services."""
        resp, body = self.get('OS-KSADM/services', self.headers)
        body = self._parse_array(etree.fromstring(body))
        return resp, body

    def get_service(self, service_id):
        """Get Service."""
        url = '/OS-KSADM/services/%s' % service_id
        resp, body = self.get(url, self.headers)
        body = self._parse_body(etree.fromstring(body))
        return resp, body

    def delete_service(self, service_id):
        """Delete Service."""
        url = '/OS-KSADM/services/%s' % service_id
        return self.delete(url, self.headers)

class TokenClientXML(RestClientXML):

    def __init__(self):
        super(TokenClientXML, self).__init__(None)
        auth_url = CONF.identity.uri

        # Normalize URI to ensure /tokens is in it.
        if 'tokens' not in auth_url:
            auth_url = auth_url.rstrip('/') + '/tokens'

        self.auth_url = auth_url

    def auth(self, user, password, tenant):
        passwordCreds = Element("passwordCredentials",
                                username=user,
                                password=password)
        auth = Element("auth", tenantName=tenant)
        auth.append(passwordCreds)
        resp, body = self.post(self.auth_url, headers=self.headers,
                               body=str(Document(auth)))
        return resp, body['access']

    def request(self, method, url, headers=None, body=None):
        """A simple HTTP request interface."""
        if headers is None:
            headers = {}
        # Send XML, accept JSON. XML response is not easily
        # converted to the corresponding JSON one
        headers['Accept'] = 'application/json'
        self._log_request(method, url, headers, body)
        resp, resp_body = self.http_obj.request(url, method,
                                                headers=headers, body=body)
        self._log_response(resp, resp_body)

        if resp.status in [401, 403]:
            resp_body = json.loads(resp_body)
            raise exceptions.Unauthorized(resp_body['error']['message'])
        elif resp.status not in [200, 201]:
            raise exceptions.IdentityError(
                'Unexpected status code {0}'.format(resp.status))

        return resp, json.loads(resp_body)

    def get_token(self, user, password, tenant, auth_data=False):
        """
        Returns (token id, token data) for supplied credentials
        """
        resp, body = self.auth(user, password, tenant)

        if auth_data:
            return body['token']['id'], body
        else:
            return body['token']['id']


text:
package com.hubspot.singularity.runner.base.configuration;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.hubspot.singularity.runner.base.constraints.DirectoryExists;
import java.util.Optional;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;

@Configuration(filename = "/etc/singularity.base.yaml", consolidatedField = "base")
public class SingularityRunnerBaseConfiguration extends BaseRunnerConfiguration {
  @DirectoryExists
  @JsonProperty
  private String s3UploaderMetadataDirectory;

  @NotEmpty
  @JsonProperty
  private String s3UploaderMetadataSuffix = ".s3.json";

  @DirectoryExists
  @JsonProperty
  private String logWatcherMetadataDirectory;

  @NotEmpty
  @JsonProperty
  private String logWatcherMetadataSuffix = ".tail.json";

  @JsonProperty
  private Optional<String> sentryDsn = Optional.empty();

  @NotNull
  @JsonProperty
  private String sentryPrefix = "";

  @JsonProperty
  private Optional<String> useCompressProgram = Optional.empty();

  public SingularityRunnerBaseConfiguration() {
    super(Optional.<String>empty());
    this.setLoggingDirectory(Optional.of("/var/log/singularity/"));
  }

  public String getS3UploaderMetadataDirectory() {
    return s3UploaderMetadataDirectory;
  }

  public void setS3UploaderMetadataDirectory(String s3UploaderMetadataDirectory) {
    this.s3UploaderMetadataDirectory = s3UploaderMetadataDirectory;
  }

  public String getS3UploaderMetadataSuffix() {
    return s3UploaderMetadataSuffix;
  }

  public void setS3UploaderMetadataSuffix(String s3UploaderMetadataSuffix) {
    this.s3UploaderMetadataSuffix = s3UploaderMetadataSuffix;
  }

  public String getLogWatcherMetadataDirectory() {
    return logWatcherMetadataDirectory;
  }

  public void setLogWatcherMetadataDirectory(String logWatcherMetadataDirectory) {
    this.logWatcherMetadataDirectory = logWatcherMetadataDirectory;
  }

  public String getLogWatcherMetadataSuffix() {
    return logWatcherMetadataSuffix;
  }

  public void setLogWatcherMetadataSuffix(String logWatcherMetadataSuffix) {
    this.logWatcherMetadataSuffix = logWatcherMetadataSuffix;
  }

  public Optional<String> getSentryDsn() {
    return sentryDsn;
  }

  public void setSentryDsn(Optional<String> sentryDsn) {
    this.sentryDsn = sentryDsn;
  }

  public String getSentryPrefix() {
    return sentryPrefix;
  }

  public void setSentryPrefix(String sentryPrefix) {
    this.sentryPrefix = sentryPrefix;
  }

  public Optional<String> getUseCompressProgram() {
    return useCompressProgram;
  }

  public void setUseCompressProgram(Optional<String> useCompressProgram) {
    this.useCompressProgram = useCompressProgram;
  }

  @Override
  public String toString() {
    return (
      "SingularityRunnerBaseConfiguration[" +
      "s3UploaderMetadataDirectory='" +
      s3UploaderMetadataDirectory +
      '\'' +
      ", s3UploaderMetadataSuffix='" +
      s3UploaderMetadataSuffix +
      '\'' +
      ", logWatcherMetadataDirectory='" +
      logWatcherMetadataDirectory +
      '\'' +
      ", logWatcherMetadataSuffix='" +
      logWatcherMetadataSuffix +
      '\'' +
      ", useCompressProgram=" +
      useCompressProgram +
      ']'
    );
  }
}


text:
START_ATF_NAMESPACE
    namespace Detail
    {

        Info::_guild_list_result_zoclctor__guild_list_result_zocl2_ptr _guild_list_result_zoclctor__guild_list_result_zocl2_next(nullptr);
        Info::_guild_list_result_zoclctor__guild_list_result_zocl2_clbk _guild_list_result_zoclctor__guild_list_result_zocl2_user(nullptr);

        Info::_guild_list_result_zoclsize4_ptr _guild_list_result_zoclsize4_next(nullptr);
        Info::_guild_list_result_zoclsize4_clbk _guild_list_result_zoclsize4_user(nullptr);

        void _guild_list_result_zoclctor__guild_list_result_zocl2_wrapper(struct _guild_list_result_zocl* _this)
        {
           _guild_list_result_zoclctor__guild_list_result_zocl2_user(_this, _guild_list_result_zoclctor__guild_list_result_zocl2_next);
        };
        int _guild_list_result_zoclsize4_wrapper(struct _guild_list_result_zocl* _this)
        {
           return _guild_list_result_zoclsize4_user(_this, _guild_list_result_zoclsize4_next);
        };

        ::std::array<hook_record, 2> _guild_list_result_zocl_functions =
        {
            _hook_record {
                (LPVOID)0x14025e220L,
                (LPVOID *)&_guild_list_result_zoclctor__guild_list_result_zocl2_user,
                (LPVOID *)&_guild_list_result_zoclctor__guild_list_result_zocl2_next,
                (LPVOID)cast_pointer_function(_guild_list_result_zoclctor__guild_list_result_zocl2_wrapper),
                (LPVOID)cast_pointer_function((void(_guild_list_result_zocl::*)())&_guild_list_result_zocl::ctor__guild_list_result_zocl)
            },
            _hook_record {
                (LPVOID)0x14025e240L,
                (LPVOID *)&_guild_list_result_zoclsize4_user,
                (LPVOID *)&_guild_list_result_zoclsize4_next,
                (LPVOID)cast_pointer_function(_guild_list_result_zoclsize4_wrapper),
                (LPVOID)cast_pointer_function((int(_guild_list_result_zocl::*)())&_guild_list_result_zocl::size)
            },
        };
    }; // end namespace Detail
END_ATF_NAMESPACE


text:
#include "config.h"
#include "core/html/HTMLWBRElement.h"

#include "core/HTMLNames.h"
#include "core/rendering/RenderWordBreak.h"

namespace blink {

using namespace HTMLNames;

inline HTMLWBRElement::HTMLWBRElement(Document& document)
    : HTMLElement(wbrTag, document)
{
}

DEFINE_NODE_FACTORY(HTMLWBRElement)

RenderObject* HTMLWBRElement::createRenderer(RenderStyle* style)
{
    return new RenderWordBreak(this);
}

}


text:
package com.cloud.storage;

import java.util.List;

import org.apache.log4j.Logger;

import com.cloud.agent.Listener;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.AgentControlCommand;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupStorageCommand;
import com.cloud.agent.api.StoragePoolInfo;
import com.cloud.capacity.Capacity;
import com.cloud.capacity.CapacityVO;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.exception.ConnectionException;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;

public class LocalStoragePoolListener implements Listener {
    private final static Logger s_logger = Logger.getLogger(LocalStoragePoolListener.class);
    @Inject StoragePoolDao _storagePoolDao;
    @Inject StoragePoolHostDao _storagePoolHostDao;
    @Inject CapacityDao _capacityDao;
    @Inject StorageManager _storageMgr;

    @Override
    public int getTimeout() {
        return 0;
    }

    @Override
    public boolean isRecurring() {
        return false;
    }

    @Override
    public boolean processAnswers(long agentId, long seq, Answer[] answers) {
        return false;
    }

    @Override
    public boolean processCommands(long agentId, long seq, Command[] commands) {
        return false;
    }

    @Override
    @DB
    public void processConnect(HostVO host, StartupCommand cmd, boolean forRebalance) throws ConnectionException {
        if (!(cmd instanceof StartupStorageCommand)) {
            return;
        }

        StartupStorageCommand ssCmd = (StartupStorageCommand)cmd;

        if (ssCmd.getResourceType() != Storage.StorageResourceType.STORAGE_POOL) {
            return;
        }

        StoragePoolInfo pInfo = ssCmd.getPoolInfo();
        if (pInfo == null) {
            return;
        }

        try {
            StoragePoolVO pool = _storagePoolDao.findPoolByHostPath(host.getDataCenterId(), host.getPodId(), pInfo.getHost(), pInfo.getHostPath(), pInfo.getUuid());
        	if(pool == null && host.getHypervisorType() == HypervisorType.VMware) {
        		// perform run-time upgrade. In versions prior to 2.2.12, there is a bug that we don't save local datastore info (host path is empty), this will cause us
        		// not able to distinguish multiple local datastores that may be available on the host, to support smooth migration, we
        		// need to perform runtime upgrade here
        		if(pInfo.getHostPath().length() > 0) {
        			pool = _storagePoolDao.findPoolByHostPath(host.getDataCenterId(), host.getPodId(), pInfo.getHost(), "", pInfo.getUuid());
        		}
        	}

            if (pool == null) {

                long poolId = _storagePoolDao.getNextInSequence(Long.class, "id");
                String name = cmd.getName() == null ? (host.getName() + " Local Storage") : cmd.getName();
                Transaction txn = Transaction.currentTxn();
                txn.start();
                pool = new StoragePoolVO(poolId, name, pInfo.getUuid(), pInfo.getPoolType(), host.getDataCenterId(),
                                         host.getPodId(), pInfo.getAvailableBytes(), pInfo.getCapacityBytes(), pInfo.getHost(), 0,
                                         pInfo.getHostPath());
                pool.setClusterId(host.getClusterId());
                _storagePoolDao.persist(pool, pInfo.getDetails());
                StoragePoolHostVO poolHost = new StoragePoolHostVO(pool.getId(), host.getId(), pInfo.getLocalPath());
                _storagePoolHostDao.persist(poolHost);
                _storageMgr.createCapacityEntry(pool, Capacity.CAPACITY_TYPE_LOCAL_STORAGE, pool.getCapacityBytes() - pool.getAvailableBytes());

                txn.commit();
            } else {
                Transaction txn = Transaction.currentTxn();
                txn.start();
                pool.setPath(pInfo.getHostPath());
                pool.setAvailableBytes(pInfo.getAvailableBytes());
                pool.setCapacityBytes(pInfo.getCapacityBytes());
                _storagePoolDao.update(pool.getId(), pool);
                if (pInfo.getDetails() != null) {
                    _storagePoolDao.updateDetails(pool.getId(), pInfo.getDetails());
                }
                StoragePoolHostVO poolHost = _storagePoolHostDao.findByPoolHost(pool.getId(), host.getId());
                if (poolHost == null) {
                    poolHost = new StoragePoolHostVO(pool.getId(), host.getId(), pInfo.getLocalPath());
                    _storagePoolHostDao.persist(poolHost);
                }

                _storageMgr.createCapacityEntry(pool, Capacity.CAPACITY_TYPE_LOCAL_STORAGE, pool.getCapacityBytes() - pool.getAvailableBytes());

                txn.commit();
            }
        } catch (Exception e) {
            s_logger.warn("Unable to setup the local storage pool for " + host, e);
            throw new ConnectionException(true, "Unable to setup the local storage pool for " + host, e);
        }
    }

    @Override
    public AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd) {
        return null;
    }

    @Override
    public boolean processDisconnect(long agentId, Status state) {
        return false;
    }

    @Override
    public boolean processTimeout(long agentId, long seq) {
        return false;
    }
}


text:
module VagrantPlugins
  module TiktalikVagrant
    module Action
      class MessageAlreadyCreated
        def initialize(app, env)
          @app = app
        end

        def call(env)
          env[:ui].info(I18n.t("vagrant_tiktalik.already_created"))
          @app.call(env)
        end
      end
    end
  end
end


text:
<?php

use Illuminate\Auth\Access\Gate;
use Illuminate\Container\Container;

class GateTest extends PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \InvalidArgumentException
     */
    public function test_gate_throws_exception_on_invalid_callback_type()
    {
        $this->getBasicGate()->define('foo', 'foo');
    }

    public function test_basic_closures_can_be_defined()
    {
        $gate = $this->getBasicGate();

        $gate->define('foo', function ($user) { return true; });
        $gate->define('bar', function ($user) { return false; });

        $this->assertTrue($gate->check('foo'));
        $this->assertFalse($gate->check('bar'));
    }

    public function test_before_callbacks_can_override_result_if_necessary()
    {
        $gate = $this->getBasicGate();

        $gate->define('foo', function ($user) { return true; });
        $gate->before(function ($user, $ability) {
            $this->assertEquals('foo', $ability);

            return false;
        });

        $this->assertFalse($gate->check('foo'));
    }

    public function test_before_callbacks_dont_interrupt_gate_check_if_no_value_is_returned()
    {
        $gate = $this->getBasicGate();

        $gate->define('foo', function ($user) { return true; });
        $gate->before(function () {});

        $this->assertTrue($gate->check('foo'));
    }

    public function test_current_user_that_is_on_gate_always_injected_into_closure_callbacks()
    {
        $gate = $this->getBasicGate();

        $gate->define('foo', function ($user) {
            $this->assertEquals(1, $user->id);

            return true;
        });

        $this->assertTrue($gate->check('foo'));
    }

    public function test_a_single_argument_can_be_passed_when_checking_abilities()
    {
        $gate = $this->getBasicGate();

        $dummy = new AccessGateTestDummy;

        $gate->define('foo', function ($user, $x) use ($dummy) {
            $this->assertEquals($dummy, $x);

            return true;
        });

        $this->assertTrue($gate->check('foo', $dummy));
    }

    public function test_multiple_arguments_can_be_passed_when_checking_abilities()
    {
        $gate = $this->getBasicGate();

        $dummy1 = new AccessGateTestDummy;
        $dummy2 = new AccessGateTestDummy;

        $gate->define('foo', function ($user, $x, $y) use ($dummy1, $dummy2) {
            $this->assertEquals($dummy1, $x);
            $this->assertEquals($dummy2, $y);

            return true;
        });

        $this->assertTrue($gate->check('foo', [$dummy1, $dummy2]));
    }

    public function test_classes_can_be_defined_as_callbacks_using_at_notation()
    {
        $gate = $this->getBasicGate();

        $gate->define('foo', 'AccessGateTestClass@foo');

        $this->assertTrue($gate->check('foo'));
    }

    public function test_policy_classes_can_be_defined_to_handle_checks_for_given_type()
    {
        $gate = $this->getBasicGate();

        $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);

        $this->assertTrue($gate->check('update', new AccessGateTestDummy));
    }

    public function test_policy_classes_can_be_defined_to_handle_checks_for_given_class_name()
    {
        $gate = $this->getBasicGate();

        $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);

        $this->assertTrue($gate->check('create', AccessGateTestDummy::class));
    }

    public function test_policies_may_have_before_methods_to_override_checks()
    {
        $gate = $this->getBasicGate();

        $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithBefore::class);

        $this->assertTrue($gate->check('update', new AccessGateTestDummy));
    }

    public function test_policies_always_override_closures_with_same_name()
    {
        $gate = $this->getBasicGate();

        $gate->define('update', function () { $this->fail(); });

        $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);

        $this->assertTrue($gate->check('update', new AccessGateTestDummy));
    }

    public function test_for_user_method_attaches_a_new_user_to_a_new_gate_instance()
    {
        $gate = $this->getBasicGate();

        // Assert that the callback receives the new user with ID of 2 instead of ID of 1...
        $gate->define('foo', function ($user) {
            $this->assertEquals(2, $user->id);

            return true;
        });

        $this->assertTrue($gate->forUser((object) ['id' => 2])->check('foo'));
    }

    protected function getBasicGate()
    {
        return new Gate(new Container, function () { return (object) ['id' => 1]; });
    }
}

class AccessGateTestClass
{
    public function foo()
    {
        return true;
    }
}

class AccessGateTestDummy
{
    //
}

class AccessGateTestPolicy
{
    public function create($user)
    {
        return true;
    }

    public function update($user, AccessGateTestDummy $dummy)
    {
        return $user instanceof StdClass;
    }
}

class AccessGateTestPolicyWithBefore
{
    public function before($user, $ability)
    {
        return true;
    }

    public function update($user, AccessGateTestDummy $dummy)
    {
        return false;
    }
}


text:
var _;

_ = Tower._;

Tower.StoreSerializerString = {
  from: function(serialized) {
    if (_.none(serialized)) {
      return null;
    } else {
      return String(serialized);
    }
  },
  to: function(deserialized) {
    if (_.none(deserialized)) {
      return null;
    } else {
      return String(deserialized);
    }
  }
};

Tower.StoreSerializerNumber = {
  from: function(serialized) {
    if (_.none(serialized)) {
      return null;
    } else {
      return Number(serialized);
    }
  },
  to: function(deserialized) {
    if (_.none(deserialized)) {
      return null;
    } else {
      return Number(deserialized);
    }
  }
};

Tower.StoreSerializerInteger = {
  from: function(serialized) {
    if (_.none(serialized)) {
      return null;
    } else {
      return parseInt(serialized);
    }
  },
  to: function(deserialized) {
    if (_.none(deserialized)) {
      return null;
    } else {
      return parseInt(deserialized);
    }
  }
};

Tower.StoreSerializerFloat = {
  from: function(serialized) {
    return parseFloat(serialized);
  },
  to: function(deserialized) {
    return deserialized;
  }
};

Tower.StoreSerializerBoolean = {
  from: function(serialized) {
    if (typeof serialized === 'string') {
      return !!(serialized !== 'false');
    } else {
      return Boolean(serialized);
    }
  },
  to: function(deserialized) {
    return Tower.StoreSerializerBoolean.from(deserialized);
  }
};

Tower.StoreSerializerDate = {
  from: function(date) {
    return date;
  },
  to: function(date) {
    return _.toDate(date);
  }
};

Tower.StoreSerializerGeo = {
  from: function(serialized) {
    return serialized;
  },
  to: function(deserialized) {
    switch (_.kind(deserialized)) {
      case 'array':
        return {
          lat: deserialized[0],
          lng: deserialized[1]
        };
      case 'object':
        return {
          lat: deserialized.lat || deserialized.latitude,
          lng: deserialized.lng || deserialized.longitude
        };
      default:
        deserialized = deserialized.split(/,\ */);
        return {
          lat: parseFloat(deserialized[0]),
          lng: parseFloat(deserialized[1])
        };
    }
  }
};

Tower.StoreSerializerArray = {
  from: function(serialized) {
    if (_.none(serialized)) {
      return null;
    } else {
      return _.castArray(serialized);
    }
  },
  to: function(deserialized) {
    return Tower.StoreSerializerArray.from(deserialized);
  }
};

Tower.StoreSerializerDecimal = Tower.StoreSerializerFloat;

Tower.StoreSerializerTime = Tower.StoreSerializerDate;

Tower.StoreSerializerDateTime = Tower.StoreSerializerDate;

module.exports = Tower.StoreSerializer;