text:
> [Introduced][ce-37115] in GitLab 10.0. Generally available on GitLab 11.0.

Auto DevOps automatically detects, builds, tests, deploys, and monitors your
applications.

## Overview

With Auto DevOps, the software development process becomes easier to set up
as every project can have a complete workflow from verification to monitoring
without needing to configure anything. Just push your code and GitLab takes
care of everything else. This makes it easier to start new projects and brings
consistency to how applications are set up throughout a company.

## Quick start

If you are using GitLab.com, see the [quick start guide](quick_start_guide.md)
for using Auto DevOps with GitLab.com and a Kubernetes cluster on Google Kubernetes
Engine.

## Comparison to application platforms and PaaS

Auto DevOps provides functionality described by others as an application
platform or as a Platform as a Service (PaaS). It takes inspiration from the
innovative work done by [Heroku](https://www.heroku.com/) and goes beyond it
in a couple of ways:

1. Auto DevOps works with any Kubernetes cluster, you're not limited to running
   on GitLab's infrastructure (note that many features also work without Kubernetes).
1. There is no additional cost (no markup on the infrastructure costs), and you
   can use a self-hosted Kubernetes cluster or Containers as a Service on any
   public cloud (for example [Google Kubernetes Engine](https://cloud.google.com/kubernetes-engine/)).
1. Auto DevOps has more features including security testing, performance testing,
   and code quality testing.
1. It offers an incremental graduation path. If you need advanced customizations
   you can start modifying the templates without having to start over on a
   completely different platform.

## Features

Comprised of a set of stages, Auto DevOps brings these best practices to your
project in a simple and automatic way:

1. [Auto Build](#auto-build)
1. [Auto Test](#auto-test)
1. [Auto Code Quality](#auto-code-quality) **[STARTER]**
1. [Auto SAST (Static Application Security Testing)](#auto-sast) **[ULTIMATE]**
1. [Auto Dependency Scanning](#auto-dependency-scanning) **[ULTIMATE]**
1. [Auto License Management](#auto-license-management) **[ULTIMATE]**
1. [Auto Container Scanning](#auto-container-scanning)
1. [Auto Review Apps](#auto-review-apps)
1. [Auto DAST (Dynamic Application Security Testing)](#auto-dast) **[ULTIMATE]**
1. [Auto Deploy](#auto-deploy)
1. [Auto Browser Performance Testing](#auto-browser-performance-testing) **[PREMIUM]**
1. [Auto Monitoring](#auto-monitoring)

As Auto DevOps relies on many different components, it's good to have a basic
knowledge of the following:

- [Kubernetes](https://kubernetes.io/docs/home/)
- [Helm](https://docs.helm.sh/)
- [Docker](https://docs.docker.com)
- [GitLab Runner](https://docs.gitlab.com/runner/)
- [Prometheus](https://prometheus.io/docs/introduction/overview/)

Auto DevOps provides great defaults for all the stages; you can, however,
[customize](#customizing) almost everything to your needs.

For an overview on the creation of Auto DevOps, read the blog post [From 2/3 of the Self-Hosted Git Market, to the Next-Generation CI System, to Auto DevOps](https://about.gitlab.com/2017/06/29/whats-next-for-gitlab-ci/).

## Requirements

TIP: **Tip:**
For self-hosted installations, the easiest way to make use of Auto DevOps is to
install GitLab inside a Kubernetes cluster using the [GitLab Omnibus Helm Chart]
which automatically installs and configures everything you need!

To make full use of Auto DevOps, you will need:

1. **GitLab Runner** (needed for all stages) - Your Runner needs to be
   configured to be able to run Docker. Generally this means using the
   [Docker](https://docs.gitlab.com/runner/executors/docker.html) or [Kubernetes
   executor](https://docs.gitlab.com/runner/executors/kubernetes.html), with
   [privileged mode enabled](https://docs.gitlab.com/runner/executors/docker.html#use-docker-in-docker-with-privileged-mode).
   The Runners do not need to be installed in the Kubernetes cluster, but the
   Kubernetes executor is easy to use and is automatically autoscaling.
   Docker-based Runners can be configured to autoscale as well, using [Docker
   Machine](https://docs.gitlab.com/runner/install/autoscaling.html). Runners
   should be registered as [shared Runners](../../ci/runners/README.md#registering-a-shared-runner)
   for the entire GitLab instance, or [specific Runners](../../ci/runners/README.md#registering-a-specific-runner)
   that are assigned to specific projects.
1. **Base domain** (needed for Auto Review Apps and Auto Deploy) - You will need
   a domain configured with wildcard DNS which is going to be used by all of your
   Auto DevOps applications. [Read the specifics](#auto-devops-base-domain).
1. **Kubernetes** (needed for Auto Review Apps, Auto Deploy, and Auto Monitoring) -
   To enable deployments, you will need Kubernetes 1.5+. You need a [Kubernetes cluster][kubernetes-clusters]
   for the project, or a Kubernetes [default service template](../../user/project/integrations/services_templates.md)
   for the entire GitLab installation.
    1. **A load balancer** - You can use NGINX ingress by deploying it to your
       Kubernetes cluster using the
       [`nginx-ingress`](https://github.com/kubernetes/charts/tree/master/stable/nginx-ingress)
       Helm chart.
    1. **Wildcard TLS termination** - You can deploy the
       [`kube-lego`](https://github.com/kubernetes/charts/tree/master/stable/kube-lego)
       Helm chart to your Kubernetes cluster to automatically issue certificates
       for your domains using Let's Encrypt.
1. **Prometheus** (needed for Auto Monitoring) - To enable Auto Monitoring, you
   will need Prometheus installed somewhere (inside or outside your cluster) and
   configured to scrape your Kubernetes cluster. To get response metrics
   (in addition to system metrics), you need to
   [configure Prometheus to monitor NGINX](../../user/project/integrations/prometheus_library/nginx_ingress.md#configuring-prometheus-to-monitor-for-nginx-ingress-metrics).
   The [Prometheus service](../../user/project/integrations/prometheus.md)
   integration needs to be enabled for the project, or enabled as a
   [default service template](../../user/project/integrations/services_templates.md)
   for the entire GitLab installation.

NOTE: **Note:**
If you do not have Kubernetes or Prometheus installed, then Auto Review Apps,
Auto Deploy, and Auto Monitoring will be silently skipped.

## Auto DevOps base domain

The Auto DevOps base domain is required if you want to make use of [Auto
Review Apps](#auto-review-apps) and [Auto Deploy](#auto-deploy). It can be defined
in three places:

- either under the project's CI/CD settings while [enabling Auto DevOps](#enabling-auto-devops)
- or in instance-wide settings in the **admin area > Settings** under the "Continuous Integration and Delivery" section
- or at the project or group level as a variable: `AUTO_DEVOPS_DOMAIN` (required if you want to use [multiple clusters](#using-multiple-kubernetes-clusters))

A wildcard DNS A record matching the base domain(s) is required, for example,
given a base domain of `example.com`, you'd need a DNS entry like:

```
*.example.com   3600     A     1.2.3.4
```

In this case, `example.com` is the domain name under which the deployed apps will be served,
and `1.2.3.4` is the IP address of your load balancer; generally NGINX
([see requirements](#requirements)). How to set up the DNS record is beyond
the scope of this document; you should check with your DNS provider.

Alternatively you can use free public services like [nip.io](http://nip.io)
which provide automatic wildcard DNS without any configuration. Just set the
Auto DevOps base domain to `1.2.3.4.nip.io`.

Once set up, all requests will hit the load balancer, which in turn will route
them to the Kubernetes pods that run your application(s).

NOTE: **Note:**
If GitLab is installed using the [GitLab Omnibus Helm Chart], there are two
options: provide a static IP, or have one assigned. For more information see the
relevant docs on the [network prerequisites](../../install/kubernetes/gitlab_omnibus.md#networking-prerequisites).

## Using multiple Kubernetes clusters **[PREMIUM]**

When using Auto DevOps, you may want to deploy different environments to
different Kubernetes clusters. This is possible due to the 1:1 connection that
[exists between them](../../user/project/clusters/index.md#multiple-kubernetes-clusters).

In the [Auto DevOps template](https://gitlab.com/gitlab-org/gitlab-ci-yml/blob/master/Auto-DevOps.gitlab-ci.yml)
(used behind the scenes by Auto DevOps), there are currently 3 defined environment names that you need to know:

- `review/` (every environment starting with `review/`)
- `staging`
- `production`

Those environments are tied to jobs that use [Auto Deploy](#auto-deploy), so
except for the environment scope, they would also need to have a different
domain they would be deployed to. This is why you need to define a separate
`AUTO_DEVOPS_DOMAIN` variable for all the above
[based on the environment](../../ci/variables/README.md#limiting-environment-scopes-of-variables).

The following table is an example of how the three different clusters would
be configured.

| Cluster name | Cluster environment scope | `AUTO_DEVOPS_DOMAIN` variable value | Variable environment scope | Notes |
| ------------ | -------------- | ----------------------------- | ------------- | ------ |
| review       |  `review/*`    | `review.example.com`  | `review/*`      | The review cluster which will run all [Review Apps](../../ci/review_apps/index.md). `*` is a wildcard, which means it will be used by every environment name starting with `review/`. |
| staging      |  `staging`     | `staging.example.com` | `staging`       | (Optional) The staging cluster which will run the deployments of the staging environments. You need to [enable it first](#deploy-policy-for-staging-and-production-environments). |
| production   |  `production`  | `example.com`         | `production`    | The production cluster which will run the deployments of the production environment. You can use [incremental rollouts](#incremental-rollout-to-production). |

To add a different cluster for each environment:

1. Navigate to your project's **Operations > Kubernetes** and create the Kubernetes clusters
   with their respective environment scope as described from the table above.

    ![Auto DevOps multiple clusters](img/autodevops_multiple_clusters.png)

1. After the clusters are created, navigate to each one and install Helm Tiller
   and Ingress.
1. Make sure you have [configured your DNS](#auto-devops-base-domain) with the
   specified Auto DevOps domains.
1. Navigate to your project's **Settings > CI/CD > Variables** and add
   the `AUTO_DEVOPS_DOMAIN` variables with their respective environment
   scope.

    ![Auto DevOps domain variables](img/autodevops_domain_variables.png)

Now that all is configured, you can test your setup by creating a merge request
and verifying that your app is deployed as a review app in the Kubernetes
cluster with the `review/*` environment scope. Similarly, you can check the
other environments.

## Enabling Auto DevOps

If you haven't done already, read the [requirements](#requirements) to make
full use of Auto DevOps. If this is your fist time, we recommend you follow the
[quick start guide](quick_start_guide.md).

To enable Auto DevOps to your project:

1. Check that your project doesn't have a `.gitlab-ci.yml`, or remove it otherwise
1. Go to your project's **Settings > CI/CD > Auto DevOps**
1. Select "Enable Auto DevOps"
1. Optionally, but recommended, add in the [base domain](#auto-devops-base-domain)
   that will be used by Kubernetes to [deploy your application](#auto-deploy)
   and choose the [deployment strategy](#deployment-strategy)
1. Hit **Save changes** for the changes to take effect

Once saved, an Auto DevOps pipeline will be triggered on the default branch.

NOTE: **Note:**
For GitLab versions 10.0 - 10.2, when enabling Auto DevOps, a pipeline needs to be
manually triggered either by pushing a new commit to the repository or by visiting
`https://example.gitlab.com/<username>/<project>/pipelines/new` and creating
a new pipeline for your default branch, generally `master`.

NOTE: **Note:**
If you are a GitLab Administrator, you can enable Auto DevOps instance wide
in **Admin Area > Settings > Continuous Integration and Deployment**. Doing that,
all the projects that haven't explicitly set an option will have Auto DevOps
enabled by default.

NOTE: **Note:**
There is also a feature flag to enable Auto DevOps to a percentage of projects
which can be enabled from the console with
`Feature.get(:force_autodevops_on_by_default).enable_percentage_of_actors(10)`.

NOTE: **Enabled by default:**
Starting with GitLab 11.3, the Auto DevOps pipeline will be enabled by default for all
projects. If it's not explicitly enabled for the project, Auto DevOps will be automatically
disabled on the first pipeline failure. Your project will continue to use an alternative
[CI/CD configuration file](../../ci/yaml/README.md) if one is found.

### Deployment strategy

> [Introduced](https://gitlab.com/gitlab-org/gitlab-ce/issues/38542) in GitLab 11.0.

You can change the deployment strategy used by Auto DevOps by going to your
project's **Settings > CI/CD > Auto DevOps**.

The available options are:

- **Continuous deployment to production** - enables [Auto Deploy](#auto-deploy)
  by setting the [`STAGING_ENABLED`](#deploy-policy-for-staging-and-production-environments) and
  [`INCREMENTAL_ROLLOUT_ENABLED`](#incremental-rollout-to-production) variables
  to false.
- **Automatic deployment to staging, manual deployment to production** - sets the
  [`STAGING_ENABLED`](#deploy-policy-for-staging-and-production-environments) and
  [`INCREMENTAL_ROLLOUT_ENABLED`](#incremental-rollout-to-production) variables
  to true, and the user is responsible for manually deploying to staging and production.

## Stages of Auto DevOps

The following sections describe the stages of Auto DevOps. Read them carefully
to understand how each one works.

### Auto Build

Auto Build creates a build of the application in one of two ways:

- If there is a `Dockerfile`, it will use `docker build` to create a Docker image.
- Otherwise, it will use [Herokuish](https://github.com/gliderlabs/herokuish)
  and [Heroku buildpacks](https://devcenter.heroku.com/articles/buildpacks)
  to automatically detect and build the application into a Docker image.

Either way, the resulting Docker image is automatically pushed to the
[Container Registry][container-registry] and tagged with the commit SHA.

CAUTION: **Important:**
If you are also using Auto Review Apps and Auto Deploy and choose to provide
your own `Dockerfile`, make sure you expose your application to port
`5000` as this is the port assumed by the default Helm chart.

### Auto Test

Auto Test automatically runs the appropriate tests for your application using
[Herokuish](https://github.com/gliderlabs/herokuish) and [Heroku
buildpacks](https://devcenter.heroku.com/articles/buildpacks) by analyzing
your project to detect the language and framework. Several languages and
frameworks are detected automatically, but if your language is not detected,
you may succeed with a [custom buildpack](#custom-buildpacks). Check the
[currently supported languages](#currently-supported-languages).

NOTE: **Note:**
Auto Test uses tests you already have in your application. If there are no
tests, it's up to you to add them.

### Auto Code Quality **[STARTER]**

Auto Code Quality uses the
[Code Quality image](https://gitlab.com/gitlab-org/security-products/codequality) to run
static analysis and other code checks on the current code. The report is
created, and is uploaded as an artifact which you can later download and check
out.

In GitLab Starter, differences between the source and
target branches are also
[shown in the merge request widget](https://docs.gitlab.com/ee/user/project/merge_requests/code_quality.html).

### Auto SAST **[ULTIMATE]**

> Introduced in [GitLab Ultimate][ee] 10.3.

Static Application Security Testing (SAST) uses the
[SAST Docker image](https://gitlab.com/gitlab-org/security-products/sast) to run static
analysis on the current code and checks for potential security issues. Once the
report is created, it's uploaded as an artifact which you can later download and
check out.

In GitLab Ultimate, any security warnings are also
[shown in the merge request widget](https://docs.gitlab.com/ee//user/project/merge_requests/sast.html).

### Auto Dependency Scanning **[ULTIMATE]**

> Introduced in [GitLab Ultimate][ee] 10.7.

Dependency Scanning uses the
[Dependency Scanning Docker image](https://gitlab.com/gitlab-org/security-products/dependency-scanning)
to run analysis on the project dependencies and checks for potential security issues. Once the
report is created, it's uploaded as an artifact which you can later download and
check out.

Any security warnings are also
[shown in the merge request widget](https://docs.gitlab.com/ee//user/project/merge_requests/dependency_scanning.html).

### Auto License Management **[ULTIMATE]**

> Introduced in [GitLab Ultimate][ee] 11.0.

License Management uses the
[License Management Docker image](https://gitlab.com/gitlab-org/security-products/license-management)
to search the project dependencies for their license. Once the
report is created, it's uploaded as an artifact which you can later download and
check out.

Any licenses are also
[shown in the merge request widget](https://docs.gitlab.com/ee//user/project/merge_requests/license_management.html).

### Auto Container Scanning

> Introduced in GitLab 10.4.

Vulnerability Static Analysis for containers uses
[Clair](https://github.com/coreos/clair) to run static analysis on a
Docker image and checks for potential security issues. Once the report is
created, it's uploaded as an artifact which you can later download and
check out.

In GitLab Ultimate, any security warnings are also
[shown in the merge request widget](https://docs.gitlab.com/ee//user/project/merge_requests/container_scanning.html).

### Auto Review Apps

NOTE: **Note:**
This is an optional step, since many projects do not have a Kubernetes cluster
available. If the [requirements](#requirements) are not met, the job will
silently be skipped.

CAUTION: **Caution:**
Your apps should *not* be manipulated outside of Helm (using Kubernetes directly.)
This can cause confusion with Helm not detecting the change, and subsequent
deploys with Auto DevOps can undo your changes. Also, if you change something
and want to undo it by deploying again, Helm may not detect that anything changed
in the first place, and thus not realize that it needs to re-apply the old config.

[Review Apps][review-app] are temporary application environments based on the
branch's code so developers, designers, QA, product managers, and other
reviewers can actually see and interact with code changes as part of the review
process. Auto Review Apps create a Review App for each branch.

The Review App will have a unique URL based on the project name, the branch
name, and a unique number, combined with the Auto DevOps base domain. For
example, `user-project-branch-1234.example.com`. A link to the Review App shows
up in the merge request widget for easy discovery. When the branch is deleted,
for example after the merge request is merged, the Review App will automatically
be deleted.

### Auto DAST **[ULTIMATE]**

> Introduced in [GitLab Ultimate][ee] 10.4.

Dynamic Application Security Testing (DAST) uses the
popular open source tool [OWASP ZAProxy](https://github.com/zaproxy/zaproxy)
to perform an analysis on the current code and checks for potential security
issues. Once the report is created, it's uploaded as an artifact which you can
later download and check out.

In GitLab Ultimate, any security warnings are also
[shown in the merge request widget](https://docs.gitlab.com/ee//user/project/merge_requests/dast.html).

### Auto Browser Performance Testing **[PREMIUM]**

> Introduced in [GitLab Premium][ee] 10.4.

Auto Browser Performance Testing utilizes the [Sitespeed.io container](https://hub.docker.com/r/sitespeedio/sitespeed.io/) to measure the performance of a web page. A JSON report is created and uploaded as an artifact, which includes the overall performance score for each page. By default, the root page of Review and Production environments will be tested. If you would like to add additional URL's to test, simply add the paths to a file named `.gitlab-urls.txt` in the root directory, one per line. For example:

```
/
/features
/direction
```

In GitLab Premium, performance differences between the source
and target branches are [shown in the merge request widget](https://docs.gitlab.com/ee//user/project/merge_requests/browser_performance_testing.html).

### Auto Deploy

NOTE: **Note:**
This is an optional step, since many projects do not have a Kubernetes cluster
available. If the [requirements](#requirements) are not met, the job will
silently be skipped.

CAUTION: **Caution:**
Your apps should *not* be manipulated outside of Helm (using Kubernetes directly.)
This can cause confusion with Helm not detecting the change, and subsequent
deploys with Auto DevOps can undo your changes. Also, if you change something
and want to undo it by deploying again, Helm may not detect that anything changed
in the first place, and thus not realize that it needs to re-apply the old config.

After a branch or merge request is merged into the project's default branch (usually
`master`), Auto Deploy deploys the application to a `production` environment in
the Kubernetes cluster, with a namespace based on the project name and unique
project ID, for example `project-4321`.

Auto Deploy doesn't include deployments to staging or canary by default, but the
[Auto DevOps template] contains job definitions for these tasks if you want to
enable them.

You can make use of [environment variables](#helm-chart-variables) to automatically
scale your pod replicas.

It's important to note that when a project is deployed to a Kubernetes cluster,
it relies on a Docker image that has been pushed to the
[GitLab Container Registry](../../user/project/container_registry.md). Kubernetes
fetches this image and uses it to run the application. If the project is public,
the image can be accessed by Kubernetes without any authentication, allowing us
to have deployments more usable. If the project is private/internal, the
Registry requires credentials to pull the image. Currently, this is addressed
by providing `CI_JOB_TOKEN` as the password that can be used, but this token will
no longer be valid as soon as the deployment job finishes. This means that
Kubernetes can run the application, but in case it should be restarted or
executed somewhere else, it cannot be accessed again.

> [Introduced][ce-19507] in GitLab 11.0.

For internal and private projects a [GitLab Deploy Token](../../user/project/deploy_tokens/index.md###gitlab-deploy-token)
will be automatically created, when Auto DevOps is enabled and the Auto DevOps settings are saved. This Deploy Token
can be used for permanent access to the registry.

Note: **Note**
When the GitLab Deploy Token has been manually revoked, it won't be automatically created.

### Auto Monitoring

NOTE: **Note:**
Check the [requirements](#requirements) for Auto Monitoring to make this stage
work.

Once your application is deployed, Auto Monitoring makes it possible to monitor
your application's server and response metrics right out of the box. Auto
Monitoring uses [Prometheus](../../user/project/integrations/prometheus.md) to
get system metrics such as CPU and memory usage directly from
[Kubernetes](../../user/project/integrations/prometheus_library/kubernetes.md),
and response metrics such as HTTP error rates, latency, and throughput from the
[NGINX server](../../user/project/integrations/prometheus_library/nginx_ingress.md).

The metrics include:

- **Response Metrics:** latency, throughput, error rate
- **System Metrics:** CPU utilization, memory utilization

If GitLab has been deployed using the [GitLab Omnibus Helm Chart], no
configuration is required.

If you have installed GitLab using a different method, you need to:

1. [Deploy Prometheus](../../user/project/integrations/prometheus.md#configuring-your-own-prometheus-server-within-kubernetes) into your Kubernetes cluster
1. If you would like response metrics, ensure you are running at least version
   0.9.0 of NGINX Ingress and
   [enable Prometheus metrics](https://github.com/kubernetes/ingress-nginx/blob/master/docs/examples/customization/custom-vts-metrics-prometheus/nginx-vts-metrics-conf.yaml).
1. Finally, [annotate](https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/)
   the NGINX Ingress deployment to be scraped by Prometheus using
   `prometheus.io/scrape: "true"` and `prometheus.io/port: "10254"`.

To view the metrics, open the
[Monitoring dashboard for a deployed environment](../../ci/environments.md#monitoring-environments).

![Auto Metrics](img/auto_monitoring.png)

## Customizing

While Auto DevOps provides great defaults to get you started, you can customize
almost everything to fit your needs; from custom [buildpacks](#custom-buildpacks),
to [`Dockerfile`s](#custom-dockerfile), [Helm charts](#custom-helm-chart), or
even copying the complete [CI/CD configuration](#customizing-gitlab-ci-yml)
into your project to enable staging and canary deployments, and more.

### Custom buildpacks

If the automatic buildpack detection fails for your project, or if you want to
use a custom buildpack, you can override the buildpack(s) using a project variable
or a `.buildpacks` file in your project:

- **Project variable** - Create a project variable `BUILDPACK_URL` with the URL
  of the buildpack to use.
- **`.buildpacks` file** - Add a file in your project's repo called  `.buildpacks`
  and add the URL of the buildpack to use on a line in the file. If you want to
  use multiple buildpacks, you can enter them in, one on each line.

CAUTION: **Caution:**
Using multiple buildpacks isn't yet supported by Auto DevOps.

### Custom `Dockerfile`

If your project has a `Dockerfile` in the root of the project repo, Auto DevOps
will build a Docker image based on the Dockerfile rather than using buildpacks.
This can be much faster and result in smaller images, especially if your
Dockerfile is based on [Alpine](https://hub.docker.com/_/alpine/).

### Custom Helm Chart

Auto DevOps uses [Helm](https://helm.sh/) to deploy your application to Kubernetes.
You can override the Helm chart used by bundling up a chart into your project
repo or by specifying a project variable:

- **Bundled chart** - If your project has a `./chart` directory with a `Chart.yaml`
  file in it, Auto DevOps will detect the chart and use it instead of the [default
  one](https://gitlab.com/charts/auto-deploy-app).
  This can be a great way to control exactly how your application is deployed.
- **Project variable** - Create a [project variable](../../ci/variables/README.md#secret-variables)
  `AUTO_DEVOPS_CHART` with the URL of a custom chart to use.

### Customizing `.gitlab-ci.yml`

If you want to modify the CI/CD pipeline used by Auto DevOps, you can copy the
[Auto DevOps template] into your project's repo and edit as you see fit.

Assuming that your project is new or it doesn't have a `.gitlab-ci.yml` file
present:

1. From your project home page, either click on the "Set up CI/CD" button, or click
   on the plus button and (`+`), then "New file"
1. Pick `.gitlab-ci.yml` as the template type
1. Select "Auto-DevOps" from the template dropdown
1. Edit the template or add any jobs needed
1. Give an appropriate commit message and hit "Commit changes"

TIP: **Tip:** The Auto DevOps template includes useful comments to help you
customize it. For example, if you want deployments to go to a staging environment
instead of directly to a production one, you can enable the `staging` job by
renaming `.staging` to `staging`. Then make sure to uncomment the `when` key of
the `production` job to turn it into a manual action instead of deploying
automatically.

### PostgreSQL database support

In order to support applications that require a database,
[PostgreSQL][postgresql] is provisioned by default. The credentials to access
the database are preconfigured, but can be customized by setting the associated
[variables](#environment-variables). These credentials can be used for defining a
`DATABASE_URL` of the format:

```yaml
postgres://user:password@postgres-host:postgres-port/postgres-database
```

### Environment variables

The following variables can be used for setting up the Auto DevOps domain,
providing a custom Helm chart, or scaling your application. PostgreSQL can
also be customized, and you can easily use a [custom buildpack](#custom-buildpacks).

| **Variable**                 | **Description**                                                                                |
| ------------                 | ---------------                                                                                |
| `AUTO_DEVOPS_DOMAIN`         | The [Auto DevOps domain](#auto-devops-domain); by default set automatically by the [Auto DevOps setting](#enabling-auto-devops).                                                                                |
| `AUTO_DEVOPS_CHART`          | The Helm Chart used to deploy your apps; defaults to the one [provided by GitLab](https://gitlab.com/charts/auto-deploy-app).                                                             |
| `REPLICAS`                   | The number of replicas to deploy; defaults to 1.                                                                                |
| `PRODUCTION_REPLICAS`        | The number of replicas to deploy in the production environment. This takes precedence over `REPLICAS`; defaults to 1.                                                                                |
| `CANARY_REPLICAS`            | The number of canary replicas to deploy for [Canary Deployments](https://docs.gitlab.com/ee/user/project/canary_deployments.html); defaults to 1                                                                              |
| `CANARY_PRODUCTION_REPLICAS` | The number of canary replicas to deploy for [Canary Deployments](https://docs.gitlab.com/ee/user/project/canary_deployments.html) in the production environment. This takes precedence over `CANARY_REPLICAS`; defaults to 1  |
| `POSTGRES_ENABLED`           | Whether PostgreSQL is enabled; defaults to `"true"`. Set to `false` to disable the automatic deployment of PostgreSQL.                                                                                |
| `POSTGRES_USER`              | The PostgreSQL user; defaults to `user`. Set it to use a custom username.                                                                                |
| `POSTGRES_PASSWORD`          | The PostgreSQL password; defaults to `testing-password`. Set it to use a custom password.                                                                                |
| `POSTGRES_DB`                | The PostgreSQL database name; defaults to the value of [`$CI_ENVIRONMENT_SLUG`](../../ci/variables/README.md#predefined-variables-environment-variables). Set it to use a custom database name.                               |
| `BUILDPACK_URL`              | The buildpack's full URL. It can point to either Git repositories or a tarball URL. For Git repositories, it is possible to point to a specific `ref`, for example `https://github.com/heroku/heroku-buildpack-ruby.git#v142` |
| `SAST_CONFIDENCE_LEVEL`      | The minimum confidence level of security issues you want to be reported; `1` for Low, `2` for Medium, `3` for High; defaults to `3`.|
| `DEP_SCAN_DISABLE_REMOTE_CHECKS` | Whether remote Dependency Scanning checks are disabled; defaults to `"false"`. Set to `"true"` to disable checks that send data to GitLab central servers. [Read more about remote checks](https://gitlab.com/gitlab-org/security-products/dependency-scanning#remote-checks).|
| `STAGING_ENABLED`            | From GitLab 10.8, this variable can be used to define a [deploy policy for staging and production environments](#deploy-policy-for-staging-and-production-environments). |
| `CANARY_ENABLED`             | From GitLab 11.0, this variable can be used to define a [deploy policy for canary environments](#deploy-policy-for-canary-environments). |
| `INCREMENTAL_ROLLOUT_ENABLED`| From GitLab 10.8, this variable can be used to enable an [incremental rollout](#incremental-rollout-to-production) of your application for the production environment. |
| `TEST_DISABLED`              | From GitLab 11.0, this variable can be used to disable the `test` job. If the variable is present, the job will not be created. |
| `CODE_QUALITY_DISABLED`       | From GitLab 11.0, this variable can be used to disable the `codequality` job. If the variable is present, the job will not be created. |
| `SAST_DISABLED`              | From GitLab 11.0, this variable can be used to disable the `sast` job. If the variable is present, the job will not be created. |
| `DEPENDENCY_SCANNING_DISABLED` | From GitLab 11.0, this variable can be used to disable the `dependency_scanning` job. If the variable is present, the job will not be created. |
| `CONTAINER_SCANNING_DISABLED` | From GitLab 11.0, this variable can be used to disable the `sast:container` job. If the variable is present, the job will not be created. |
| `REVIEW_DISABLED`            | From GitLab 11.0, this variable can be used to disable the `review` and the manual `review:stop` job. If the variable is present, these jobs will not be created. |
| `DAST_DISABLED`              | From GitLab 11.0, this variable can be used to disable the `dast` job. If the variable is present, the job will not be created. |
| `PERFORMANCE_DISABLED`       | From GitLab 11.0, this variable can be used to disable the `performance` job. If the variable is present, the job will not be created. |

TIP: **Tip:**
Set up the replica variables using a
[project variable](../../ci/variables/README.md#secret-variables)
and scale your application by just redeploying it!

CAUTION: **Caution:**
You should *not* scale your application using Kubernetes directly. This can
cause confusion with Helm not detecting the change, and subsequent deploys with
Auto DevOps can undo your changes.

#### Advanced replica variables setup

Apart from the two replica-related variables for production mentioned above,
you can also use others for different environments.

There's a very specific mapping between Kubernetes' label named `track`,
GitLab CI/CD environment names, and the replicas environment variable.
The general rule is: `TRACK_ENV_REPLICAS`. Where:

- `TRACK`: The capitalized value of the `track`
  [Kubernetes label](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/)
  in the Helm Chart app definition. If not set, it will not be taken into account
  to the variable name.
- `ENV`: The capitalized environment name of the deploy job that is set in
  `.gitlab-ci.yml`.

That way, you can define your own `TRACK_ENV_REPLICAS` variables with which
you will be able to scale the pod's replicas easily.

In the example below, the environment's name is `qa` and it deploys the track
`foo` which would result in looking for the `FOO_QA_REPLICAS` environment
variable:

```yaml
QA testing:
  stage: deploy
  environment:
    name: qa
  script:
  - deploy foo
```

The track `foo` being referenced would also need to be defined in the
application's Helm chart, like:

```yaml
replicaCount: 1
image:
  repository: gitlab.example.com/group/project
  tag: stable
  pullPolicy: Always
  secrets:
    - name: gitlab-registry
application:
  track: foo
  tier: web
service:
  enabled: true
  name: web
  type: ClusterIP
  url: http://my.host.com/
  externalPort: 5000
  internalPort: 5000
```

#### Deploy policy for staging and production environments

> [Introduced](https://gitlab.com/gitlab-org/gitlab-ci-yml/merge_requests/160)
in GitLab 10.8.

TIP: **Tip:**
You can also set this inside your [project's settings](#deployment-strategy).

The normal behavior of Auto DevOps is to use Continuous Deployment, pushing
automatically to the `production` environment every time a new pipeline is run
on the default branch. However, there are cases where you might want to use a
staging environment and deploy to production manually. For this scenario, the
`STAGING_ENABLED` environment variable was introduced.

If `STAGING_ENABLED` is defined in your project (e.g., set `STAGING_ENABLED` to
`1` as a secret variable), then the application will be automatically deployed
to a `staging` environment, and a  `production_manual` job will be created for
you when you're ready to manually deploy to production.

#### Deploy policy for canary environments **[PREMIUM]**

> [Introduced](https://gitlab.com/gitlab-org/gitlab-ci-yml/merge_requests/171)
in GitLab 11.0.

A [canary environment](https://docs.gitlab.com/ee/user/project/canary_deployments.html) can be used
before any changes are deployed to production.

If `CANARY_ENABLED` is defined in your project (e.g., set `CANARY_ENABLED` to
`1` as a secret variable) then two manual jobs will be created:

- `canary` which will deploy the application to the canary environment
- `production_manual` which is to be used by you when you're ready to manually
  deploy to production.

#### Incremental rollout to production **[PREMIUM]**

> [Introduced](https://gitlab.com/gitlab-org/gitlab-ee/issues/5415) in GitLab 10.8.

TIP: **Tip:**
You can also set this inside your [project's settings](#deployment-strategy).

When you have a new version of your app to deploy in production, you may want
to use an incremental rollout to replace just a few pods with the latest code.
This will allow you to first check how the app is behaving, and later manually
increasing the rollout up to 100%.

If `INCREMENTAL_ROLLOUT_ENABLED` is defined in your project (e.g., set
`INCREMENTAL_ROLLOUT_ENABLED` to `1` as a secret variable), then instead of the
standard `production` job, 4 different
[manual jobs](../../ci/pipelines.md#manual-actions-from-the-pipeline-graph)
will be created:

1. `rollout 10%`
1. `rollout 25%`
1. `rollout 50%`
1. `rollout 100%`

The percentage is based on the `REPLICAS` variable and defines the number of
pods you want to have for your deployment. If you say `10`, and then you run
the `10%` rollout job, there will be `1` new pod + `9` old ones.

To start a job, click on the play icon next to the job's name. You are not
required to go from `10%` to `100%`, you can jump to whatever job you want.
You can also scale down by running a lower percentage job, just before hitting
`100%`. Once you get to `100%`, you cannot scale down, and you'd have to roll
back by redeploying the old version using the
[rollback button](../../ci/environments.md#rolling-back-changes) in the
environment page.

Below, you can see how the pipeline will look if the rollout or staging
variables are defined.

- **Without `INCREMENTAL_ROLLOUT_ENABLED` and without `STAGING_ENABLED`**

    ![Staging and rollout disabled](img/rollout_staging_disabled.png)

- **Without `INCREMENTAL_ROLLOUT_ENABLED` and with `STAGING_ENABLED`**

    ![Staging enabled](img/staging_enabled.png)

- **With `INCREMENTAL_ROLLOUT_ENABLED` and without `STAGING_ENABLED`**

    ![Rollout enabled](img/rollout_enabled.png)

- **With `INCREMENTAL_ROLLOUT_ENABLED` and with `STAGING_ENABLED`**

    ![Rollout and staging enabled](img/rollout_staging_enabled.png)

## Currently supported languages

NOTE: **Note:**
Not all buildpacks support Auto Test yet, as it's a relatively new
enhancement. All of Heroku's [officially supported
languages](https://devcenter.heroku.com/articles/heroku-ci#currently-supported-languages)
support it, and some third-party buildpacks as well e.g., Go, Node, Java, PHP,
Python, Ruby, Gradle, Scala, and Elixir all support Auto Test, but notably the
multi-buildpack does not.

As of GitLab 10.0, the supported buildpacks are:

```
- heroku-buildpack-multi     v1.0.0
- heroku-buildpack-ruby      v168
- heroku-buildpack-nodejs    v99
- heroku-buildpack-clojure   v77
- heroku-buildpack-python    v99
- heroku-buildpack-java      v53
- heroku-buildpack-gradle    v23
- heroku-buildpack-scala     v78
- heroku-buildpack-play      v26
- heroku-buildpack-php       v122
- heroku-buildpack-go        v72
- heroku-buildpack-erlang    fa17af9
- buildpack-nginx            v8
```

## Limitations

The following restrictions apply.

### Private project support

CAUTION: **Caution:** Private project support in Auto DevOps is experimental.

When a project has been marked as private, GitLab's [Container
Registry][container-registry] requires authentication when downloading
containers. Auto DevOps will automatically provide the required authentication
information to Kubernetes, allowing temporary access to the registry.
Authentication credentials will be valid while the pipeline is running, allowing
for a successful initial deployment.

After the pipeline completes, Kubernetes will no longer be able to access the
Container Registry. **Restarting a pod, scaling a service, or other actions which
require on-going access to the registry may fail**. On-going secure access is
planned for a subsequent release.

## Troubleshooting

- Auto Build and Auto Test may fail in detecting your language/framework. There
  may be no buildpack for your application, or your application may be missing the
  key files the buildpack is looking for. For example, for ruby apps, you must
  have a `Gemfile` to be properly detected, even though it is possible to write a
  Ruby app without a `Gemfile`. Try specifying a [custom
  buildpack](#custom-buildpacks).
- Auto Test may fail because of a mismatch between testing frameworks. In this
  case, you may need to customize your `.gitlab-ci.yml` with your test commands.

### Disable the banner instance wide

If an administrator would like to disable the banners on an instance level, this
feature can be disabled either through the console:

```sh
sudo gitlab-rails console
```

Then run:

```ruby
Feature.get(:auto_devops_banner_disabled).enable
```

Or through the HTTP API with an admin access token:

```sh
curl --data "value=true" --header "PRIVATE-TOKEN: personal_access_token" https://gitlab.example.com/api/v4/features/auto_devops_banner_disabled
```

[ce-37115]: https://gitlab.com/gitlab-org/gitlab-ce/issues/37115
[kubernetes-clusters]: ../../user/project/clusters/index.md
[docker-in-docker]: ../../docker/using_docker_build.md#use-docker-in-docker-executor
[review-app]: ../../ci/review_apps/index.md
[container-registry]: ../../user/project/container_registry.md
[postgresql]: https://www.postgresql.org/
[Auto DevOps template]: https://gitlab.com/gitlab-org/gitlab-ci-yml/blob/master/Auto-DevOps.gitlab-ci.yml
[GitLab Omnibus Helm Chart]: ../../install/kubernetes/gitlab_omnibus.md
[ee]: https://about.gitlab.com/pricing/
[ce-19507]: https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/19507


text:
<?php

namespace cleverdev\BannerBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class BannerBundle extends Bundle
{
}

redpajama_set_name: RedPajamaGithub


text:
@interface ATZShell : NSObject

+ (BOOL)areCommandLineToolsAvailable;

- (void)executeCommand:(NSString *)command withArguments:(NSArray *)arguments
            completion:(void(^)(NSString *output, NSError *error))completion;

- (void)executeCommand:(NSString *)command withArguments:(NSArray *)arguments inWorkingDirectory:(NSString *)path
            completion:(void(^)(NSString *output, NSError *error))completion;

@end


text:
use ESL::Dispatch;
use Data::Dumper;
my $daemon = init ESL::Dispatch({});

$| = 1;

sub worker {
  my $self = shift;
  print "I'm a worker\n";
}

sub heartbeat {
  my $self = shift;
  my $event = shift;
  print Dumper $event;
}

sub channel_hangup {
  my $self = shift;
  my $event = shift;
  print Dumper $event;
  print "DO SQL GOODIES HERE!\n";
}

$0 = "ESL::Dispatch rocks!";

$daemon->set_worker(\&worker, 2000);
$daemon->set_callback("heartbeat", \&heartbeat);
$daemon->set_callback("channel_hangup", \&channel_hangup);

$daemon->run;


text:
import getCategories from './getCategories'
import urlSlug from './urlSlug'

function getCategoryBySlug(slug) {
  const categories = getCategories()
  let mapping = {}
  for (let i = 0; i < categories.length; i++) {
    const currentCategory = categories[i]
    mapping[urlSlug(currentCategory)] = currentCategory
  }
  return mapping[slug]
}

export default getCategoryBySlug


text:
module ExpressionRelationshipsHelper
end


text:
from os.path import abspath, basename, dirname, join
import sys
from fabric.api import env

#
# Project-specific settings, alter as needed
#
env.project_name = basename(dirname(__file__))
env.django = False

#
# Add paths
#
def add_paths(*args):
    """Make paths are in sys.path."""
    for p in args:
        if p not in sys.path:
            sys.path.append(p)

project_path = dirname(abspath(__file__))
repos_path = dirname(project_path)

add_paths(project_path, repos_path)

#
# Import from fablib
#
from fablib import *


text:
<?php

namespace Embajada\EventosBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CategoriaType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nombre')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Embajada\EventosBundle\Entity\Categoria'
        ));
    }

    public function getName()
    {
        return 'embajada_eventosbundle_categoriatype';
    }
}


text:
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import './Parallax.scss';

export default class Parallax extends Component {
  static propTypes = {
    backLayerClassName: PropTypes.string,
    className: PropTypes.string,
    backLayer: PropTypes.node,
    children: PropTypes.node,
  }

  render() {
    const backLayerClassName = classnames([
      'Parallax-layer',
      'Parallax-layer--back',
      this.props.backLayerClassName,
    ]);

    const baseLayerClassName = classnames([
      'Parallax-layer',
      'Parallax-layer--base',
      this.props.className,
    ]);

    return (

          {this.props.backLayer}

          {this.props.children}

    );
  }
}


text:
package client

import (
	"context"
	"fmt"

	"github.com/openconfig/gnmi/ctree"
)

// Client adds a caching layer on top of a simple query client.
//
// It works similarly to BaseClient and adds the Leaves method to return
// current tree state.
type CacheClient struct {
	*BaseClient
	*ctree.Tree
	synced        chan struct{}
	clientHandler NotificationHandler
}

var _ Client = &CacheClient{}

// New returns an initialized caching client.
func New() *CacheClient {
	c := &CacheClient{
		BaseClient: &BaseClient{},
		Tree:       &ctree.Tree{},
		synced:     make(chan struct{}),
	}
	return c
}

// Subscribe implements the Client interface.
func (c *CacheClient) Subscribe(ctx context.Context, q Query, clientType ...string) error {
	q.ProtoHandler = nil
	if q.NotificationHandler != nil {
		c.clientHandler = q.NotificationHandler
	}
	q.NotificationHandler = c.defaultHandler
	return c.BaseClient.Subscribe(ctx, q, clientType...)
}

// defaultHandler is passed into the client specific implementations. It will
// be called for each leaf notification generated by the client.
func (c *CacheClient) defaultHandler(n Notification) error {
	switch v := n.(type) {
	default:
		return fmt.Errorf("invalid type %#v", v)
	case Connected: // Ignore.
	case Error:
		return fmt.Errorf("received error: %v", v)
	case Update:
		c.Add(v.Path, TreeVal{TS: v.TS, Val: v.Val})
	case Delete:
		c.Delete(v.Path)
	case Sync:
		select {
		default:
			close(c.synced)
		case <-c.synced:
		}
	}
	if c.clientHandler != nil {
		return c.clientHandler(n)
	}
	return nil
}

// Poll implements the Client interface.
// Poll also closes the channel returned by Synced and resets it.
func (c *CacheClient) Poll() error {
	select {
	default:
		close(c.synced)
	case <-c.synced:
	}
	return c.BaseClient.Poll()
}

// Synced will close when a sync is recieved from the query.
func (c *CacheClient) Synced() <-chan struct{} {
	return c.synced
}

// Leaves returns the current state of the received tree. It's safe to call at
// any point after New.
func (c *CacheClient) Leaves() Leaves {
	// Convert node items into Leaf (expand TreeVal leaves).
	var pvs Leaves
	c.WalkSorted(func(path []string, _ *ctree.Leaf, value interface{}) error {
		tv, ok := value.(TreeVal)
		if !ok {
			return fmt.Errorf("Invalid value in tree: %s=%#v", path, value)
		}
		pvs = append(pvs, Leaf{Path: path, Val: tv.Val, TS: tv.TS})
		return nil
	})
	return pvs
}


text:
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef FPLBASE_RENDER_STATE_H
#define FPLBASE_RENDER_STATE_H

#include "fplbase/internal/detailed_render_state.h"
#include "fplbase/viewport.h"

namespace fplbase {

/// @brief Specifies the type for the Stencil Mask.
typedef uint32_t StencilMask;

/// @brief Specifies stencil modes for the stencil test.
enum StencilMode {
  kStencilDisabled,     /**< No stencil test. */
  kStencilCompareEqual, /**< Compare the that reference written reference and
                           given reference are equal, if they are, write to the
                           pixel buffer. */
  kStencilWrite,   /**< Always pass the test and write to the pixel and stencil
                      buffers. */
  kStencilUnknown, /**< An unknown mode, usually happens when accessing the
                      graphics API directly.  */
  kStencilModeCount
};

/// @brief Specifies the blending mode used by the blend function.
enum BlendMode {
  kBlendModeOff = 0, /**< No blending is done. The alpha channel is ignored. */
  kBlendModeTest,  /**< Used to provide a function via `glAlphaFunc` instead of
                        `glBlendFunc`.*/
  kBlendModeAlpha, /**< Normal alpha channel blending. */
  kBlendModeAdd, /**< Additive blending, where the resulting color is the sum of
                      the two colors. */
  kBlendModeAddAlpha, /**< Additive blending, where the resulting color is the
                           sum of the two colors, and the image is affected
                           by the alpha. (Note: The background is not affected
                           by the image's alpha.) */
  kBlendModeMultiply, /**< Multiplicative blending, where the resulting color is
                           the product of the image color and the background
                           color. */
  kBlendModePreMultipliedAlpha, /**< Like Alpha, except the source RGB values
                                     are assumed to have already been multiplied
                                     by the alpha, so the blend function doesn't
                                     touch them. */
  kBlendModeUnknown, /**< An unknown mode, usually happens when accessing the
                        graphics API directly.  */
  kBlendModeCount    /** Used at the end of the enum as sentinel value. */
};

/// @brief Specifies the depth function used for rendering.
enum DepthFunction {
  kDepthFunctionDisabled,
  kDepthFunctionNever,
  kDepthFunctionAlways,
  kDepthFunctionLess,
  kDepthFunctionLessEqual,
  kDepthFunctionGreater,
  kDepthFunctionGreaterEqual,
  kDepthFunctionEqual,
  kDepthFunctionNotEqual,
  kDepthFunctionUnknown, /**< An unknown mode, usually happens when accessing
                            the graphics API directly.  */
  kDepthFunctionCount
};

/// @brief Specifies the which face is culled when rendering.
enum CullingMode {
  kCullingModeNone,
  kCullingModeFront,
  kCullingModeBack,
  kCullingModeFrontAndBack,
  kCullingModeUnknown /**< An unknown mode, usually happens when accessing the
                       graphics API directly.  */
};

}  // namespace fplbase

#endif  // FPLBASE_RENDER_STATE_H


text:
module AdminData
  class ApplicationController < ::ApplicationController

    layout 'admin_data'

    before_filter :ensure_is_allowed_to_view

    helper_method :is_allowed_to_update?

    before_filter :build_klasses,
      :build_drop_down_for_klasses,
      :check_page_parameter,
      :prepare_drop_down_klasses

    attr_reader :klass

    protected

    self.config.asset_path = lambda {|asset| "/admin_data/public#{asset}"}

    private

    def prepare_drop_down_klasses
      k = params[:klass] || ''
      @drop_down_url = "http://#{request.host_with_port}/admin_data/quick_search/#{CGI.escape(k)}"
    end

    def ensure_is_allowed_to_view
      render :text => 'not authorized' unless is_allowed_to_view?
    end

    def ensure_is_allowed_to_update
      render :text => 'not authorized' unless is_allowed_to_update?
    end

    def get_class_from_params
      begin
        @klass = Util.camelize_constantize(params[:klass])
      rescue TypeError => e # in case no params[:klass] is supplied
        render :text => 'wrong params[:klass] was supplied' and return
      rescue NameError # in case wrong params[:klass] is supplied
        render :text => 'wrong params[:klass] was supplied' and return
      end
    end

    def build_klasses
      @klasses = _build_all_klasses
    end

    def _build_all_klasses
      if defined? $admin_data_all_klasses
        return $admin_data_all_klasses
      else
        model_dir = File.join(Rails.root, 'app', 'models')
        model_names = Dir.chdir(model_dir) { Dir["*.rb"] }
        klasses = get_klass_names(model_names)
        $admin_data_all_klasses = remove_klasses_without_table(klasses).sort_by {|r| r.name.underscore}
      end
    end

    def remove_klasses_without_table(klasses)
      klasses.select { |k| k.ancestors.include?(ActiveRecord::Base) && k.connection.table_exists?(k.table_name) }
    end

    def get_klass_names(model_names)
      model_names.inject([]) do |output, model_name|
        klass_name = model_name.sub(/\.rb$/,'').camelize
        begin
          output << Util.constantize_klass(klass_name)
        rescue Exception => e
          Rails.logger.debug e.message
        end
        output
      end
    end

    def build_drop_down_for_klasses
      @drop_down_for_klasses = ModelFinder.models.inject([]) do |result, klass|
        result << [klass, search_url(:klass => klass)]
      end
    end

    def check_page_parameter
      # Got hoptoad error because of url like
      # http://localhost:3000/admin_data/User/advance_search?page=http://201.134.249.164/intranet/on.txt?
      if params[:page].blank? || (params[:page] =~ /\A\d+\z/)
        # proceed
      else
        render :text => 'Invalid params[:page]', :status => :unprocessable_entity
      end
    end

    def per_page
      AdminData.config.number_of_records_per_page
    end

    def is_allowed_to_view?
      AdminData.config.is_allowed_to_view.call(self)
    end

    def is_allowed_to_update?
      AdminData.config.is_allowed_to_update.call(self)
    end

  end
end


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Answers;
use AppBundle\Entity\Users;
use AppBundle\Form\UserQuestionsType;
use AppBundle\Form\UsersType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Serializer\Encoder\JsonEncode;

class ApiController extends Controller
{
    const USER_ID = 'user_id';
    const TIMER_SESSION = 'time';

    /**
     * @Route("/api/stream", name="stream")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function streamAction()
    {
        return $this->render('AppBundle:api:stream.xml.twig');
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Interfaced;
using Protobuf.Interface;

#pragma warning disable 1998

namespace Protobuf.Program
{
    public class PedanticActor : InterfacedActor, IPedantic
    {
        async Task IPedantic.TestCall()
        {
            Console.WriteLine("JustCall");
        }

        async Task<int?> IPedantic.TestOptional(int? value)
        {
            return value;
        }

        async Task<Tuple<int, string>> IPedantic.TestTuple(Tuple<int, string> value)
        {
            return value;
        }

        async Task<int[]> IPedantic.TestParams(params int[] values)
        {
            return values;
        }

        async Task<string> IPedantic.TestPassClass(TestParam param)
        {
            return string.Format("{0}:{1}", param.Name, param.Price);
        }

        async Task<TestResult> IPedantic.TestReturnClass(int value, int offset)
        {
            return new TestResult { Value = value, Offset = offset };
        }
    }
}

#pragma  warning restore 1998


text:
namespace BWSAL
{
  ReservedMap* ReservedMap::s_reservedMap = NULL;

  ReservedMap* ReservedMap::create()
  {
    if ( s_reservedMap )
    {
      return s_reservedMap;
    }
    s_reservedMap = new ReservedMap();
    return s_reservedMap;
  }

  ReservedMap* ReservedMap::getInstance()
  {
    return s_reservedMap;
  }

  void ReservedMap::destroy()
  {
    if ( s_reservedMap )
    {
      delete s_reservedMap;
    }
  }

  ReservedMap::ReservedMap()
  {
    m_reservedMap.resize( BWAPI::Broodwar->mapWidth(), BWAPI::Broodwar->mapHeight() );
    m_reservedMap.setTo( BWAPI::UnitTypes::None );
  }

  ReservedMap::~ReservedMap()
  {
    s_reservedMap = NULL;
  }

  void ReservedMap::reserveTiles( BWAPI::TilePosition position, BWAPI::UnitType type, int width, int height )
  {
    for ( int x = position.x; x < position.x + width && x < (int)m_reservedMap.getWidth(); x++ )
    {
      for ( int y = position.y; y < position.y + height && y < (int)m_reservedMap.getHeight(); y++ )
      {
        m_reservedMap[x][y] = type;
      }
    }
  }

  void ReservedMap::freeTiles( BWAPI::TilePosition position, int width, int height )
  {
    for ( int x = position.x; x < position.x + width && x < (int)m_reservedMap.getWidth(); x++ )
    {
      for ( int y = position.y; y < position.y + height && y < (int)m_reservedMap.getHeight(); y++ )
      {
        m_reservedMap[x][y] = BWAPI::UnitTypes::None;
      }
    }
  }

  bool ReservedMap::isReserved( int x, int y ) const
  {
    return m_reservedMap[x][y] != BWAPI::UnitTypes::None;
  }

  bool ReservedMap::isReserved( BWAPI::TilePosition p ) const
  {
    return m_reservedMap[p.x][p.y] != BWAPI::UnitTypes::None;
  }

  bool ReservedMap::canBuildHere( BWAPI::Unit builder, BWAPI::TilePosition position, BWAPI::UnitType type ) const
  {
    if ( type.isAddon() )
    {
      type = type.whatBuilds().first;
    }
    // returns true if we can build this type of unit here. Takes into account reserved tiles.
	if (!BWAPI::Broodwar->canBuildHere(position, type, builder))
    {
      return false;
    }
    for ( int x = position.x; x < position.x + type.tileWidth(); x++ )
    {
      for ( int y = position.y; y < position.y + type.tileHeight(); y++ )
      {
        if ( m_reservedMap[x][y] != BWAPI::UnitTypes::None )
        {
          return false;
        }
      }
    }
    return true;
  }

  BWAPI::UnitType ReservedMap::getReservedType( int x, int y ) const
  {
    return m_reservedMap[x][y];
  }

  BWAPI::UnitType ReservedMap::getReservedType( BWAPI::TilePosition p ) const
  {
    return m_reservedMap[p.x][p.y];
  }
}


text:
The test suite is located in the `test/` directory.  All new features are
expected to have corresponding test cases with complete code coverage.  Patches
that increase test coverage are happily accepted.

Ensure that the test suite passes by executing:

```bash
$ make test
```

Coverage reports can be viewed by executing:

```bash
$ make test-cov
$ make view-cov
```


text:
package org.rdtif.zaxslackbot.slack;

import com.slack.api.methods.MethodsClient;
import com.slack.api.methods.SlackApiException;
import com.slack.api.methods.request.chat.ChatPostMessageRequest;
import com.slack.api.methods.request.chat.ChatUpdateRequest;
import com.slack.api.methods.response.chat.ChatPostMessageResponse;
import com.slack.api.methods.response.chat.ChatUpdateResponse;

import javax.inject.Inject;
import javax.inject.Provider;
import java.io.IOException;

public class SlackClient {
    private final Provider<MethodsClient> methodsClient;

    @Inject
    public SlackClient(Provider<MethodsClient> methodsClient) {
        this.methodsClient = methodsClient;
    }

    public ChatPostMessageResponse chatPostMessage(ChatPostMessageRequest request) {
        try {
            return methodsClient.get().chatPostMessage(request);
        } catch (IOException | SlackApiException exception) {
            throw new RuntimeException(exception);
        }
    }

    public ChatUpdateResponse chatUpdate(ChatUpdateRequest request) {
        try {
            return methodsClient.get().chatUpdate(request);
        } catch (IOException | SlackApiException exception) {
            throw new RuntimeException(exception);
        }
    }
}


text:
package com.facebook.stetho.urlconnection;

import com.facebook.stetho.inspector.network.DefaultResponseHandler;
import com.facebook.stetho.inspector.network.NetworkEventReporter;
import com.facebook.stetho.inspector.network.NetworkEventReporterImpl;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Individual connection flow manager that aids in communicating network events to Stetho
 * via the {@link NetworkEventReporter} API.  This class is stateful and should be instantiated
 * for each individual HTTP request.
 *

 * Be aware that there are caveats with inspection using {@link HttpURLConnection} on Android:
 *

 *
Compressed payload sizes are typically not available, even when compression was in use over
 * the wire.
 *
Redirects are by default handled internally, making it impossible to visualize them.
 * To visualize them, redirects must be handled manually by invoking
 * {@link HttpURLConnection#setFollowRedirects(boolean)}.
 *

 */
@NotThreadSafe
public class StethoURLConnectionManager {
  private static final AtomicInteger sSequenceNumberGenerator = new AtomicInteger(0);

  private final NetworkEventReporter mStethoHook = NetworkEventReporterImpl.get();
  private final int mRequestId;
  @Nullable private final String mFriendlyName;

  @Nullable private String mRequestIdString;

  private HttpURLConnection mConnection;
  @Nullable private URLConnectionInspectorRequest mInspectorRequest;

  public StethoURLConnectionManager(@Nullable String friendlyName) {
    mRequestId = sSequenceNumberGenerator.getAndIncrement();
    mFriendlyName = friendlyName;
  }

  public boolean isStethoEnabled() {
    return mStethoHook.isEnabled();
  }

  /**
   * Indicates that the {@link HttpURLConnection} instance has been configured and is about
   * to be used to initiate an actual HTTP connection.  Call this method before any of the
   * active methods such as {@link HttpURLConnection#connect()},
   * {@link HttpURLConnection#getInputStream()}, or {@link HttpURLConnection#getOutputStream()}
   *
   * @param connection Connection instance configured with a method and headers.
   * @param requestEntity Represents the request body if the request method supports it.
   */
  public void preConnect(
      HttpURLConnection connection,
      @Nullable SimpleRequestEntity requestEntity) {
    throwIfConnection();
    mConnection = connection;
    if (isStethoEnabled()) {
      mInspectorRequest = new URLConnectionInspectorRequest(
          getStethoRequestId(),
          mFriendlyName,
          connection,
          requestEntity);
      mStethoHook.requestWillBeSent(mInspectorRequest);
    }
  }

  /**
   * Indicates that the {@link HttpURLConnection} has just successfully exchanged HTTP messages
   * (request headers + body and response headers) with the server but has not yet consumed
   * the response body.
   *
   * @throws IOException May throw an exception internally due to {@link HttpURLConnection}
   *     method signatures.  The request should be considered aborted/failed if this method
   *     throws.
   */
  public void postConnect() throws IOException {
    throwIfNoConnection();
    if (isStethoEnabled()) {
      if (mInspectorRequest != null) {
        byte[] body = mInspectorRequest.body();
        if (body != null) {
          mStethoHook.dataSent(getStethoRequestId(), body.length, body.length);
        }
      }
      mStethoHook.responseHeadersReceived(
          new URLConnectionInspectorResponse(
              getStethoRequestId(),
              mConnection));
    }
  }

  /**
   * Indicates that there was a non-recoverable failure during HTTP message exchange at some
   * point between {@link #preConnect} and {@link #interpretResponseStream}.
   *
   * @param ex Relay the exception that was thrown from {@link java.net.HttpURLConnection}
   */
  public void httpExchangeFailed(IOException ex) {
    throwIfNoConnection();
    if (isStethoEnabled()) {
      mStethoHook.httpExchangeFailed(getStethoRequestId(), ex.toString());
    }
  }

  /**
   * Deliver the response stream from {@link HttpURLConnection#getInputStream()} to
   * Stetho so that it can be intercepted.  Note that compression is transparently
   * supported on modern Android systems and no special awareness is necessary for
   * gzip compression on the wire.  Unfortunately this means that it is sometimes impossible
   * to determine whether compression actually occurred and so Stetho may report inflated
   * byte counts.
   *

   * If the {@code Content-Length} header is provided by the server, this will be assumed to be
   * the raw byte count on the wire.
   *
   * @param responseStream Stream as furnished by {@link HttpURLConnection#getInputStream()}.
   *
   * @return The filtering stream which is to be read after this method is called.
   */
  public InputStream interpretResponseStream(@Nullable InputStream responseStream) {
    throwIfNoConnection();
    if (isStethoEnabled()) {
      // Note that Content-Encoding is stripped out by HttpURLConnection on modern versions of
      // Android (fun fact, it's powered by okhttp) when decompression is handled transparently.
      // When this occurs, we will not be able to report the compressed size properly.  Callers,
      // however, can disable this behaviour which will once again give us access to the raw
      // Content-Encoding so that we can handle it properly.
      responseStream = mStethoHook.interpretResponseStream(
          getStethoRequestId(),
          mConnection.getHeaderField("Content-Type"),
          mConnection.getHeaderField("Content-Encoding"),
          responseStream,
          new DefaultResponseHandler(mStethoHook, getStethoRequestId()));
    }
    return responseStream;
  }

  private void throwIfNoConnection() {
    if (mConnection == null) {
      throw new IllegalStateException("Must call preConnect");
    }
  }

  private void throwIfConnection() {
    if (mConnection != null) {
      throw new IllegalStateException("Must not call preConnect twice");
    }
  }

  /**
   * Convenience method to access the lower level {@link NetworkEventReporter} API.
   */
  public NetworkEventReporter getStethoHook() {
    return mStethoHook;
  }

  /**
   * Low level method to access this request's unique identifier according to
   * {@link NetworkEventReporter}.  Most callers won't need this.
   */
  @Nonnull
  public String getStethoRequestId() {
    if (mRequestIdString == null) {
      mRequestIdString = String.valueOf(mRequestId);
    }
    return mRequestIdString;
  }
}


text:
package com.navercorp.pinpoint.batch.alarm.collector;

import com.navercorp.pinpoint.web.alarm.DataCollectorCategory;
import com.navercorp.pinpoint.web.applicationmap.histogram.TimeHistogram;
import com.navercorp.pinpoint.web.dao.MapResponseDao;
import com.navercorp.pinpoint.web.vo.Application;
import com.navercorp.pinpoint.common.server.util.time.Range;
import com.navercorp.pinpoint.web.vo.ResponseTime;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author minwoo.jung
 */
public class ResponseTimeDataCollector extends DataCollector {

    private final Application application;
    private final MapResponseDao responseDao;
    private final long timeSlotEndTime;
    private final long slotInterval;
    private final AtomicBoolean init =new AtomicBoolean(false); // need to consider a race condition when checkers start simultaneously.

    private long slowCount = 0;
    private long errorCount = 0;
    private long totalCount = 0;
    private long slowRate = 0;
    private long errorRate = 0;

    public ResponseTimeDataCollector(DataCollectorCategory category, Application application, MapResponseDao responseDAO, long timeSlotEndTime, long slotInterval) {
        super(category);
        this.application = application;
        this.responseDao = responseDAO;
        this.timeSlotEndTime = timeSlotEndTime;
        this.slotInterval = slotInterval;
    }

    @Override
    public void collect() {
        if (init.get()) {
            return;
        }

        Range range = Range.newUncheckedRange(timeSlotEndTime - slotInterval, timeSlotEndTime);
        List<ResponseTime> responseTimes = responseDao.selectResponseTime(application, range);

        for (ResponseTime responseTime : responseTimes) {
            sum(responseTime.getAgentResponseHistogramList());
        }

        setSlowRate();
        setErrorRate();

        init.set(true);
    }

    private void setSlowRate() {
        slowRate = calculatePercent(slowCount);
    }

    private void setErrorRate() {
        errorRate = calculatePercent(errorCount);
    }

    private long calculatePercent(long value) {
        if (totalCount == 0 || value == 0) {
            return 0;
        } else {
            return (value * 100L) / totalCount;
        }
    }

    private void sum(Collection<TimeHistogram> timeHistograms) {
        for (TimeHistogram timeHistogram : timeHistograms) {
            slowCount += timeHistogram.getSlowCount();
            slowCount += timeHistogram.getVerySlowCount();
            errorCount += timeHistogram.getTotalErrorCount();
            totalCount += timeHistogram.getTotalCount();
        }
    }

    public long getSlowCount() {
        return slowCount;
    }

    public long getErrorCount() {
        return errorCount;
    }

    public long getTotalCount() {
        return totalCount;
    }

    public long getSlowRate() {
        return slowRate;
    }

    public long getErrorRate() {
        return errorRate;
    }

}


text:
package org.tensorflow.lite.task.core.vision;

import android.graphics.Rect;

import com.google.auto.value.AutoValue;

/**
 * Options to configure the image processing pipeline, which operates before inference.
 *
 *
The Task Library Vision API performs image preprocessing on the input image over the region of
 * interest, so that it fits model requirements (e.g. upright 224x224 RGB) and populate the
 * corresponding input tensor. This is performed by (in this order):
 *
 *

 *
cropping the frame buffer to the region of interest (which, in most cases, just covers the
 *       entire input image),
 *
resizing it (with bilinear interpolation, aspect-ratio *not* preserved) to the dimensions
 *       of the model input tensor,
 *
converting it to the colorspace of the input tensor (i.e. RGB, which is the only supported
 *       colorspace for now),
 *
rotating it according to its {@link Orientation} so that inference is performed on an
 *       "upright" image.
 *

 *
 *
IMPORTANT: as a consequence of cropping occurring first, the provided region of interest is
 * expressed in the unrotated frame of reference coordinates system, i.e. in {@code [0,
 * TensorImage.getWidth()) x [0, TensorImage.getHeight())}, which are the dimensions of the
 * underlying image data before any orientation gets applied. If the region is out of these bounds,
 * the inference method, such as {@link ImageClassifier#classify}, will return error.
 */
@AutoValue
public abstract class ImageProcessingOptions {
    /**
     * Orientation type that follows EXIF specification.
     *
     *
The name of each enum value defines the position of the 0th row and the 0th column of the
     * image content. See the EXIF orientation
     * documentation for details.
     */
    public enum Orientation {
        TOP_LEFT(0),
        TOP_RIGHT(1),
        BOTTOM_RIGHT(2),
        BOTTOM_LEFT(3),
        LEFT_TOP(4),
        RIGHT_TOP(5),
        RIGHT_BOTTOM(6),
        LEFT_BOTTOM(7);

        private final int value;

        Orientation(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }
    ;

    private static final Rect defaultRoi = new Rect();
    private static final Orientation DEFAULT_ORIENTATION = Orientation.TOP_LEFT;

    public abstract Rect getRoi();

    public abstract Orientation getOrientation();

    public static Builder builder() {
        return new AutoValue_ImageProcessingOptions.Builder()
                .setRoi(defaultRoi)
                .setOrientation(DEFAULT_ORIENTATION);
    }

    /** Builder for {@link ImageProcessingOptions}. */
    @AutoValue.Builder
    public abstract static class Builder {
        /**
         * Sets the region of interest (ROI) of the image. Defaults to the entire image.
         *
         *
Cropping according to this region of interest is prepended to the pre-processing
         * operations.
         */
        public abstract Builder setRoi(Rect roi);

        /**
         * Sets the orientation of the image. Defaults to {@link Orientation#TOP_LEFT}.
         *
         *
Rotation will be applied accordingly so that inference is performed on an "upright"
         * image.
         */
        public abstract Builder setOrientation(Orientation orientation);

        abstract Rect getRoi();

        abstract ImageProcessingOptions autoBuild();

        public ImageProcessingOptions build() {
            setRoi(new Rect(getRoi())); // Make a defensive copy, since Rect is mutable.
            return autoBuild();
        }
    }
}


text:
package agent

import (
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/buildkite/agent/api"
	"github.com/buildkite/agent/logger"
	"github.com/buildkite/agent/process"
	"github.com/buildkite/agent/retry"
)

type JobRunner struct {
	// The job being run
	Job *api.Job

	// The APIClient that will be used when updating the job
	APIClient *api.Client

	// The endpoint that should be used when communicating with the API
	Endpoint string

	// The registred agent API record running this job
	Agent *api.Agent

	// The configuration of the agent from the CLI
	AgentConfiguration *AgentConfiguration

	// The interal process of the job
	process *process.Process

	// The internal header time streamer
	headerTimesStreamer *HeaderTimesStreamer

	// The internal log streamer
	logStreamer *LogStreamer

	// If the job is being cancelled
	cancelled bool

	// Used to wait on various routines that we spin up
	routineWaitGroup sync.WaitGroup
}

// Initializes the job runner
func (r JobRunner) Create() (runner *JobRunner, err error) {
	runner = &r

	// Our own APIClient using the endpoint and the agents access token
	runner.APIClient = APIClient{Endpoint: r.Endpoint, Token: r.Agent.AccessToken}.Create()

	// // Create our header times struct
	runner.headerTimesStreamer = &HeaderTimesStreamer{UploadCallback: r.onUploadHeaderTime}

	// The log streamer that will take the output chunks, and send them to
	// the Buildkite Agent API
	runner.logStreamer = LogStreamer{MaxChunkSizeBytes: r.Job.ChunksMaxSizeBytes, Callback: r.onUploadChunk}.New()

	// The process that will run the bootstrap script
	runner.process = &process.Process{
		Script:        r.AgentConfiguration.BootstrapScript,
		Env:           r.createEnvironment(),
		PTY:           r.AgentConfiguration.RunInPty,
		StartCallback: r.onProcessStartCallback,
		LineCallback:  runner.headerTimesStreamer.Scan,
	}

	return
}

// Runs the job
func (r *JobRunner) Run() error {
	logger.Info("Starting job %s", r.Job.ID)

	// Start the build in the Buildkite Agent API. This is the first thing
	// we do so if it fails, we don't have to worry about cleaning things
	// up like started log streamer workers, etc.
	if err := r.startJob(time.Now()); err != nil {
		return err
	}

	// Start the header time streamer
	if err := r.headerTimesStreamer.Start(); err != nil {
		return err
	}

	// Start the log streamer
	if err := r.logStreamer.Start(); err != nil {
		return err
	}

	// Start the process. This will block until it finishes.
	if err := r.process.Start(); err != nil {
		// Send the error as output
		r.logStreamer.Process(fmt.Sprintf("%s", err))
	} else {
		// Add the final output to the streamer
		r.logStreamer.Process(r.process.Output())
	}

	// Store the finished at time
	finishedAt := time.Now()

	// Stop the header time streamer. This will block until all the chunks
	// have been uploaded
	r.headerTimesStreamer.Stop()

	// Stop the log streamer. This will block until all the chunks have
	// been uploaded
	r.logStreamer.Stop()

	// Warn about failed chunks
	if r.logStreamer.ChunksFailedCount > 0 {
		logger.Warn("%d chunks failed to upload for this job", r.logStreamer.ChunksFailedCount)
	}

	// Finish the build in the Buildkite Agent API
	r.finishJob(finishedAt, r.process.ExitStatus, int(r.logStreamer.ChunksFailedCount))

	// Wait for the routines that we spun up to finish
	logger.Debug("[JobRunner] Waiting for all other routines to finish")
	r.routineWaitGroup.Wait()

	logger.Info("Finished job %s", r.Job.ID)

	return nil
}

func (r *JobRunner) Kill() error {
	if !r.cancelled {
		logger.Info("Canceling job %s", r.Job.ID)
		r.cancelled = true

		if r.process != nil {
			r.process.Kill()
		} else {
			logger.Error("No process to kill")
		}
	}

	return nil
}

// Creates the environment variables that will be used in the process
func (r *JobRunner) createEnvironment() []string {
	// Create a clone of our jobs environment. We'll then set the
	// environment variables provided by the agent, which will override any
	// sent by Buildkite. The variables below should always take
	// precedence.
	env := make(map[string]string)
	for key, value := range r.Job.Env {
		env[key] = value
	}

	// Add agent environment variables
	env["BUILDKITE_AGENT_ENDPOINT"] = r.Endpoint
	env["BUILDKITE_AGENT_ACCESS_TOKEN"] = r.Agent.AccessToken
	env["BUILDKITE_AGENT_DEBUG"] = fmt.Sprintf("%t", logger.GetLevel() == logger.DEBUG)
	env["BUILDKITE_AGENT_PID"] = fmt.Sprintf("%d", os.Getpid())

	// We know the BUILDKITE_BIN_PATH dir, because it's the path to the
	// currently running file (there is only 1 binary)
	dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	env["BUILDKITE_BIN_PATH"] = dir

	// Add misc options
	env["BUILDKITE_BUILD_PATH"] = r.AgentConfiguration.BuildPath
	env["BUILDKITE_HOOKS_PATH"] = r.AgentConfiguration.HooksPath
	env["BUILDKITE_PLUGINS_PATH"] = r.AgentConfiguration.PluginsPath
	env["BUILDKITE_SSH_FINGERPRINT_VERIFICATION"] = fmt.Sprintf("%t", r.AgentConfiguration.SSHFingerprintVerification)
	env["BUILDKITE_COMMAND_EVAL"] = fmt.Sprintf("%t", r.AgentConfiguration.CommandEval)

	// Convert the env map into a slice (which is what the script gear
	// needs)
	envSlice := []string{}
	for key, value := range env {
		envSlice = append(envSlice, fmt.Sprintf("%s=%s", key, value))
	}

	return envSlice
}

// Starts the job in the Buildkite Agent API. We'll retry on connection-related
// issues, but if a connection succeeds and we get an error response back from
// Buildkite, we won't bother retrying. For example, a "no such host" will
// retry, but a 422 from Buildkite won't.
func (r *JobRunner) startJob(startedAt time.Time) error {
	r.Job.StartedAt = startedAt.UTC().Format(time.RFC3339Nano)

	return retry.Do(func(s *retry.Stats) error {
		_, err := r.APIClient.Jobs.Start(r.Job)

		if err != nil {
			if api.IsRetryableError(err) {
				logger.Warn("%s (%s)", err, s)
			} else {
				logger.Warn("Buildkite rejected the call to start the job (%s)", err)
				s.Break()
			}
		}

		return err
	}, &retry.Config{Maximum: 30, Interval: 1 * time.Second})
}

// Finishes the job in the Buildkite Agent API. This call will keep on retrying
// forever until it finally gets a successfull response from the API.
func (r *JobRunner) finishJob(finishedAt time.Time, exitStatus string, failedChunkCount int) error {
	r.Job.FinishedAt = finishedAt.UTC().Format(time.RFC3339Nano)
	r.Job.ExitStatus = exitStatus
	r.Job.ChunksFailedCount = failedChunkCount

	return retry.Do(func(s *retry.Stats) error {
		response, err := r.APIClient.Jobs.Finish(r.Job)
		if err != nil {
			// If the API returns with a 422, that means that we
			// succesfully tried to finish the job, but Buildkite
			// rejected the finish for some reason. This can
			// sometimes mean that Buildkite has cancelled the job
			// before we get a chance to send the final API call
			// (maybe this agent took too long to kill the
			// process). In that case, we don't want to keep trying
			// to finish the job forever so we'll just bail out and
			// go find some more work to do.
			if response != nil && response.StatusCode == 422 {
				logger.Warn("Buildkite rejected the call to finish the job (%s)", err)
				s.Break()
			} else {
				logger.Warn("%s (%s)", err, s)
			}
		}

		return err
	}, &retry.Config{Forever: true, Interval: 1 * time.Second})
}

func (r *JobRunner) onProcessStartCallback() {
	// Since we're spinning up 2 routines here, we might as well add them
	// to the routine wait group here.
	r.routineWaitGroup.Add(2)

	// Start a routine that will grab the output every few seconds and send
	// it back to Buildkite
	go func() {
		for r.process.IsRunning() {
			// Send the output of the process to the log streamer
			// for processing
			r.logStreamer.Process(r.process.Output())

			// Check the output in another second
			time.Sleep(1 * time.Second)
		}

		// Mark this routine as done in the wait group
		r.routineWaitGroup.Done()

		logger.Debug("[JobRunner] Routine that processes the log has finished")
	}()

	// Start a routine that will constantly ping Buildkite to see if the
	// job has been canceled
	go func() {
		for r.process.IsRunning() {
			// Re-get the job and check it's status to see if it's been
			// cancelled
			jobState, _, err := r.APIClient.Jobs.GetState(r.Job.ID)
			if err != nil {
				// We don't really care if it fails, we'll just
				// try again in a second anyway
				logger.Warn("Problem with getting job state %s (%s)", r.Job.ID, err)
			} else if jobState.State == "canceling" || jobState.State == "canceled" {
				r.Kill()
			}

			// Check for cancellations every few seconds
			time.Sleep(3 * time.Second)
		}

		// Mark this routine as done in the wait group
		r.routineWaitGroup.Done()

		logger.Debug("[JobRunner] Routine that refreshes the job has finished")
	}()
}

func (r *JobRunner) onUploadHeaderTime(cursor int, total int, times map[string]string) {
	retry.Do(func(s *retry.Stats) error {
		_, err := r.APIClient.HeaderTimes.Save(r.Job.ID, &api.HeaderTimes{Times: times})
		if err != nil {
			logger.Warn("%s (%s)", err, s)
		}

		return err
	}, &retry.Config{Maximum: 10, Interval: 1 * time.Second})
}

// Call when a chunk is ready for upload. It retry the chunk upload with an
// interval before giving up.
func (r *JobRunner) onUploadChunk(chunk *LogStreamerChunk) error {
	return retry.Do(func(s *retry.Stats) error {
		_, err := r.APIClient.Chunks.Upload(r.Job.ID, &api.Chunk{
			Data:     chunk.Data,
			Sequence: chunk.Order,
		})
		if err != nil {
			logger.Warn("%s (%s)", err, s)
		}

		return err
	}, &retry.Config{Maximum: 10, Interval: 1 * time.Second})
}


text:
sfepy.applications.pde_solver_app module
========================================

.. automodule:: sfepy.applications.pde_solver_app
   :members:
   :undoc-members:


text:
import activityActions from '../actions/activity-actions';

export default class OnTurnActions {
    constructor($ngRedux) {

        this.$ngRedux = $ngRedux
    }

    generatePersonActivities(){
        this.$ngRedux.dispatch(activityActions.generatePersonActivities())
    }

}


text:
/*
 * @test
 * @bug 8011805
 * @summary Update sun.tools.java class file reading/writing support to include the new constant pool entries (including invokedynamic)
 */

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import sun.tools.java.ClassDeclaration;
import sun.tools.java.Identifier;
import sun.rmi.rmic.BatchEnvironment;

public class CFCTest {

    /* Constant table */
    private static final int CONSTANT_UTF8 = 1;
    private static final int CONSTANT_INTEGER = 3;
    private static final int CONSTANT_FLOAT = 4;
    private static final int CONSTANT_LONG = 5;
    private static final int CONSTANT_DOUBLE = 6;
    private static final int CONSTANT_CLASS = 7;
    private static final int CONSTANT_STRING = 8;
    private static final int CONSTANT_FIELD = 9;
    private static final int CONSTANT_METHOD = 10;
    private static final int CONSTANT_INTERFACEMETHOD = 11;
    private static final int CONSTANT_NAMEANDTYPE = 12;
    private static final int CONSTANT_METHODHANDLE = 15;
    private static final int CONSTANT_METHODTYPE = 16;
    private static final int CONSTANT_INVOKEDYNAMIC = 18;

    String testClassName = this.getClass().getCanonicalName();
    String testClassPath = System.getProperty("test.classes", ".");

    interface I {
        int get();
    }

    public static void main(String[] args) throws Exception {
        new CFCTest().testNewConstants();
    }

    void testNewConstants() throws Exception {
        // Presence of lambda causes new constant pool constant types to be used
        I lam = () -> 88;
        if (lam.get() == 88) {
            System.out.println("Sanity passed: Lambda worked.");
        } else {
            throw new RuntimeException("Sanity failed: bad lambda execution");
        }

        // Verify that all the new constant pool constant types are present
        String clsName = testClassPath + File.separator + testClassName + ".class";
        ClassConstantChecker ccc = new ClassConstantChecker(clsName);
        ccc.checkFound(CONSTANT_METHODHANDLE);
        ccc.checkFound(CONSTANT_METHODTYPE);
        ccc.checkFound(CONSTANT_INVOKEDYNAMIC);

        // Heart of test: read the class file with the new constant types
        exerciseClassDefinition();
        System.out.println("ClassDefinition read without failure.\n");
   }

    /**
     * Failure is seen when getClassDefinition causes class read
     */
    void exerciseClassDefinition() throws Exception {
        BatchEnvironment env = new BatchEnvironment(System.out,
                BatchEnvironment.createClassPath(testClassPath, null, null),
                null);
        try {
            ClassDeclaration decl = env.getClassDeclaration(
                    Identifier.lookup(testClassName));
            decl.getClassDefinition(env);
        } finally {
            env.flushErrors();
            env.shutdown();
        }
    }

    private class ClassConstantChecker {

        private DataInputStream in;
        private boolean[] found;

        ClassConstantChecker(String clsName) throws IOException {
            in = new DataInputStream(new FileInputStream(clsName));
            found = new boolean[CONSTANT_INVOKEDYNAMIC + 20];
            try {
                check();
            } finally {
                in.close();
            }
        }

        void checkFound(int tag) throws Exception {
            if (found[tag]) {
                System.out.printf("Constant pool tag found: %d\n", tag);
            } else {
                throw new RuntimeException("Insufficient test, constant pool tag NOT found: " + tag);
            }
        }

        private void skip(int n) throws IOException {
            if (in.skipBytes(n) != n) {
                throw new EOFException();
            }
        }

        private void check() throws IOException {
            skip(8); // magic, version
            int count = in.readUnsignedShort();
            for (int i = 1; i < count; i++) {
                int j = i;
                // JVM 4.4 cp_info.tag
                int tag = in.readByte();
                found[tag] = true;
                switch (tag) {
                    case CONSTANT_UTF8:
                        in.readUTF();
                        break;
                    case CONSTANT_LONG:
                    case CONSTANT_DOUBLE:
                        skip(8);
                        break;
                    case CONSTANT_CLASS:
                    case CONSTANT_STRING:
                        skip(2);
                        break;
                    case CONSTANT_INTEGER:
                    case CONSTANT_FLOAT:
                    case CONSTANT_FIELD:
                    case CONSTANT_METHOD:
                    case CONSTANT_INTERFACEMETHOD:
                    case CONSTANT_NAMEANDTYPE:
                        skip(4);
                        break;

                    case CONSTANT_METHODHANDLE:
                        skip(3);
                        break;
                    case CONSTANT_METHODTYPE:
                        skip(2);
                        break;
                    case CONSTANT_INVOKEDYNAMIC:
                        skip(4);
                        break;

                    case 0:
                    default:
                        throw new ClassFormatError("invalid constant type: " + tag);
                }
            }
        }
    }
}


text:
using Advanced.Algorithms.Graph;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Advanced.Algorithms.Tests.Graph
{
    [TestClass]
    public class BiPartititeMatch_Tests
    {
        /// <summary>
        /// Test Max BiParitite Edges using Ford-Fukerson algorithm
        /// </summary>
        [TestMethod]
        public void MaxBiPartiteMatch_AdjacencyListGraph_Smoke_Test()
        {
            var graph = new Advanced.Algorithms.DataStructures.Graph.AdjacencyList.Graph<char>();

            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('E');

            graph.AddVertex('F');
            graph.AddVertex('G');
            graph.AddVertex('H');
            graph.AddVertex('I');

            graph.AddEdge('A', 'F');
            graph.AddEdge('B', 'F');
            graph.AddEdge('B', 'G');
            graph.AddEdge('C', 'H');
            graph.AddEdge('C', 'I');
            graph.AddEdge('D', 'G');
            graph.AddEdge('D', 'H');
            graph.AddEdge('E', 'F');
            graph.AddEdge('E', 'I');

            var algorithm = new BiPartiteMatching<char>(new BiPartiteMatchOperators());

            var result = algorithm.GetMaxBiPartiteMatching(graph);

            Assert.AreEqual(result.Count, 4);
        }

        /// <summary>
        /// Test Max BiParitite Edges using Ford-Fukerson algorithm
        /// </summary>
        [TestMethod]
        public void MaxBiPartiteMatch_AdjacencyListGraph_Accuracy_Test_1()
        {
            var graph = new Advanced.Algorithms.DataStructures.Graph.AdjacencyList.Graph<char>();

            graph.AddVertex('0');
            graph.AddVertex('1');
            graph.AddVertex('2');
            graph.AddVertex('3');

            graph.AddEdge('0', '2');
            graph.AddEdge('1', '3');

            var algorithm = new BiPartiteMatching<char>(new BiPartiteMatchOperators());

            var result = algorithm.GetMaxBiPartiteMatching(graph);

            Assert.AreEqual(result.Count, 2);
        }

        [TestMethod]
        public void MaxBiPartiteMatch_AdjacencyMatrixGraph_Smoke_Test()
        {
            var graph = new Advanced.Algorithms.DataStructures.Graph.AdjacencyMatrix.Graph<char>();

            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('E');

            graph.AddVertex('F');
            graph.AddVertex('G');
            graph.AddVertex('H');
            graph.AddVertex('I');

            graph.AddEdge('A', 'F');
            graph.AddEdge('B', 'F');
            graph.AddEdge('B', 'G');
            graph.AddEdge('C', 'H');
            graph.AddEdge('C', 'I');
            graph.AddEdge('D', 'G');
            graph.AddEdge('D', 'H');
            graph.AddEdge('E', 'F');
            graph.AddEdge('E', 'I');

            var algorithm = new BiPartiteMatching<char>(new BiPartiteMatchOperators());

            var result = algorithm.GetMaxBiPartiteMatching(graph);

            Assert.AreEqual(result.Count, 4);
        }

        /// <summary>
        /// Test Max BiParitite Edges using Ford-Fukerson algorithm
        /// </summary>
        [TestMethod]
        public void MaxBiPartiteMatch_AdjacencyMatrixGraph_Accuracy_Test_1()
        {
            var graph = new Advanced.Algorithms.DataStructures.Graph.AdjacencyMatrix.Graph<char>();

            graph.AddVertex('0');
            graph.AddVertex('1');
            graph.AddVertex('2');
            graph.AddVertex('3');

            graph.AddEdge('0', '2');
            graph.AddEdge('1', '3');

            var algorithm = new BiPartiteMatching<char>(new BiPartiteMatchOperators());

            var result = algorithm.GetMaxBiPartiteMatching(graph);

            Assert.AreEqual(result.Count, 2);
        }

        [TestMethod]
        public void MaxBiPartiteMatch_AdjacencyListGraph_Accurancy_Test()
        {
            var graph = new Advanced.Algorithms.DataStructures.Graph.AdjacencyList.Graph<char>();

            graph.AddVertex('E');
            graph.AddVertex('N');
            graph.AddVertex('J');
            graph.AddVertex('O');
            graph.AddVertex('Y');
            graph.AddVertex('Z');

            graph.AddVertex('1');
            graph.AddVertex('2');
            graph.AddVertex('3');
            graph.AddVertex('4');
            graph.AddVertex('5');
            graph.AddVertex('6');

            graph.AddEdge('E', '1');

            graph.AddEdge('N', '4');

            graph.AddEdge('J', '1');
            graph.AddEdge('J', '2');
            graph.AddEdge('J', '4');

            graph.AddEdge('O', '2');
            graph.AddEdge('O', '3');

            graph.AddEdge('Y', '3');
            graph.AddEdge('Y', '5');

            graph.AddEdge('Z', '4');
            graph.AddEdge('Z', '5');
            graph.AddEdge('Z', '6');

            var algorithm = new BiPartiteMatching<char>(new BiPartiteMatchOperators());

            var result = algorithm.GetMaxBiPartiteMatching(graph);

            Assert.AreEqual(result.Count, 6);

        }

        [TestMethod]
        public void MaxBiPartiteMatch_AdjacencyListGraph_Accurancy_Test_Fully_Connected_Bipartite_Graph()
        {
            var graph = new Advanced.Algorithms.DataStructures.Graph.AdjacencyList.Graph<char>();

            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('E');
            graph.AddVertex('F');

            graph.AddEdge('A', 'D');
            graph.AddEdge('A', 'E');
            graph.AddEdge('A', 'F');
            graph.AddEdge('B', 'D');
            graph.AddEdge('B', 'E');
            graph.AddEdge('B', 'F');
            graph.AddEdge('C', 'D');
            graph.AddEdge('C', 'E');
            graph.AddEdge('C', 'F');

            var algorithm = new BiPartiteMatching<char>(new BiPartiteMatchOperators());

            var result = algorithm.GetMaxBiPartiteMatching(graph);

            Assert.AreEqual(result.Count, 3);

        }

        /// <summary>
        /// operators for generics
        /// implemented for int type for edge weights
        /// </summary>
        public class BiPartiteMatchOperators : IBiPartiteMatchOperators<char>
        {

            private int currentIndex = 0;
            private char[] randomVertices = new char[] { '#', '*' };

            public int defaultWeight
            {
                get
                {
                    return 0;
                }
            }

            public int MaxWeight
            {
                get
                {
                    return int.MaxValue;
                }
            }

            public int AddWeights(int a, int b)
            {
                return checked(a + b);
            }

            /// <summary>
            /// we need only two random unique vertices not in given graph
            /// for Source & Sink dummy nodes
            /// </summary>
            /// <returns></returns>
            public char GetRandomUniqueVertex()
            {
                currentIndex = currentIndex == 2 ? 0 : currentIndex;
                var random = randomVertices[currentIndex];
                currentIndex++;
                return random;
            }

            public int SubstractWeights(int a, int b)
            {
                return checked(a - b);
            }
        }
    }
}