text:
exports.decorator = function(coffee) {
    var originalCost = coffee.getCost;
    var originalIngredients = coffee.getIngredients;

    coffee.getCost = function() {
        return originalCost.apply(this, arguments) + 2;
    }
    coffee.getIngredients = function() {
        return originalIngredients.apply(this, arguments) + " Whip";
    }

    return coffee;
}


text:
// # Copyright © 2011-2012, Novus Craft
// # All rights reserved.

using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Machine.Specifications;
using Moq;

namespace NovusCraft.Specifications.SpecUtils
{
	public static class RouteTestExtensions
	{
		public static void ShouldBeIgnored(this string requestUrl)
		{
			var routeData = GetRouteData(requestUrl);

			routeData.ShouldNotBeNull();
			routeData.RouteHandler.ShouldBeOfType<StopRoutingHandler>();
		}

		public static void ShouldMapTo<TController>(this string requestUrl, Expression<Action<TController>> action) where TController : Controller
		{
			var routeData = GetRouteData(requestUrl);

			routeData.ShouldNotBeNull();

			var controllerName = typeof(TController).Name.Replace("Controller", string.Empty);
			routeData.Values["controller"].ShouldEqual(controllerName);

			var actionName = ((MethodCallExpression)action.Body).Method.Name;
			routeData.Values["action"].ShouldEqual(actionName);
		}

		static RouteData GetRouteData(string requestUrl)
		{
			var httpContext = new Mock<HttpContextBase>();
			httpContext.Setup(c => c.Request.AppRelativeCurrentExecutionFilePath).Returns(requestUrl);

			var routeData = RouteTable.Routes.GetRouteData(httpContext.Object);
			return routeData;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
Houndapp::Application.routes.draw do
  mount Resque::Server, at: "/queue"
  mount JasmineRails::Engine => "/specs" if defined?(JasmineRails)

  get "/auth/github/callback", to: "sessions#create"
  get "/sign_out", to: "sessions#destroy"
  get "/configuration", to: "pages#configuration"
  get "/faq", to: "pages#show", id: "faq"
  get "/database_cleaner", to: "database_cleaner#index"

  resource :account, only: [:show]
  resources :builds, only: [:create]

  resources :repos, only: [:index] do
    with_options(defaults: { format: :json }) do
      resource :activation, only: [:create]
      resource :deactivation, only: [:create]
      resource :subscription, only: [:create, :destroy]
    end
  end

  with_options(defaults: { format: :json }) do
    resource :credit_card, only: [:update]
    resources :repo_syncs, only: [:index, :create]
    resource :user, only: [:show]
  end

  %w(404 422 500).each do |status_code|
    get status_code, to: "errors#show", code: status_code
  end

  root to: "home#index"
end


text:
{{ object.title }}

{% if object.get_image_url %}

{% endif %}

{% if price == 'True'%}
    {{ object.variations.first.get_html_price }}
{% endif %}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.anysoftkeyboard.themes.israel64.pack">

    <application>
        <receiver
            android:name="com.anysoftkeyboard.themes.israel64.pack.PackBroadcastReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="com.anysoftkeyboard.plugin.KEYBOARD_THEME" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.ALTERNATIVE" />
                <category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
            </intent-filter>

            <meta-data
                android:name="com.anysoftkeyboard.plugindata.keyboardtheme"
                android:resource="@xml/israel64_themes" />
        </receiver>
    </application>
</manifest>


text:
from selenium import webdriver
from page_objects import *
from datetime import datetime
import unittest
import argparse

tender_id = None

class SeleniumMixin(unittest.TestCase):
    def assertlementIsPresentById(self, elem_id):
        try:
            self.driver.find_element_by_id(elem_id)
        except NoSuchElementException as error:
            self.fail(error)

class TestCreateTender(SeleniumMixin):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get(broker['url'])
        self.driver.set_window_size(1200, 1000)
        self.login_page_owner = LoginPage(
            owner_users['email'], owner_users['password'], self.driver
        )
        self.create_tender_page = CreateTenderPage(self.driver)
        self.find_tender = FindTenderPage(self.driver)

    def test_create_tender(self):
        self.login_page_owner.login_as_owner()
        self.create_tender_page.create_tender()

        is_found = False
        for i in range(1, 10):
            try:
                given_tender_id = self.find_tender.get_tender_id()
                print given_tender_id
                if given_tender_id:
                    with open('load_results_create.txt', 'a') as f:
                        f.write(
                            'Tender_Owner created tender with {}, finished at {} ------------------ PASSED\n'.format(
                                given_tender_id, datetime.now())
                        )
                        f.close()
                is_found = True
                break
            except NoSuchElementException or UnicodeEncodeError:
                sleep(30)
                self.driver.refresh()
                self.driver.execute_script("window.scrollTo(0, 1582);")

                if not is_found:
                    with open('load_results_create.txt', 'a') as f:
                        f.write('Tender_Owner did NOT create tender, finished at {} ------------ FAILED\n'.format(
                            datetime.now())
                        )
                        f.close()
                    return False

    def tearDown(self):
        self.driver.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(prog='create_tender')

    suite = unittest.TestSuite()
    suite.addTest(TestCreateTender("test_create_tender"))
    runner = unittest.TextTestRunner()
    runner.run(suite)


text:
"""Monitors provide a mechanism for periodically collecting data and
automatically persisting values in a measurement.

Monitors are implemented similar to phase functions - they are decorated
with plugs.plug() to pass plugs in.  The return value of a monitor
function, however, will be used to append a value to a measurement.

Monitors by default poll at a rate of 1 second between invokations of
the monitor function.  The poll interval (given in milliseconds) determines the
approximate frequency at which values will be sampled.  A sample is considered
to have been taken at the time when the monitor function *returns*, not when
it is called.

The approximate average duration of calls to the monitor function is taken into
account, so that samples are obtained on as close to interval_ms boundaries as
can be.  A poll interval of 0 will cause the monitor function to be called in a
tight loop with no delays.

Example:

@plugs.plug(current_meter=current_meter.CurrentMeter)
def CurrentMonitor(test, current_meter):
  return current_meter.GetReading()

@monitors.monitors('current_draw', CurrentMonitor, units=units.AMPERE)
def MyPhase(test):
  # Do some stuff for a while...

# MyPhase will have a dimensioned measurement on it, with units of 'AMPERE' and
# a single dimension of 'MILLISECONDS', and will have values for roughly every
# second while MyPhase was executing.
"""

import functools
import inspect
import time

import openhtf
from openhtf import plugs
from openhtf.core import measurements
from openhtf.util import threads
from openhtf.util import units as uom

class _MonitorThread(threads.KillableThread):

  daemon = True

  def __init__(self, measurement_name, monitor_desc, extra_kwargs, test_state,
               interval_ms):
    super(_MonitorThread, self).__init__(
        name='%s_MonitorThread' % measurement_name)
    self.measurement_name = measurement_name
    self.monitor_desc = monitor_desc
    self.test_state = test_state
    self.interval_ms = interval_ms
    self.extra_kwargs = extra_kwargs

  def get_value(self):
    arg_info = inspect.getargspec(self.monitor_desc.func)
    if arg_info.keywords:
      # Monitor phase takes **kwargs, so just pass everything in.
      kwargs = self.extra_kwargs
    else:
      # Only pass in args that the monitor phase takes.
      kwargs = {arg: val for arg, val in self.extra_kwargs
                if arg in arg_info.args}
    return self.monitor_desc.with_args(**kwargs)(self.test_state)

  def _thread_proc(self):
    measurement = getattr(self.test_state.test_api.measurements,
                          self.measurement_name)
    start_time = time.time()

    # Special case tight-loop monitoring.
    if not self.interval_ms:
      while True:
        measurement[(time.time() - start_time) * 1000] = self.get_value()

    # Helper to take sample, return sample number and sample duration.
    def _take_sample():
      pre_time, value, post_time = time.time(), self.get_value(), time.time()
      measurement[(post_time - start_time) * 1000] = value
      return (int((post_time - start_time) * 1000 / self.interval_ms),
              (post_time - pre_time) * 1000)

    # Track the last sample number, and an approximation of the mean time
    # it takes to sample (so we can account for it in how long we sleep).
    last_sample, mean_sample_ms = _take_sample()
    while True:
      # Find what sample number (float) we would be on if we sampled now.
      current_time = time.time()
      new_sample = ((((current_time - start_time) * 1000) + mean_sample_ms) /
                    self.interval_ms)
      if new_sample < last_sample + 1:
        time.sleep(start_time - current_time +
                   ((last_sample + 1) * self.interval_ms / 1000.0) -
                   (mean_sample_ms / 1000.0))
        continue
      elif new_sample > last_sample + 2:
        self.test_state.logger.warning(
            'Monitor for "%s" skipping %s sample(s).', self.measurement_name,
            new_sample - last_sample - 1)
      last_sample, cur_sample_ms = _take_sample()
      # Approximate 10-element sliding window average.
      mean_sample_ms = ((9 * mean_sample_ms) + cur_sample_ms) / 10.0

def monitors(measurement_name, monitor_func, units=None, poll_interval_ms=1000):
  monitor_desc = openhtf.PhaseDescriptor.wrap_or_copy(monitor_func)
  def wrapper(phase_func):
    phase_desc = openhtf.PhaseDescriptor.wrap_or_copy(phase_func)

    # Re-key this dict so we don't have to worry about collisions with
    # plug.plug() decorators on the phase function.  Since we aren't
    # updating kwargs here, we don't have to worry about collisions with
    # kwarg names.
    monitor_plugs = {('_' * idx) + measurement_name + '_monitor': plug.cls for
                     idx, plug in enumerate(monitor_desc.plugs, start=1)}

    @openhtf.PhaseOptions(requires_state=True)
    @plugs.plug(update_kwargs=False, **monitor_plugs)
    @measurements.measures(
        measurements.Measurement(measurement_name).with_units(
            units).with_dimensions(uom.MILLISECOND))
    @functools.wraps(phase_desc.func)
    def monitored_phase_func(test_state, *args, **kwargs):
      # Start monitor thread, it will run monitor_desc periodically.
      monitor_thread = _MonitorThread(
          measurement_name, monitor_desc, phase_desc.extra_kwargs, test_state,
          poll_interval_ms)
      monitor_thread.start()
      try:
        return phase_desc(test_state, *args, **kwargs)
      finally:
        monitor_thread.kill()
    return monitored_phase_func
  return wrapper


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <include layout="@layout/viewpager" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Light">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include layout="@layout/nav_header"/>

            <android.support.v7.widget.RecyclerView
                android:id="@+id/left_drawer"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="start"
                android:divider="@android:color/transparent"
                android:dividerHeight="0dp"/>

        </LinearLayout>

    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>


text:
//
//  UIImage+Merge.m
//  LXFCommonCode
//
//  Created by 林洵锋 on 2017/3/2.
//  Copyright © 2017年 LXF. All rights reserved.
//
//  GitHub: https://github.com/LinXunFeng
//  简书: http://www.jianshu.com/users/31e85e7a22a2

#import "UIImage+Merge.h"

@implementation UIImage (Merge)

/**
 *  @brief  合并两个图片
 *
 *  @param firstImage  一个图片
 *  @param secondImage 二个图片
 *
 *  @return 合并后图片
 */
+ (UIImage*)mergeImage:(UIImage*)firstImage withImage:(UIImage*)secondImage {
    CGImageRef firstImageRef = firstImage.CGImage;
    CGFloat firstWidth = CGImageGetWidth(firstImageRef);
    CGFloat firstHeight = CGImageGetHeight(firstImageRef);
    CGImageRef secondImageRef = secondImage.CGImage;
    CGFloat secondWidth = CGImageGetWidth(secondImageRef);
    CGFloat secondHeight = CGImageGetHeight(secondImageRef);
    CGSize mergedSize = CGSizeMake(MAX(firstWidth, secondWidth), MAX(firstHeight, secondHeight));
    UIGraphicsBeginImageContext(mergedSize);
    [firstImage drawInRect:CGRectMake(0, 0, firstWidth, firstHeight)];
    [secondImage drawInRect:CGRectMake(0, 0, secondWidth, secondHeight)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end


text:
namespace AnimatGUI
{
	namespace Interfaces
	{

SimGUICallback::SimGUICallback(ManagedAnimatInterfaces::ISimulatorInterface ^doSim)
{
	m_doSim = doSim;
}

SimGUICallback::~SimGUICallback(void)
{
}

void SimGUICallback::NeedToStopSimulation()
{
	m_doSim->FireNeedToStopSimulationEvent();
}

void SimGUICallback::HandleNonCriticalError(std::string strError)
{
	System::String ^sError = gcnew System::String(strError.c_str());

	m_doSim->FireHandleNonCriticalErrorEvent(sError);
}

void SimGUICallback::HandleCriticalError(std::string strError)
{
	System::String ^sError = gcnew System::String(strError.c_str());

	m_doSim->FireHandleCriticalErrorEvent(sError);
}

	}
}


text:
Template.search.events({
  "keyup #search": _.throttle(function(event) {
    var text = $(event.target).val().trim();
    Session.set('task_query', text);
  }, 200)
});

var sorts = {
  'created-desc': { created_at: -1 },
  'created-asc': { created_at: 1 },
  'guilt-desc': { guilt: -1 }
}

searchTasks = function(query) {
  var selector = {}
  if (query && query.length > 0) {
    var regExp = buildRegExp(query);
    selector = {
      $or: [
        { title: { $regex: regExp } },
        { content: { $regex: regExp } },
        { project: { $regex: regExp } }
      ]
    };
  }
  var showComplete = Session.get('task_show_complete');
  if (!showComplete) {
    selector = {
      $and: [
        { completed: false },
        selector
      ]
    }
  }
  var sort = sorts[Session.get('task_sort')] || { created_at: -1 };
  var result = Tasks.find(selector, { sort: sort });
  populateStats(result);
  return result;
}

function populateStats(raw_result) {
  // Filter out completed tasks
  var result = raw_result.fetch().filter(function(t) {
    return !(t.completed);
  });

  // Number of tasks
  n_tasks = result.length;
  Session.set('n_tasks', n_tasks);

  // Number of projects
  var n_projects = _.uniq(result.map(function(t) {
    return t.project;
  })).length;
  Session.set('n_projects', n_projects);

  // Due this week
  var week_end = moment().endOf('isoWeek');
  var tasks_weekdue = result.filter(function(t) {
    var due_at = moment(t.due_at);
    return t.due_at && // has a due date
      (due_at > moment()) && // due after now
      (due_at < week_end); // due before end of week
  }).length;
  Session.set('tasks_weekdue', tasks_weekdue);

  // Overdue
  var tasks_overdue = result.filter(function(t) {
    var due_at = moment(t.due_at);
    return t.due_at && // has a due date
      (due_at < moment()) // due before now
  }).length;
  Session.set('tasks_overdue', tasks_overdue);

}

function buildRegExp(query) {
  // this is a dumb implementation
  var parts = query.trim().split(/[ \-\:]+/);
  return "(" + parts.join('|') + ")";
}


text:
<?php

namespace Oprokidnev\CacheableRendering\View\Helper\Placeholder;

/**
 * Description of PlaceholderDelegator
 *
 * @author oprokidnev
 */
class PlaceholderDelegator extends \Zend\View\Helper\Placeholder
{
    public function createContainer($key, array $value = [])
    {
        $container = parent::createContainer($key, $value);
        if ($container instanceof TrackableContainer) {
            $container->setPlaceholderName($key);
        }
        return $container;
    }

    public function setContainerClass($containerClass)
    {
        $this->containerClass = $containerClass;
        return $this;
    }
}


text:
package org.springframework.security.web.authentication.switchuser;

import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;

import org.junit.*;
import org.junit.rules.ExpectedException;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.util.FieldUtils;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AnyRequestMatcher;

import javax.servlet.FilterChain;
import java.util.*;

/**
 * Tests
 * {@link org.springframework.security.web.authentication.switchuser.SwitchUserFilter}.
 *
 * @author Mark St.Godard
 * @author Luke Taylor
 */
public class SwitchUserFilterTests {
	private final static List<GrantedAuthority> ROLES_12 = AuthorityUtils
			.createAuthorityList("ROLE_ONE", "ROLE_TWO");
	@Rule
	public ExpectedException thrown = ExpectedException.none();

	@Before
	public void authenticateCurrentUser() {
		UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
				"dano", "hawaii50");
		SecurityContextHolder.getContext().setAuthentication(auth);
	}

	@After
	public void clearContext() {
		SecurityContextHolder.clearContext();
	}

	private MockHttpServletRequest createMockSwitchRequest() {
		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setScheme("http");
		request.setServerName("localhost");
		request.setRequestURI("/login/impersonate");

		return request;
	}

	private Authentication switchToUser(String name) {
		MockHttpServletRequest request = new MockHttpServletRequest();
		request.addParameter("myUsernameParameter", name);

		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setUsernameParameter("myUsernameParameter");
		filter.setUserDetailsService(new MockUserDetailsService());

		return filter.attemptSwitchUser(request);

	}

	private Authentication switchToUserWithAuthorityRole(String name, String switchAuthorityRole) {
		MockHttpServletRequest request = new MockHttpServletRequest();
		request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, name);

		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setUserDetailsService(new MockUserDetailsService());
		filter.setSwitchAuthorityRole(switchAuthorityRole);

		return filter.attemptSwitchUser(request);
	}

	@Test
	public void requiresExitUserMatchesCorrectly() {
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setExitUserUrl("/j_spring_security_my_exit_user");

		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setRequestURI("/j_spring_security_my_exit_user");

		assertThat(filter.requiresExitUser(request)).isTrue();
	}

	@Test
	// gh-4249
	public void requiresExitUserWhenEndsWithThenDoesNotMatch() {
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setExitUserUrl("/j_spring_security_my_exit_user");

		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setRequestURI("/foo/bar/j_spring_security_my_exit_user");

		assertThat(filter.requiresExitUser(request)).isFalse();
	}

	@Test
	public void requiresExitUserWhenMatcherThenWorks() {
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setExitUserMatcher(AnyRequestMatcher.INSTANCE);

		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setRequestURI("/foo/bar/j_spring_security_my_exit_user");

		assertThat(filter.requiresExitUser(request)).isTrue();
	}

	@Test
	public void requiresSwitchMatchesCorrectly() {
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setSwitchUserUrl("/j_spring_security_my_switch_user");

		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setRequestURI("/j_spring_security_my_switch_user");

		assertThat(filter.requiresSwitchUser(request)).isTrue();
	}

	@Test
	// gh-4249
	public void requiresSwitchUserWhenEndsWithThenDoesNotMatch() {
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setSwitchUserUrl("/j_spring_security_my_exit_user");

		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setRequestURI("/foo/bar/j_spring_security_my_exit_user");

		assertThat(filter.requiresSwitchUser(request)).isFalse();
	}

	@Test
	public void requiresSwitchUserWhenMatcherThenWorks() {
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setSwitchUserMatcher(AnyRequestMatcher.INSTANCE);

		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setRequestURI("/foo/bar/j_spring_security_my_exit_user");

		assertThat(filter.requiresSwitchUser(request)).isTrue();
	}

	@Test(expected = UsernameNotFoundException.class)
	public void attemptSwitchToUnknownUserFails() throws Exception {

		MockHttpServletRequest request = new MockHttpServletRequest();
		request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
				"user-that-doesnt-exist");

		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setUserDetailsService(new MockUserDetailsService());
		filter.attemptSwitchUser(request);
	}

	@Test(expected = DisabledException.class)
	public void attemptSwitchToUserThatIsDisabledFails() throws Exception {
		switchToUser("mcgarrett");
	}

	@Test(expected = AccountExpiredException.class)
	public void attemptSwitchToUserWithAccountExpiredFails() throws Exception {
		switchToUser("wofat");
	}

	@Test(expected = CredentialsExpiredException.class)
	public void attemptSwitchToUserWithExpiredCredentialsFails() throws Exception {
		switchToUser("steve");
	}

	@Test(expected = UsernameNotFoundException.class)
	public void switchUserWithNullUsernameThrowsException() throws Exception {
		switchToUser(null);
	}

	@Test
	public void attemptSwitchUserIsSuccessfulWithValidUser() throws Exception {
		assertThat(switchToUser("jacklord")).isNotNull();
	}

	@Test
	public void switchToLockedAccountCausesRedirectToSwitchFailureUrl() throws Exception {
		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setRequestURI("/login/impersonate");
		request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
				"mcgarrett");
		MockHttpServletResponse response = new MockHttpServletResponse();
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setTargetUrl("/target");
		filter.setUserDetailsService(new MockUserDetailsService());
		filter.afterPropertiesSet();

		// Check it with no url set (should get a text response)
		FilterChain chain = mock(FilterChain.class);
		filter.doFilter(request, response, chain);
		verify(chain, never()).doFilter(request, response);

		assertThat(response.getErrorMessage()).isNotNull();

		// Now check for the redirect
		request.setContextPath("/mywebapp");
		request.setRequestURI("/mywebapp/login/impersonate");
		filter = new SwitchUserFilter();
		filter.setTargetUrl("/target");
		filter.setUserDetailsService(new MockUserDetailsService());
		filter.setSwitchFailureUrl("/switchfailed");
		filter.afterPropertiesSet();
		response = new MockHttpServletResponse();

		chain = mock(FilterChain.class);
		filter.doFilter(request, response, chain);
		verify(chain, never()).doFilter(request, response);

		assertThat(response.getRedirectedUrl()).isEqualTo("/mywebapp/switchfailed");
		assertThat(FieldUtils.getFieldValue(filter, "switchFailureUrl")).isEqualTo("/switchfailed");
	}

	@Test(expected = IllegalArgumentException.class)
	public void configMissingUserDetailsServiceFails() throws Exception {
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setSwitchUserUrl("/login/impersonate");
		filter.setExitUserUrl("/logout/impersonate");
		filter.setTargetUrl("/main.jsp");
		filter.afterPropertiesSet();
	}

	@Test(expected = IllegalArgumentException.class)
	public void testBadConfigMissingTargetUrl() throws Exception {
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setUserDetailsService(new MockUserDetailsService());
		filter.setSwitchUserUrl("/login/impersonate");
		filter.setExitUserUrl("/logout/impersonate");
		filter.afterPropertiesSet();
	}

	@Test
	public void defaultProcessesFilterUrlMatchesUrlWithPathParameter() {
		MockHttpServletRequest request = createMockSwitchRequest();
		request.setContextPath("/webapp");
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setSwitchUserUrl("/login/impersonate");

		request.setRequestURI("/webapp/login/impersonate;jsessionid=8JHDUD723J8");
		assertThat(filter.requiresSwitchUser(request)).isTrue();
	}

	@Test
	public void exitUserJackLordToDanoSucceeds() throws Exception {
		// original user
		UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken(
				"dano", "hawaii50", ROLES_12);

		// set current user (Admin)
		List<GrantedAuthority> adminAuths = new ArrayList<>();
		adminAuths.addAll(ROLES_12);
		adminAuths.add(new SwitchUserGrantedAuthority("PREVIOUS_ADMINISTRATOR", source));
		UsernamePasswordAuthenticationToken admin = new UsernamePasswordAuthenticationToken(
				"jacklord", "hawaii50", adminAuths);

		SecurityContextHolder.getContext().setAuthentication(admin);

		MockHttpServletRequest request = createMockSwitchRequest();
		request.setRequestURI("/logout/impersonate");

		// setup filter
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setUserDetailsService(new MockUserDetailsService());
		filter.setExitUserUrl("/logout/impersonate");
		filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(
				"/webapp/someOtherUrl"));

		// run 'exit'
		FilterChain chain = mock(FilterChain.class);
		MockHttpServletResponse response = new MockHttpServletResponse();
		filter.doFilter(request, response, chain);

		verify(chain, never()).doFilter(request, response);

		// check current user, should be back to original user (dano)
		Authentication targetAuth = SecurityContextHolder.getContext()
				.getAuthentication();
		assertThat(targetAuth).isNotNull();
		assertThat(targetAuth.getPrincipal()).isEqualTo("dano");
	}

	@Test(expected = AuthenticationException.class)
	public void exitUserWithNoCurrentUserFails() throws Exception {
		// no current user in secure context
		SecurityContextHolder.clearContext();

		MockHttpServletRequest request = createMockSwitchRequest();
		request.setRequestURI("/logout/impersonate");

		// setup filter
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setUserDetailsService(new MockUserDetailsService());
		filter.setExitUserUrl("/logout/impersonate");

		// run 'exit', expect fail due to no current user
		FilterChain chain = mock(FilterChain.class);
		MockHttpServletResponse response = new MockHttpServletResponse();
		filter.doFilter(request, response, chain);

		verify(chain, never()).doFilter(request, response);
	}

	@Test
	public void redirectToTargetUrlIsCorrect() throws Exception {
		MockHttpServletRequest request = createMockSwitchRequest();
		request.setContextPath("/webapp");
		request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
				"jacklord");
		request.setRequestURI("/webapp/login/impersonate");

		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setSwitchUserUrl("/login/impersonate");
		filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(
				"/someOtherUrl"));
		filter.setUserDetailsService(new MockUserDetailsService());

		FilterChain chain = mock(FilterChain.class);
		MockHttpServletResponse response = new MockHttpServletResponse();
		filter.doFilter(request, response, chain);

		verify(chain, never()).doFilter(request, response);

		assertThat(response.getRedirectedUrl()).isEqualTo("/webapp/someOtherUrl");
	}

	@Test
	public void redirectOmitsContextPathIfUseRelativeContextSet() throws Exception {
		// set current user
		UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
				"dano", "hawaii50");
		SecurityContextHolder.getContext().setAuthentication(auth);

		MockHttpServletRequest request = createMockSwitchRequest();
		request.setContextPath("/webapp");
		request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
				"jacklord");
		request.setRequestURI("/webapp/login/impersonate");

		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setSwitchUserUrl("/login/impersonate");
		SimpleUrlAuthenticationSuccessHandler switchSuccessHandler = new SimpleUrlAuthenticationSuccessHandler(
				"/someOtherUrl");
		DefaultRedirectStrategy contextRelativeRedirector = new DefaultRedirectStrategy();
		contextRelativeRedirector.setContextRelative(true);
		switchSuccessHandler.setRedirectStrategy(contextRelativeRedirector);
		filter.setSuccessHandler(switchSuccessHandler);
		filter.setUserDetailsService(new MockUserDetailsService());

		FilterChain chain = mock(FilterChain.class);
		MockHttpServletResponse response = new MockHttpServletResponse();

		filter.doFilter(request, response, chain);

		verify(chain, never()).doFilter(request, response);

		assertThat(response.getRedirectedUrl()).isEqualTo("/someOtherUrl");
	}

	@Test
	public void testSwitchRequestFromDanoToJackLord() throws Exception {
		// set current user
		UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
				"dano", "hawaii50");
		SecurityContextHolder.getContext().setAuthentication(auth);

		// http request
		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setRequestURI("/webapp/login/impersonate");
		request.setContextPath("/webapp");
		request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
				"jacklord");

		// http response
		MockHttpServletResponse response = new MockHttpServletResponse();

		// setup filter
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setUserDetailsService(new MockUserDetailsService());
		filter.setSwitchUserUrl("/login/impersonate");
		filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(
				"/webapp/someOtherUrl"));

		FilterChain chain = mock(FilterChain.class);

		// test updates user token and context
		filter.doFilter(request, response, chain);
		verify(chain, never()).doFilter(request, response);

		// check current user
		Authentication targetAuth = SecurityContextHolder.getContext()
				.getAuthentication();
		assertThat(targetAuth).isNotNull();
		assertThat(targetAuth.getPrincipal() instanceof UserDetails).isTrue();
		assertThat(((User) targetAuth.getPrincipal()).getUsername()).isEqualTo("jacklord");
	}

	@Test
	public void modificationOfAuthoritiesWorks() {
		UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
				"dano", "hawaii50");
		SecurityContextHolder.getContext().setAuthentication(auth);

		MockHttpServletRequest request = new MockHttpServletRequest();
		request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
				"jacklord");

		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setUserDetailsService(new MockUserDetailsService());
		filter.setSwitchUserAuthorityChanger((targetUser, currentAuthentication, authoritiesToBeGranted) -> {
			List<GrantedAuthority> auths = new ArrayList<>();
			auths.add(new SimpleGrantedAuthority("ROLE_NEW"));
			return auths;
		});

		Authentication result = filter.attemptSwitchUser(request);
		assertThat(result != null).isTrue();
		assertThat(result.getAuthorities()).hasSize(2);
		assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains(
				"ROLE_NEW");
	}

	// SEC-1763
	@Test
	public void nestedSwitchesAreNotAllowed() throws Exception {
		// original user
		UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken(
				"orig", "hawaii50", ROLES_12);
		SecurityContextHolder.getContext().setAuthentication(source);
		SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord"));
		Authentication switched = switchToUser("dano");

		SwitchUserGrantedAuthority switchedFrom = null;

		for (GrantedAuthority ga : switched.getAuthorities()) {
			if (ga instanceof SwitchUserGrantedAuthority) {
				switchedFrom = (SwitchUserGrantedAuthority) ga;
				break;
			}
		}

		assertThat(switchedFrom).isNotNull();
		assertThat(source).isSameAs(switchedFrom.getSource());
	}

	// gh-3697
	@Test
	public void switchAuthorityRoleCannotBeNull() throws Exception {
		thrown.expect(IllegalArgumentException.class);
		thrown.expectMessage("switchAuthorityRole cannot be null");
		switchToUserWithAuthorityRole("dano", null);
	}

	// gh-3697
	@Test
	public void switchAuthorityRoleCanBeChanged() throws Exception {
		String switchAuthorityRole = "PREVIOUS_ADMINISTRATOR";

		// original user
		UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken(
				"orig", "hawaii50", ROLES_12);
		SecurityContextHolder.getContext().setAuthentication(source);
		SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord"));
		Authentication switched = switchToUserWithAuthorityRole("dano", switchAuthorityRole);

		SwitchUserGrantedAuthority switchedFrom = null;

		for (GrantedAuthority ga : switched.getAuthorities()) {
			if (ga instanceof SwitchUserGrantedAuthority) {
				switchedFrom = (SwitchUserGrantedAuthority) ga;
				break;
			}
		}

		assertThat(switchedFrom).isNotNull();
		assertThat(switchedFrom.getSource()).isSameAs(source);
		assertThat(switchAuthorityRole).isEqualTo(switchedFrom.getAuthority());
	}

	@Test(expected = IllegalArgumentException.class)
	public void setSwitchFailureUrlWhenNullThenThrowException() {
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setSwitchFailureUrl(null);
	}

	@Test(expected = IllegalArgumentException.class)
	public void setSwitchFailureUrlWhenEmptyThenThrowException() {
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setSwitchFailureUrl("");
	}

	@Test
	public void setSwitchFailureUrlWhenValidThenNoException() {
		SwitchUserFilter filter = new SwitchUserFilter();
		filter.setSwitchFailureUrl("/foo");
	}
	// ~ Inner Classes
	// ==================================================================================================

	private class MockUserDetailsService implements UserDetailsService {
		private String password = "hawaii50";

		public UserDetails loadUserByUsername(String username)
				throws UsernameNotFoundException {
			// jacklord, dano (active)
			// mcgarrett (disabled)
			// wofat (account expired)
			// steve (credentials expired)
			if ("jacklord".equals(username) || "dano".equals(username)) {
				return new User(username, password, true, true, true, true, ROLES_12);
			}
			else if ("mcgarrett".equals(username)) {
				return new User(username, password, false, true, true, true, ROLES_12);
			}
			else if ("wofat".equals(username)) {
				return new User(username, password, true, false, true, true, ROLES_12);
			}
			else if ("steve".equals(username)) {
				return new User(username, password, true, true, false, true, ROLES_12);
			}
			else {
				throw new UsernameNotFoundException("Could not find: " + username);
			}
		}
	}
}


text:
require 'sparql/client'

module Api
  class CoursesController < ApplicationController
    skip_before_action :authenticate_user!, only: %i(keyword)

    def keyword
      @description = upload params[:keyword]
      render 'api/courses/keyword.json.jbuilder'
    end

    private

    def upload(keyword)
      sparql = SPARQL::Client.new("http://dbpedia.org/sparql")
      solution = upload_rus sparql, keyword
      solution = upload_rus_mod(sparql, keyword) if solution.blank? || solution.size < 1 || solution.first[:description].value.size < 50
      solution = upload_eng(sparql, keyword) if solution.blank? || solution.size < 1
      solution = upload_eng_mod(sparql, keyword) if solution.blank? || solution.size < 1 || solution.first[:description].value.size < 50
      return '' if solution.blank? || solution.size < 1
      solution.first[:description].value
    end

    # get rus text from rdfs:comment
    def upload_rus(sparql, keyword)
      sparql.query(
        <<-SPARQL
          SELECT DISTINCT ?concept ?description
          WHERE {
            ?concept rdfs:comment ?description .
            ?concept rdfs:label "#{keyword}"@en .
            FILTER ( lang(?description) = "ru" )
          }
        SPARQL
      )
    end

    # get rus text from dbo:abstract
    def upload_rus_mod(sparql, keyword)
      sparql.query(
        <<-SPARQL
          SELECT DISTINCT ?concept ?description
          WHERE {
            ?concept dbo:abstract ?description .
            ?concept rdfs:label "#{keyword}"@en .
            FILTER ( lang(?description) = "ru" )
          }
        SPARQL
      )
    end

    # get eng text from rdfs:comment
    def upload_eng(sparql, keyword)
      sparql.query(
        <<-SPARQL
          SELECT DISTINCT ?concept ?description
          WHERE {
            ?concept rdfs:comment ?description .
            ?concept rdfs:label "#{keyword}"@en .
            FILTER ( lang(?description) = "en" )
          }
        SPARQL
      )
    end

    # get eng text from dbo:abstract
    def upload_eng_mod(sparql, keyword)
      sparql.query(
        <<-SPARQL
          SELECT DISTINCT ?concept ?description
          WHERE {
            ?concept dbo:abstract ?description .
            ?concept rdfs:label "#{keyword}"@en .
            FILTER ( lang(?description) = "en" )
          }
        SPARQL
      )
    end
  end
end


text:
package edu.uci.ics.hyracks.dataflow.hadoop;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.Counters.Counter;
import org.apache.hadoop.mapred.FileOutputCommitter;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.lib.NullOutputFormat;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.ReflectionUtils;

import edu.uci.ics.hyracks.api.io.FileReference;
import edu.uci.ics.hyracks.api.job.IOperatorDescriptorRegistry;
import edu.uci.ics.hyracks.dataflow.hadoop.util.DatatypeHelper;
import edu.uci.ics.hyracks.dataflow.std.file.AbstractFileWriteOperatorDescriptor;
import edu.uci.ics.hyracks.dataflow.std.file.FileSplit;
import edu.uci.ics.hyracks.dataflow.std.file.IRecordWriter;
import edu.uci.ics.hyracks.hdfs.ContextFactory;

public class HadoopWriteOperatorDescriptor extends AbstractFileWriteOperatorDescriptor {

    private class HadoopFileWriter implements IRecordWriter {

        Object recordWriter;
        JobConf conf;
        Path finalOutputFile;
        Path tempOutputFile;
        Path tempDir;

        HadoopFileWriter(Object recordWriter, int index, JobConf conf) throws Exception {
            this.recordWriter = recordWriter;
            this.conf = conf;
            initialize(index, conf);
        }

        private void initialize(int index, JobConf conf) throws Exception {
            if (!(conf.getOutputFormat() instanceof NullOutputFormat)) {
                boolean isMap = conf.getNumReduceTasks() == 0;
                TaskAttemptID taskAttempId = new TaskAttemptID("0", index, isMap, index, index);
                conf.set("mapred.task.id", taskAttempId.toString());
                String suffix = new String("part-00000");
                suffix = new String(suffix.substring(0, suffix.length() - ("" + index).length()));
                suffix = suffix + index;
                outputPath = new Path(conf.get("mapred.output.dir"));
                tempDir = new Path(outputPath, FileOutputCommitter.TEMP_DIR_NAME);
                FileSystem fileSys = tempDir.getFileSystem(conf);
                if (!fileSys.mkdirs(tempDir)) {
                    throw new IOException("Mkdirs failed to create " + tempDir.toString());
                }
                tempOutputFile = new Path(tempDir, new Path("_" + taskAttempId.toString()));
                tempOutputFile = new Path(tempOutputFile, suffix);
                finalOutputFile = new Path(outputPath, suffix);
                if (conf.getUseNewMapper()) {
                    org.apache.hadoop.mapreduce.JobContext jobContext = new ContextFactory().createJobContext(conf);
                    org.apache.hadoop.mapreduce.OutputFormat newOutputFormat = (org.apache.hadoop.mapreduce.OutputFormat) ReflectionUtils
                            .newInstance(jobContext.getOutputFormatClass(), conf);
                    recordWriter = newOutputFormat.getRecordWriter(new ContextFactory().createContext(conf,
                            taskAttempId));
                } else {
                    recordWriter = conf.getOutputFormat().getRecordWriter(FileSystem.get(conf), conf, suffix,
                            new Progressable() {
                                @Override
                                public void progress() {
                                }
                            });
                }
            }
        }

        @Override
        public void write(Object[] record) throws Exception {
            if (recordWriter != null) {
                if (conf.getUseNewMapper()) {
                    ((org.apache.hadoop.mapreduce.RecordWriter) recordWriter).write(record[0], record[1]);
                } else {
                    ((org.apache.hadoop.mapred.RecordWriter) recordWriter).write(record[0], record[1]);
                }
            }
        }

        @Override
        public void close() {
            try {
                if (recordWriter != null) {
                    if (conf.getUseNewMapper()) {
                        ((org.apache.hadoop.mapreduce.RecordWriter) recordWriter).close(new ContextFactory()
                                .createContext(conf, new TaskAttemptID()));
                    } else {
                        ((org.apache.hadoop.mapred.RecordWriter) recordWriter).close(null);
                    }
                    if (outputPath != null) {
                        FileSystem fileSystem = FileSystem.get(conf);
                        fileSystem.rename(tempOutputFile, finalOutputFile);
                        fileSystem.delete(tempDir, true);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static final long serialVersionUID = 1L;
    Map<String, String> jobConfMap;

    @Override
    protected IRecordWriter createRecordWriter(FileSplit fileSplit, int index) throws Exception {
        JobConf conf = DatatypeHelper.map2JobConf((HashMap) jobConfMap);
        conf.setClassLoader(this.getClass().getClassLoader());
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        FileSystem fileSystem = FileSystem.get(conf);
        Object recordWriter = null;
        return new HadoopFileWriter(recordWriter, index, conf);
    }

    Path outputPath;
    Path outputTempPath;

    protected Reporter createReporter() {
        return new Reporter() {
            @Override
            public Counter getCounter(Enum<?> name) {
                return null;
            }

            @Override
            public Counter getCounter(String group, String name) {
                return null;
            }

            @Override
            public InputSplit getInputSplit() throws UnsupportedOperationException {
                return null;
            }

            @Override
            public void incrCounter(Enum<?> key, long amount) {

            }

            @Override
            public void incrCounter(String group, String counter, long amount) {

            }

            @Override
            public void progress() {

            }

            @Override
            public void setStatus(String status) {

            }

            @Override
            public float getProgress() {
                // TODO Auto-generated method stub
                return 0;
            }
        };
    }

    private boolean checkIfCanWriteToHDFS(FileSplit[] fileSplits) throws Exception {
        JobConf conf = DatatypeHelper.map2JobConf((HashMap) jobConfMap);
        try {
            FileSystem fileSystem = FileSystem.get(conf);
            for (FileSplit fileSplit : fileSplits) {
                Path path = new Path(fileSplit.getLocalFile().getFile().getPath());
                if (fileSystem.exists(path)) {
                    throw new Exception(" Output path :  already exists : " + path);
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
            throw ioe;
        }
        return true;
    }

    private static FileSplit[] getOutputSplits(JobConf conf, int noOfMappers) throws ClassNotFoundException {
        int numOutputters = conf.getNumReduceTasks() != 0 ? conf.getNumReduceTasks() : noOfMappers;
        Object outputFormat = null;
        if (conf.getUseNewMapper()) {
            outputFormat = ReflectionUtils.newInstance(new ContextFactory().createJobContext(conf)
                    .getOutputFormatClass(), conf);
        } else {
            outputFormat = conf.getOutputFormat();
        }
        if (outputFormat instanceof NullOutputFormat) {
            FileSplit[] outputFileSplits = new FileSplit[numOutputters];
            for (int i = 0; i < numOutputters; i++) {
                String outputPath = "/tmp/" + System.currentTimeMillis() + i;
                outputFileSplits[i] = new FileSplit("localhost", new FileReference(new File(outputPath)));
            }
            return outputFileSplits;
        } else {

            FileSplit[] outputFileSplits = new FileSplit[numOutputters];
            String absolutePath = FileOutputFormat.getOutputPath(conf).toString();
            for (int index = 0; index < numOutputters; index++) {
                String suffix = new String("part-00000");
                suffix = new String(suffix.substring(0, suffix.length() - ("" + index).length()));
                suffix = suffix + index;
                String outputPath = absolutePath + "/" + suffix;
                outputFileSplits[index] = new FileSplit("localhost", outputPath);
            }
            return outputFileSplits;
        }
    }

    public HadoopWriteOperatorDescriptor(IOperatorDescriptorRegistry jobSpec, JobConf jobConf, int numMapTasks)
            throws Exception {
        super(jobSpec, getOutputSplits(jobConf, numMapTasks));
        this.jobConfMap = DatatypeHelper.jobConf2Map(jobConf);
        checkIfCanWriteToHDFS(super.splits);
    }
}


text:
require 'spec_helper'

describe FromUnion do
  describe '.from_union' do
    let(:model) do
      Class.new(ActiveRecord::Base) do
        self.table_name = 'users'

        include FromUnion
      end
    end

    it 'selects from the results of the UNION' do
      query = model.from_union([model.where(id: 1), model.where(id: 2)])

      expect(query.to_sql).to match(/FROM \(SELECT.+UNION.+SELECT.+\) users/m)
    end

    it 'supports the use of a custom alias for the sub query' do
      query = model.from_union(
        [model.where(id: 1), model.where(id: 2)],
        alias_as: 'kittens'
      )

      expect(query.to_sql).to match(/FROM \(SELECT.+UNION.+SELECT.+\) kittens/m)
    end

    it 'supports keeping duplicate rows' do
      query = model.from_union(
        [model.where(id: 1), model.where(id: 2)],
        remove_duplicates: false
      )

      expect(query.to_sql)
        .to match(/FROM \(SELECT.+UNION ALL.+SELECT.+\) users/m)
    end
  end
end


text:
========
Usage
========

To use doubleloging in a project::

    import doubleloging


text:
function Get-Profiles
{
  <#
    .Synopsis
    Gets a list of user profiles on a computer.

    .Description
    This command gets a list of user priles on a computer. The info is pipable and can be used to do other useful tasks.

    .Parameter computer
    The computer on which you wish to recieve profiles. (defaults to localhost)

    .Example
    Get-Profiles -comptuer comp1
    Gets all of the profiles from comp1

    .Example
    Get-Content .\computers.txt | Get-Profiles
    Returns all of the profiles for the computers listed in computers.txt

    .Link
          Remove-Profiles
          Author:    Scott Keiffer
    Date:      08/27/09
  #>
  [CmdletBinding()]
  param ([parameter(ValueFromPipeLine=$true)][String]$computer = "localhost")
  process {
    $ErrorActionPreference = "SilentlyContinue"
    # Check for pipe input
    if ($_.Name)
    {
      $computer = $_.Name
    }
    elseif ($_)
    {
      $computer = $_
    }

    $profiles=$null
    # Get the userprofile list and then filter out the built-in accounts
    if ($computer)
    {
      $profiles = Get-WmiObject win32_userprofile -computerName $computer | ?{ $_.SID -like "S-1-5-21-*" -or $_.SID -like "S-1-5-82-*" }
      if (!$?)
      {
        Write-Warning "Unable to communicate with - $computer"
      }
    }
    else {
      Write-Warning "Unable to communicate with specified host."
    }

    if ($profiles.count -gt 0 -or ($profiles -and ($profiles.GetType()).Name -eq "ManagementObject"))
    {
      # Loop through the list of profiles
      foreach ($profile in $profiles)
      {
        Write-Verbose ("Reading profile for SID " + $profile.SID + " on $computer")
        $user = $null
        $objUser = $null
        #Create output objects
        $Output = New-Object PSObject
        # create a new secuity identifier object
        $ObjSID = New-Object System.Security.Principal.SecurityIdentifier($profile.SID)
        # Try to link the user SID to an actual user object (can fail for local accounts on remote machines,
        #  or the user no long exists but the profile still remains)
        try
        {
          $objUser = $objSID.Translate([System.Security.Principal.NTAccount])
        }
        catch
        {
          $user = "ERROR: Not Readable"
        }

        if ($objUser.Value)
        {
          $user = $objUser.Value
        }

        $Output | Add-Member NoteProperty Computer $computer
        $Output | Add-Member NoteProperty Username $user
        $Output | Add-Member NoteProperty SID $profile.SID
        $Output | Add-Member NoteProperty Path $profile.LocalPath
        #$Output | Add-Member NoteProperty Profile $profile

        Write-Output $Output
      }
    }
  }
}

function Remove-Profiles
{
  <#
    .Synopsis
    Deletes a list of profiles from a computer

    .Description
    This command deletes all profiles from a given computer. Or all profiles that have been piped in from the Get-Profiles command.

    .Parameter computer
    The computer on which you wish to delete profiles from. (defaults to localhost)

    .parameter commit
    This switch is used to write the changes. If switch is missing, no profiles will be deleted.

    .Example
    Remove-Profiles -comptuer comp1 -commit
    Deletes all of the profiles from comp1.

    .Example
    Get-Content .\computers.txt | Get-Profiles | Remove-Profiles
    Does a dry run of deleteing all user profiles from all of the computers listed in computers.txt

    .example
    Get-Content .\computers.txt | Get-Profiles | ?{$_.Username -like "*billy"} | Remove-Profiles -commit
    Deletes billy's user profile from all comptuers listed in computers.txt

    .Link
          Get-Profiles
          AUTHOR:    Scott Keiffer
    Date:      08/28/09
  #>
  [CmdletBinding()]
  param ([parameter(ValueFromPipeLine=$true)][String]$computer = "localhost", [Switch]$commit)
  begin
  {
    if (!$commit)
    {
      Write-Host -ForegroundColor Cyan "** No Profiles will be Deleted **"
    }
  }
  process
  {
    $ErrorActionPreference = "SilentlyContinue"
    # if piped info is present, use it. if not get the profiles from the given computer
    if ($_)
    {
      if (!$_.SID -or !$_.Computer)
      {
        Write-Warning "Malformed input, SID or Computer name missing from input."
        continue
      }
      #get the profile for the current SID
      $profile = Get-WmiObject -query ("select * from win32_userprofile where SID='" + $_.SID + "'") -computer $_.Computer

      #if commit flag is present do the delete
      $success = $true
      if ($commit)
      {
        Write-Verbose "Attempting to delete profile for user: " + $_.Username
        # The delete process can take some time per profile, timeout is also very high, be patient.
        try
        {
          $profile.Delete()
        }
        catch
        {
          $success = $false
        }
      }

      if ($success)
      {
        Write-Host "Deleted Profile with Username:" $_.Username "From:" $_.Computer
      }
      else
      {
        Write-Warning ("Unable to Delete or Fully Delete Profile (possibly logged in, or file in use) with Username: " + $_.Username + " From: " + $_.Computer)
        #Write-Host $profile.SID
      }
    }
    else
    {
      # Get the userprofile list and then filter out the built-in accounts
      $profiles = Get-WmiObject win32_userprofile -computer $computer | ?{ $_.SID -like "S-1-5-21*" }
      if ($?)
      {
        foreach ($profile in $profiles)
        {
          $success = $true
          if ($commit)
          {
            Write-Verbose ("Attempting to delete profile for SID: " + $profile.SID)
            # The delete process can take some time per profile, timeout is also very high, be patient.
            try
            {
              $profile.Delete()
            }
            catch
            {
              $success = $false
            }
          }
          if($success)
          {
            Write-Host "Deleted Profile with SID:" $profile.SID "From:" $computer
          }
          else
          {
            Write-Warning "Unable to Delete or Fully Delete Profile (possibly logged in, or file in use) with SID: " + $profile.SID + " From: " + $computer
          }
        }
      }
      else
      {
        Write-Warning "Unable to communicate with - $computer"
      }
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 330543 $ -->
<refentry xml:id="function.sqlite-create-function" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>sqlite_create_function</refname>
  <refname>SQLiteDatabase::createFunction</refname>
  <refpurpose>
   Registers a "regular" User Defined Function for use in SQL statements
  </refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>void</type><methodname>sqlite_create_function</methodname>
   <methodparam><type>resource</type><parameter>dbhandle</parameter></methodparam>
   <methodparam><type>string</type><parameter>function_name</parameter></methodparam>
   <methodparam><type>callable</type><parameter>callback</parameter></methodparam>
   <methodparam choice="opt"><type>int</type><parameter>num_args</parameter><initializer>-1</initializer></methodparam>
  </methodsynopsis>
  <para>&style.oop; (method):</para>
  <methodsynopsis>
   <modifier>public</modifier> <type>void</type><methodname>SQLiteDatabase::createFunction</methodname>
   <methodparam><type>string</type><parameter>function_name</parameter></methodparam>
   <methodparam><type>callable</type><parameter>callback</parameter></methodparam>
   <methodparam choice="opt"><type>int</type><parameter>num_args</parameter><initializer>-1</initializer></methodparam>
  </methodsynopsis>
  <para>
   <function>sqlite_create_function</function> allows you to register a PHP
   function with SQLite as an <acronym>UDF</acronym> (User Defined
   Function), so that it can be called from within your SQL statements.
  </para>
  <para>
   The UDF can be used in any SQL statement that can call functions, such as
   SELECT and UPDATE statements and also in triggers.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>dbhandle</parameter></term>
     <listitem>
      <para>
       The SQLite Database resource; returned from <function>sqlite_open</function>
       when used procedurally.  This parameter is not required
       when using the object-oriented method.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>function_name</parameter></term>
     <listitem>
      <para>
       The name of the function used in SQL statements.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>callback</parameter></term>
     <listitem>
      <para>
       Callback function to handle the defined SQL function.
      </para>
      <note>
       <simpara>
        Callback functions should return a type understood by SQLite (i.e.
        <link linkend="language.types.intro">scalar type</link>).
       </simpara>
      </note>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>num_args</parameter></term>
     <listitem>
      <para>
       Hint to the SQLite parser if the callback function accepts a
       predetermined number of arguments.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
  &sqlite.param-compat;
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   &return.void;
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title><function>sqlite_create_function</function> example</title>
    <programlisting role="php">
<![CDATA[
<?php
function md5_and_reverse($string)
{
    return strrev(md5($string));
}

if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {

    sqlite_create_function($dbhandle, 'md5rev', 'md5_and_reverse', 1);

    $sql  = 'SELECT md5rev(filename) FROM files';
    $rows = sqlite_array_query($dbhandle, $sql);
} else {
    echo 'Error opening sqlite db: ' . $sqliteerror;
    exit;
}
?>
]]>
    </programlisting>
   </example>
  </para>
  <para>
   In this example, we have a function that calculates the md5 sum of a
   string, and then reverses it.  When the SQL statement executes, it
   returns the value of the filename transformed by our function.  The data
   returned in <parameter>$rows</parameter> contains the processed result.
  </para>
  <para>
   The beauty of this technique is that you do not need to process the
   result using a &foreach; loop after you have queried for the data.
  </para>
  <para>
   PHP registers a special function named <literal>php</literal> when the
   database is first opened.  The php function can be used to call any PHP
   function without having to register it first.
  </para>
  <para>
   <example>
    <title>Example of using the PHP function</title>
    <programlisting role="php">
<![CDATA[
<?php
$rows = sqlite_array_query($dbhandle, "SELECT php('md5', filename) from files");
?>
]]>
    </programlisting>
    <para>
     This example will call the <function>md5</function> on each
     <literal>filename</literal> column in the database and return the result
     into <parameter>$rows</parameter>
    </para>
   </example>
  </para>
  <note>
   <para>
    For performance reasons, PHP will not automatically encode/decode binary
    data passed to and from your UDF's.  You need to manually encode/decode
    the parameters and return values if you need to process binary data in
    this way.  Take a look at <function>sqlite_udf_encode_binary</function>
    and <function>sqlite_udf_decode_binary</function> for more details.
   </para>
  </note>
  <tip>
   <para>
    It is not recommended to use UDF's to handle processing of
    binary data, unless high performance is not a key requirement of your
    application.
   </para>
  </tip>
  <tip>
   <para>
    You can use <function>sqlite_create_function</function> and
    <function>sqlite_create_aggregate</function> to override SQLite native
    SQL functions.
   </para>
  </tip>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>sqlite_create_aggregate</function></member>
   </simplelist>
  </para>
 </refsect1>
</refentry>

<!-- Keep this comment at the end of the file
 Local variables:
 mode: sgml
 sgml-omittag:t
 sgml-shorttag:t
 sgml-minimize-attributes:nil
 sgml-always-quote-attributes:t
 sgml-indent-step:1
 sgml-indent-data:t
 sgml-parent-document:nil
 sgml-default-dtd-file:"~/.phpdoc/manual.ced"
 sgml-exposed-tags:nil
 sgml-local-catalogs:nil
 sgml-local-ecat-files:nil
 End:
 vim600: syn=xml fen fdm=syntax fdl=2 si
 vim: et tw=78 syn=sgml
 vi: ts=1 sw=1
 -->


text:
import AllyCard from "../../../src/artifact/js/AllyCard.js";
import AttachmentCard from "../../../src/artifact/js/AttachmentCard.js";
import EnemyCard from "../../../src/artifact/js/EnemyCard.js";
import HeroCard from "../../../src/artifact/js/HeroCard.js";
import LocationCard from "../../../src/artifact/js/LocationCard.js";
import ObjectiveCard from "../../../src/artifact/js/ObjectiveCard.js";
import QuestCard from "../../../src/artifact/js/QuestCard.js";
import Scenario from "../../../src/artifact/js/Scenario.js";
import Sphere from "../../../src/artifact/js/Sphere.js";
import Action from "../../../src/model/js/Action.js";
import Agent from "../../../src/model/js/Agent.js";
import AgentAction from "../../../src/model/js/AgentAction.js";
import CardAction from "../../../src/model/js/CardAction.js";
import CardInstance from "../../../src/model/js/CardInstance.js";
import EventObserver from "../../../src/model/js/EventObserver.js";
import Environment from "../../../src/model/js/Environment.js";
import PlayerDeckBuilder from "../../../src/model/js/PlayerDeckBuilder.js";
import Reducer from "../../../src/model/js/Reducer.js";
import ScenarioDeckBuilder from "../../../src/model/js/ScenarioDeckBuilder.js";

QUnit.module("CardInstance");

QUnit.test("CardInstance()", function(assert)
{
   // Setup.
   var store = Redux.createStore(Reducer.root);
   var cardKey = HeroCard.ARAGORN_CORE;
   var card = HeroCard.properties[cardKey];

   // Run.
   var result = new CardInstance(store, card);

   // Verify.
   assert.ok(result);
   assert.equal(result.id(), 1);
   assert.equal(result.card().key, cardKey);
   assert.equal(Object.keys(store.getState().cardInstances).length, 1);
});

QUnit.test("attack() Chieftain Ufthak", function(assert)
{
   // Setup.
   var store = Redux.createStore(Reducer.root);
   var cardKey = EnemyCard.CHIEFTAN_UFTHAK;
   var card = EnemyCard.properties[cardKey];
   var cardInstance = new CardInstance(store, card);

   // Run.
   var result = cardInstance.attack();

   // Verify.
   assert.equal(result, 3);

   // Run.
   store.dispatch(CardAction.addResources(cardInstance, 1));
   result = cardInstance.attack();

   // Verify.
   assert.equal(result, 5);
});

QUnit.test("bonusAttack() Chieftain Ufthak", function(assert)
{
   // Setup.
   var store = Redux.createStore(Reducer.root);
   var cardKey = EnemyCard.CHIEFTAN_UFTHAK;
   var card = EnemyCard.properties[cardKey];
   var cardInstance = new CardInstance(store, card);

   // Run.
   var result = cardInstance.bonusAttack();

   // Verify.
   assert.equal(result, 0);

   // Run.
   store.dispatch(CardAction.addResources(cardInstance, 1));
   result = cardInstance.bonusAttack();

   // Verify.
   assert.equal(result, 2);
});

QUnit.test("bonusAttack() Gimli", function(assert)
{
   // Setup.
   var store = Redux.createStore(Reducer.root);
   var cardKey = HeroCard.GIMLI;
   var card = HeroCard.properties[cardKey];
   var cardInstance = new CardInstance(store, card);

   // Run.
   var result = cardInstance.bonusAttack();

   // Verify.
   assert.equal(result, 0);

   // Run.
   store.dispatch(CardAction.addWounds(cardInstance, 1));
   result = cardInstance.bonusAttack();

   // Verify.
   assert.equal(result, 1);
});

QUnit.test("bonusAttack() Gimli + Dwarven Axe", function(assert)
{
   // Setup.
   var scenarioKey = Scenario.PASSAGE_THROUGH_MIRKWOOD;
   var environment = createEnvironment(scenarioKey);
   var store = environment.store();
   var agent4 = environment.agentQueue()[3];
   var cardInstance = new CardInstance(store, HeroCard.properties[HeroCard.GIMLI]);
   agent4.drawPlayerCard(AttachmentCard.DWARVEN_AXE);
   var attachmentInstance = agent4.hand()[agent4.hand().length - 1];
   store.dispatch(AgentAction.playCard(agent4, attachmentInstance));
   store.dispatch(AgentAction.attachCard(agent4, cardInstance, attachmentInstance));

   // Run.
   var result = cardInstance.bonusAttack();

   // Verify.
   assert.equal(result, 2);

   // Run.
   store.dispatch(CardAction.addWounds(cardInstance, 1));
   result = cardInstance.bonusAttack();

   // Verify.
   assert.equal(result, 3);
});

QUnit.test("bonusDefense() Gimli + Dwarven Axe", function(assert)
{
   // Setup.
   var scenarioKey = Scenario.PASSAGE_THROUGH_MIRKWOOD;
   var environment = createEnvironment(scenarioKey);
   var store = environment.store();
   var agent4 = environment.agentQueue()[3];
   var cardInstance = new CardInstance(store, HeroCard.properties[HeroCard.GIMLI]);
   agent4.drawPlayerCard(AttachmentCard.DWARVEN_AXE);
   var attachmentInstance = agent4.hand()[agent4.hand().length - 1];
   store.dispatch(AgentAction.playCard(agent4, attachmentInstance));
   store.dispatch(AgentAction.attachCard(agent4, cardInstance, attachmentInstance));

   // Run.
   var result = cardInstance.bonusDefense();

   // Verify.
   assert.equal(result, 0);
});

QUnit.test("bonusHitPoints() Gimli + Dwarven Axe", function(assert)
{
   // Setup.
   var scenarioKey = Scenario.PASSAGE_THROUGH_MIRKWOOD;
   var environment = createEnvironment(scenarioKey);
   var store = environment.store();
   var agent4 = environment.agentQueue()[3];
   var cardInstance = new CardInstance(store, HeroCard.properties[HeroCard.GIMLI]);
   agent4.drawPlayerCard(AttachmentCard.DWARVEN_AXE);
   var attachmentInstance = agent4.hand()[agent4.hand().length - 1];
   store.dispatch(AgentAction.playCard(agent4, attachmentInstance));
   store.dispatch(AgentAction.attachCard(agent4, cardInstance, attachmentInstance));

   // Run.
   var result = cardInstance.bonusHitPoints();

   // Verify.
   assert.equal(result, 0);
});

QUnit.test("bonusWillpower() Gimli + Dwarven Axe", function(assert)
{
   // Setup.
   var scenarioKey = Scenario.PASSAGE_THROUGH_MIRKWOOD;
   var environment = createEnvironment(scenarioKey);
   var store = environment.store();
   var agent4 = environment.agentQueue()[3];
   var cardInstance = new CardInstance(store, HeroCard.properties[HeroCard.GIMLI]);
   agent4.drawPlayerCard(AttachmentCard.DWARVEN_AXE);
   var attachmentInstance = agent4.hand()[agent4.hand().length - 1];
   store.dispatch(AgentAction.playCard(agent4, attachmentInstance));
   store.dispatch(AgentAction.attachCard(agent4, cardInstance, attachmentInstance));

   // Run.
   var result = cardInstance.bonusWillpower();

   // Verify.
   assert.equal(result, 0);
});

QUnit.test("get()", function(assert)
{
   // Setup.
   var store = Redux.createStore(Reducer.root);
   var cardKey = HeroCard.ARAGORN_CORE;
   var card = HeroCard.properties[cardKey];
   var cardInstance = new CardInstance(store, card);
   assert.equal(Object.keys(store.getState().cardInstances).length, 1);

   // Run.
   var result = CardInstance.get(store, cardInstance.id());

   // Verify.
   assert.ok(result);
   assert.equal(result.id(), 1);
   assert.equal(result.card().key, cardKey);
   assert.equal(Object.keys(store.getState().cardInstances).length, 1);
});

QUnit.test("hasAttachment() Gimli + Dwarven Axe", function(assert)
{
   // Setup.
   var scenarioKey = Scenario.PASSAGE_THROUGH_MIRKWOOD;
   var environment = createEnvironment(scenarioKey);
   var store = environment.store();
   var agent4 = environment.agentQueue()[3];
   var cardInstance = new CardInstance(store, HeroCard.properties[HeroCard.GIMLI]);

   // Run.
   var result = cardInstance.hasAttachment(AttachmentCard.DWARVEN_AXE);

   // Verify.
   assert.equal(result, false);

   // Run.
   agent4.drawPlayerCard(AttachmentCard.DWARVEN_AXE);
   var attachmentInstance = agent4.hand()[agent4.hand().length - 1];
   store.dispatch(AgentAction.playCard(agent4, attachmentInstance));
   store.dispatch(AgentAction.attachCard(agent4, cardInstance, attachmentInstance));
   result = cardInstance.hasAttachment(AttachmentCard.DWARVEN_AXE);

   // Verify.
   assert.equal(result, true);
});

QUnit.test("isEncounterType", function(assert)
{
   // Setup.
   var store = Redux.createStore(Reducer.root);
   var cardInstance0 = new CardInstance(store, EnemyCard.properties[EnemyCard.BLACK_FOREST_BATS_PTM]);
   var cardInstance1 = new CardInstance(store, HeroCard.properties[HeroCard.ARAGORN_CORE]);
   var cardInstance2 = new CardInstance(store, QuestCard.properties[QuestCard.PTM1B_FLIES_AND_SPIDERS]);

   // Run / Verify.
   assert.equal(cardInstance0.isEncounterType(), true);
   assert.equal(cardInstance1.isEncounterType(), false);
   assert.equal(cardInstance2.isEncounterType(), false);
});

QUnit.test("isPlayerType()", function(assert)
{
   // Setup.
   var store = Redux.createStore(Reducer.root);
   var cardInstance0 = new CardInstance(store, EnemyCard.properties[EnemyCard.BLACK_FOREST_BATS_PTM]);
   var cardInstance1 = new CardInstance(store, HeroCard.properties[HeroCard.ARAGORN_CORE]);
   var cardInstance2 = new CardInstance(store, QuestCard.properties[QuestCard.PTM1B_FLIES_AND_SPIDERS]);

   // Run / Verify.
   assert.equal(cardInstance0.isPlayerType(), false);
   assert.equal(cardInstance1.isPlayerType(), true);
   assert.equal(cardInstance2.isPlayerType(), false);
});

QUnit.test("isQuestType", function(assert)
{
   // Setup.
   var store = Redux.createStore(Reducer.root);
   var cardInstance0 = new CardInstance(store, EnemyCard.properties[EnemyCard.BLACK_FOREST_BATS_PTM]);
   var cardInstance1 = new CardInstance(store, HeroCard.properties[HeroCard.ARAGORN_CORE]);
   var cardInstance2 = new CardInstance(store, QuestCard.properties[QuestCard.PTM1B_FLIES_AND_SPIDERS]);

   // Run / Verify.
   assert.equal(cardInstance0.isQuestType(), false);
   assert.equal(cardInstance1.isQuestType(), false);
   assert.equal(cardInstance2.isQuestType(), true);
});

QUnit.test("shadowCards()", function(assert)
{
   // Setup.
   var store = Redux.createStore(Reducer.root);
   var scenarioDeck = ScenarioDeckBuilder.PassageThroughMirkwoodDeckBuilder.buildDeck(store);
   store.dispatch(Action.setEncounterDeck(scenarioDeck.encounterInstances));
   var cardKey = HeroCard.ARAGORN_CORE;
   var card = HeroCard.properties[cardKey];
   var cardInstance = new CardInstance(store, card);

   // Run.
   var result = cardInstance.shadowCards();

   // Verify.
   assert.ok(result);
   assert.equal(result.length, 0);

   store.dispatch(Action.dealShadowCard(cardInstance));

   // Run.
   result = cardInstance.shadowCards();

   // Verify.
   assert.ok(result);
   assert.equal(result.length, 1);
});

QUnit.test("sphereKeys() Aragorn", function(assert)
{
   // Setup.
   var store = Redux.createStore(Reducer.root);
   var cardInstance = new CardInstance(store, HeroCard.properties[HeroCard.ARAGORN_CORE]);

   // Run.
   var result = cardInstance.sphereKeys();

   // Verify.
   assert.ok(result);
   assert.equal(result.length, 1);
   assert.equal(result[0], Sphere.LEADERSHIP);
});

QUnit.test("sphereKeys() Aragorn with Celebrian's Stone", function(assert)
{
   // Setup.
   var scenarioKey = Scenario.PASSAGE_THROUGH_MIRKWOOD;
   var environment = createEnvironment(scenarioKey);
   var store = environment.store();
   var agent1 = environment.agentQueue()[0];
   var cardInstance = new CardInstance(store, HeroCard.properties[HeroCard.ARAGORN_CORE]);
   agent1.drawPlayerCard(AttachmentCard.CELEBRIANS_STONE);
   var attachmentInstance = agent1.hand()[agent1.hand().length - 1];
   store.dispatch(AgentAction.playCard(agent1, attachmentInstance));
   store.dispatch(AgentAction.attachCard(agent1, cardInstance, attachmentInstance));

   // Run.
   var result = cardInstance.sphereKeys();

   // Verify.
   assert.ok(result);
   assert.equal(result.length, 2);
   assert.equal(result[0], Sphere.LEADERSHIP);
   assert.equal(result[1], Sphere.SPIRIT);
});

QUnit.test("sphereKeys() Gimli with Celebrian's Stone", function(assert)
{
   // Setup.
   var scenarioKey = Scenario.PASSAGE_THROUGH_MIRKWOOD;
   var environment = createEnvironment(scenarioKey);
   var store = environment.store();
   var agent1 = environment.agentQueue()[0];
   var cardInstance = new CardInstance(store, HeroCard.properties[HeroCard.GIMLI]);
   agent1.drawPlayerCard(AttachmentCard.CELEBRIANS_STONE);
   var attachmentInstance = agent1.hand()[agent1.hand().length - 1];
   store.dispatch(AgentAction.playCard(agent1, attachmentInstance));
   store.dispatch(AgentAction.attachCard(agent1, cardInstance, attachmentInstance));

   // Run.
   var result = cardInstance.sphereKeys();

   // Verify.
   assert.ok(result);
   assert.equal(result.length, 1);
   assert.equal(result[0], Sphere.TACTICS);
});

QUnit.test("threat() The Hunt for Gollum", function(assert)
{
   // Setup.
   var scenarioKey = Scenario.THE_HUNT_FOR_GOLLUM;
   var environment = createEnvironment(scenarioKey);
   var store = environment.store();
   var agent1 = environment.firstAgent();
   agent1.drawPlayerCard(AllyCard.FARAMIR);
   var cardInstance = agent1.hand()[agent1.hand().length - 1];
   store.dispatch(AgentAction.playCard(agent1, cardInstance));
   assert.equal(environment.cardsInPlay().length, 14);
   var cardInstance0 = environment.firstCardInstance(LocationCard.THE_OLD_FORD);

   // Run.
   assert.ok(cardInstance0);
   assert.equal(cardInstance0.threat(), 1);
});

QUnit.test("threat() A Journey to Rhosgobel", function(assert)
{
   // Setup.
   var scenarioKey = Scenario.A_JOURNEY_TO_RHOSGOBEL;
   var environment = createEnvironment(scenarioKey);
   environment.drawEncounterCard(LocationCard.RHOSGOBEL);
   var cardInstance0 = environment.stagingArea()[environment.stagingArea().length - 1];
   environment.drawEncounterCard(ObjectiveCard.ATHELAS);
   var cardInstance1 = environment.stagingArea()[environment.stagingArea().length - 1];

   // Run.
   assert.ok(cardInstance0);
   assert.equal(cardInstance0.threat(), 4);
   assert.ok(cardInstance1);
   assert.equal(cardInstance1.threat(), 0);
});

function createEnvironment(scenarioKey)
{
   var store = Redux.createStore(Reducer.root);
   var scenarioDeckBuilder = ScenarioDeckBuilder.ScenarioDeckBuilder.findByScenario(scenarioKey);
   var scenarioDeck = scenarioDeckBuilder.buildDeck(store);
   var agent1 = new Agent(store, "agent1");
   var agent2 = new Agent(store, "agent2");
   var agent3 = new Agent(store, "agent3");
   var agent4 = new Agent(store, "agent4");
   var playerData = [
      {
         agent: agent1,
         playerDeck: PlayerDeckBuilder.CoreLeadershipDeckBuilder.buildDeck(store),
    },
      {
         agent: agent2,
         playerDeck: PlayerDeckBuilder.CoreLoreDeckBuilder.buildDeck(store),
    },
      {
         agent: agent3,
         playerDeck: PlayerDeckBuilder.CoreSpiritDeckBuilder.buildDeck(store),
    },
      {
         agent: agent4,
         playerDeck: PlayerDeckBuilder.CoreTacticsDeckBuilder.buildDeck(store),
    }, ];

   var environment = new Environment(store, scenarioDeck, playerData);
   store.dispatch(Action.setFirstAgent(playerData[0].agent));
   playerData.forEach(function(data)
   {
      var agent = data.agent;
      for (var i = 0; i < 6; i++)
      {
         store.dispatch(AgentAction.drawPlayerCard(agent));
      }
   });
   store.dispatch(Action.drawQuestCard());
   EventObserver.observeStore(store);

   return environment;
}

var CardInstanceTest = {};
export default CardInstanceTest;


text:
<?php
namespace Afrittella\LaravelLoggable\Traits;

trait HasLogs
{
    public function logs()
    {
        return $this->morphMany(config('loggable.log_model'), 'loggable');
    }

    public function hasLogs()
    {
        return (count($this->logs->toArray()) > 0);
    }

    public function delete()
    {
        if ($this->hasLogs()) {
            $this->logs()->each(function($item) {
                $item->delete();
            });
        }

        return parent::delete();
    }
}


text:
.miqGreeter {
  background-color: red;
  color: white; }

td.miqTextLeft {
  text-align: left; }

td.miqTextRight {
  text-align: right; }

table.mig-table-with-footer {
  margin-bottom: 0px; }

.dataTables_footer span {
  margin-left: 10px; }

.form-actions button.btn {
  margin-right: 5px; }

.mig-table thead th {
  color: #0099d3;
  cursor: pointer; }

.miq-alert-section {
  margin-top: 10px; }
  .miq-alert-section .miq-info-alert {
    text-align: center; }

.toolbar-pf-actions .toolbar-pf-actions.miq-toolbar-actions {
  display: inline; }

img.miq-gradient-background {
  border-radius: 15px;
  background: #adadad;
  /* Old browsers */
  background: -moz-linear-gradient(top, #adadad 5%, #adadad 5%, #000000 98%, #000000 98%);
  /* FF3.6-15 */
  background: -webkit-linear-gradient(top, #adadad 5%, #adadad 5%, #000000 98%, #000000 98%);
  /* Chrome10-25,Safari5.1-6 */
  background: linear-gradient(to bottom, #adadad 5%, #adadad 5%, #000000 98%, #000000 98%);
  /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#adadad', endColorstr='#000000',GradientType=0 );
  /* IE6-9 */ }

.miq-row-margin-only-top {
  margin-top: 15px;
  margin-left: 0;
  margin-right: 0; }

.miq-tile-section div.miq-load-more {
  text-align: center; }

.miq-tile-with-body .card-view-pf .card {
  width: 350px;
  height: 170px;
  animation: fade-in 2s; }
  .miq-tile-with-body .card-view-pf .card .card-content {
    overflow: hidden; }
  .miq-tile-with-body .card-view-pf .card .miq-icon-section {
    padding-right: 0; }
  .miq-tile-with-body .card-view-pf .card .miq-info-section {
    padding-left: 0; }
    .miq-tile-with-body .card-view-pf .card .miq-info-section dd {
      text-align: left; }

.miq-small-tile .card-view-pf .card {
  width: 170px;
  height: 140px;
  animation: fade-in 2s; }
  .miq-small-tile .card-view-pf .card .card-content a {
    word-wrap: break-word; }

@keyframes fade-in {
  0% {
    opacity: 0; }
  60% {
    opacity: 1; }
  100% {
    opacity: 1; } }

.miq-data-tables-header {
  text-align: left; }

.form-group.miq-toolbar-group {
  margin-right: 20px;
  display: inline-block; }
  .form-group.miq-toolbar-group .miq-custom-html form {
    display: inline-block; }
  .form-group.miq-toolbar-group .miq-custom-html .form-group {
    margin-bottom: 0 !important;
    border-right: 0; }

/*# sourceMappingURL=hawkular-ui-components.css.map*/


text:
package com.connectsdk.service;

import com.connectsdk.discovery.DiscoveryManager;
import com.connectsdk.service.capability.CapabilityMethods;
import com.connectsdk.service.capability.MediaControl;
import com.connectsdk.service.capability.MediaPlayer;
import com.connectsdk.service.capability.listeners.ResponseListener;
import com.connectsdk.service.command.NotSupportedServiceCommandError;
import com.connectsdk.service.command.ServiceCommand;
import com.connectsdk.service.command.ServiceCommandError;
import com.connectsdk.service.config.ServiceConfig;
import com.connectsdk.service.config.ServiceDescription;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class NetCastTVServiceTest {

    private NetcastTVService service;

    private ServiceDescription serviceDescription;

    private ServiceConfig serviceConfig;

    @Before
    public void setUp() {
        serviceDescription = Mockito.mock(ServiceDescription.class);
        Mockito.when(serviceDescription.getModelNumber()).thenReturn("4.0");
        serviceConfig = Mockito.mock(ServiceConfig.class);
        service = new NetcastTVService(serviceDescription, serviceConfig);
    }

    @Test
    public void testDecToHex() {
        Assert.assertEquals("0000000000000010", service.decToHex("16"));
    }

    @Test
    public void testDecToHexWithNullArgument() {
        Assert.assertEquals(null, service.decToHex(null));
    }

    @Test
    public void testDecToHexWithEmptyArgument() {
        Assert.assertEquals(null, service.decToHex(""));
    }

    @Test
    public void testDecToHexWithWrongArgument() {
        Assert.assertEquals(null, service.decToHex("Not a number"));
    }

    @Test
    public void testDecToHexWithWrongCharactersArgument() {
        Assert.assertEquals("0000000000000010", service.decToHex(" 16\r\n"));
    }

    @Test
    public void testServiceShouldHasSubtitleCapabilityWhenPairingLevelOn() {
        setPairingLevel(DiscoveryManager.PairingLevel.OFF);
        Assert.assertTrue(service.hasCapability(MediaPlayer.Subtitle_SRT));
    }

    @Test
    public void testServiceShouldHasSubtitleCapabilityWhenPairingLevelOff() {
        setPairingLevel(DiscoveryManager.PairingLevel.ON);
        Assert.assertTrue(service.hasCapability(MediaPlayer.Subtitle_SRT));
    }

    @Test
    public void testShouldNotContainRewindCapabilityWhenPairingLevelOff() {
        setPairingLevel(DiscoveryManager.PairingLevel.OFF);
        Assert.assertFalse(service.hasCapability(MediaControl.Rewind));
    }

    @Test
    public void testShouldNotContainRewindCapabilityWhenPairingLevelOn() {
        setPairingLevel(DiscoveryManager.PairingLevel.ON);
        Assert.assertFalse(service.hasCapability(MediaControl.Rewind));
    }

    @Test
    public void testShouldNotContainFastForwardCapabilityWhenPairingLevelOff() {
        setPairingLevel(DiscoveryManager.PairingLevel.OFF);
        Assert.assertFalse(service.hasCapability(MediaControl.FastForward));
    }

    @Test
    public void testShouldNotContainFastForwardCapabilityWhenPairingLevelOn() {
        setPairingLevel(DiscoveryManager.PairingLevel.ON);
        Assert.assertFalse(service.hasCapability(MediaControl.FastForward));
    }

    @Test
    public void testRewindShouldSendNotSupportedError() {
        ResponseListener<Object> listener = Mockito.mock(ResponseListener.class);
        service.rewind(listener);
        verifyNotImplemented(listener);
    }

    @Test
    public void testFastForwardShouldSendNotSupportedError() {
        ResponseListener<Object> listener = Mockito.mock(ResponseListener.class);
        service.fastForward(listener);
        verifyNotImplemented(listener);
    }

    @Test
    public void testMediaPlayerPriorityShouldBeHigh() {
        Assert.assertEquals(CapabilityMethods.CapabilityPriorityLevel.HIGH,
                service.getMediaPlayerCapabilityLevel());
    }

    @Test
    public void testMediaControlPriorityShouldBeHigh() {
        Assert.assertEquals(CapabilityMethods.CapabilityPriorityLevel.HIGH,
                service.getMediaControlCapabilityLevel());
    }

    private void verifyNotImplemented(ResponseListener<Object> listener) {
        ArgumentCaptor<ServiceCommandError> argError
                = ArgumentCaptor.forClass(ServiceCommandError.class);
        Mockito.verify(listener).onError(argError.capture());
        Assert.assertTrue(argError.getValue() instanceof NotSupportedServiceCommandError);
    }

    private void setPairingLevel(DiscoveryManager.PairingLevel level) {
        DiscoveryManager.init(Robolectric.application);
        DiscoveryManager.getInstance().setPairingLevel(level);
    }

}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:dslv="http://schemas.android.com/apk/res/com.jams.music.player"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/customize_screens_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="5dp"
        android:layout_marginRight="15dp"
        android:text="@string/customize_screens_text"
        android:textAppearance="?android:attr/textAppearanceSmall" />

	<com.mobeta.android.dslv.DragSortListView
	    xmlns:dslv="http://schemas.android.com/apk/res/com.jams.music.player"
	    android:id="@+id/customize_screens_listview"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_margin="3dp"
	    android:layout_below="@+id/customize_screens_text"
	    android:choiceMode="multipleChoice"
	    dslv:drag_enabled="true"
	    dslv:drag_handle_id="@+id/customize_screens_handle"
	    dslv:drag_scroll_start="0.33"
	    dslv:drag_start_mode="onDown"
	    dslv:float_alpha="0.6"
	    dslv:slide_shuffle_speed="0.3" />

</RelativeLayout>


text:
<?php
require_once 'init.php';

if (isset($_POST['content'])) {
  sendMessage($currentUser['id'], $_GET['id'], $_POST['content']);
}

$messages = getMessagesWithUserId($currentUser['id'], $_GET['id']);
$user = findUserById($_GET['id']);

?>
<?php include 'header.php' ?>

Cuộc trò chuyện với: <?php echo $user['fullname'] ?>

<?php foreach ($messages as $message) : ?>

    <?php if ($message['type'] == 1) : ?>

      <?php echo $user['fullname'] ?>:
      <?php echo $message['content'] ?>

    <?php else: ?>

      <?php echo $message['content'] ?>

    <?php endif; ?>

<?php endforeach; ?>
<form method="POST">

    Tin nhắn:
    <textarea class="form-control" id="content" name="content" rows="3"></textarea>

  <button type="submit" class="btn btn-primary">Gửi tin nhắn</button>
</form>
<?php include 'footer.php' ?>