text:
Phoenix controllers act as intermediary modules. Their functions - called actions - are invoked from the router in response to HTTP requests. The actions, in turn, gather all the necessary data and perform all the necessary steps before invoking the view layer to render a template or returning a JSON response.

Phoenix controllers also build on the Plug package, and are themselves plugs. Controllers provide the functions to do almost anything we need to in an action. If we do find ourselves looking for something that Phoenix controllers don't provide, we might find what we're looking for in Plug itself. Please see the [Plug Guide](plug.html) or [Plug Documentation](https://hexdocs.pm/plug/) for more information.

A newly generated Phoenix app will have a single controller, the `PageController`, which can be found at `lib/hello_web/controllers/page_controller.ex` and looks like this.

```elixir
defmodule HelloWeb.PageController do
  use HelloWeb, :controller

  def index(conn, _params) do
    render(conn, "index.html")
  end
end
```

The first line below the module definition invokes the `__using__/1` macro of the `HelloWeb` module, which imports some useful modules.

The `PageController` gives us the `index` action to display the Phoenix welcome page associated with the default route Phoenix defines in the router.

## Actions
Controller actions are just functions. We can name them anything we like as long as they follow Elixir's naming rules. The only requirement we must fulfill is that the action name matches a route defined in the router.

For example, in `lib/hello_web/router.ex` we could change the action name in the default route that Phoenix gives us in a new app from index:

```elixir
get "/", PageController, :index
```

To test:

```elixir
get "/", PageController, :test
```

As long as we change the action name in the `PageController` to `test` as well, the welcome page will load as before.

```elixir
defmodule HelloWeb.PageController do
  ...

  def test(conn, _params) do
    render(conn, "index.html")
  end
end
```

While we can name our actions whatever we like, there are conventions for action names which we should follow whenever possible. We went over these in the [Routing Guide](routing.html), but we'll take another quick look here.

- index   - renders a list of all items of the given resource type
- show    - renders an individual item by id
- new     - renders a form for creating a new item
- create  - receives params for one new item and saves it in a datastore
- edit    - retrieves an individual item by id and displays it in a form for editing
- update  - receives params for one edited item and saves it to a datastore
- delete  - receives an id for an item to be deleted and deletes it from a datastore

Each of these actions takes two parameters, which will be provided by Phoenix behind the scenes.

The first parameter is always `conn`, a struct which holds information about the request such as the host, path elements, port, query string, and much more. `conn`, comes to Phoenix via Elixir's Plug middleware framework. More detailed info about `conn` can be found in [plug's documentation](https://hexdocs.pm/plug/Plug.Conn.html).

The second parameter is `params`. Not surprisingly, this is a map which holds any parameters passed along in the HTTP request. It is a good practice to pattern match against params in the function signature to provide data in a simple package we can pass on to rendering. We saw this in the [Adding Pages guide](adding_pages.html) when we added a messenger parameter to our `show` route in `lib/hello_web/controllers/hello_controller.ex`.

```elixir
defmodule HelloWeb.HelloController do
  ...

  def show(conn, %{"messenger" => messenger}) do
    render(conn, "show.html", messenger: messenger)
  end
end
```

In some cases - often in `index` actions, for instance - we don't care about parameters because our behavior doesn't depend on them. In those cases, we don't use the incoming params, and simply prepend the variable name with an underscore, `_params`. This will keep the compiler from complaining about the unused variable while still keeping the correct arity.

### Gathering Data

While Phoenix does not ship with its own data access layer, the Elixir project [Ecto](https://hexdocs.pm/ecto) provides a very nice solution for those using the [Postgres](http://www.postgresql.org/) relational database. We cover how to use Ecto in a Phoenix project in the [Ecto Guide](ecto.html). Databases supported by Ecto are covered in the [Usage section of the Ecto README](https://github.com/elixir-lang/ecto#usage).

Of course, there are many other data access options. [Ets](http://www.erlang.org/doc/man/ets.html) and [Dets](http://www.erlang.org/doc/man/dets.html) are key value data stores built into [OTP](http://www.erlang.org/doc/). OTP also provides a relational database called [mnesia](http://www.erlang.org/doc/man/mnesia.html) with its own query language called QLC. Both Elixir and Erlang also have a number of libraries for working with a wide range of popular data stores.

The data world is your oyster, but we won't be covering these options in these guides.

## Flash Messages

There are times when we need to communicate with users during the course of an action. Maybe there was an error updating a schema. Maybe we just want to welcome them back to the application. For this, we have flash messages.

The `Phoenix.Controller` module provides the `put_flash/3` and `get_flash/2` functions to help us set and retrieve flash messages as a key value pair. Let's set two flash messages in our `HelloWeb.PageController` to try this out.

To do this we modify the `index` action as follows:

```elixir
defmodule HelloWeb.PageController do
  ...
  def index(conn, _params) do
    conn
    |> put_flash(:info, "Welcome to Phoenix, from flash info!")
    |> put_flash(:error, "Let's pretend we have an error.")
    |> render("index.html")
  end
end
```

The `Phoenix.Controller` module is not particular about the keys we use. As long as we are internally consistent, all will be well. `:info` and `:error`, however, are common.

In order to see our flash messages, we need to be able to retrieve them and display them in a template/layout. One way to do the first part is with `get_flash/2` which takes `conn` and the key we care about. It then returns the value for that key.

Fortunately, our application layout, `lib/hello_web/templates/layout/app.html.eex`, already has markup for displaying flash messages.

```html
<p class="alert alert-info" role="alert"><%= get_flash(@conn, :info) %></p>
<p class="alert alert-danger" role="alert"><%= get_flash(@conn, :error) %></p>
```

When we reload the [Welcome Page](http://localhost:4000/), our messages should appear just above "Welcome to Phoenix!"

Besides `put_flash/3` and `get_flash/2`, the `Phoenix.Controller` module has another useful function worth knowing about. `clear_flash/1` takes only `conn` and removes any flash messages which might be stored in the session.

## Rendering

Controllers have several ways of rendering content. The simplest is to render some plain text using the `text/2` function which Phoenix provides.

Let's say we have a `show` action which receives an id from the params map, and all we want to do is return some text with the id. For that, we could do the following.

```elixir
def show(conn, %{"id" => id}) do
  text(conn, "Showing id #{id}")
end
```
Assuming we had a route for `get "/our_path/:id"` mapped to this `show` action, going to `/our_path/15` in your browser should display `Showing id 15` as plain text without any HTML.

A step beyond this is rendering pure JSON with the `json/2` function. We need to pass it something that the [Jason library](https://github.com/michalmuskala/jason) can decode into JSON, such as a map. (Jason is one of Phoenix's dependencies.)

```elixir
def show(conn, %{"id" => id}) do
  json(conn, %{id: id})
end
```
If we again visit `our_path/15` in the browser, we should see a block of JSON with the key `id` mapped to the number `15`.

```json
{"id": "15"}
```
Phoenix controllers can also render HTML without a template. As you may have already guessed, the `html/2` function does just that. This time, we implement the `show` action like this.

```elixir
def show(conn, %{"id" => id}) do
  html(conn, """
     <html>
       <head>
          <title>Passing an Id</title>
       </head>
       <body>
         <p>You sent in id #{id}</p>
       </body>
     </html>
    """)
end
```

Hitting `/our_path/15` now renders the HTML string we defined in the `show` action, with the value `15` interpolated. Note that what we wrote in the action is not an `eex` template. It's a multi-line string, so we interpolate the `id` variable like this `#{id}` instead of this `<%= id %>`.

It is worth noting that the `text/2`, `json/2`, and `html/2` functions require neither a Phoenix view, nor a template to render.

The `json/2` function is obviously useful for writing APIs, and the other two may come in handy, but rendering a template into a layout with values we pass in is a very common case.

For this, Phoenix provides the `render/3` function.

Interestingly, `render/3` is defined in the `Phoenix.View` module instead of `Phoenix.Controller`, but it is aliased in `Phoenix.Controller` for convenience.

We have already seen the render function in the [Adding Pages Guide](adding_pages.html). Our `show` action in `lib/hello_web/controllers/hello_controller.ex` looked like this.

```elixir
defmodule HelloWeb.HelloController do
  use HelloWeb, :controller

  def show(conn, %{"messenger" => messenger}) do
    render(conn, "show.html", messenger: messenger)
  end
end
```

In order for the `render/3` function to work correctly, the controller must have the same root name as the individual view. The individual view must also have the same root name as the template directory where the `show.html.eex` template lives. In other words, the `HelloController` requires `HelloView`, and `HelloView` requires the existence of the `lib/hello_web/templates/hello` directory, which must contain the `show.html.eex` template.

`render/3` will also pass the value which the `show` action received for `messenger` from the params hash into the template for interpolation.

If we need to pass values into the template when using `render`, that's easy. We can pass a dictionary like we've seen with `messenger: messenger`, or we can use `Plug.Conn.assign/3`, which conveniently returns `conn`.

```elixir
def index(conn, _params) do
  conn
  |> assign(:message, "Welcome Back!")
  |> render("index.html")
end
```
Note: The `Phoenix.Controller` module imports `Plug.Conn`, so shortening the call to `assign/3` works just fine.

We can access this message in our `index.html.eex` template, or in our layout, with this `<%= @message %>`.

Passing more than one value in to our template is as simple as connecting `assign/3` functions together in a pipeline.

```elixir
def index(conn, _params) do
  conn
  |> assign(:message, "Welcome Back!")
  |> assign(:name, "Dweezil")
  |> render("index.html")
end
```
With this, both `@message` and `@name` will be available in the `index.html.eex` template.

What if we want to have a default welcome message that some actions can override? That's easy, we just use `plug` and transform `conn` on its way towards the controller action.

```elixir
plug :assign_welcome_message, "Welcome Back"

def index(conn, _params) do
  conn
  |> assign(:message, "Welcome Forward")
  |> render("index.html")
end

defp assign_welcome_message(conn, msg) do
  assign(conn, :message, msg)
end
```

What if we want to plug `assign_welcome_message`, but only for some of our actions? Phoenix offers a solution to this by letting us specify which actions a plug should be applied to. If we only wanted `plug :assign_welcome_message` to work on the `index` and `show` actions, we could do this.

```elixir
defmodule HelloWeb.PageController do
  use HelloWeb, :controller

  plug :assign_welcome_message, "Hi!" when action in [:index, :show]
...
```

### Sending responses directly

If none of the rendering options above quite fits our needs, we can compose our own using some of the functions that Plug gives us. Let's say we want to send a response with a status of "201" and no body whatsoever. We can easily do that with the `send_resp/3` function.

```elixir
def index(conn, _params) do
  conn
  |> send_resp(201, "")
end
```

Reloading [http://localhost:4000](http://localhost:4000) should show us a completely blank page. The network tab of our browser's developer tools should show a response status of "201".

If we would like to be really specific about the content type, we can use `put_resp_content_type/2` in conjunction with `send_resp/3`.

```elixir
def index(conn, _params) do
  conn
  |> put_resp_content_type("text/plain")
  |> send_resp(201, "")
end
```

Using Plug functions in this way, we can craft just the response we need.

Rendering does not end with the template, though. By default, the results of the template render will be inserted into a layout, which will also be rendered.

[Templates and layouts](templates.html) have their own guide, so we won't spend much time on them here. What we will look at is how to assign a different layout, or none at all, from inside a controller action.

### Assigning Layouts

Layouts are just a special subset of templates. They live in `lib/hello_web/templates/layout`. Phoenix created one for us when we generated our app. It's called `app.html.eex`, and it is the layout into which all templates will be rendered by default.

Since layouts are really just templates, they need a view to render them. This is the `LayoutView` module defined in `lib/hello_web/views/layout_view.ex`. Since Phoenix generated this view for us, we won't have to create a new one as long as we put the layouts we want to render inside the `lib/hello_web/templates/layout` directory.

Before we create a new layout, though, let's do the simplest possible thing and render a template with no layout at all.

The `Phoenix.Controller` module provides the `put_layout/2` function for us to switch layouts. This takes `conn` as its first argument and a string for the basename of the layout we want to render. Another clause of the function will match on the boolean `false` for the second argument, and that's how we will render the Phoenix welcome page without a layout.

In a freshly generated Phoenix app, edit the `index` action of the `PageController` module `lib/hello_web/controllers/page_controller.ex` to look like this.

```elixir
def index(conn, _params) do
  conn
  |> put_layout(false)
  |> render("index.html")
end
```
After reloading [http://localhost:4000/](http://localhost:4000/), we should see a very different page, one with no title, logo image, or css styling at all.

Very Important! For function calls in a pipeline, it is critical to use parentheses around the arguments because the pipe operator binds very tightly. This leads to parsing problems and very strange results.

If you ever get a stack trace that looks like this,

```console
**(FunctionClauseError) no function clause matching in Plug.Conn.get_resp_header/2

Stacktrace

    (plug) lib/plug/conn.ex:353: Plug.Conn.get_resp_header(false, "content-type")
```

where your argument replaces `conn` as the first argument, one of the first things to check is whether there are parentheses in the right places.

This is fine.

```elixir
def index(conn, _params) do
  conn
  |> put_layout(false)
  |> render("index.html")
end
```

Whereas this won't work.

```elixir
def index(conn, _params) do
  conn
  |> put_layout false
  |> render "index.html"
end
```

Now let's actually create another layout and render the index template into it. As an example, let's say we had a different layout for the admin section of our application which didn't have the logo image. To do this, let's copy the existing `app.html.eex` to a new file `admin.html.eex` in the same directory `lib/hello_web/templates/layout`. Then let's remove the line in `admin.html.eex` that displays the logo.

```html
<span class="logo"></span> <!-- remove this line -->
```

Then, pass the basename of the new layout into `put_layout/2` in our `index` action in `lib/hello_web/controllers/page_controller.ex`.

```elixir
def index(conn, _params) do
  conn
  |> put_layout("admin.html")
  |> render("index.html")
end
```
When we load the page, we should be rendering the admin layout without a logo.

### Overriding Rendering Formats

Rendering HTML through a template is fine, but what if we need to change the rendering format on the fly? Let's say that sometimes we need HTML, sometimes we need plain text, and sometimes we need JSON. Then what?

Phoenix allows us to change formats on the fly with the `_format` query string parameter. To make this happen, Phoenix requires an appropriately named view and an appropriately named template in the correct directory.

As an example, let's take the `PageController` index action from a newly generated app. Out of the box, this has the right view, `PageView`, the right templates directory, `lib/hello_web/templates/page`, and the right template for rendering HTML, `index.html.eex`.

```elixir
def index(conn, _params) do
  render(conn, "index.html")
end
```
What it doesn't have is an alternative template for rendering text. Let's add one at `lib/hello_web/templates/page/index.text.eex`. Here is our example `index.text.eex` template.

```html
OMG, this is actually some text.
```

There are just a few more things we need to do to make this work. We need to tell our router that it should accept the `text` format. We do that by adding `text` to the list of accepted formats in the `:browser` pipeline. Let's open up `lib/hello_web/router.ex` and change the `plug :accepts` to include `text` as well as `html` like this.

```elixir
defmodule HelloWeb.Router do
  use HelloWeb, :router

  pipeline :browser do
    plug :accepts, ["html", "text"]
    plug :fetch_session
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end
...
```

We also need to tell the controller to render a template with the same format as the one returned by `Phoenix.Controller.get_format/1`. We do that by substituting the name of the template "index.html" with the atom version `:index`.

```elixir
def index(conn, _params) do
  render(conn, :index)
end
```

If we go to [http://localhost:4000/?_format=text](http://localhost:4000/?_format=text), we will see `OMG, this is actually some text.`

Of course, we can pass data into our template as well. Let's change our action to take in a message parameter by removing the `_` in front of `params` in the function definition. This time, we'll use the somewhat less-flexible string version of our text template, just to see that it works as well.

```elixir
def index(conn, params) do
  render(conn, "index.text", message: params["message"])
end
```

And let's add a bit to our text template.

```html
OMG, this is actually some text. <%= @message %>
```

Now if we go to `http://localhost:4000/?_format=text&message=CrazyTown`, we will see "OMG, this is actually some text. CrazyTown"

### Setting the Content Type

Analogous to the `_format` query string param, we can render any sort of format we want by modifying the HTTP Content-Type Header and providing the appropriate template.

If we wanted to render an xml version of our `index` action, we might implement the action like this in `lib/hello_web/page_controller.ex`.

```elixir
def index(conn, _params) do
  conn
  |> put_resp_content_type("text/xml")
  |> render("index.xml", content: some_xml_content)
end
```

We would then need to provide an `index.xml.eex` template which created valid xml, and we would be done.

For a list of valid content mime-types, please see the [mime.types](https://github.com/elixir-plug/mime/blob/master/priv/mime.types) documentation from the mime type library.

### Setting the HTTP Status

We can also set the HTTP status code of a response similarly to the way we set the content type. The `Plug.Conn` module, imported into all controllers, has a `put_status/2` function to do this.

`Plug.Conn.put_status/2` takes `conn` as the first parameter and as the second parameter either an integer or a "friendly name" used as an atom for the status code we want to set. The list of status code atom representations can be found in `Plug.Conn.Status.code/1` documentation.

Let's change the status in our `PageController` `index` action.

```elixir
def index(conn, _params) do
  conn
  |> put_status(202)
  |> render("index.html")
end
```

The status code we provide must be valid - [Cowboy](https://github.com/ninenines/cowboy), the web server Phoenix runs on, will throw an error on invalid codes. If we look at our development logs (which is to say, the iex session), or use our browser's web inspection network tool, we will see the status code being set as we reload the page.

If the action sends a response - either renders or redirects - changing the code will not change the behavior of the response. If, for example, we set the status to 404 or 500 and then `render("index.html")`, we do not get an error page. Similarly, no 300 level code will actually redirect. (It wouldn't know where to redirect to, even if the code did affect behavior.)

The following implementation of the `HelloWeb.PageController` `index` action, for example, will _not_ render the default `not_found` behavior as expected.

```elixir
def index(conn, _params) do
  conn
  |> put_status(:not_found)
  |> render("index.html")
end
```

The correct way to render the 404 page from `HelloWeb.PageController` is:

```elixir
def index(conn, _params) do
  conn
  |> put_status(:not_found)
  |> put_view(HelloWeb.ErrorView)
  |> render("404.html")
end
```

## Redirection

Often, we need to redirect to a new url in the middle of a request. A successful `create` action, for instance, will usually redirect to the `show` action for the schema we just created. Alternately, it could redirect to the `index` action to show all the things of that same type. There are plenty of other cases where redirection is useful as well.

Whatever the circumstance, Phoenix controllers provide the handy `redirect/2` function to make redirection easy. Phoenix differentiates between redirecting to a path within the application and redirecting to a url - either within our application or external to it.

In order to try out `redirect/2`, let's create a new route in `lib/hello_web/router.ex`.

```elixir
defmodule HelloWeb.Router do
  use HelloWeb, :router
  ...

  scope "/", HelloWeb do
    ...
    get "/", PageController, :index
  end

  # New route for redirects
  scope "/", HelloWeb do
    get "/redirect_test", PageController, :redirect_test, as: :redirect_test
  end
  ...
end
```

Then we'll change the `index` action to do nothing but redirect to our new route.

```elixir
def index(conn, _params) do
  redirect(conn, to: "/redirect_test")
end
```

Finally, let's define in the same file the action we redirect to, which simply renders the text `Redirect!`.

```elixir
def redirect_test(conn, _params) do
  text(conn, "Redirect!")
end
```

When we reload our [Welcome Page](http://localhost:4000), we see that we've been redirected to `/redirect_test` which has rendered the text `Redirect!`. It works!

If we care to, we can open up our developer tools, click on the network tab, and visit our root route again. We see two main requests for this page - a get to `/` with a status of `302`, and a get to `/redirect_test` with a status of `200`.

Notice that the redirect function takes `conn` as well as a string representing a relative path within our application. It can also take `conn` and a string representing a fully-qualified url.

```elixir
def index(conn, _params) do
  redirect(conn, external: "https://elixir-lang.org/")
end
```

We can also make use of the path helpers we learned about in the [Routing Guide](routing.html).

```elixir
defmodule HelloWeb.PageController do
  use HelloWeb, :controller

  def index(conn, _params) do
    redirect(conn, to: Routes.redirect_test_path(conn, :redirect_test))
  end
end
```

Note that we can't use the url helper here because `redirect/2` using the atom `:to`, expects a path. For example, the following will fail.

```elixir
def index(conn, _params) do
  redirect(conn, to: Routes.redirect_test_url(conn, :redirect_test))
end
```

If we want to use the url helper to pass a full url to `redirect/2`, we must use the atom `:external`. Note that the url does not have to be truly external to our application to use `:external`, as we see in this example.

```elixir
def index(conn, _params) do
  redirect(conn, external: Routes.redirect_test_url(conn, :redirect_test))
end
```

## Action Fallback

Action Fallback allows us to centralize error handling code in plugs which are called when a controller action fails to return a `Plug.Conn.t`. These plugs receive both the conn which was originally passed to the controller action along with the return value of the action.

Let's say we have a `show` action which uses `with` to fetch a blog post and then authorize the current user to view that blog post. In this example we might expect `Blog.fetch_post/1` to return `{:error, :not_found}` if the post is not found and `Authorizer.authorize/3` might return `{:error, :unauthorized}` if the user is unauthorized. We could render the error views for these non-happy-paths directly.

```elixir
defmodule HelloWeb.MyController do
  use Phoenix.Controller
  alias Hello.{Authorizer, Blog}
  alias HelloWeb.ErrorView

  def show(conn, %{"id" => id}, current_user) do
    with {:ok, post} <- Blog.fetch_post(id),
         :ok <- Authorizer.authorize(current_user, :view, post) do

      render(conn, "show.json", post: post)
    else
      {:error, :not_found} ->
        conn
        |> put_status(:not_found)
        |> put_view(ErrorView)
        |> render(:"404")
      {:error, :unauthorized} ->
        conn
        |> put_status(403)
        |> put_view(ErrorView)
        |> render(:"403")
    end
  end
end
```

Many times - especially when implementing controllers for an API - error handling in the controllers like this results in a lot of repetition. Instead we can define a plug which knows how to handle these error cases.

```elixir
defmodule HelloWeb.MyFallbackController do
  use Phoenix.Controller
  alias HelloWeb.ErrorView

  def call(conn, {:error, :not_found}) do
    conn
    |> put_status(:not_found)
    |> put_view(ErrorView)
    |> render(:"404")
  end

  def call(conn, {:error, :unauthorized}) do
    conn
    |> put_status(403)
    |> put_view(ErrorView)
    |> render(:"403")
  end
end
```

Then we can reference that plug using action_fallback and simply remove the `else` block from our `with`.  Our plug will receive the original conn as well as the result of the action and respond appropriately.

```elixir
defmodule HelloWeb.MyController do
  use Phoenix.Controller
  alias Hello.{Authorizer, Blog}

  action_fallback HelloWeb.MyFallbackController

  def show(conn, %{"id" => id}, current_user) do
    with {:ok, post} <- Blog.fetch_post(id),
         :ok <- Authorizer.authorize(current_user, :view, post) do

      render(conn, "show.json", post: post)
    end
  end
end
```

## Halting the Plug Pipeline

As we mentioned - Controllers are plugs.... specifically plugs which are called toward the end of the plug pipeline.  At any step of the pipeline we might have cause to stop processing - typically because we've redirected or rendered a response. `Plug.Conn.t` has a `:halted` key - setting it to true will cause downstream plugs to be skipped. We can do that easily using `Plug.Conn.halt/1`.

Consider a `HelloWeb.PostFinder` plug. On call, if we find a post related to a given id then we add it to `conn.assigns`; and if we don't find the post we respond with a 404 page.

```elixir
defmodule HelloWeb.PostFinder do
  use Plug
  import Plug.Conn

  alias Hello.Blog

  def init(opts), do: opts

  def call(conn, _) do
    case Blog.get_post(conn.params["id"]) do
      {:ok, post} ->
        assign(conn, :post, post)
      {:error, :notfound} ->
        conn
        |> send_resp(404, "Not found")
    end
  end
end
```

If we call this plug as part of the plug pipeline any downstream plugs will still be processed. If we want to prevent downstream plugs from being processed in the event of the 404 response we can simply call `Plug.Conn.halt/1`.

```elixir
    ...
    case Blog.get_post(conn.params["id"]) do
      {:ok, post} ->
        assign(conn, :post, post)
      {:error, :notfound} ->
        conn
        |> send_resp(404, "Not found")
        |> halt()
    end
```

It's important to note that `halt/1` simply sets the `:halted` key on `Plug.Conn.t` to `true`.  This is enough to prevent downstream plugs from being invoked but it will not stop the execution of code locally. As such

```elixir
conn
|> send_resp(404, "Not found")
|> halt()
```

... is functionally equivalent to...

```elixir
conn
|> halt()
|> send_resp(404, "Not found")
```

It's also important to note that halting will only stop the plug pipeline from continuing. Function plugs will still execute unless their implementation checks for the `:halted` value.

```elixir
def post_authorization_plug(%{halted: true} = conn, _), do: conn
def post_authorization_plug(conn, _) do
  ...
end
```


text:
class AddHistogramToItem < ActiveRecord::Migration
  def self.up
    add_column :items, :histogram, :text
  end

  def self.down
    remove_column :items, :histogram
  end
end

redpajama_set_name: RedPajamaGithub


text:
import React, { Component, PropTypes } from 'react';
import THREE from 'three';
import Textures from 'Textures';

export default [
    ...Object.keys( Textures ).map( key =>
        <meshPhongMaterial
            key={ key }
            resourceId={ key }
            color={ 0xffffff }
        >
            <texture
                url={ Textures[ key ] }
                wrapS={ THREE.RepeatWrapping }
                wrapT={ THREE.RepeatWrapping }
                anisotropy={ 16 }
            />
        </meshPhongMaterial>
    ),
    <boxGeometry
        key={ 11947 }
        resourceId="1x1box"
        width={ 1 }
        height={ 1 }
        depth={ 1 }
        widthSegments={ 1 }
        heightSegments={ 1 }
    />,
    <meshBasicMaterial
        key={ 11948 }
        resourceId="transparent"
        visible={ false }
    />,
    <meshPhongMaterial
        key={ 11949 }
        resourceId="finishFlag"
        side={ THREE.DoubleSide }
        transparent
        opacity={ 0.7 }
    />,
    <meshPhongMaterial
        key={ 11950 }
        resourceId="placeholder2"
        side={ THREE.DoubleSide }
        transparent
        opacity={ 0.8 }
        color={ 0x00ff00 }
    />,
    <meshPhongMaterial
        key={ 11951 }
        resourceId="placeholder"
        side={ THREE.DoubleSide }
        transparent
        opacity={ 0.8 }
        color={ 0xff0000 }
    />,
    <planeBufferGeometry
        key={ 11952 }
        resourceId="1x1plane"
        width={ 1 }
        height={ 1 }
        widthSegments={ 1 }
        heightSegments={ 1 }
    />,
    <sphereGeometry
        key={ 11953 }
        resourceId="radius1sphere"
        radius={ 0.5 }
        widthSegments={ 6 }
        heightSegments={ 6 }
    />,
    <meshBasicMaterial
        key={ 11954 }
        resourceId="semitransparent"
        opacity={ 0.1 }
        color={ 0xff0000 }
    />,
    <meshPhongMaterial
        key={ 11955 }
        resourceId="white"
        color={ 0xffffff }
    />,
    <meshPhongMaterial
        key={ 11956 }
        resourceId="lightGray"
        color={ 0x666666 }
    />,
    <meshPhongMaterial
        key={ 11957 }
        resourceId="wreathMaterial"
        side={ THREE.DoubleSide }
        transparent
    >
        <texture
            url={ Textures.vineWreath }
            anisotropy={ 16 }
            transparent
        />
    </meshPhongMaterial>,
];


text:
var gulp = require('gulp');

var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var webserver = require('gulp-webserver');

var paths = {
  stylesheets: './stylesheets/**/*'
};

gulp.task('sass', function () {
    gulp.src('./stylesheets/app.scss')
        .pipe(sourcemaps.init())
        .pipe(sass({includePaths: ['./bower_components/'], style: 'expanded'}))
        .pipe(sourcemaps.write({includeContent: false}))
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(autoprefixer({browsers: ['last 2 versions']}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./css'));
});

gulp.task('webserver', function() {
  gulp.src('./')
    .pipe(webserver({
      directoryListing: true,
      open: true
    }));
});

// Rerun the task when a file changes
gulp.task('watch', function() {
  gulp.watch(paths.stylesheets, ['sass']);
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['watch', 'sass']);


text:
package app

import (
	"fmt"
	"runtime"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"

	"k8s.io/kubernetes/cmd/kube-proxy/app/options"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/apis/componentconfig"
	"k8s.io/kubernetes/pkg/util/iptables"
)

type fakeNodeInterface struct {
	node api.Node
}

func (fake *fakeNodeInterface) Get(hostname string) (*api.Node, error) {
	return &fake.node, nil
}

type fakeIptablesVersioner struct {
	version string // what to return
	err     error  // what to return
}

func (fake *fakeIptablesVersioner) GetVersion() (string, error) {
	return fake.version, fake.err
}

type fakeKernelCompatTester struct {
	ok bool
}

func (fake *fakeKernelCompatTester) IsCompatible() error {
	if !fake.ok {
		return fmt.Errorf("error")
	}
	return nil
}

func Test_getProxyMode(t *testing.T) {
	if runtime.GOOS != "linux" {
		t.Skip("skipping on non-Linux")
	}
	var cases = []struct {
		flag            string
		annotationKey   string
		annotationVal   string
		iptablesVersion string
		kernelCompat    bool
		iptablesError   error
		expected        string
	}{
		{ // flag says userspace
			flag:     "userspace",
			expected: proxyModeUserspace,
		},
		{ // flag says iptables, error detecting version
			flag:          "iptables",
			iptablesError: fmt.Errorf("oops!"),
			expected:      proxyModeUserspace,
		},
		{ // flag says iptables, version too low
			flag:            "iptables",
			iptablesVersion: "0.0.0",
			expected:        proxyModeUserspace,
		},
		{ // flag says iptables, version ok, kernel not compatible
			flag:            "iptables",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    false,
			expected:        proxyModeUserspace,
		},
		{ // flag says iptables, version ok, kernel is compatible
			flag:            "iptables",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    true,
			expected:        proxyModeIptables,
		},
		{ // detect, error
			flag:          "",
			iptablesError: fmt.Errorf("oops!"),
			expected:      proxyModeUserspace,
		},
		{ // detect, version too low
			flag:            "",
			iptablesVersion: "0.0.0",
			expected:        proxyModeUserspace,
		},
		{ // detect, version ok, kernel not compatible
			flag:            "",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    false,
			expected:        proxyModeUserspace,
		},
		{ // detect, version ok, kernel is compatible
			flag:            "",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    true,
			expected:        proxyModeIptables,
		},
		{ // annotation says userspace
			flag:          "",
			annotationKey: "net.experimental.kubernetes.io/proxy-mode",
			annotationVal: "userspace",
			expected:      proxyModeUserspace,
		},
		{ // annotation says iptables, error detecting
			flag:          "",
			annotationKey: "net.experimental.kubernetes.io/proxy-mode",
			annotationVal: "iptables",
			iptablesError: fmt.Errorf("oops!"),
			expected:      proxyModeUserspace,
		},
		{ // annotation says iptables, version too low
			flag:            "",
			annotationKey:   "net.experimental.kubernetes.io/proxy-mode",
			annotationVal:   "iptables",
			iptablesVersion: "0.0.0",
			expected:        proxyModeUserspace,
		},
		{ // annotation says iptables, version ok, kernel not compatible
			flag:            "",
			annotationKey:   "net.experimental.kubernetes.io/proxy-mode",
			annotationVal:   "iptables",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    false,
			expected:        proxyModeUserspace,
		},
		{ // annotation says iptables, version ok, kernel is compatible
			flag:            "",
			annotationKey:   "net.experimental.kubernetes.io/proxy-mode",
			annotationVal:   "iptables",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    true,
			expected:        proxyModeIptables,
		},
		{ // annotation says something else, version ok
			flag:            "",
			annotationKey:   "net.experimental.kubernetes.io/proxy-mode",
			annotationVal:   "other",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    true,
			expected:        proxyModeIptables,
		},
		{ // annotation says nothing, version ok
			flag:            "",
			annotationKey:   "net.experimental.kubernetes.io/proxy-mode",
			annotationVal:   "",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    true,
			expected:        proxyModeIptables,
		},
		{ // annotation says userspace
			flag:          "",
			annotationKey: "net.beta.kubernetes.io/proxy-mode",
			annotationVal: "userspace",
			expected:      proxyModeUserspace,
		},
		{ // annotation says iptables, error detecting
			flag:          "",
			annotationKey: "net.beta.kubernetes.io/proxy-mode",
			annotationVal: "iptables",
			iptablesError: fmt.Errorf("oops!"),
			expected:      proxyModeUserspace,
		},
		{ // annotation says iptables, version too low
			flag:            "",
			annotationKey:   "net.beta.kubernetes.io/proxy-mode",
			annotationVal:   "iptables",
			iptablesVersion: "0.0.0",
			expected:        proxyModeUserspace,
		},
		{ // annotation says iptables, version ok, kernel not compatible
			flag:            "",
			annotationKey:   "net.beta.kubernetes.io/proxy-mode",
			annotationVal:   "iptables",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    false,
			expected:        proxyModeUserspace,
		},
		{ // annotation says iptables, version ok, kernel is compatible
			flag:            "",
			annotationKey:   "net.beta.kubernetes.io/proxy-mode",
			annotationVal:   "iptables",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    true,
			expected:        proxyModeIptables,
		},
		{ // annotation says something else, version ok
			flag:            "",
			annotationKey:   "net.beta.kubernetes.io/proxy-mode",
			annotationVal:   "other",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    true,
			expected:        proxyModeIptables,
		},
		{ // annotation says nothing, version ok
			flag:            "",
			annotationKey:   "net.beta.kubernetes.io/proxy-mode",
			annotationVal:   "",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    true,
			expected:        proxyModeIptables,
		},
		{ // flag says userspace, annotation disagrees
			flag:            "userspace",
			annotationKey:   "net.experimental.kubernetes.io/proxy-mode",
			annotationVal:   "iptables",
			iptablesVersion: iptables.MinCheckVersion,
			expected:        proxyModeUserspace,
		},
		{ // flag says iptables, annotation disagrees
			flag:            "iptables",
			annotationKey:   "net.experimental.kubernetes.io/proxy-mode",
			annotationVal:   "userspace",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    true,
			expected:        proxyModeIptables,
		},
		{ // flag says userspace, annotation disagrees
			flag:            "userspace",
			annotationKey:   "net.beta.kubernetes.io/proxy-mode",
			annotationVal:   "iptables",
			iptablesVersion: iptables.MinCheckVersion,
			expected:        proxyModeUserspace,
		},
		{ // flag says iptables, annotation disagrees
			flag:            "iptables",
			annotationKey:   "net.beta.kubernetes.io/proxy-mode",
			annotationVal:   "userspace",
			iptablesVersion: iptables.MinCheckVersion,
			kernelCompat:    true,
			expected:        proxyModeIptables,
		},
	}
	for i, c := range cases {
		getter := &fakeNodeInterface{}
		getter.node.Annotations = map[string]string{c.annotationKey: c.annotationVal}
		versioner := &fakeIptablesVersioner{c.iptablesVersion, c.iptablesError}
		kcompater := &fakeKernelCompatTester{c.kernelCompat}
		r := getProxyMode(c.flag, getter, "host", versioner, kcompater)
		if r != c.expected {
			t.Errorf("Case[%d] Expected %q, got %q", i, c.expected, r)
		}
	}
}

// This test verifies that Proxy Server does not crash that means
// Config and iptinterface are not nil when CleanupAndExit is true.
// To avoid proxy crash: https://github.com/kubernetes/kubernetes/pull/14736
func TestProxyServerWithCleanupAndExit(t *testing.T) {
	// creates default config
	config := options.NewProxyConfig()

	// sets CleanupAndExit manually
	config.CleanupAndExit = true

	// creates new proxy server
	proxyserver, err := NewProxyServerDefault(config)

	// verifies that nothing is nill except error
	assert.Nil(t, err)
	assert.NotNil(t, proxyserver)
	assert.NotNil(t, proxyserver.Config)
	assert.NotNil(t, proxyserver.IptInterface)
}

func TestGetConntrackMax(t *testing.T) {
	ncores := runtime.NumCPU()
	testCases := []struct {
		config   componentconfig.KubeProxyConfiguration
		expected int
		err      string
	}{
		{
			config:   componentconfig.KubeProxyConfiguration{},
			expected: 0,
		},
		{
			config: componentconfig.KubeProxyConfiguration{
				ConntrackMax: 12345,
			},
			expected: 12345,
		},
		{
			config: componentconfig.KubeProxyConfiguration{
				ConntrackMax:        12345,
				ConntrackMaxPerCore: 67890,
			},
			expected: -1,
			err:      "mutually exclusive",
		},
		{
			config: componentconfig.KubeProxyConfiguration{
				ConntrackMaxPerCore: 67890, // use this if other is 0
			},
			expected: 67890 * ncores,
		},
	}

	for i, tc := range testCases {
		cfg := options.ProxyServerConfig{KubeProxyConfiguration: tc.config}
		x, e := getConntrackMax(&cfg)
		if e != nil {
			if tc.err == "" {
				t.Errorf("[%d] unexpected error: %v", i, e)
			} else if !strings.Contains(e.Error(), tc.err) {
				t.Errorf("[%d] expected an error containing %q: %v", i, tc.err, e)
			}
		} else if x != tc.expected {
			t.Errorf("[%d] expected %d, got %d", i, tc.expected, x)
		}
	}
}


text:
using System;
using Citysim.Map;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Citysim
{
    public class Camera
    {
        public Vector2 position = new Vector2(0, 0);

        public int speed = Setting.Camera.lowSpeed;

        public int tileSize = Setting.Tiles.tileSize;

        // Current X/Y coords where the mouse is hovering.
        public Vector2 hovering = new Vector2(0, 0);

        // Current X/Y coords where the mouse is hovering (exact to the decimal).
        public Vector2 hoveringExact = new Vector2(0, 0);

        public void Update(Citysim game, GameTime gameTime)
        {
            // Handle movement.
            if (KeyboardHelper.IsKeyDown(Keys.LeftShift))
                game.camera.speed = Setting.Camera.highSpeed;
            else
                game.camera.speed = Setting.Camera.lowSpeed;

            int speed = game.camera.speed;

            if (KeyboardHelper.IsKeyDown(Keys.W))
                game.camera.position.Y += speed;
            if (KeyboardHelper.IsKeyDown(Keys.A))
                game.camera.position.X += speed;
            if (KeyboardHelper.IsKeyDown(Keys.S))
                game.camera.position.Y -= speed;
            if (KeyboardHelper.IsKeyDown(Keys.D))
                game.camera.position.X -= speed;

            // Handle mouse.
            MouseState mouseState = Mouse.GetState();
            hoveringExact.X = mouseState.Position.X - game.camera.position.X;
            hoveringExact.Y = mouseState.Position.Y - game.camera.position.Y;

            hovering.X = (int)Math.Floor(hoveringExact.X / tileSize);
            hovering.Y = (int)Math.Floor(hoveringExact.Y / tileSize);
        }
    }
}


text:
var R = require('ramda');

module.exports = R.reverse([
  {
    eventId: 8,
    eventType: 'ActivityTaskScheduled',
    activityTaskScheduledEventAttributes: {
      activityId: 'activity3',
      activityType: { name: 'type3', version: '1' }
    }
  },
  {
    eventId: 7,
    eventType: 'ActivityTaskTimedOut',
    activityTaskTimedOutEventAttributes: {
      scheduledEventId: 4
    }
  },
  {
    eventId: 6,
    eventType: 'ActivityTaskCompleted',
    activityTaskCompletedEventAttributes: {
      scheduledEventId: 5
    }
  },
  {
    eventId: 5,
    eventType: 'ActivityTaskScheduled',
    activityTaskScheduledEventAttributes: {
      activityId: 'activity1',
      activityType: { name: 'type1', version: '1' }
    }
  },
  {
    eventId: 4,
    eventType: 'ActivityTaskScheduled',
    activityTaskScheduledEventAttributes: {
      activityId: 'activity2',
      activityType: { name: 'type2', version: '1' }
    }
  },
  {
    eventId: 3,
    eventType: 'ActivityTaskFailed',
    activityTaskFailedEventAttributes: {
      scheduledEventId: 2
    }
  },
  {
    eventId: 2,
    eventType: 'ActivityTaskScheduled',
    activityTaskScheduledEventAttributes: {
      activityId: 'activity1',
      activityType: { name: 'type1', version: '1' }
    }
  },
  {
    eventId: 1,
    eventType: 'WorkflowExecutionStarted',
    workflowExecutionStartedEventAttributes: {
      input: 'workflow input'
    }
  }
]);


text:
layout: default
---

{{ page.title }}{{ .shortUrl }}

        {% include post/meta.html %}

        {{ content }}

[top]

            {% capture url %}{{ site.url }}{{ page.url }}{% endcapture %}

            {% if page.shortUrl != null %}
                {% assign url = page.shortUrl %}
            {% endif %}

            {% assign tagStr = '' %}
            {% for tag in page.tags %}
                {% capture tagStr %}{{ tagStr }}{{ tag }},{% endcapture %}
            {% endfor %}

            Facebook

Twitter

Google+

{% if site.disqus-id %}

        Please enable JavaScript to view the  comments.
        comments powered byDisqus

{% endif %}


text:
package com.mediaplayer.zoro.mediaplayer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class PlayListActivity extends ListActivity {
	// Songs list
	public ArrayList<Song> songsList = new ArrayList<Song>();
	private ListView songView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.playlist);
		songView = (ListView)getListView();

		SongsManager plm = new SongsManager(this);
		// get all songs from sdcard
		this.songsList = plm.getPlayList();

		Collections.sort(this.songsList, new Comparator<Song>() {
			public int compare(Song a, Song b) {
				return a.getTitle().compareTo(b.getTitle());
			}
		});

		SongAdapter songAdt = new SongAdapter(this, songsList);
		songView.setAdapter(songAdt);

	}

	public void songPicked(View view){
		int songIndex = Integer.parseInt(view.getTag().toString());
		Intent in = new Intent(getApplicationContext(),
				AndroidBuildingMusicPlayerActivity.class);
		// Sending songIndex to PlayerActivity
		in.putExtra("songIndex", songIndex);
		setResult(100, in);
	}
}


text:
<?php

namespace Omnipay\InterKassa\Message;

use Omnipay\Common\Exception\InvalidResponseException;
use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RequestInterface;

/**
 * InterKassa Complete Purchase Response.
 */
class CompletePurchaseResponse extends AbstractResponse
{
    /**
     * {@inheritdoc}
     * @var CompletePurchaseRequest
     */
    public $request;

    /**
     * {@inheritdoc}
     */
    public function __construct(RequestInterface $request, $data)
    {
        parent::__construct($request, $data);

        $signKey = $this->request->getTestMode() ? $this->request->getTestKey() : $this->request->getSignKey();
        $signExpected = $this->request->calculateSign($this->data, $signKey);

        if ($this->getCheckoutId() !== $this->request->getCheckoutId()) {
            throw new InvalidResponseException('Wrong checkout ID');
        }

        if ($this->getSign() !== $signExpected) {
            throw new InvalidResponseException('Failed to validate signature');
        }

        if ($this->getState() !== 'success') {
            throw new InvalidResponseException('The payment was not success');
        }
    }

    /**
     * Whether the payment is successful.
     *
     * @return boolean
     */
    public function isSuccessful()
    {
        return $this->getState() === 'success';
    }

    /**
     * The checkout ID.
     *
     * @return string
     */
    public function getCheckoutId()
    {
        return $this->data['ik_co_id'];
    }

    /**
     * @return string
     */
    public function getSign()
    {
        return $this->data['ik_sign'];
    }

    /**
     * The transaction identifier generated by the merchant website.
     *
     * @return string
     */
    public function getTransactionId()
    {
        return $this->data['ik_pm_no'];
    }

    /**
     * {@inheritdoc}
     */
    public function getTransactionReference()
    {
        return $this->data['ik_inv_id'];
    }

    /**
     * The amount of payment.
     *
     * @return mixed
     */
    public function getAmount()
    {
        return $this->data['ik_am'];
    }

    /**
     * The currency of the payment.
     * @return string
     */
    public function getCurrency()
    {
        return strtoupper($this->data['ik_cur']);
    }

    /**
     * The time of request processing.
     *
     * @return string
     */
    public function getTime()
    {
        $date = new \DateTime($this->data['ik_inv_prc'], new \DateTimeZone('Europe/Moscow'));
        return $date->format('c');
    }

    /**
     * @return string the payment method inside a gateway (Visa, WebMoney, etc)
     */
    public function getPayer()
    {
        return $this->data['ik_pw_via'];
    }

    /**
     * The state of the payment.
     * Possible results:
     *  - `new`: newly created payment
     *  - `waitAccept`: waits for the payment
     *  - `process`: the payment is being processed
     *  - `success`: the payment processed successfully
     *  - `canceled`: the payment have been canceled
     *  - `fail`: the payment failed.
     *
     * @return string
     * @see isSuccessful
     */
    public function getState()
    {
        return $this->data['ik_inv_st'];
    }
}


text:
interface ParallelProcessingParams<T> {
    arrayValues: T[];

    processingFn(params: ProcessingFnParams<T>): void | Promise<void>;

    nextValueFn?(params: NextValueFnParams<T>): boolean | Promise<boolean>;

    cycleTimeout?: number;
    parallel?: number;
    awaitRes?: boolean;

    cb?(stackError: StackError<T>): void | Promise<void>;
}

interface ProcessingFnParams<T> {
    value: T;
    index: number;
    arrayValues: T[];
    iteration: number;
}

interface NextValueFnParams<T> {
    value: T;
    index: number;
    arrayValues: T[];
    iteration: number;
}

interface StackError<T> {
    value: T;
    index: number;
    iteration: number;
    error: any;
}

declare function parallelProcessing<T>(params: ParallelProcessingParams<T>): Promise<Array<StackError<T>>> | undefined;

export = parallelProcessing;


text:
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import iView from 'iview'
import i18n from '@/locale'
import config from '@/config'
import importDirective from '@/directive'
import { directive as clickOutside } from 'v-click-outside-x'
import installPlugin from '@/plugin'
import './index.less'
import '@/assets/icons/iconfont.css'
import TreeTable from 'tree-table-vue'
import VOrgTree from 'v-org-tree'
import 'v-org-tree/dist/v-org-tree.css'
// 实际打包时应该不引入mock
/* eslint-disable */
if (process.env.NODE_ENV !== 'production') require('@/mock')

Vue.use(iView, {
  i18n: (key, value) => i18n.t(key, value)
})
Vue.use(TreeTable)
Vue.use(VOrgTree)
/**
 * @description 注册admin内置插件
 */
installPlugin(Vue)
/**
 * @description 生产环境关掉提示
 */
Vue.config.productionTip = false
/**
 * @description 全局注册应用配置
 */
Vue.prototype.$config = config
/**
 * 注册指令
 */
importDirective(Vue)
Vue.directive('clickOutside', clickOutside)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  i18n,
  store,
  render: h => h(App)
})


text:
/*
	jQuery Mobile Icon Pack
	andy matthews
	@commadelimited
*/

/* Icons
-----------------------------------------------------------------------------------------------------------*/

.ui-icon,
.ui-icon-searchfield:after {
	background: #666666;
	background:  rgba(0,0,0,.4);
	background-image: url('images/icons-18-white-pack.png');
	background-repeat: no-repeat;
	-moz-border-radius: 9px;
	-webkit-border-radius: 9px;
	border-radius: 9px;
}

/* Alt icon color
-----------------------------------------------------------------------------------------------------------*/

.ui-icon-alt {
	background: #ffffff;
	background: rgba(255,255,255,.3);
	background-image: url('images/icons-18-black-pack.png');
	background-repeat: no-repeat;
}

/* restore default loading image */
.ui-icon-loading {
    background: url('images/ajax-loader.gif');
    background-size: 46px 46px;
}

/* HD/"retina" sprite
-----------------------------------------------------------------------------------------------------------*/

@media only screen and (-webkit-min-device-pixel-ratio: 1.3),
		only screen and (-o-min-device-pixel-ratio: 3/2),
		only screen and (min--moz-device-pixel-ratio: 1.3),
		only screen and (min-device-pixel-ratio: 1.3),
		only screen and (min-resolution: 1.3dppx) {

	.ui-icon-plus, .ui-icon-minus, .ui-icon-delete, .ui-icon-arrow-r,
	.ui-icon-arrow-l, .ui-icon-arrow-u, .ui-icon-arrow-d, .ui-icon-check,
	.ui-icon-gear, .ui-icon-refresh, .ui-icon-forward, .ui-icon-back,
	.ui-icon-grid, .ui-icon-star, .ui-icon-alert, .ui-icon-info2, .ui-icon-home, .ui-icon-search, .ui-icon-searchfield:after,
	.ui-icon-checkbox-off, .ui-icon-checkbox-on, .ui-icon-radio-off, .ui-icon-radio-on, .ui-icon-email , .ui-icon-page,
	.ui-icon-question , .ui-icon-foursquare , .ui-icon-twitter , .ui-icon-facebook , .ui-icon-dollar , .ui-icon-euro,
	.ui-icon-pound , .ui-icon-apple , .ui-icon-chat , .ui-icon-trash , .ui-icon-bell , .ui-icon-mappin , .ui-icon-direction,
	.ui-icon-heart , .ui-icon-wrench , .ui-icon-play , .ui-icon-pause , .ui-icon-stop , .ui-icon-person , .ui-icon-music,
	.ui-icon-rss , .ui-icon-wifi , .ui-icon-phone , .ui-icon-power , .ui-icon-lock , .ui-icon-flag , .ui-icon-calendar,
	.ui-icon-lightning , .ui-icon-drink , .ui-icon-android , .ui-icon-edit, .ui-icon-link {
		background-image: url('images/icons-36-white-pack.png');
		-moz-background-size: 774px 54px;
		-o-background-size: 774px 54px;
		-webkit-background-size: 774px 54px;
		background-size: 774px 54px;
	}
	.ui-icon-alt {
		background-image: url('images/icons-36-black-pack.png'	);
	}
}

/* first row */
.ui-icon-plus { background-position: -0 -0; }
.ui-icon-minus { background-position: -36px -0; }
.ui-icon-delete { background-position: -72px -0; }
.ui-icon-arrow-r { background-position: -108px -0; }
.ui-icon-arrow-l { background-position: -144px -0; }
.ui-icon-arrow-u { background-position: -180px -0; }
.ui-icon-arrow-d { background-position: -216px -0; }
.ui-icon-check { background-position: -252px -0; }
.ui-icon-gear { background-position: -288px -0; }
.ui-icon-refresh { background-position: -324px -0; }
.ui-icon-forward { background-position: -360px -0; }
.ui-icon-back { background-position: -396px -0; }
.ui-icon-grid { background-position: -432px -0; }
.ui-icon-star { background-position: -468px -0; }
.ui-icon-alert { background-position: -504px -0; }
.ui-icon-info2 { background-position: -540px -0; }
.ui-icon-home { background-position: -576px -0; }
.ui-icon-search,.ui-icon-searchfield:after { background-position: -612px -0; }
.ui-icon-checkbox-off { background-position: -684px -0; }
.ui-icon-checkbox-on { background-position: -648px -0; }
.ui-icon-radio-off { background-position: -756px -0; }
.ui-icon-radio-on { background-position: -718px -0; }

/* begin icon pack definitions */
/* second row */
.ui-icon-email { background-position: -0 -18px; }
.ui-icon-page { background-position: -36px -18px; }
.ui-icon-question { background-position: -72px -18px; }
.ui-icon-foursquare { background-position: -108px -18px; }
.ui-icon-twitter { background-position: -144px -18px; }
.ui-icon-facebook { background-position: -180px -18px; }
.ui-icon-dollar { background-position: -216px -18px; }
.ui-icon-euro { background-position: -252px -18px; }
.ui-icon-pound { background-position: -288px -18px; }
.ui-icon-apple { background-position: -324px -18px; }
.ui-icon-chat { background-position: -360px -18px; }
.ui-icon-trash { background-position: -396px -18px; }
.ui-icon-bell { background-position: -432px -18px; }
.ui-icon-mappin { background-position: -468px -18px;}
.ui-icon-direction { background-position: -504px -18px; }
.ui-icon-heart { background-position: -540px -18px; }
.ui-icon-wrench { background-position: -576px -18px; }
.ui-icon-play { background-position: -612px -18px; }
.ui-icon-pause { background-position: -648px -18px; }
.ui-icon-stop { background-position: -684px -18px; }
.ui-icon-person { background-position: -720px -18px; }
.ui-icon-music { background-position: -756px -18px; }

/* third row */
.ui-icon-rss { background-position: -0 -36px; }
.ui-icon-wifi { background-position: -36px -36px; }
.ui-icon-phone { background-position: -72px -36px; }
.ui-icon-power { background-position: -108px -36px; }
.ui-icon-lock { background-position: -144px -36px; }
.ui-icon-flag { background-position: -180px -36px; }
.ui-icon-calendar { background-position: -216px -36px; }
.ui-icon-lightning { background-position: -252px -36px; }
.ui-icon-drink { background-position: -288px -36px; }
.ui-icon-android { background-position: -324px -36px; }
.ui-icon-edit    { background-position: -360px -36px; }
.ui-icon-link    { background-position: -396px -36px; }
.ui-icon-youtube { background-position: -432px -36px; }
.ui-icon-menu    { background-position: -468px -36px; }


text:
Respond CMS
===========

Respond is an open source, responsive content management system that you can use to build responsive sites. Respond features a REST API, a lightning-fast Angular-powered UI, Bootstrap 3.0, Polymer-based plugins, multilingual support, and an enhanced data layer using PDO.

Learn more about Respond CMS at: http://respondcms.com

View our documentation at: http://respondcms.com/learn

New in version 4.6:
- Improved slideshows (support for headlines, captions, and link buttons)
- Improved CSS class support for site components
- Support for a system message (see setup.php)
- Bug fixes
- Moved composer.json to top level directory
- Secured passcode for site creation
- Fixed shipping/taxes in cart

Upgrading from 4.5:
- Pull latest version
- Update dependencies (php composer.phar update) from /app
- Republish sites


text:
using System;
using System.Collections.Generic;
using NGUI.Internal;
using UnityEngine;

[AddComponentMenu("NGUI/UI/Atlas")]
// ReSharper disable once CheckNamespace
public class UIAtlas : MonoBehaviour
{
    [SerializeField, HideInInspector]
    private Material material;
    [HideInInspector, SerializeField]
    private Coordinates mCoordinates;
    [HideInInspector, SerializeField]
    private float mPixelSize = 1f;
    private int mPMA = -1;
    [SerializeField, HideInInspector]
    private UIAtlas mReplacement;
    [SerializeField, HideInInspector]
    private List<Sprite> sprites = new List<Sprite>();

    public static bool CheckIfRelated(UIAtlas a, UIAtlas b)
    {
        return a != null && b != null && (a == b || a.References(b) || b.References(a));
    }

    private static int CompareString(string a, string b)
    {
        return a.CompareTo(b);
    }

    public List<string> GetListOfSprites()
    {
        if (this.mReplacement != null)
        {
            return this.mReplacement.GetListOfSprites();
        }
        List<string> list = new List<string>();
        int num = 0;
        int count = this.sprites.Count;
        while (num < count)
        {
            Sprite sprite = this.sprites[num];
            if (sprite != null && !string.IsNullOrEmpty(sprite.name))
            {
                list.Add(sprite.name);
            }
            num++;
        }
        return list;
    }

    public List<string> GetListOfSprites(string match)
    {
        if (this.mReplacement != null)
        {
            return this.mReplacement.GetListOfSprites(match);
        }
        if (string.IsNullOrEmpty(match))
        {
            return this.GetListOfSprites();
        }
        List<string> list = new List<string>();
        int num = 0;
        int count = this.sprites.Count;
        while (num < count)
        {
            Sprite sprite = this.sprites[num];
            if (sprite != null && !string.IsNullOrEmpty(sprite.name) && string.Equals(match, sprite.name, StringComparison.OrdinalIgnoreCase))
            {
                list.Add(sprite.name);
                return list;
            }
            num++;
        }
        char[] separator = new char[] { ' ' };
        string[] strArray = match.Split(separator, StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < strArray.Length; i++)
        {
            strArray[i] = strArray[i].ToLower();
        }
        int num4 = 0;
        int num5 = this.sprites.Count;
        while (num4 < num5)
        {
            Sprite sprite2 = this.sprites[num4];
            if (sprite2 != null && !string.IsNullOrEmpty(sprite2.name))
            {
                string str = sprite2.name.ToLower();
                int num6 = 0;
                for (int j = 0; j < strArray.Length; j++)
                {
                    if (str.Contains(strArray[j]))
                    {
                        num6++;
                    }
                }
                if (num6 == strArray.Length)
                {
                    list.Add(sprite2.name);
                }
            }
            num4++;
        }
        return list;
    }

    public Sprite GetSprite(string name)
    {
        if (this.mReplacement != null)
        {
            return this.mReplacement.GetSprite(name);
        }
        if (!string.IsNullOrEmpty(name))
        {
            int num = 0;
            int count = this.sprites.Count;
            while (num < count)
            {
                Sprite sprite = this.sprites[num];
                if (!string.IsNullOrEmpty(sprite.name) && name == sprite.name)
                {
                    return sprite;
                }
                num++;
            }
        }
        return null;
    }

    public void MarkAsDirty()
    {
        if (this.mReplacement != null)
        {
            this.mReplacement.MarkAsDirty();
        }
        UISprite[] spriteArray = NGUITools.FindActive<UISprite>();
        int index = 0;
        int length = spriteArray.Length;
        while (index < length)
        {
            UISprite sprite = spriteArray[index];
            if (CheckIfRelated(this, sprite.atlas))
            {
                UIAtlas atlas = sprite.atlas;
                sprite.atlas = null;
                sprite.atlas = atlas;
            }
            index++;
        }
        UIFont[] fontArray = Resources.FindObjectsOfTypeAll(typeof(UIFont)) as UIFont[];
        int num3 = 0;
        int num4 = fontArray.Length;
        while (num3 < num4)
        {
            UIFont font = fontArray[num3];
            if (CheckIfRelated(this, font.atlas))
            {
                UIAtlas atlas2 = font.atlas;
                font.atlas = null;
                font.atlas = atlas2;
            }
            num3++;
        }
        UILabel[] labelArray = NGUITools.FindActive<UILabel>();
        int num5 = 0;
        int num6 = labelArray.Length;
        while (num5 < num6)
        {
            UILabel label = labelArray[num5];
            if (label.font != null && CheckIfRelated(this, label.font.atlas))
            {
                UIFont font2 = label.font;
                label.font = null;
                label.font = font2;
            }
            num5++;
        }
    }

    private bool References(UIAtlas atlas)
    {
        if (atlas == null)
        {
            return false;
        }
        return atlas == this || this.mReplacement != null && this.mReplacement.References(atlas);
    }

    public Coordinates coordinates
    {
        get
        {
            return this.mReplacement == null ? this.mCoordinates : this.mReplacement.coordinates;
        }
        set
        {
            if (this.mReplacement != null)
            {
                this.mReplacement.coordinates = value;
            }
            else if (this.mCoordinates != value)
            {
                if (this.material == null || this.material.mainTexture == null)
                {
                    Debug.LogError("Can't switch coordinates until the atlas material has a valid texture");
                }
                else
                {
                    this.mCoordinates = value;
                    Texture mainTexture = this.material.mainTexture;
                    int num = 0;
                    int count = this.sprites.Count;
                    while (num < count)
                    {
                        Sprite sprite = this.sprites[num];
                        if (this.mCoordinates == Coordinates.TexCoords)
                        {
                            sprite.outer = NGUIMath.ConvertToTexCoords(sprite.outer, mainTexture.width, mainTexture.height);
                            sprite.inner = NGUIMath.ConvertToTexCoords(sprite.inner, mainTexture.width, mainTexture.height);
                        }
                        else
                        {
                            sprite.outer = NGUIMath.ConvertToPixels(sprite.outer, mainTexture.width, mainTexture.height, true);
                            sprite.inner = NGUIMath.ConvertToPixels(sprite.inner, mainTexture.width, mainTexture.height, true);
                        }
                        num++;
                    }
                }
            }
        }
    }

    public float pixelSize
    {
        get
        {
            return this.mReplacement == null ? this.mPixelSize : this.mReplacement.pixelSize;
        }
        set
        {
            if (this.mReplacement != null)
            {
                this.mReplacement.pixelSize = value;
            }
            else
            {
                float num = Mathf.Clamp(value, 0.25f, 4f);
                if (this.mPixelSize != num)
                {
                    this.mPixelSize = num;
                    this.MarkAsDirty();
                }
            }
        }
    }

    public bool premultipliedAlpha
    {
        get
        {
            if (this.mReplacement != null)
            {
                return this.mReplacement.premultipliedAlpha;
            }
            if (this.mPMA == -1)
            {
                Material spriteMaterial = this.spriteMaterial;
                this.mPMA = spriteMaterial == null || spriteMaterial.shader == null || !spriteMaterial.shader.name.Contains("Premultiplied") ? 0 : 1;
            }
            return this.mPMA == 1;
        }
    }

    public UIAtlas replacement
    {
        get
        {
            return this.mReplacement;
        }
        set
        {
            UIAtlas atlas = value;
            if (atlas == this)
            {
                atlas = null;
            }
            if (this.mReplacement != atlas)
            {
                if (atlas != null && atlas.replacement == this)
                {
                    atlas.replacement = null;
                }
                if (this.mReplacement != null)
                {
                    this.MarkAsDirty();
                }
                this.mReplacement = atlas;
                this.MarkAsDirty();
            }
        }
    }

    public List<Sprite> spriteList
    {
        get
        {
            return this.mReplacement == null ? this.sprites : this.mReplacement.spriteList;
        }
        set
        {
            if (this.mReplacement != null)
            {
                this.mReplacement.spriteList = value;
            }
            else
            {
                this.sprites = value;
            }
        }
    }

    public Material spriteMaterial
    {
        get
        {
            return this.mReplacement == null ? this.material : this.mReplacement.spriteMaterial;
        }
        set
        {
            if (this.mReplacement != null)
            {
                this.mReplacement.spriteMaterial = value;
            }
            else if (this.material == null)
            {
                this.mPMA = 0;
                this.material = value;
            }
            else
            {
                this.MarkAsDirty();
                this.mPMA = -1;
                this.material = value;
                this.MarkAsDirty();
            }
        }
    }

    public Texture texture
    {
        get
        {
            return this.mReplacement == null ? (this.material == null ? null : this.material.mainTexture) : this.mReplacement.texture;
        }
    }

    public enum Coordinates
    {
        Pixels,
        TexCoords
    }

    [Serializable]
    public class Sprite
    {
        public Rect inner = new Rect(0f, 0f, 1f, 1f);
        public string name = "Unity Bug";
        public Rect outer = new Rect(0f, 0f, 1f, 1f);
        public float paddingBottom;
        public float paddingLeft;
        public float paddingRight;
        public float paddingTop;
        public bool rotated;

        public bool hasPadding
        {
            get
            {
                return this.paddingLeft != 0f || this.paddingRight != 0f || this.paddingTop != 0f || this.paddingBottom != 0f;
            }
        }
    }
}


text:
package com.badr.infodota.hero.api.responses;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * Created by ABadretdinov
 * 19.06.2015
 * 16:28
 */
public class HeroResponsesSection implements Serializable {
    private String code;
    private String name;
    /*not using it by now*/
    private String ability;
    private java.util.List<HeroResponse> responses;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAbility() {
        return ability;
    }

    public void setAbility(String ability) {
        this.ability = ability;
    }

    public java.util.List<HeroResponse> getResponses() {
        return responses;
    }

    public void setResponses(java.util.List<HeroResponse> responses) {
        this.responses = responses;
    }

    public static class List extends ArrayList<HeroResponsesSection> {
    }
}


text:
#region Alchemi Copyright and License Notice

#endregion

using System;

namespace Alchemi.Core.Manager.Storage
{
	/// <summary>
	/// Sets up a specific storage structure.
	///
	/// A storage should know how to set itself up. In the event that the
	/// storage detects that it is not setup it might decide to initialize
	/// the required data structures automatically.
	/// </summary>
	public interface IManagerStorageSetup
	{
		/// <summary>
		/// Create the physical storage.
		/// For databases this means creating the actual database files.
		/// </summary>
		void CreateStorage(string databaseName);

		/// <summary>
		/// Create the basic storage structures such as tables.
		/// </summary>
		void SetUpStorage();

		/// <summary>
		/// Add default storage data.
		/// </summary>
		void InitializeStorageData();

		/// <summary>
		/// Remove the structures initialized by this storage.
		/// </summary>
		void TearDownStorage();
	}
}


text:
// JSLint settings:
/*global
  ADAPT_CONFIG,
  clearTimeout,
  setTimeout
*/

/*
  Adapt.js licensed under GPL and MIT.

  Read more here: http://adapt.960.gs
*/

// Closure.
(function(w, d, config, undefined) {
  // If no config, exit.
  if (!config) {
    return;
  }

  // Empty vars to use later.
  var url, url_old, timer;

  // Alias config values.
  var callback = config.callback || function(){};
  var path = config.path ? config.path : '';
  var range = config.range;
  var range_len = range.length;

  // Create empty link tag:
  // <link rel="stylesheet" />
  var css = d.createElement('link');
  css.rel = 'stylesheet';
  css.media = 'screen';

  // Called from within adapt().
  function change(i, width) {
    // Set the URL.
    css.href = url;
    url_old = url;

    // Fire callback.
    callback(i, width);
  }

  // Adapt to width.
  function adapt() {
    // This clearTimeout is for IE.
    // Really it belongs in react(),
    // but doesn't do any harm here.
    clearTimeout(timer);

    // Parse viewport width.
    var width = d.documentElement ? d.documentElement.clientWidth : 0;

    // While loop vars.
    var arr, arr_0, val_1, val_2, is_range, file;

    // How many ranges?
    var i = range_len;
    var last = range_len - 1;

    // Start with blank URL.
    url = '';

    while (i--) {
      // Turn string into array.
      arr = range[i].split('=');

      // Width is to the left of "=".
      arr_0 = arr[0];

      // File name is to the right of "=".
      // Presuppoes a file with no spaces.
      // If no file specified, make empty.
      file = arr[1] ? arr[1].replace(/\s/g, '') : undefined;

      // Assume max if "to" isn't present.
      is_range = arr_0.match('to');

      // If it's a range, split left/right sides of "to",
      // and then convert each one into numerical values.
      // If it's not a range, turn maximum into a number.
      val_1 = is_range ? parseInt(arr_0.split('to')[0], 10) : parseInt(arr_0, 10);
      val_2 = is_range ? parseInt(arr_0.split('to')[1], 10) : undefined;

      // Check for maxiumum or range.
      if ((!val_2 && i === last && width > val_1) || (width > val_1 && width <= val_2)) {
        // Build full URL to CSS file.
        file && (url = path + file);

        // Exit the while loop. No need to continue
        // if we've already found a matching range.
        break;
      }
    }

    // Was it created yet?
    if (!url_old) {
      // Apply changes.
      change(i, width);

      // Add the CSS, only if path is defined.
      // Use faster document.head if possible.
      path && (d.head || d.getElementsByTagName('head')[0]).appendChild(css);
    }
    else if (url_old !== url) {
      // Apply changes.
      change(i, width);
    }
  }

  // Fire off once.
  adapt();

  // Slight delay.
  function react() {
    // Clear the timer as window resize fires,
    // so that it only calls adapt() when the
    // user has finished resizing the window.
    clearTimeout(timer);

    // Start the timer countdown.
    timer = setTimeout(adapt, 16);
    // -----------------------^^
    // Note: 15.6 milliseconds is lowest "safe"
    // duration for setTimeout and setInterval.
    //
    // http://www.nczonline.net/blog/2011/12/14/timer-resolution-in-browsers
  }

  // Do we want to watch for
  // resize and device tilt?
  if (config.dynamic) {
    // Event listener for window resize,
    // also triggered by phone rotation.
    if (w.addEventListener) {
      // Good browsers.
      w.addEventListener('resize', react, false);
    }
    else if (w.attachEvent) {
      // Legacy IE support.
      w.attachEvent('onresize', react);
    }
    else {
      // Old-school fallback.
      w.onresize = react;
    }
  }

// Pass in window, document, config, undefined.
})(this, this.document, ADAPT_CONFIG);


text:
package org.apache.flink.table.runtime.generated;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.configuration.Configuration;

/** Describes a generated {@link NamespaceAggsHandleFunction}. */
public class GeneratedNamespaceAggsHandleFunction<N>
        extends GeneratedClass<NamespaceAggsHandleFunction<N>> {

    private static final long serialVersionUID = 2L;

    @VisibleForTesting
    public GeneratedNamespaceAggsHandleFunction(
            String className, String code, Object[] references) {
        super(className, code, references, new Configuration());
    }

    public GeneratedNamespaceAggsHandleFunction(
            String className, String code, Object[] references, Configuration conf) {
        super(className, code, references, conf);
    }
}


text: A Perl language documentation website built with the latest front-end best practices and APIs.


text:
package com.github.lukaszkusek.roulette.rest;

import cz.jirutka.spring.exhandler.RestHandlerExceptionResolver;
import cz.jirutka.spring.exhandler.support.HttpMessageConverterUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import java.util.List;

@Configuration
public class RouletteApplicationConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(exceptionHandlerExceptionResolver());
        resolvers.add(restExceptionResolver());
    }

    @Bean
    public RestHandlerExceptionResolver restExceptionResolver() {
        return RestHandlerExceptionResolver.builder()
                .defaultContentType(MediaType.APPLICATION_JSON)
                .addErrorMessageHandler(HttpMessageNotReadableException.class, HttpStatus.BAD_REQUEST)
                .build();
    }

    @Bean
    public ExceptionHandlerExceptionResolver exceptionHandlerExceptionResolver() {
        ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver();
        resolver.setMessageConverters(HttpMessageConverterUtils.getDefaultHttpMessageConverters());
        return resolver;
    }
}


text:
import gov.nih.nci.system.applicationservice.*;
import java.util.*;

import gov.nih.nci.cabio.domain.*;
import gov.nih.nci.cabio.domain.impl.*;
import gov.nih.nci.common.util.*;
import gov.nih.nci.system.comm.client.*;
import org.hibernate.criterion.*;

/**
	* TestClient.java demonstartes various ways to execute searches with and without
    * using Application Service Layer (convenience layer that abstracts building criteria
    * Uncomment different scenarios below to demonstrate the various types of searches
*/

public class TestSecurity {

    public static void main(String[] args) {

		System.out.println("*** Test Secured Client...");

		try{

			ClientSession session = ClientSession.getInstance();
			session.startSession("userId", "password");
			ApplicationService appService = ApplicationServiceProvider.getApplicationService();

			try {

				System.out.println("Retrieving all genes based on symbol=IL*");
				Gene gene = new GeneImpl();
				gene.setSymbol("IL*");

				try {
					List resultList = appService.search(Gene.class, gene);
					for (Iterator resultsIterator = resultList.iterator(); resultsIterator.hasNext();) {
						Gene returnedGene = (Gene) resultsIterator.next();
						System.out.println(
							"Symbol: " + returnedGene.getSymbol() + "\n" +
							"\tTaxon:" + returnedGene.getTaxon().getScientificName() + "\n" +
							"\tName " + returnedGene.getTitle() + "\n" +
							"");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} catch (RuntimeException e2) {
				e2.printStackTrace();
			}
		}
		catch(Exception ex){
			ex.printStackTrace();
			System.out.println("Test client throws Exception = "+ ex);
		}

	}
}