text:
import java.util.ArrayList;
import java.util.List;

import java.util.HashMap;
import spark.ModelAndView;
import spark.template.velocity.VelocityTemplateEngine;
import static spark.Spark.*;

public class App {
  public static void main(String[] args) {
    staticFileLocation("/public");
    String layout = "templates/layout.vtl";

    get("/", (request, response) -> {
      HashMap<String, Object> model = new HashMap<String, Object>();
      model.put("template", "templates/index.vtl");
      return new ModelAndView(model, layout);
    }, new VelocityTemplateEngine());

// READ ALL STORES

    get("/stores", (request, response) -> {
      HashMap<String, Object> model = new HashMap<String, Object>();
      model.put("stores", Store.all());
      model.put("template", "templates/stores.vtl");
      return new ModelAndView(model, layout);
    }, new VelocityTemplateEngine());

// CREATE NEW STORE

    post("/stores", (request, response) -> {
      HashMap<String, Object> model = new HashMap<String, Object>();
      Store store = new Store(request.queryParams("store-name"));
      store.save();
      model.put("store", store);
      response.redirect("/");
      return null;
    });

// DELETE A STORE

    post("/stores/delete", (request, response) -> {
      Store store = Store.find(Integer.parseInt(request.queryParams("id")));
      store.delete();
      response.redirect("/stores");
      return null;
    });

// READ SINGULAR STORE

    get("/store/:id", (request, response) -> {
      HashMap<String, Object> model = new HashMap<String, Object>();
      model.put("store", Store.find(Integer.parseInt(request.params(":id"))));
      model.put("brands", Brand.all());
      model.put("template", "templates/store.vtl");
      return new ModelAndView(model, layout);
    }, new VelocityTemplateEngine());

// UPDATE STORE

    post("/store/:id", (request, response) -> {
      Store store = Store.find(Integer.parseInt(request.params("id")));
      String newName = request.queryParams("new-name");
      store.update(newName);
      response.redirect("/store/" + store.getId());
      return null;
    });

// ADD A BRAND TO STORE

    post("/store/:id/add-brand", (request, response) -> {
      Store store = Store.find(Integer.parseInt(request.queryParams("store-id")));
      store.addBrand(Integer.parseInt(request.queryParams("add-brand")));
      response.redirect("/store/" + store.getId());
      return null;
    });

// TO-DO Remove a brand from a store using Brand.removeBrand() method

// READ ALL BRANDS

    get("/brands", (request, response) -> {
      HashMap<String, Object> model = new HashMap<String, Object>();
      model.put("brands", Brand.all());
      model.put("template", "templates/brands.vtl");
      return new ModelAndView(model, layout);
    }, new VelocityTemplateEngine());

// CREATE BRAND

    post("/brands", (request, response) -> {
      HashMap<String, Object> model = new HashMap<String, Object>();
      Brand brand = new Brand(request.queryParams("brand-name"));
      brand.save();
      model.put("brand", brand);
      response.redirect("/");
      return null;
    });

// READ SINGULAR BRAND

    get("/brand/:id", (request, response) -> {
      HashMap<String, Object> model = new HashMap<String, Object>();
      model.put("brand", Brand.find(Integer.parseInt(request.params(":id"))));
      model.put("stores", Store.all());
      model.put("template", "templates/brand.vtl");
      return new ModelAndView(model, layout);
    }, new VelocityTemplateEngine());

// ADD A STORE TO A BRAND

    post("/brand/:id/add-store", (request, response) -> {
      Brand brand = Brand.find(Integer.parseInt(request.queryParams("brand-id")));
      brand.addStore(Integer.parseInt(request.queryParams("add-store")));
      response.redirect("/brand/" +brand.getId());
      return null;
    });

  }
}


text:
/**
 * AnotherFSM is yet another implementation of state machines,
 * a library for Java programming language.
 *
 *
Features

 *
 *

 *
Deterministic state machine, optionally with timeouts.

 *
Global and local listeners of transitions and state enter/exit.

 *
Type-based and equals-based event preprocessors.

 *
Predefined and user defined events.

 *
Separated state machine building, registration of listeners and processing of events.

 *
Support for Qfsm graphical design tool with code generation.

 *
Generalized logging, whatever backend can be injected.

 *
Suitable for event driven development.

 *
Well-designed API, fully documented code, unit tests with high coverage.

 *
Apache 2 license, version 2.0.

 *

 *
 * @author Michal Turek
 */
package net.sourceforge.anotherfsm;

redpajama_set_name: RedPajamaGithub


text:
package knorxx.framework.gettingstarted.client.page;

import knorxx.framework.generator.web.client.WebPage;
import org.springframework.stereotype.Component;
import static org.stjs.javascript.Global.alert;
import org.stjs.javascript.dom.Element;
import org.stjs.javascript.jquery.Event;
import static org.stjs.javascript.jquery.GlobalJQueryUI.$;
import org.stjs.javascript.jquery.JQuery;
import org.stjs.javascript.jquery.plugins.ButtonOptions;

/**
 *
 * @author sj
 */
@Component
public class GettingStartedWebPage extends WebPage {

	@Override
	public void render() {
		ButtonOptions buttonOptions = new ButtonOptions();
		buttonOptions.label = "Click me";

		$(CONTAINER_ID)
			.append((JQuery) $("
I'm a Knorxx Framework application!
"))
			.append($("
").button(buttonOptions).click((Event event, Element elmnt) -> {
				alert("Hello Knorxx!");
				return true;
			}));
	}
}


text:
#include <cstdio>
#include <cstring>
#include <cerrno>

#include <mosquitto.h>

#include "Client.hh"

static void s_init() {
  static bool bFirst = true;

  if (bFirst) {
    bFirst = false;
    mosquitto_lib_init();
  }
}

Client::Client(const char * client_id, bool verbose) :
  m_cs(cs_NoConnection),
  m_broker("127.0.0.1"),
  m_port(1883),
  m_mid(0),
  m_keepalive(60),
  m_qos(0),
  m_retain(false),
  m_verbose(verbose)
{
  s_init();
  m_M = mosquitto_new(client_id, true, this);
}

Client::~Client() {
  disconnect();
  mosquitto_destroy(m_M);
}

void Client::s_on_connect(struct mosquitto * M, void * user_data, int rc) {
  Client * C = reinterpret_cast<Client *>(user_data);

  if (!rc) {
    if (C->verbose())
      fprintf(stdout, "client: connect: success\n");
    C->m_cs = cs_Connected;
    C->setup();
  } else {
    if (C->verbose())
      fprintf(stdout, "client: connect: failed (%d)\n", rc);
    C->m_cs = cs_NoConnection;
  }
}

bool Client::connect() {
  mosquitto_connect_callback_set(m_M, Client::s_on_connect);
  mosquitto_disconnect_callback_set(m_M, Client::s_on_disconnect);
  mosquitto_subscribe_callback_set(m_M, Client::s_on_subscribe);
  mosquitto_message_callback_set(m_M, Client::s_on_message);

  if (m_cs != cs_NoConnection) {
    return false;
  }

  int result = mosquitto_connect(m_M, m_broker, m_port, m_keepalive);
  if (result == MOSQ_ERR_SUCCESS) {
    m_cs = cs_Connecting;
    return true;
  } else if (result == MOSQ_ERR_ERRNO) {
    if (verbose())
      fprintf(stdout, "client: connect[%s:%d]: error (%s)\n", m_broker, m_port, strerror(errno));
    return false;
  } else {
    if (verbose())
      fprintf(stdout, "client: connect: error (%d)\n", result);
    return false;
  }
}

void Client::s_on_disconnect(struct mosquitto * M, void * user_data, int rc) {
  Client * C = reinterpret_cast<Client *>(user_data);
  if (C->verbose())
    fprintf(stdout, "client: disconnected (%d)\n", rc);
  C->m_cs = cs_NoConnection;
}

void Client::disconnect() {
  m_cs = cs_Disconnecting;
  mosquitto_disconnect(m_M);
}

void Client::s_on_publish(struct mosquitto * M, void * user_data, int mid) {
  Client * C = reinterpret_cast<Client *>(user_data);
  if (C->verbose())
    fprintf(stdout, "client: %d published\n", mid);
}

bool Client::publish(const char * topic, const char * message) {
  mosquitto_publish_callback_set(m_M, Client::s_on_publish);

  m_mid = 0;
  if (mosquitto_publish(m_M, &m_mid, topic, strlen(message), message, m_qos, m_retain) == MOSQ_ERR_SUCCESS) {
    if (verbose())
      fprintf(stdout, "client: %d publishing...\n", m_mid);
    return true;
  } else {
    return false;
  }
}

void Client::message(const char * topic, const char * message, int length) {
  // ...
}

void Client::s_on_message(struct mosquitto * M, void * user_data, const struct mosquitto_message * message) {
  Client * C = reinterpret_cast<Client *>(user_data);
  if (C->verbose())
    fprintf(stdout, "client: message received on topic %s\n", message->topic);
  C->message(message->topic, reinterpret_cast<const char *>(message->payload), message->payloadlen);
}

void Client::s_on_subscribe(struct mosquitto * M, void * user_data, int mid, int qos_count, const int * granted_qos) {
  Client * C = reinterpret_cast<Client *>(user_data);
  if (C->verbose())
    fprintf(stdout, "client: %d subscribed (%d)\n", mid, qos_count);
}

bool Client::subscribe(const char * pattern) {
  bool success = true;

  m_mid = 0;
  if (mosquitto_subscribe(m_M, &m_mid, pattern, m_qos) == MOSQ_ERR_SUCCESS) {
    if (verbose())
      fprintf(stdout, "Client: %d subscribing...\n", m_mid);
  } else {
    if (verbose())
      fprintf(stdout, "Client: %d subscribe failed...\n", m_mid);
    success = false;
  }
  return success;
}

void Client::setup() {
  // ...
}

void Client::tick() {
  mosquitto_loop(m_M, 0, 1);

  Ticker::tick();
}

void Client::second() {
  if (!connected()) {
    if (!connecting()) {
      connect();
    }
  }
}


text:
module Azure::DevTestLabs::Mgmt::V2018_09_15
  module Models
    #
    # A custom image.
    #
    class CustomImageFragment < UpdateResource

      include MsRestAzure

      # @return [CustomImagePropertiesFromVmFragment] The virtual machine from
      # which the image is to be created.
      attr_accessor :vm

      # @return [CustomImagePropertiesCustomFragment] The VHD from which the
      # image is to be created.
      attr_accessor :vhd

      # @return [String] The description of the custom image.
      attr_accessor :description

      # @return [String] The author of the custom image.
      attr_accessor :author

      # @return [String] The Managed Image Id backing the custom image.
      attr_accessor :managed_image_id

      # @return [String] The Managed Snapshot Id backing the custom image.
      attr_accessor :managed_snapshot_id

      # @return [Array<DataDiskStorageTypeInfoFragment>] Storage information
      # about the data disks present in the custom image
      attr_accessor :data_disk_storage_info

      # @return [CustomImagePropertiesFromPlanFragment] Storage information
      # about the plan related to this custom image
      attr_accessor :custom_image_plan

      # @return [Boolean] Whether or not the custom images underlying
      # offer/plan has been enabled for programmatic deployment
      attr_accessor :is_plan_authorized

      #
      # Mapper for CustomImageFragment class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'CustomImageFragment',
          type: {
            name: 'Composite',
            class_name: 'CustomImageFragment',
            model_properties: {
              tags: {
                client_side_validation: true,
                required: false,
                serialized_name: 'tags',
                type: {
                  name: 'Dictionary',
                  value: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'StringElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              },
              vm: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.vm',
                type: {
                  name: 'Composite',
                  class_name: 'CustomImagePropertiesFromVmFragment'
                }
              },
              vhd: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.vhd',
                type: {
                  name: 'Composite',
                  class_name: 'CustomImagePropertiesCustomFragment'
                }
              },
              description: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.description',
                type: {
                  name: 'String'
                }
              },
              author: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.author',
                type: {
                  name: 'String'
                }
              },
              managed_image_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.managedImageId',
                type: {
                  name: 'String'
                }
              },
              managed_snapshot_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.managedSnapshotId',
                type: {
                  name: 'String'
                }
              },
              data_disk_storage_info: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.dataDiskStorageInfo',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'DataDiskStorageTypeInfoFragmentElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'DataDiskStorageTypeInfoFragment'
                      }
                  }
                }
              },
              custom_image_plan: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.customImagePlan',
                type: {
                  name: 'Composite',
                  class_name: 'CustomImagePropertiesFromPlanFragment'
                }
              },
              is_plan_authorized: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.isPlanAuthorized',
                type: {
                  name: 'Boolean'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>GS Maheswari on Reflections</title>
    <link>http://blog.shiv.me/tags/gs-maheswari/</link>
    <description>Recent content in GS Maheswari on Reflections</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <copyright>Copyright 2016 &copy; Shivanand Velmurugan</copyright>
    <lastBuildDate>Sun, 25 May 2008 00:00:00 +0000</lastBuildDate><atom:link href="http://blog.shiv.me/tags/gs-maheswari/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>So long and thanks for all the good times</title>
      <link>http://blog.shiv.me/2008/05/25/so-long-and-thanks-for-all-the-good-times/</link>
      <pubDate>Sun, 25 May 2008 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2008/05/25/so-long-and-thanks-for-all-the-good-times/</guid>
      <description>I have been away from the internet for most of the last week. There are only a few things that can keep me away from spending hours reading feeds or uploading pictures, and when those things do happen, it is not very pleasant.
Last week I lost yet another wonderful person from my life. I lost my father-in-law, Mr. Ghanshyam Maheswari. He was a good man, a good soul, a great father, and most of all, someone who lived his life - truly lived every moment of it.</description>
    </item>

  </channel>
</rss>


text:
xDirect3DVertexDeclaration9::xDirect3DVertexDeclaration9( IDirect3DVertexDeclaration9* decl ):xDirect3DResourceBase(eDRT_VertexDeclaration, (res_index)this, (res_index)decl)
{
	m_decl = decl;
}

STDMETHODIMP xDirect3DVertexDeclaration9::QueryInterface( THIS_ REFIID riid, void** ppvObj )
{
	STDMETHODIMP hr;
	hr = m_decl->QueryInterface( riid, ppvObj );
	CHECKCALL(hr, __FUNCTION__);
	return hr;
}

STDMETHODIMP xDirect3DVertexDeclaration9::GetDevice( THIS_ IDirect3DDevice9** ppDevice )
{
	STDMETHODIMP hr;
	hr = m_decl->GetDevice( ppDevice );
	CHECKCALL(hr, __FUNCTION__);
	return hr;
}

STDMETHODIMP xDirect3DVertexDeclaration9::GetDeclaration( THIS_ D3DVERTEXELEMENT9* pElement,UINT* pNumElements )
{
	STDMETHODIMP hr;
	hr = m_decl->GetDeclaration( pElement, pNumElements );
	CHECKCALL(hr, __FUNCTION__);
	return hr;
}

ULONG xDirect3DVertexDeclaration9::Release( THIS )
{
	ULONG hr;
	hr = m_decl->Release(   );
	if (hr == 0)
	{
		delete this;
	}
	return hr;
}

ULONG xDirect3DVertexDeclaration9::AddRef( THIS )
{
	ULONG hr;
	hr = m_decl->AddRef(   );
	return hr;
}


text:
'''
Tests for functions in util.py
'''

from scaper.util import _close_temp_files
from scaper.util import _set_temp_logging_level
from scaper.util import _validate_folder_path
from scaper.util import _get_sorted_files
from scaper.util import _populate_label_list
from scaper.util import _sample_trunc_norm, _sample_choose, _sample_choose_weighted
from scaper.util import max_polyphony
from scaper.util import polyphony_gini
from scaper.util import is_real_number, is_real_array
from scaper.util import _check_random_state
from scaper.scaper_exceptions import ScaperError
from scaper.scaper_warnings import ScaperWarning
import tempfile
import os
import logging
import pytest
import shutil
import numpy as np
from scipy.stats import truncnorm
import jams
from scaper.core import EventSpec
from scaper import Scaper

# FIXTURES
BG_PATH = 'tests/data/audio/background/'
FG_PATH = 'tests/data/audio/foreground/'
FG_PATH_HUMANVOICE = 'tests/data/audio/foreground/human_voice'

FG_LABEL_LIST = ['car_horn', 'human_voice', 'siren']
HUMANVOICE_FILES = (
    [os.path.join(FG_PATH_HUMANVOICE,
                  '42-Human-Vocal-Voice-all-aboard_edit.wav'),
     os.path.join(FG_PATH_HUMANVOICE, '42-Human-Vocal-Voice-taxi-1_edit.wav'),
     os.path.join(FG_PATH_HUMANVOICE, '42-Human-Vocal-Voice-taxi-2_edit.wav')])
SIREN_FILE = os.path.join(FG_PATH, 'siren', '69-Siren-1.wav')

def test_close_temp_files():
    '''
    Create a bunch of temp files and then make sure they've been closed and
    deleted.

    '''
    # With delete=True
    tmpfiles = []
    with _close_temp_files(tmpfiles):
        for _ in range(5):
            tmpfiles.append(
                tempfile.NamedTemporaryFile(suffix='.wav', delete=True))

    for tf in tmpfiles:
        assert tf.file.closed
        assert not os.path.isfile(tf.name)

    # With delete=False
    tmpfiles = []
    with _close_temp_files(tmpfiles):
        for _ in range(5):
            tmpfiles.append(
                tempfile.NamedTemporaryFile(suffix='.wav', delete=False))

    for tf in tmpfiles:
        assert tf.file.closed
        assert not os.path.isfile(tf.name)

    # with an exception before exiting
    try:
        tmpfiles = []
        with _close_temp_files(tmpfiles):
            tmpfiles.append(
                tempfile.NamedTemporaryFile(suffix='.wav', delete=True))
            raise ScaperError
    except ScaperError:
        for tf in tmpfiles:
            assert tf.file.closed
            assert not os.path.isfile(tf.name)
    else:
        assert False, 'Exception was not reraised.'

def test_set_temp_logging_level():
    '''
    Ensure temp logging level is set as expected

    '''
    logger = logging.getLogger()
    logger.setLevel('DEBUG')
    with _set_temp_logging_level('CRITICAL'):
        assert logging.getLevelName(logger.level) == 'CRITICAL'
    assert logging.getLevelName(logger.level) == 'DEBUG'

def test_get_sorted_files():
    '''
    Ensure files are returned in expected order.

    '''
    assert _get_sorted_files(FG_PATH_HUMANVOICE) == HUMANVOICE_FILES

def test_validate_folder_path():
    '''
    Make sure invalid folder paths are caught

    '''
    # bad folder path
    pytest.raises(ScaperError, _validate_folder_path,
                  '/path/to/invalid/folder/')

    # good folder path should raise no error
    # make temp folder
    tmpdir = tempfile.mkdtemp()
    # validate
    _validate_folder_path(tmpdir)
    # remove it
    shutil.rmtree(tmpdir)

def test_populate_label_list():
    '''
    Should add folder names contained within provided folder to provided list.

    '''
    labellist = []
    _populate_label_list(FG_PATH, labellist)
    assert sorted(labellist) == sorted(FG_LABEL_LIST)

def test_check_random_state():
    # seed is None
    rng_type = type(np.random.RandomState(10))
    rng = _check_random_state(None)
    assert type(rng) == rng_type

    # seed is int
    rng = _check_random_state(10)
    assert type(rng) == rng_type

    # seed is RandomState
    rng_test = np.random.RandomState(10)
    rng = _check_random_state(rng_test)
    assert type(rng) == rng_type

    # seed is none of the above : error
    pytest.raises(ValueError, _check_random_state, 'random')

def test_sample_choose():
    # using choose with duplicates will issue a warning
    rng = _check_random_state(0)
    pytest.warns(ScaperWarning, _sample_choose, [0, 1, 2, 2, 2], rng)

def test_sample_choose_weighted():
    # make sure probabilities are factored in
    rng = _check_random_state(0)
    assert _sample_choose_weighted([0, 1, 2], [1, 0, 0], rng) == 0
    assert _sample_choose_weighted([0, 1, 2], [0, 1, 0], rng) == 1
    assert _sample_choose_weighted([0, 1, 2], [0, 0, 1], rng) == 2

    samples = []
    for _ in range(100000):
        samples.append(_sample_choose_weighted([0, 1], [0.3, 0.7], rng))

    samples = np.asarray(samples)
    zero_ratio = (samples == 0).sum() / len(samples)
    one_ratio = (samples == 1).sum() / len(samples)
    assert np.allclose(zero_ratio, 0.3, atol=1e-2)
    assert np.allclose(one_ratio, 0.7, atol=1e-2)

def test_sample_trunc_norm():
    '''
    Should return values from a truncated normal distribution.

    '''
    rng = _check_random_state(0)
    # sample values from a distribution
    mu, sigma, trunc_min, trunc_max = 2, 1, 0, 5
    x = [_sample_trunc_norm(mu, sigma, trunc_min, trunc_max, random_state=rng) for _ in range(100000)]
    x = np.asarray(x)

    # simple check: values must be within truncated bounds
    assert (x >= trunc_min).all() and (x <= trunc_max).all()

    # trickier check: values must approximate distribution's PDF
    hist, bins = np.histogram(x, bins=np.arange(0, 10.1, 0.2), density=True)
    xticks = bins[:-1] + 0.1
    a, b = (trunc_min - mu) / float(sigma), (trunc_max - mu) / float(sigma)
    trunc_closed = truncnorm.pdf(xticks, a, b, mu, sigma)
    assert np.allclose(hist, trunc_closed, atol=0.015)

def test_max_polyphony():
    '''
    Test the computation of polyphony of a scaper soundscape instantiation.

    '''
    def __create_annotation_with_overlapping_events(n_events):

        ann = jams.Annotation(namespace='scaper')
        ann.duration = n_events / 2. + 10

        for ind in range(n_events):
            instantiated_event = EventSpec(label='siren',
                                           source_file='/the/source/file.wav',
                                           source_time=0,
                                           event_time=ind / 2.,
                                           event_duration=10,
                                           snr=0,
                                           role='foreground',
                                           pitch_shift=None,
                                           time_stretch=None)

            ann.append(time=ind / 2.,
                       duration=10,
                       value=instantiated_event._asdict(),
                       confidence=1.0)

        return ann

    def __create_annotation_without_overlapping_events(n_events):

        ann = jams.Annotation(namespace='scaper')
        ann.duration = n_events * 10

        for ind in range(n_events):
            instantiated_event = EventSpec(label='siren',
                                           source_file='/the/source/file.wav',
                                           source_time=0,
                                           event_time=ind * 10,
                                           event_duration=5,
                                           snr=0,
                                           role='foreground',
                                           pitch_shift=None,
                                           time_stretch=None)

            ann.append(time=ind * 10,
                       duration=5,
                       value=instantiated_event._asdict(),
                       confidence=1.0)

        return ann

    # 0 through 10 overlapping events
    for poly in range(11):
        ann = __create_annotation_with_overlapping_events(poly)
        est_poly = max_polyphony(ann)
        assert est_poly == poly

    # 1 through 10 NON-overlapping events
    for n_events in range(1, 11):
        ann = __create_annotation_without_overlapping_events(n_events)
        est_poly = max_polyphony(ann)
        assert est_poly == 1

def test_polyphony_gini():
    '''
    Test computation of polyphony gini
    '''

    # Annotation must have namespace scaper, otherwise raise error
    ann = jams.Annotation('tag_open', duration=10)
    gini = pytest.raises(ScaperError, polyphony_gini, ann)

    # Annotation without duration set should raise error
    ann = jams.Annotation('scaper', duration=None)
    gini = pytest.raises(ScaperError, polyphony_gini, ann)

    # Annotation with no foreground events returns a gini of 0
    sc = Scaper(10.0, FG_PATH, BG_PATH)

    # add background
    sc.add_background(label=('choose', []),
                      source_file=('choose', []),
                      source_time=('const', 0))
    jam = sc._instantiate()
    ann = jam.annotations[0]
    gini = polyphony_gini(ann)
    assert gini == 0

    def __test_gini_from_event_times(event_time_list, expected_gini,
                                     hop_size=0.01):

        print(event_time_list)

        # create scaper
        sc = Scaper(10.0, FG_PATH, BG_PATH)

        # add background
        sc.add_background(label=('choose', []),
                          source_file=('choose', []),
                          source_time=('const', 0))

        # add foreground events based on the event time list
        # always use siren file since it is 26 s long, so we can choose the
        # event duration flexibly
        for onset, offset in event_time_list:

            sc.add_event(label=('const', 'siren'),
                         source_file=('const', SIREN_FILE),
                         source_time=('const', 0),
                         event_time=('const', onset),
                         event_duration=('const', offset - onset),
                         snr=('uniform', 6, 30),
                         pitch_shift=('uniform', -3, 3),
                         time_stretch=None)

        jam = sc._instantiate()
        ann = jam.annotations[0]
        gini = polyphony_gini(ann, hop_size=hop_size)
        print(gini, expected_gini)
        assert np.allclose([gini], [expected_gini], atol=1e-5)

    event_time_lists = ([
        [],
        [(0, 1)],
        [(0, 5), (5, 10)],
        [(0, 10), (3, 7), (4, 6)]
    ])

    expected_ginis = [0, 0.1, 1, 0.75]

    for etl, g in zip(event_time_lists, expected_ginis):
        __test_gini_from_event_times(etl, g, hop_size=0.01)

    for etl, g in zip(event_time_lists, expected_ginis):
        __test_gini_from_event_times(etl, g, hop_size=1.0)

def test_is_real_number():

    non_reals = [None, 1j, 'yes']
    yes_reals = [-1e12, -1, -1.0, 0, 1, 1.0, 1e12]

    # test single value
    for nr in non_reals:
        assert not is_real_number(nr)
    for yr in yes_reals:
        assert is_real_number(yr)

def test_is_real_array():

    non_reals = [None, 1j, 'yes']
    yes_reals = [-1e12, -1, -1.0, 0, 1, 1.0, 1e12]

    # non-list non-array types must return false
    for x in non_reals + yes_reals:
        assert not is_real_array(x)

    # test array
    for nr in non_reals:
        assert not is_real_array([nr])
    for yr in yes_reals:
        assert is_real_array([yr])


text:
package raza;

import personaje.Personaje;

public class PersonajePrueba extends Personaje{
	/**
	 * Personaje de prueba, tiene todos los atributos en 0
	 * y las defensas tambien en 0.
	 * salud 120 y energia 100.
	 * ataque de 15.
	 * @param nombre
	 */
	public PersonajePrueba(String nombre) {
		super(nombre);
		this.sprite = "pelado"; // Por ahora asi.
		this.ataqueFisico = 15;
		this.energiaBase = 100;
		this.saludBase = 120;
		this.defensaFisica = 0;
		this.defensaMagica = 0;
		this.saludActual = calcularSaludTotal();
		this.energiaActual = calcularEnergiaTotal();
	}
	public PersonajePrueba() {
		super();
	}
	@Override
	public  int calcularSaludTotal(){
		return saludBase+getVitalidad()*4; // cada 5 puntos da 20 de vida.
	}
	@Override
	public int calcularEnergiaTotal(){
		return energiaBase+getDestreza()*2; // cada 5 puntos da 10 de energia.
	}
}


text:
An Angular range slider with accessibility. It only supports horizontal mode with one handle. As for now I'm not going to implement vertical mode or two handles as I don't need them.

This should work in IE9+ (And ofc any real browser like Chrome or FF). Also tested on iOS and Android 4.4 & 6

## Demo
[On CodePen](http://codepen.io/stofolus/pen/NxrmyM)

## Dependencies
Angular

## What's working:
* Model binding
* Min
* Max
* Step
* Dragging the handle
* Touch supported dragging
* Clicking the bar to goto value
* No need to redraw on hide/show or resize
* Aria attributes for a11y
* Keyboard support for a11y

## Usage
### Javascript

Include the script on the site
```html
<script src="./distribute/slider.js"></script>
```

Add the `chasselberg.slider` module to your Angular app
```javascript
    angular.module('your.ng.app', ['chasselberg.slider']);
```
Add sliders to your views
```html
    <slider model="sliderValue" step="2" min="0" max="100"></slider>
```

### SCSS
Include the `slider.scss` in your main SCSS file using
```scss
    @import "slider.scss"
```
You can define the following variables BEFORE you include `slider.scss`
```scss
$ch-slider-bar-height: 10px;
$ch-slider-bar-radius: 10px;
$ch-slider-bar-color: grey;

$ch-slider-handle-height: 20px;
$ch-slider-handle-width: 20px;
$ch-slider-handle-color: blue;
$ch-slider-handle-radius: 9999px;

$ch-slider-fill-color: green;
$ch-slider-disabled-color: grey;
$ch-slider-disabled-fill-color: black;
```

### CSS
If you don't want to use the SCSS file you can instead include the css file in your HTML
```html
    <link href="./distribute/slider.css" rel="stylesheet">
```


text:
package com.suscipio_solutions.consecro_mud.core.collections;

import java.util.Comparator;
import java.util.TreeMap;

public class CaselessTreeMap<K> extends TreeMap<String,K>
{
	private static final long serialVersionUID = 5949532522375107316L;
	public CaselessTreeMap()
	{
		super(new Comparator<String>()
		{
			@Override
			public int compare(String arg0, String arg1)
			{
				return arg0.compareToIgnoreCase(arg1);
			}
		});
	}
}


text:
package corewar.pit;

public final class PitError extends PitNotification {

	private PitError(int line, String cause, String context, String message) {
		super(Type.ERROR, line, cause, context, message);
	}

	public static PitError create(int line, String cause, String context, String message) {
		return new PitError(line, cause, context, message);
	}

	public static PitError create(String message) {
		return create(-1, "", "", message);
	}

	public static PitError create(int line, String message) {
		return create(line, "", "", message);
	}

	public static PitError createInvalid(int line, String cause, String context, String key) {
		return create(line, cause, context, "Invalid " + key);
	}

	public static PitError createParameterCount(int line, String cause, int expectedCount) {
		return create(line, cause, "",
				"Expected " + expectedCount + " parameter" + (expectedCount > 1 ? "s" : ""));
	}
}


text:
require 'active_support'

require 'reru/sink/operations'
require 'reru/stream'

class Reru::Perform < Reru::Stream
  def initialize(sink, method = nil, &block)
    super(sink)
    @runner = Reru::UnaryRunner.new(method, &block)
  end

  def dispatch(event)
    if event.value?
      @runner.run(event.value)
    end
    super
  end

  module SinkOperations
    extend ActiveSupport::Concern

    included do
      def perform(&block)
        Reru::Perform.new(self, &block)
      end

      def log(prefix = '')
        prefix = prefix + ' ' unless prefix.empty?
        Reru::Perform.new(self) { |x| puts "#{prefix}#{x.inspect}" }
      end

      def write(io = $stdout)
        Reru::Perform.new(self) { |x| io.write(x) }
      end
    end
  end
  Reru::Sink::Operations.send :include, SinkOperations
end


text:
package com.facebook.buck.artifact_cache;

import com.facebook.buck.counters.CounterRegistry;
import com.facebook.buck.counters.IntegerCounter;
import com.facebook.buck.counters.SamplingCounter;
import com.facebook.buck.counters.TagSetCounter;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.io.BorrowablePath;
import com.facebook.buck.io.LazyPath;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.log.Logger;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.util.HumanReadableException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;

/**
 * The {@link DirArtifactCache} and {@link HttpArtifactCache} caches use a straightforward rulekey
 * -> (metadata, artifact) mapping. This works well and is easy to reason about. That also means
 * that we will fetch `artifact` whenever they `key` or `metadata` change possibly resulting in
 * fetching the same artifact multiple times. This class is an attempt at reducing the number of
 * repeated fetches for the same artifact. The data is stored and retrieved using the following
 * scheme: rulekey -> (metadata, content hash) content hash -> artifact This means we only download
 * the artifact when its contents change. This means that rules with different keys but identical
 * outputs require less network bandwidth at the expense of doubling latency for downloading rules
 * whose outputs we had not yet seen.
 */
public class TwoLevelArtifactCacheDecorator implements ArtifactCache, CacheDecorator {

  @VisibleForTesting static final String METADATA_KEY = "TWO_LEVEL_CACHE_CONTENT_HASH";
  private static final String COUNTER_CATEGORY = "buck_two_level_cache_stats";

  private static final Logger LOG = Logger.get(TwoLevelArtifactCacheDecorator.class);

  private final ArtifactCache delegate;
  private final ProjectFilesystem projectFilesystem;
  private final Path emptyFilePath;
  private final boolean performTwoLevelStores;
  private final long minimumTwoLevelStoredArtifactSize;
  private final Optional<Long> maximumTwoLevelStoredArtifactSize;

  private final TagSetCounter secondLevelCacheHitTypes;
  private final SamplingCounter secondLevelCacheHitBytes;
  private final IntegerCounter secondLevelCacheMisses;
  private final SamplingCounter secondLevelHashComputationTimeMs;

  public TwoLevelArtifactCacheDecorator(
      ArtifactCache delegate,
      ProjectFilesystem projectFilesystem,
      BuckEventBus buckEventBus,
      boolean performTwoLevelStores,
      long minimumTwoLevelStoredArtifactSize,
      Optional<Long> maximumTwoLevelStoredArtifactSize) {
    this.delegate = delegate;
    this.projectFilesystem = projectFilesystem;
    this.performTwoLevelStores = performTwoLevelStores;
    this.minimumTwoLevelStoredArtifactSize = minimumTwoLevelStoredArtifactSize;
    this.maximumTwoLevelStoredArtifactSize = maximumTwoLevelStoredArtifactSize;

    Path tmpDir = projectFilesystem.getBuckPaths().getTmpDir();
    try {
      projectFilesystem.mkdirs(tmpDir);
      this.emptyFilePath =
          projectFilesystem.resolve(
              projectFilesystem.createTempFile(tmpDir, ".buckcache", ".empty"));
    } catch (IOException e) {
      throw new HumanReadableException(
          "Could not create file in " + projectFilesystem.resolve(tmpDir));
    }

    secondLevelCacheHitTypes =
        new TagSetCounter(COUNTER_CATEGORY, "second_level_cache_hit_types", ImmutableMap.of());
    secondLevelCacheHitBytes =
        new SamplingCounter(COUNTER_CATEGORY, "second_level_cache_hit_bytes", ImmutableMap.of());
    secondLevelCacheMisses =
        new IntegerCounter(COUNTER_CATEGORY, "second_level_cache_misses", ImmutableMap.of());
    secondLevelHashComputationTimeMs =
        new SamplingCounter(
            COUNTER_CATEGORY, "second_level_hash_computation_time_ms", ImmutableMap.of());
    buckEventBus.post(
        new CounterRegistry.AsyncCounterRegistrationEvent(
            ImmutableSet.of(
                secondLevelCacheHitTypes,
                secondLevelCacheHitBytes,
                secondLevelCacheMisses,
                secondLevelHashComputationTimeMs)));
  }

  @Override
  public ListenableFuture<CacheResult> fetchAsync(RuleKey ruleKey, LazyPath output) {
    return Futures.transformAsync(
        delegate.fetchAsync(ruleKey, output),
        (CacheResult fetchResult) -> {
          if (!fetchResult.getType().isSuccess()) {
            LOG.verbose("Missed first-level lookup.");
            return Futures.immediateFuture(fetchResult);
          } else if (!fetchResult.getMetadata().containsKey(METADATA_KEY)) {
            LOG.verbose("Found a single-level entry.");
            return Futures.immediateFuture(fetchResult);
          }
          LOG.verbose("Found a first-level artifact with metadata: %s", fetchResult.getMetadata());

          String contentHashKey = fetchResult.getMetadata().get(METADATA_KEY);
          ListenableFuture<CacheResult> outputFileFetchResultFuture =
              delegate.fetchAsync(new RuleKey(contentHashKey), output);

          return Futures.transformAsync(
              outputFileFetchResultFuture,
              (CacheResult outputFileFetchResult) -> {
                outputFileFetchResult =
                    outputFileFetchResult.withTwoLevelContentHashKey(contentHashKey);

                if (!outputFileFetchResult.getType().isSuccess()) {
                  LOG.verbose("Missed second-level lookup.");
                  secondLevelCacheMisses.inc();

                  // Note: for misses, the fetchResult metadata is not important, so we return
                  // outputFileFetchResult to signal the miss (as fetchResult was a hit).
                  return Futures.immediateFuture(outputFileFetchResult);
                }

                if (outputFileFetchResult.cacheSource().isPresent()) {
                  secondLevelCacheHitTypes.add(outputFileFetchResult.cacheSource().get());
                }
                if (outputFileFetchResult.artifactSizeBytes().isPresent()) {
                  secondLevelCacheHitBytes.addSample(
                      outputFileFetchResult.artifactSizeBytes().get());
                }

                LOG.verbose(
                    "Found a second-level artifact with metadata: %s",
                    outputFileFetchResult.getMetadata());
                // Note: in the case of a hit, we return fetchResult, rather than outputFileFetchResult,
                // so that the client gets the correct metadata.

                CacheResult finalResult = fetchResult.withTwoLevelContentHashKey(contentHashKey);
                return Futures.immediateFuture(finalResult);
              },
              MoreExecutors.directExecutor());
        },
        MoreExecutors.directExecutor());
  }

  @Override
  public ListenableFuture<Void> store(final ArtifactInfo info, final BorrowablePath output) {

    return Futures.transformAsync(
        attemptTwoLevelStore(info, output),
        input -> {
          if (input) {
            return Futures.immediateFuture(null);
          }
          return delegate.store(info, output);
        });
  }

  @Override
  public ArtifactCache getDelegate() {
    return delegate;
  }

  private ListenableFuture<Boolean> attemptTwoLevelStore(
      final ArtifactInfo info, final BorrowablePath output) {

    return Futures.transformAsync(
        Futures.immediateFuture(null),
        (AsyncFunction<Void, Boolean>)
            input -> {
              long fileSize = projectFilesystem.getFileSize(output.getPath());

              if (!performTwoLevelStores
                  || fileSize < minimumTwoLevelStoredArtifactSize
                  || (maximumTwoLevelStoredArtifactSize.isPresent()
                      && fileSize > maximumTwoLevelStoredArtifactSize.get())) {
                return Futures.immediateFuture(false);
              }

              long hashComputationStart = System.currentTimeMillis();
              String hashCode = projectFilesystem.computeSha1(output.getPath()) + "2c00";
              long hashComputationEnd = System.currentTimeMillis();
              secondLevelHashComputationTimeMs.addSample(hashComputationEnd - hashComputationStart);

              ImmutableMap<String, String> metadataWithCacheKey =
                  ImmutableMap.<String, String>builder()
                      .putAll(info.getMetadata())
                      .put(METADATA_KEY, hashCode)
                      .build();

              return Futures.transform(
                  Futures.allAsList(
                      delegate.store(
                          ArtifactInfo.builder()
                              .setRuleKeys(info.getRuleKeys())
                              .setMetadata(metadataWithCacheKey)
                              .build(),
                          BorrowablePath.notBorrowablePath(emptyFilePath)),
                      delegate.store(
                          ArtifactInfo.builder().addRuleKeys(new RuleKey(hashCode)).build(),
                          output)),
                  Functions.constant(true));
            });
  }

  @Override
  public CacheReadMode getCacheReadMode() {
    return delegate.getCacheReadMode();
  }

  @Override
  public void close() {
    delegate.close();
    try {
      projectFilesystem.deleteFileAtPath(emptyFilePath);
    } catch (IOException e) {
      LOG.debug("Exception when deleting temp file %s.", emptyFilePath, e);
    }
  }
}


text:
from .Gazeta import Gazeta
from .Tass import Tass
from .Lenta import Lenta
from .Vedomosti import Vedomosti
from .Novaya import Novaya
from .Meduza import Meduza


text:
package main

import (
	"errors"
	"net/http"
	"net/url"
	"testing"
	"time"

	"github.com/go-resty/resty"
	"github.com/stretchr/testify/assert"
)

func TestExpirationHandler(t *testing.T) {
	_, idp, svc := newTestProxyService(nil)
	cases := []struct {
		ExpireIn time.Duration
		Expects  int
	}{
		{
			Expects: http.StatusUnauthorized,
		},
		{
			ExpireIn: time.Duration(-24 * time.Hour),
			Expects:  http.StatusUnauthorized,
		},
		{
			ExpireIn: time.Duration(14 * time.Hour),
			Expects:  http.StatusOK,
		},
	}

	for i, c := range cases {
		token := newTestToken(idp.getLocation())
		token.setExpiration(time.Now().Add(c.ExpireIn))
		// sign the token
		signed, _ := idp.signToken(token.claims)
		// make the request
		resp, err := resty.New().SetAuthToken(signed.Encode()).R().Get(svc + oauthURL + expiredURL)
		if !assert.NoError(t, err, "case %d unable to make the request, error: %s", i, err) {
			continue
		}
		assert.Equal(t, c.Expects, resp.StatusCode(), "case %d, expects: %d but got: %d", i, c.Expects, resp.StatusCode())
	}
}

func TestLoginHandlerDisabled(t *testing.T) {
	config := newFakeKeycloakConfig()
	config.EnableLoginHandler = false

	_, _, url := newTestProxyService(config)
	resp, err := resty.DefaultClient.R().Post(url + "/oauth/login")
	assert.NoError(t, err)
	assert.NotNil(t, resp)
	assert.Equal(t, http.StatusNotImplemented, resp.StatusCode())
}

func TestLoginHandlerNotDisabled(t *testing.T) {
	config := newFakeKeycloakConfig()
	config.EnableLoginHandler = true
	_, _, url := newTestProxyService(config)
	resp, err := http.Post(url+"/oauth/login", "", nil)
	assert.NoError(t, err)
	assert.NotNil(t, resp)
	assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}

func TestLoginHandler(t *testing.T) {
	_, _, u := newTestProxyService(nil)

	cs := []struct {
		Username     string
		Password     string
		ExpectedCode int
	}{
		{
			Username:     "",
			Password:     "",
			ExpectedCode: http.StatusBadRequest,
		},
		{
			Username:     "test",
			Password:     "",
			ExpectedCode: http.StatusBadRequest,
		},
		{
			Username:     "",
			Password:     "test",
			ExpectedCode: http.StatusBadRequest,
		},
		{
			Username:     "test",
			Password:     "test",
			ExpectedCode: http.StatusOK,
		},
		{
			Username:     "test",
			Password:     "notmypassword",
			ExpectedCode: http.StatusUnauthorized,
		},
	}

	for i, x := range cs {
		uri := u + oauthURL + loginURL
		values := url.Values{}
		if x.Username != "" {
			values.Add("username", x.Username)
		}
		if x.Password != "" {
			values.Add("password", x.Password)
		}

		resp, err := http.PostForm(uri, values)
		if err != nil {
			t.Errorf("case %d, unable to make requets, error: %s", i, err)
			continue
		}
		assert.Equal(t, x.ExpectedCode, resp.StatusCode, "case %d, expect: %v, got: %d",
			i, x.ExpectedCode, resp.StatusCode)
	}
}

func TestLogoutHandlerBadRequest(t *testing.T) {
	_, _, u := newTestProxyService(nil)

	res, err := http.Get(u + oauthURL + logoutURL)
	assert.NoError(t, err)
	assert.NotNil(t, res)
	assert.Equal(t, res.StatusCode, http.StatusBadRequest)
}

func TestLogoutHandlerBadToken(t *testing.T) {
	u := newTestService()
	req, err := http.NewRequest("GET", u+oauthURL+logoutURL, nil)
	assert.NoError(t, err)
	req.Header.Add("kc-access", "this.is.a.bad.token")
	res, err := http.DefaultTransport.RoundTrip(req)
	assert.NoError(t, err)
	assert.NotNil(t, res)
	assert.Equal(t, http.StatusBadRequest, res.StatusCode)
}

func TestLogoutHandlerGood(t *testing.T) {
	u := newTestService()
	// step: first we login and get a token
	token, err := makeTestOauthLogin(u + "/admin")
	if !assert.NoError(t, err) {
		t.Errorf("failed to perform oauth login, reason: %s", err)
		t.Fail()
	}

	// step: attempt to logout
	res, err := resty.DefaultClient.R().
		SetAuthToken(token).
		Get(u + oauthURL + logoutURL)
	if !assert.NoError(t, err) {
		t.Fail()
	}
	assert.Equal(t, http.StatusOK, res.StatusCode())
}

func TestTokenHandler(t *testing.T) {
	token := newFakeAccessToken(nil, 0)
	svc := newTestService()
	cs := []struct {
		Token    string
		Cookie   string
		Expected int
	}{
		{
			Token:    token.Encode(),
			Expected: http.StatusOK,
		},
		{
			Expected: http.StatusBadRequest,
		},
		{
			Token:    "niothing",
			Expected: http.StatusBadRequest,
		},
		{
			Cookie:   token.Encode(),
			Expected: http.StatusOK,
		},
	}
	requrl := svc + oauthURL + tokenURL
	for _, c := range cs {
		client := resty.New().SetRedirectPolicy(resty.NoRedirectPolicy())
		if c.Token != "" {
			client.SetAuthToken(c.Token)
		}
		if c.Cookie != "" {
			client.SetCookie(&http.Cookie{
				Name:  "kc-access",
				Path:  "/",
				Value: c.Cookie,
			})
		}
		resp, err := client.R().Get(requrl)
		assert.NoError(t, err)
		assert.Equal(t, c.Expected, resp.StatusCode())
	}
}

func TestNoRedirect(t *testing.T) {
	p, _, svc := newTestProxyService(nil)
	p.config.NoRedirects = true

	req, _ := http.NewRequest("GET", svc+"/admin", nil)
	resp, err := http.DefaultTransport.RoundTrip(req)
	assert.NoError(t, err)
	assert.NotNil(t, resp)
	assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)

	p.config.NoRedirects = false
	req, _ = http.NewRequest("GET", svc+"/admin", nil)
	resp, err = http.DefaultTransport.RoundTrip(req)
	assert.NoError(t, err)
	assert.NotNil(t, resp)
	assert.Equal(t, http.StatusTemporaryRedirect, resp.StatusCode)
}

func TestAuthorizationURL(t *testing.T) {
	_, _, u := newTestProxyService(nil)
	client := &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return errors.New("no redirect")
		},
	}
	cs := []struct {
		URL          string
		ExpectedURL  string
		ExpectedCode int
	}{
		{
			URL:          "/",
			ExpectedCode: http.StatusOK,
		},
		{
			URL:          "/admin",
			ExpectedURL:  "/oauth/authorize?state=L2FkbWlu",
			ExpectedCode: http.StatusTemporaryRedirect,
		},
		{
			URL:          "/admin/test",
			ExpectedURL:  "/oauth/authorize?state=L2FkbWluL3Rlc3Q=",
			ExpectedCode: http.StatusTemporaryRedirect,
		},
		{
			URL:          "/admin/../",
			ExpectedURL:  "/oauth/authorize?state=L2FkbWluLy4uLw==",
			ExpectedCode: http.StatusTemporaryRedirect,
		},
		{
			URL:          "/admin?test=yes&test1=test",
			ExpectedURL:  "/oauth/authorize?state=L2FkbWluP3Rlc3Q9eWVzJnRlc3QxPXRlc3Q=",
			ExpectedCode: http.StatusTemporaryRedirect,
		},
	}
	for i, x := range cs {
		resp, _ := client.Get(u + x.URL)
		assert.Equal(t, x.ExpectedCode, resp.StatusCode, "case %d, expect: %v, got: %s", i, x.ExpectedCode, resp.StatusCode)
		assert.Equal(t, x.ExpectedURL, resp.Header.Get("Location"), "case %d, expect: %v, got: %s", i, x.ExpectedURL, resp.Header.Get("Location"))
	}
}

func TestCallbackURL(t *testing.T) {
	_, _, u := newTestProxyService(nil)

	cs := []struct {
		URL         string
		ExpectedURL string
	}{
		{
			URL:         "/oauth/authorize?state=L2FkbWlu",
			ExpectedURL: "/admin",
		},
		{
			URL:         "/oauth/authorize",
			ExpectedURL: "/",
		},
		{
			URL:         "/oauth/authorize?state=L2FkbWluL3Rlc3QxP3Rlc3QxJmhlbGxv",
			ExpectedURL: "/admin/test1?test1&hello",
		},
	}
	for i, x := range cs {
		// step: call the authorization endpoint
		req, err := http.NewRequest("GET", u+x.URL, nil)
		if err != nil {
			continue
		}
		resp, err := http.DefaultTransport.RoundTrip(req)
		if !assert.NoError(t, err, "case %d, should not have failed", i) {
			continue
		}
		openIDURL := resp.Header.Get("Location")
		if !assert.NotEmpty(t, openIDURL, "case %d, the open id redirection url is empty", i) {
			continue
		}
		req, _ = http.NewRequest("GET", openIDURL, nil)
		resp, err = http.DefaultTransport.RoundTrip(req)
		if !assert.NoError(t, err, "case %d, should not have failed calling the opend id url", i) {
			continue
		}
		callbackURL := resp.Header.Get("Location")
		if !assert.NotEmpty(t, callbackURL, "case %d, should have received a callback url", i) {
			continue
		}
		// step: call the callback url
		req, _ = http.NewRequest("GET", callbackURL, nil)
		resp, err = http.DefaultTransport.RoundTrip(req)
		if !assert.NoError(t, err, "case %d, unable to call the callback url", i) {
			continue
		}
		// step: check the callback location is as expected
		assert.Contains(t, resp.Header.Get("Location"), x.ExpectedURL)
	}
}

func TestHealthHandler(t *testing.T) {
	svc := newTestService()
	resp, err := resty.DefaultClient.R().Get(svc + oauthURL + healthURL)
	assert.NoError(t, err)
	assert.Equal(t, http.StatusOK, resp.StatusCode())
	assert.Equal(t, version, resp.Header().Get(versionHeader))
}


text:
package com.dmitrymalkovich.android.githubanalytics.repositories;

import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;

import com.dmitrymalkovich.android.githubanalytics.data.source.GithubDataSource;
import com.dmitrymalkovich.android.githubanalytics.data.source.GithubRepository;
import com.dmitrymalkovich.android.githubanalytics.data.source.local.LoaderProvider;

import org.eclipse.egit.github.core.Repository;

import java.util.List;

public class PublicRepositoryPresenter implements PublicRepositoryContract.Presenter,
        LoaderManager.LoaderCallbacks<Cursor>, GithubRepository.LoadDataCallback {

    private static final int REPOSITORIES_LOADER = 2;
    @SuppressWarnings("unused")
    private static String LOG_TAG = PublicRepositoryPresenter.class.getSimpleName();
    @SuppressWarnings("unused")
    @NonNull
    private final LoaderProvider mLoaderProvider;

    @NonNull
    private final LoaderManager mLoaderManager;

    @NonNull
    private GithubRepository mGithubRepository;

    @NonNull
    private PublicRepositoryContract.View mPublicRepositoriesView;

    public PublicRepositoryPresenter(@NonNull GithubRepository githubRepository,
                                     @NonNull PublicRepositoryContract.View view,
                                     @NonNull LoaderProvider loaderProvider,
                                     @NonNull LoaderManager loaderManager) {
        mGithubRepository = githubRepository;
        mPublicRepositoriesView = view;
        mLoaderProvider = loaderProvider;
        mLoaderManager = loaderManager;
        mPublicRepositoriesView.setPresenter(this);
    }

    @Override
    public void start(Bundle savedInstanceState) {
        mPublicRepositoriesView.setLoadingIndicator(true);
        if (savedInstanceState == null) {
            showRepositories();
            onRefresh();
        } else {
            mLoaderManager.initLoader(REPOSITORIES_LOADER,
                    null,
                    PublicRepositoryPresenter.this);
        }
    }

    @Override
    public void onRefresh() {
        mGithubRepository.getRepositories(new GithubDataSource.GetRepositoriesCallback() {
            @Override
            public void onRepositoriesLoaded(List<Repository> repositoryList) {
                mPublicRepositoriesView.setLoadingIndicator(false);
                mPublicRepositoriesView.setRefreshIndicator(false);
                mLoaderManager.restartLoader(REPOSITORIES_LOADER,
                        null,
                        PublicRepositoryPresenter.this);
            }

            @Override
            public void onDataNotAvailable() {
                PublicRepositoryPresenter.this.onDataNotAvailable(REPOSITORIES_LOADER);
            }
        });
    }

    @Override
    public void onDataLoaded(Cursor data, int id) {
        mPublicRepositoriesView.setLoadingIndicator(false);
        mPublicRepositoriesView.setRefreshIndicator(false);
        mPublicRepositoriesView.showRepositories(data);
    }

    @Override
    public void onDataEmpty(int id) {
        mPublicRepositoriesView.setEmptyState(true);
    }

    @Override
    public void onDataNotAvailable(int id) {
        mPublicRepositoriesView.setLoadingIndicator(false);
        mPublicRepositoriesView.setRefreshIndicator(false);
    }

    @Override
    public void onDataReset() {
        // Nothing to do
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return mLoaderProvider.createRepositoryLoader();
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if (data != null) {
            if (data.moveToLast()) {
                onDataLoaded(data, loader.getId());
            } else {
                onDataEmpty(loader.getId());
            }
        } else {
            onDataNotAvailable(loader.getId());
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        onDataReset();
    }

    private void showRepositories() {
        mLoaderManager.initLoader(REPOSITORIES_LOADER,
                null,
                PublicRepositoryPresenter.this);
    }

    @Override
    public void setPinned(boolean active, long id) {
        mGithubRepository.setPinned(active, id);
    }
}


text:
require 'spec_helper'

describe ApiV1::Admin::Security::RolesController do
  include ApiHeaderSetupTeardown
  include ApiV1::ApiVersionHelper

  before :each do
    @service = double('role_config_service')
    @entity_hashing_service = double('entity_hashing_service')
    allow(controller).to receive(:entity_hashing_service).and_return(@entity_hashing_service)
    allow(controller).to receive(:role_config_service).and_return(@service)
  end

  describe :index do
    describe :security do
      it 'should allow all with security disabled' do
        disable_security

        expect(controller).to allow_action(:get, :index)
      end

      it 'should disallow anonymous users, with security enabled' do
        enable_security
        login_as_anonymous

        expect(controller).to disallow_action(:get, :index).with(401, 'You are not authorized to perform this action.')
      end

      it 'should disallow normal users, with security enabled' do
        enable_security
        login_as_user

        expect(controller).to disallow_action(:get, :index).with(401, 'You are not authorized to perform this action.')
      end

      it 'should allow admin, with security enabled' do
        enable_security
        login_as_admin

        expect(controller).to allow_action(:get, :index)
      end

      it 'should disallow pipeline group admin users, with security enabled' do
        enable_security
        login_as_group_admin
        expect(controller).to disallow_action(:get, :index)
      end
    end

    describe 'admin' do
      before :each do
        enable_security
        login_as_admin
      end

      it 'should list all security auth configs' do
        role = PluginRoleConfig.new('foo', 'ldap')
        expect(@service).to receive(:listAll).and_return([role])

        get_with_api_header :index

        expect(response).to be_ok
        expect(actual_response).to eq(expected_response([role], ApiV1::Security::RolesConfigRepresenter))
      end

      it 'should list roles by type' do
        plugin_role_config = PluginRoleConfig.new('foo', 'ldap')
        gocd_role_config = RoleConfig.new(CaseInsensitiveString.new('bar'))

        expect(@service).to receive(:listAll).and_return([plugin_role_config, gocd_role_config])

        get_with_api_header :index, type: 'plugin'

        expect(response).to be_ok
        expect(actual_response).to eq(expected_response([plugin_role_config], ApiV1::Security::RolesConfigRepresenter))
      end

      it 'should error out if listing roles by a wrong type' do
        get_with_api_header :index, type: 'invalid'

        expect(response).to have_api_message_response(400, 'Bad role type `invalid`. Valid values are `gocd` and `plugin`')
      end
    end

    describe :route do
      describe :with_header do

        it 'should route to index action of controller' do
          expect(:get => 'api/admin/security/roles').to route_to(action: 'index', controller: 'api_v1/admin/security/roles')
        end
      end

      describe :without_header do

        before :each do
          teardown_header
        end

        it 'should not route to index action of controller without header' do
          expect(:get => 'api/admin/security/roles').to_not route_to(action: 'index', controller: 'api_v1/admin/security/roles')
          expect(:get => 'api/admin/security/roles').to route_to(controller: 'application', action: 'unresolved', url: 'api/admin/security/roles')
        end
      end
    end
  end

  describe :show do
    describe :security do
      before :each do
        allow(controller).to receive(:load_entity_from_config).and_return(nil)
      end

      it 'should allow all with security disabled' do
        disable_security

        expect(controller).to allow_action(:get, :show, role_name: 'foo')
      end

      it 'should disallow anonymous users, with security enabled' do
        enable_security
        login_as_anonymous

        expect(controller).to disallow_action(:get, :show, role_name: 'foo').with(401, 'You are not authorized to perform this action.')
      end

      it 'should disallow normal users, with security enabled' do
        enable_security
        login_as_user

        expect(controller).to disallow_action(:get, :show, role_name: 'foo').with(401, 'You are not authorized to perform this action.')
      end

      it 'should allow admin, with security enabled' do
        enable_security
        login_as_admin

        expect(controller).to allow_action(:get, :show, role_name: 'foo')
      end

      it 'should disallow pipeline group admin users, with security enabled' do
        enable_security
        login_as_group_admin
        expect(controller).to disallow_action(:get, :show, role_name: 'foo')
      end
    end

    describe 'admin' do
      before(:each) do
        enable_security
        login_as_admin
        @result = HttpLocalizedOperationResult.new
      end

      it 'should render the security auth config of specified name' do
        role = PluginRoleConfig.new('blackbird', 'ldap')
        expect(@entity_hashing_service).to receive(:md5ForEntity).with(an_instance_of(PluginRoleConfig)).and_return('md5')
        expect(@service).to receive(:findRole).with('blackbird').and_return(role)

        get_with_api_header :show, role_name: 'blackbird'

        expect(response).to be_ok
        expect(actual_response).to eq(expected_response(role, ApiV1::Security::RoleConfigRepresenter))
      end

      it 'should return 404 if the security auth config does not exist' do
        expect(@service).to receive(:findRole).with('non-existent-security-auth-config').and_return(nil)

        get_with_api_header :show, role_name: 'non-existent-security-auth-config'

        expect(response).to have_api_message_response(404, 'Either the resource you requested was not found, or you are not authorized to perform this action.')
      end
    end

    describe :route do
      describe :with_header do

        it 'should route to show action of controller for alphanumeric identifier' do
          expect(:get => 'api/admin/security/roles/foo123').to route_to(action: 'show', controller: 'api_v1/admin/security/roles', role_name: 'foo123')
        end

        it 'should route to show action of controller for identifier with dots' do
          expect(:get => 'api/admin/security/roles/foo.123').to route_to(action: 'show', controller: 'api_v1/admin/security/roles', role_name: 'foo.123')
        end

        it 'should route to show action of controller for identifier with hyphen' do
          expect(:get => 'api/admin/security/roles/foo-123').to route_to(action: 'show', controller: 'api_v1/admin/security/roles', role_name: 'foo-123')
        end

        it 'should route to show action of controller for identifier with underscore' do
          expect(:get => 'api/admin/security/roles/foo_123').to route_to(action: 'show', controller: 'api_v1/admin/security/roles', role_name: 'foo_123')
        end

        it 'should route to show action of controller for capitalized identifier' do
          expect(:get => 'api/admin/security/roles/FOO').to route_to(action: 'show', controller: 'api_v1/admin/security/roles', role_name: 'FOO')
        end
      end
      describe :without_header do
        before :each do
          teardown_header
        end
        it 'should not route to show action of controller without header' do
          expect(:get => 'api/admin/security/roles/foo').to_not route_to(action: 'show', controller: 'api_v1/admin/security/roles')
          expect(:get => 'api/admin/security/roles/foo').to route_to(controller: 'application', action: 'unresolved', url: 'api/admin/security/roles/foo')
        end
      end
    end

  end

  describe :create do
    describe :security do
      before :each do
        allow(@service).to receive(:findRole).with(anything).and_return(nil)
      end

      it 'should allow all with security disabled' do
        disable_security

        expect(controller).to allow_action(:post, :create)
      end

      it 'should disallow anonymous users, with security enabled' do
        enable_security
        login_as_anonymous

        expect(controller).to disallow_action(:post, :create).with(401, 'You are not authorized to perform this action.')
      end

      it 'should disallow normal users, with security enabled' do
        enable_security
        login_as_user

        expect(controller).to disallow_action(:post, :create).with(401, 'You are not authorized to perform this action.')
      end

      it 'should allow admin, with security enabled' do
        enable_security
        login_as_admin

        expect(controller).to allow_action(:post, :create)
      end

      it 'should disallow pipeline group admin users, with security enabled' do
        enable_security
        login_as_group_admin

        expect(controller).to disallow_action(:post, :create)
      end
    end

    describe 'admin' do
      before(:each) do
        enable_security
        login_as_admin
      end

      it 'should deserialize auth config from given parameters' do
        role = PluginRoleConfig.new('blackbird', 'blackbird', ConfigurationPropertyMother.create('foo', false, 'bar'))
        allow(controller).to receive(:etag_for).and_return('some-md5')
        expect(@service).to receive(:findRole).with(anything).and_return(nil)
        expect(@service).to receive(:create).with(anything, an_instance_of(PluginRoleConfig), an_instance_of(HttpLocalizedOperationResult))
        post_with_api_header :create, role: plugin_role_hash

        expect(response).to be_ok
        expect(actual_response).to eq(expected_response(role, ApiV1::Security::RoleConfigRepresenter))
      end

      it 'should fail to save if there are validation errors' do
        result = double('HttpLocalizedOperationResult')
        allow(HttpLocalizedOperationResult).to receive(:new).and_return(result)
        allow(result).to receive(:isSuccessful).and_return(false)
        allow(result).to receive(:message).with(anything()).and_return('Save failed')
        allow(result).to receive(:httpCode).and_return(422)

        expect(@service).to receive(:findRole).with(anything).and_return(nil)
        expect(@service).to receive(:create).with(anything, an_instance_of(RoleConfig), result)

        post_with_api_header :create, role: role_hash

        expect(response).to have_api_message_response(422, 'Save failed')
      end

      it 'should check for existence of role with same name' do
        expect(@service).to receive(:findRole).with('blackbird').and_return(PluginRoleConfig.new)

        post_with_api_header :create, role: role_hash

        expected_role = RoleConfig.new(CaseInsensitiveString.new('blackbird'), RoleUser.new('bob'), RoleUser.new('alice'))
        expected_role.addError('name', 'Role names should be unique. Role with the same name exists.')

        expect(@service).not_to receive(:create)
        expect(actual_response[:data]).to eq(expected_response(expected_role, ApiV1::Security::RoleConfigRepresenter))
        expect(response).to have_api_message_response(422, "Failed to add role. The role 'blackbird' already exists.")
      end
    end

    describe :route do
      describe :with_header do
        it 'should route to create action of controller' do
          expect(:post => 'api/admin/security/roles').to route_to(action: 'create', controller: 'api_v1/admin/security/roles')
        end
      end
      describe :without_header do
        before :each do
          teardown_header
        end
        it 'should not route to create action of controller without header' do
          expect(:post => 'api/admin/security/roles').to_not route_to(action: 'create', controller: 'api_v1/admin/security/roles')
          expect(:post => 'api/admin/security/roles').to route_to(controller: 'application', action: 'unresolved', url: 'api/admin/security/roles')
        end
      end
    end

  end

  describe :update do
    describe :security do
      before :each do
        allow(controller).to receive(:load_entity_from_config).and_return(nil)
        allow(controller).to receive(:check_for_stale_request).and_return(nil)
        allow(controller).to receive(:check_for_attempted_rename).and_return(nil)
      end
      it 'should allow all with security disabled' do
        disable_security
        expect(controller).to allow_action(:put, :update, role_name: 'foo')
      end

      it 'should disallow anonymous users, with security enabled' do
        enable_security
        login_as_anonymous

        expect(controller).to disallow_action(:put, :update, role_name: 'foo').with(401, 'You are not authorized to perform this action.')
      end

      it 'should disallow normal users, with security enabled' do
        login_as_user
        expect(controller).to disallow_action(:put, :update, role_name: 'foo').with(401, 'You are not authorized to perform this action.')
      end

      it 'should allow admin, with security enabled' do
        login_as_admin
        expect(controller).to allow_action(:put, :update, role_name: 'foo')
      end

      it 'should disallow pipeline group admin users, with security enabled' do
        login_as_group_admin
        expect(controller).to disallow_action(:put, :update, role_name: 'foo').with(401, 'You are not authorized to perform this action.')
      end
    end
    describe 'admin' do
      before(:each) do
        login_as_admin
      end

      it 'should not allow rename of auth config id' do
        role = PluginRoleConfig.new('blackbird', 'ldap')
        allow(controller).to receive(:load_entity_from_config).and_return(role)
        allow(controller).to receive(:check_for_stale_request).and_return(nil)

        put_with_api_header :update, role_name: 'foo', role: plugin_role_hash

        expect(response).to have_api_message_response(422, 'Renaming of roles is not supported by this API.')
      end

      it 'should fail update if etag does not match' do
        role = PluginRoleConfig.new('blackbird', 'ldap')
        allow(controller).to receive(:load_entity_from_config).and_return(role)
        allow(controller).to receive(:etag_for).and_return('another-etag')
        controller.request.env['HTTP_IF_MATCH'] = 'some-etag'

        put_with_api_header :update, role_name: 'blackbird', role: plugin_role_hash

        expect(response).to have_api_message_response(412, "Someone has modified the configuration for role 'blackbird'. Please update your copy of the config with the changes.")
      end

      it 'should proceed with update if etag matches' do
        controller.request.env['HTTP_IF_MATCH'] = %Q{"#{Digest::MD5.hexdigest('md5')}"}
        role = PluginRoleConfig.new('blackbird', 'blackbird', ConfigurationPropertyMother.create('foo', false, 'bar'))
        allow(controller).to receive(:load_entity_from_config).twice.and_return(role)

        expect(@entity_hashing_service).to receive(:md5ForEntity).with(an_instance_of(PluginRoleConfig)).exactly(3).times.and_return('md5')
        expect(@service).to receive(:update).with(anything, 'md5', an_instance_of(PluginRoleConfig), anything)

        put_with_api_header :update, role_name: 'blackbird', role: plugin_role_hash

        expect(response).to be_ok
        expect(actual_response).to eq(expected_response(role, ApiV1::Security::RoleConfigRepresenter))
      end
    end

    describe :route do
      describe :with_header do
        it 'should route to update action of controller for alphanumeric identifier' do
          expect(:put => 'api/admin/security/roles/foo123').to route_to(action: 'update', controller: 'api_v1/admin/security/roles', role_name: 'foo123')
        end

        it 'should route to update action of controller for identifier with dots' do
          expect(:put => 'api/admin/security/roles/foo.123').to route_to(action: 'update', controller: 'api_v1/admin/security/roles', role_name: 'foo.123')
        end

        it 'should route to update action of controller for identifier with hyphen' do
          expect(:put => 'api/admin/security/roles/foo-123').to route_to(action: 'update', controller: 'api_v1/admin/security/roles', role_name: 'foo-123')
        end

        it 'should route to update action of controller for identifier with underscore' do
          expect(:put => 'api/admin/security/roles/foo_123').to route_to(action: 'update', controller: 'api_v1/admin/security/roles', role_name: 'foo_123')
        end

        it 'should route to update action of controller for capitalized identifier' do
          expect(:put => 'api/admin/security/roles/FOO').to route_to(action: 'update', controller: 'api_v1/admin/security/roles', role_name: 'FOO')
        end
      end
      describe :without_header do
        before :each do
          teardown_header
        end
        it 'should not route to update action of controller without header' do
          expect(:put => 'api/admin/security/roles/foo').to_not route_to(action: 'update', controller: 'api_v1/admin/security/roles')
          expect(:put => 'api/admin/security/roles/foo').to route_to(controller: 'application', action: 'unresolved', url: 'api/admin/security/roles/foo')
        end
      end
    end
  end

  describe :destroy do
    describe :security do
      before :each do
        allow(controller).to receive(:load_entity_from_config).and_return(nil)
      end
      it 'should allow all with security disabled' do
        disable_security
        expect(controller).to allow_action(:delete, :destroy)
      end

      it 'should disallow anonymous users, with security enabled' do
        enable_security
        login_as_anonymous

        expect(controller).to disallow_action(:delete, :destroy, role_name: 'foo').with(401, 'You are not authorized to perform this action.')
      end

      it 'should disallow normal users, with security enabled' do
        login_as_user
        expect(controller).to disallow_action(:delete, :destroy, role_name: 'foo').with(401, 'You are not authorized to perform this action.')
      end

      it 'should allow admin, with security enabled' do
        login_as_admin
        expect(controller).to allow_action(:delete, :destroy, role_name: 'foo')
      end

      it 'should disallow pipeline group admin users, with security enabled' do
        login_as_group_admin
        expect(controller).to disallow_action(:delete, :destroy, role_name: 'foo').with(401, 'You are not authorized to perform this action.')
      end
    end
    describe 'admin' do
      before(:each) do
        enable_security
        login_as_admin
      end

      it 'should raise an error if role is not found' do
        expect(@service).to receive(:findRole).and_return(nil)

        delete_with_api_header :destroy, role_name: 'foo'

        expect(response).to have_api_message_response(404, 'Either the resource you requested was not found, or you are not authorized to perform this action.')
      end

      it 'should render the success message on deleting a role' do
        role = PluginRoleConfig.new('foo', 'ldap')
        expect(@service).to receive(:findRole).and_return(role)
        result = HttpLocalizedOperationResult.new
        allow(@service).to receive(:delete).with(anything, an_instance_of(PluginRoleConfig), result) do |user, role, result|
          result.setMessage(LocalizedMessage::string('RESOURCE_DELETE_SUCCESSFUL', 'role', 'foo'))
        end
        delete_with_api_header :destroy, role_name: 'foo'

        expect(response).to have_api_message_response(200, "The role 'foo' was deleted successfully.")
      end

      it 'should render the validation errors on failure to delete' do
        role = PluginRoleConfig.new('foo', 'ldap')
        expect(@service).to receive(:findRole).and_return(role)
        result = HttpLocalizedOperationResult.new
        allow(@service).to receive(:delete).with(anything, an_instance_of(PluginRoleConfig), result) do |user, role, result|
          result.unprocessableEntity(LocalizedMessage::string('SAVE_FAILED_WITH_REASON', 'Validation failed'))
        end
        delete_with_api_header :destroy, role_name: 'foo'

        expect(response).to have_api_message_response(422, 'Save failed. Validation failed')
      end
    end

    describe :route do
      describe :with_header do

        it 'should route to destroy action of controller for alphanumeric identifier' do
          expect(:delete => 'api/admin/security/roles/foo123').to route_to(action: 'destroy', controller: 'api_v1/admin/security/roles', role_name: 'foo123')
        end

        it 'should route to destroy action of controller for identifier with dots' do
          expect(:delete => 'api/admin/security/roles/foo.123').to route_to(action: 'destroy', controller: 'api_v1/admin/security/roles', role_name: 'foo.123')
        end

        it 'should route to destroy action of controller for identifier with hyphen' do
          expect(:delete => 'api/admin/security/roles/foo-123').to route_to(action: 'destroy', controller: 'api_v1/admin/security/roles', role_name: 'foo-123')
        end

        it 'should route to destroy action of controller for identifier with underscore' do
          expect(:delete => 'api/admin/security/roles/foo_123').to route_to(action: 'destroy', controller: 'api_v1/admin/security/roles', role_name: 'foo_123')
        end

        it 'should route to destroy action of controller for capitalized identifier' do
          expect(:delete => 'api/admin/security/roles/FOO').to route_to(action: 'destroy', controller: 'api_v1/admin/security/roles', role_name: 'FOO')
        end
      end

      describe :without_header do
        before :each do
          teardown_header
        end
        it 'should not route to destroy action of controller without header' do
          expect(:delete => 'api/admin/security/roles/foo').to_not route_to(action: 'destroy', controller: 'api_v1/admin/security/roles')
          expect(:delete => 'api/admin/security/roles/foo').to route_to(controller: 'application', action: 'unresolved', url: 'api/admin/security/roles/foo')
        end
      end
    end
  end

  def role_hash
    {
      name: 'blackbird',
      type: 'gocd',
      attributes: {
        users: %w(bob alice)
      }
    }
  end

  def plugin_role_hash
    {
      name: 'blackbird',
      type: 'plugin',
      attributes: {
        auth_config_id: 'blackbird',
        properties: [{key: 'foo', value: 'bar'}]
      }
    }
  end
end


text:
class ResqueFiller
  def self.fill(number_entries = 100)
    number_entries.times do |i|
      Resque.enqueue(ResqueEmptier, i)
    end
  end
end


text:
package ee.ria.xroad.monitor;

/**
 * Thrown by sensors to indicate a failure.
 */
public class SensorException extends RuntimeException {

    public SensorException(String message, Throwable cause) {
        super(message, cause);
    }

    public SensorException(Throwable cause) {
        super(cause);
    }
}


text:
<?xml version="1.0"?>
<phpunit xmlns="http://schema.phpunit.de/coverage/1.0">
  <file name="PackageRepository.php">
    <totals>
      <lines total="26" comments="20" code="6" executable="0" executed="0" percent=""/>
      <methods count="0" tested="0" percent=""/>
      <functions count="0" tested="0" percent=""/>
      <classes count="0" tested="0" percent=""/>
      <traits count="0" tested="0" percent=""/>
    </totals>
  </file>
</phpunit>