text:
/**
 * bluetooth.h: Serial communication over Bluetooth
 * via RN-42-I/RM
 * 2014, Zeger Van de Vannet
 */

#ifndef BLUETOOTH_H
#define BLUETOOTH_H

#include "stm32f30x.h"
#include "stm32f30x_conf.h"
#include "stm32f3_discovery.h"
#include "stm32f30x_it.h"
#include "controls.h"

/**
 * Initialize bluetooth communication
 *
 */
void bluetooth_init(void);

/**
 * Reset the RN42 module
 */
void bluetooth_reset(void);

/**
 * Write data to bluetooth module
 * data - char array with data
 * size - size of the data array
 */
void bluetooth_write(uint8_t* data, int size);

/**
 * Test integrity of the data bytes received using CRC
 * CRC is performed on blocks of 4 bytes, function will pad with zero bytes
 * data_bytes - array of bytes
 * size       - number of bytes
 * checksum   - checksum byte
 *
 * returns 0 if checksums do not match
 */
uint8_t bluetooth_check_integrity(uint8_t* data_bytes, uint8_t size, uint8_t checksum);

/**
 * Test if RN42 module is connected to remote
 *
 * returns 0 if device is not connected
 * returns 1 if device is connected
 */
uint8_t bluetooth_connected(void);

#endif

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe EventInvitationMailer do
  let(:email) { ActionMailer::Base.deliveries.last }
  let(:event) { Fabricate(:event, date_and_time: Time.zone.local(2017, 11, 12, 10, 0), name: 'Test event') }
  let(:member) { Fabricate(:member) }
  let(:invitation) { Fabricate(:invitation, event: event, member: member) }

  it '#invite_student' do
    email_subject = "Invitation: #{event.name}"
    EventInvitationMailer.invite_student(event, member, invitation).deliver_now

    expect(email.subject).to eq(email_subject)
  end

  it '#invite_coach' do
    email_subject = "Coach Invitation: #{event.name}"
    EventInvitationMailer.invite_coach(event, member, invitation).deliver_now

    expect(email.subject).to eq(email_subject)
  end

  it '#attending' do
    email_subject = "Your spot to #{event.name} has been confirmed."
    EventInvitationMailer.attending(event, member, invitation).deliver_now

    expect(email.subject).to eq(email_subject)
  end
end


text:
<?php
class Kwf_Media
{
    private static $_ouputCache;
    const DONT_HASH_TYPE_PREFIX = 'dh-';

    /**
     *
     * @param string
     * @param string
     * @param string
     * @param string
     * @param int Kann gesetzt werden wenn wir in diesem web auf das bild nicht direkten zugriff haben
     *            sondern nur für ein anderes web die url generieren
     */
    public static function getUrl($class, $id, $type, $filename, $time = null)
    {
        if ($filename instanceof Kwf_Uploads_Row) {
            $filename = $filename->filename . '.' . $filename->extension;
        }
        if ($filename == '.') $filename = '';

        //Replace Slashes and Backslashes with an underscore
        //Otherwise we would get a wrong url
        //e.g. $filename = foo/bar.png -> /media/FooModel/1/default/ab123/1234/foo/bar.png
        $filename = str_replace('/', '_', $filename);
        $filename = str_replace('\\', '_', $filename);
        $checksumType = $type;
        if (substr($type, 0, strlen(Kwf_Media::DONT_HASH_TYPE_PREFIX)) == Kwf_Media::DONT_HASH_TYPE_PREFIX) {
            $checksumType = Kwf_Media::DONT_HASH_TYPE_PREFIX;
        }
        $class = rawurlencode($class);
        $checksum = self::getChecksum($class, $id, $checksumType, rawurlencode($filename));
        $prefix = Kwf_Setup::getBaseUrl();
        if ($r = Kwf_Component_Data_Root::getInstance()) {
            if ($r->filename) {
                $prefix .= '/'.$r->filename;
            }
        }
        if (is_null($time)) {
            $cacheId = 'mtime-'.self::createCacheId($class, $id, $type);
            $time = Kwf_Media_MemoryCache::getInstance()->load($cacheId);
            if (!$time) {
                $time = time();
                Kwf_Media_MemoryCache::getInstance()->save($time, $cacheId);
            }
        }
        return $prefix.'/media/'.$class.'/'.$id.'/'.$type.'/'.$checksum.'/'.$time.'/'.rawurlencode($filename);
    }

    public static function getChecksum($class, $id, $type, $encodedFilename)
    {
        if (substr($type, 0, strlen(Kwf_Media::DONT_HASH_TYPE_PREFIX)) == Kwf_Media::DONT_HASH_TYPE_PREFIX) {
            $type = Kwf_Media::DONT_HASH_TYPE_PREFIX;
        }
        return substr(Kwf_Util_Hash::hash($class . $id . $type . rawurldecode($encodedFilename)), 0, 8);
    }

    /**
     * @param Kwf_Model_Row_Interface Row zu der ein Bild existiert
     * @param string Type
     * @param string/Kwf_Uploads_Row Wenn string wird der Dateiname verwendet
     *         wenn Kwf_Uploads_Row wird der Original-Dateiname verwendet
     *         wenn nicht gesetzt wird die uploads row mittels $type ermittelt
     *         und dieser Dateiname verwendet
     */
    public static function getUrlByRow($row, $type, $filename = null)
    {
        $pk = $row->getModel()->getPrimaryKey();
        if (!$filename) {
            $filename = $row->getParentRow($type);
        }
        return self::getUrl(get_class($row->getModel()), $row->$pk, $type, $filename);
    }

    public static function getDimensionsByRow($row, $type, $fileRow = null)
    {
        $model = get_class($row->getModel());
        $dim = call_user_func(array($model, 'getImageDimensions'), $type);
        if (!$fileRow) {
            $fileRow = $row->getParentRow($type);
        }
        if ($fileRow) {
            return Kwf_Media_Image::calculateScaleDimensions(
                $fileRow->getImageDimensions(),
                $dim
            );
        }
        return null;
    }

    public static function getOutput($class, $id, $type)
    {
        $cacheId = 'media-isvalid-'.self::createCacheId($class, $id, $type);
        if (!Kwf_Cache_Simple::fetch($cacheId)) {
            $classWithoutDot = strpos($class, '.') ? substr($class, 0, strpos($class, '.')) : $class;
            if (!Kwf_Loader::isValidClass($classWithoutDot)) throw new Kwf_Exception_NotFound();
            $isValid = Kwf_Media_Output_IsValidInterface::VALID;
            if (is_instance_of($classWithoutDot, 'Kwf_Media_Output_IsValidInterface')) {
                $isValid = call_user_func(array($classWithoutDot, 'isValidMediaOutput'), $id, $type, $class);
                if ($isValid == Kwf_Media_Output_IsValidInterface::INVALID) {
                    throw new Kwf_Exception_NotFound();
                } else if ($isValid == Kwf_Media_Output_IsValidInterface::ACCESS_DENIED) {
                    throw new Kwf_Exception_AccessDenied();
                } else if ($isValid == Kwf_Media_Output_IsValidInterface::VALID) {
                } else if ($isValid == Kwf_Media_Output_IsValidInterface::VALID_DONT_CACHE) {
                } else {
                    throw new Kwf_Exception("unknown isValidMediaOutput return value");
                }
            }
            if ($isValid != Kwf_Media_Output_IsValidInterface::VALID_DONT_CACHE) {
                Kwf_Cache_Simple::add($cacheId, true, 60*60);
            }
        }
        Zend_Session::writeClose();
        $output = self::_getOutputWithoutCheckingIsValid($class, $id, $type);
        return $output;
    }

    public static function clearCache($class, $id, $type)
    {
        $cacheId = self::createCacheId($class, $id, $type);
        Kwf_Media_MemoryCache::getInstance()->remove($cacheId);
        Kwf_Media_MemoryCache::getInstance()->remove('mtime-'.$cacheId);
        //not required to delete cache/media/$cacheId, that will be regenerated if $cacheId is deleted
    }

    public static function getOutputWithoutCheckingIsValid($class, $id, $type)
    {
        return self::_getOutputWithoutCheckingIsValid($class, $id, $type);
    }

    private static function _getOutputWithoutCheckingIsValid($class, $id, $type)
    {
        $cacheId = self::createCacheId($class, $id, $type);

        $output = Kwf_Media_MemoryCache::getInstance()->load($cacheId);

        if ($output && !isset($output['file']) && !isset($output['contents'])) {
            //scaled image is not cached in apc as it might be larger - load from disk
            $output['file'] = 'cache/media/'.$cacheId;
        }
        if (isset($output['file']) && !file_exists($output['file'])) $output = false;

        if ($output && isset($output['mtimeFiles'])) {
            foreach ($output['mtimeFiles'] as $f) {
                if (filemtime($f) > $output['mtime']) {
                    Kwf_Media_MemoryCache::getInstance()->remove($cacheId);
                    $output = false;
                    break;
                }
            }
        }

        if (!$output) {
            $classWithoutDot = strpos($class, '.') ? substr($class, 0, strpos($class, '.')) : $class;
            if (!Kwf_Loader::isValidClass($classWithoutDot) || !is_instance_of($classWithoutDot, 'Kwf_Media_Output_Interface')) {
                throw new Kwf_Exception_NotFound();
            }
            $output = call_user_func(array($classWithoutDot, 'getMediaOutput'), $id, $type, $class);
            $specificLifetime = false;
            $useCache = true;
            if (isset($output['lifetime'])) {
                $specificLifetime = $output['lifetime'];
                if (!$output['lifetime']) {
                    $useCache = false;
                }
            }
            if (!isset($output['mtime'])) {
                if (isset($output['file'])) {
                    $output['mtime'] = filemtime($output['file']);
                } else if (isset($output['mtimeFiles'])) {
                    $output['mtime'] = 0;
                    foreach ($output['mtimeFiles'] as $f) {
                        $output['mtime'] = max($output['mtime'], filemtime($f));
                    }
                } else {
                    $output['mtime'] = time();
                }
            }
            if ($useCache) {
                $cacheData = $output;
                if (isset($cacheData['contents']) && strlen($cacheData['contents']) > 20*1024) {
                    //don't cache contents larger than 20k in apc, use separate file cache
                    file_put_contents('cache/media/'.$cacheId, $cacheData['contents']);
                    unset($cacheData['contents']);
                }
                Kwf_Media_MemoryCache::getInstance()->save($cacheData, $cacheId, $specificLifetime);
            }
        }

        return $output;
    }

    public static function createCacheId($class, $id, $type)
    {
        return str_replace(array('.', '>'), array('___', '____'), $class) . '_' . str_replace('-', '__', $id) . '_' . $type;
    }
}


text:
Edit Advertisement Plan

                            <?php echo form_open('admin/updateadvplan/'.$editadvplan['advplan_id']); ?>

Plan Type :

                                    <select class="form-control droup-down-margin" id="plan_type" name="plan_type" >

                                        <option value="0">Plan Type</option>
                                        <option value="1" <?php if($editadvplan['advplan_type']=='1') echo 'selected="selected"'; ?>>Advertisement</option>
                                        <option value="2" <?php if($editadvplan['advplan_type']=='2') echo 'selected="selected"'; ?>>Hot Job</option>

                                    </select>

<?php echo form_error('plan_type'); ?>

                                    <input type="hidden" name="selectedplan" class="selectedplan" />

                                        <select class="form-control droup-down-margin">
                                            <option value="0">Select Position</option>
                                            <option value="1">Web designer</option>
                                            <option value="3">PHP developer</option>
                                            <option value="4">Software developer</option>
                                            <option value="5">Programmer</option>
                                            <option value="6">Web developer</option>
                                        </select>

Plan Headline :

<input type="text" placeholder="Enter the Headline" id="advname" name="advname" value="<?php echo $editadvplan['plan_name'];?>" >

<?php echo form_error('advname'); ?>

Price :

<input type="text" placeholder="Enter the Price" id="advprice" name="advprice" value="<?php echo $editadvplan['adv_charge'];?>" >

<?php echo form_error('advprice'); ?>

                                <?php echo form_submit(array('id' => 'submit', 'value' => 'Submit', 'class' => 'btn btn-danger')); ?>

                            <?php echo form_close(); ?>


text:
package hxckdms.hxccore.commands;

import hxckdms.hxccore.api.command.AbstractSubCommand;
import hxckdms.hxccore.api.command.HxCCommand;
import hxckdms.hxccore.api.command.TranslatedCommandException;
import hxckdms.hxccore.configs.Configuration;
import hxckdms.hxccore.configs.FakePlayerData;
import hxckdms.hxccore.configs.HomesConfigStorage;
import hxckdms.hxccore.libraries.GlobalVariables;
import hxckdms.hxccore.utilities.HxCPlayerInfoHandler;
import hxckdms.hxccore.utilities.ServerTranslationHelper;
import hxckdms.hxccore.utilities.TeleportHelper;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextFormatting;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

@HxCCommand
public class CommandHome extends AbstractSubCommand<CommandHxC> {
    {
        permissionLevel = 1;
    }

    @Override
    public String getName() {
        return "home";
    }

    @Override
    public void execute(ICommandSender sender, LinkedList<String> args) throws CommandException {
        EntityPlayerMP player = (EntityPlayerMP) sender;
        String name = args.size() == 0 ? "default" : args.get(0);
        if (!Configuration.useTextStorageofHomes) {
            NBTTagCompound homes = HxCPlayerInfoHandler.getTagCompound(player, "homes", new NBTTagCompound());

            if (!homes.getKeySet().contains(name))
                throw new TranslatedCommandException(sender, "commands.error.invalid.home", name);
            NBTTagCompound home = homes.getCompoundTag(name);

            if (GlobalVariables.server.worldServerForDimension(home.getInteger("dimension")).getBlockState(new BlockPos(home.getDouble("x"), home.getDouble("y") + 1, home.getDouble("z"))) == Blocks.AIR && !player.capabilities.isCreativeMode)
                throw new TranslatedCommandException(sender, "commands.error.teleport.nonAir");

            TeleportHelper.teleportEntityToDimension(player, home.getDouble("x"), home.getDouble("y"), home.getDouble("z"), home.getInteger("dimension"));
        } else {
            String user = Configuration.storeTextHomesUsingName ? player.getName() : player.getUniqueID().toString();
            if (HomesConfigStorage.homes.containsKey(user)) {
                if (HomesConfigStorage.homes.get(user).homes.containsKey(name)) {
                    FakePlayerData.Warp home = HomesConfigStorage.homes.get(user).homes.get(name);
                    TeleportHelper.teleportEntityToDimension(player, home.xpos, home.ypos, home.zpos, home.dimension);
                } else {
                    throw new TranslatedCommandException(sender, "commands.error.invalid.home", name);
                }
            } else {
                throw new TranslatedCommandException(sender, "commands.error.invalid.home", name);
            }
        }
        sender.addChatMessage(ServerTranslationHelper.getTranslation(sender, "commands.home.teleport.self", name).setStyle(new Style().setColor(TextFormatting.BLUE)));
    }

    @Override
    public List<String> addTabCompletionOptions(ICommandSender sender, LinkedList<String> args, @Nullable BlockPos pos) {
        return (sender instanceof EntityPlayerMP && args.size() == 1) ? new ArrayList<>(HxCPlayerInfoHandler.getTagCompound((EntityPlayer) sender, "homes", new NBTTagCompound()).getKeySet()) : Collections.emptyList();
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.handpay.dao.security.ResourcesDao">

    <!-- 查询全部资源 -->
    <select id="findAll" parameterType="String" resultType="com.handpay.entity.security.Resources" >
            select * from security_resources
    </select>

    <!-- 查询用户拥有的全部资源 -->
    <select id="findAllResourcesByUserName" parameterType="String" resultType="com.handpay.entity.security.Resources" >
            select re.*
            from security_users u , security_user_role ur , security_resources re ,security_role_resc rr
            where u.id = ur.user_id and rr.role_id=ur.role_id and rr.resc_id=re.id and u.account = #{username}
    </select>
</mapper>


text:
/*!
 * Angular Material Design
 * https://github.com/angular/material
 * @license MIT
 * v0.6.1
 */
md-backdrop.md-opaque.md-red-theme {
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute; }

md-bottom-sheet.md-red-theme {
  background-color: #fafafa;
  border-top-color: #bdbdbd; }
  md-bottom-sheet.md-red-theme.md-list md-item {
    color: rgba(0, 0, 0, 0.54); }
  md-bottom-sheet.md-red-theme .md-subheader {
    background-color: #fafafa; }
  md-bottom-sheet.md-red-theme .md-subheader {
    color: rgba(0, 0, 0, 0.54); }

.md-button.md-red-theme {
  border-radius: 3px; }
  .md-button.md-red-theme:not([disabled]):hover, .md-button.md-red-theme:not([disabled]):focus {
    background-color: rgba(158, 158, 158, 0.2); }
  .md-button.md-red-theme.md-fab {
    border-radius: 50%; }
  .md-button.md-red-theme.md-primary {
    color: #ef5350;
    fill: #ef5350; }
  .md-button.md-red-theme.md-warn {
    color: #ef5350;
    fill: #ef5350; }
  .md-button.md-red-theme.md-raised, .md-button.md-red-theme.md-fab {
    background-color: rgba(158, 158, 158, 0.185); }
    .md-button.md-red-theme.md-raised:not([disabled]):hover, .md-button.md-red-theme.md-raised:not([disabled]):focus, .md-button.md-red-theme.md-fab:not([disabled]):hover, .md-button.md-red-theme.md-fab:not([disabled]):focus {
      background-color: rgba(158, 158, 158, 0.3); }
    .md-button.md-red-theme.md-raised.md-primary, .md-button.md-red-theme.md-fab.md-primary {
      color: white;
      background-color: #f44336; }
      .md-button.md-red-theme.md-raised.md-primary:not([disabled]):hover, .md-button.md-red-theme.md-raised.md-primary:not([disabled]):focus, .md-button.md-red-theme.md-fab.md-primary:not([disabled]):hover, .md-button.md-red-theme.md-fab.md-primary:not([disabled]):focus {
        background-color: #e53935; }
    .md-button.md-red-theme.md-raised.md-warn, .md-button.md-red-theme.md-fab.md-warn {
      color: white;
      background-color: #f44336; }
      .md-button.md-red-theme.md-raised.md-warn:not([disabled]):hover, .md-button.md-red-theme.md-raised.md-warn:not([disabled]):focus, .md-button.md-red-theme.md-fab.md-warn:not([disabled]):hover, .md-button.md-red-theme.md-fab.md-warn:not([disabled]):focus {
        background-color: #d32f2f; }
  .md-button.md-red-theme[disabled], .md-button.md-red-theme.md-raised[disabled], .md-button.md-red-theme.md-fab[disabled] {
    color: rgba(0, 0, 0, 0.26);
    fill: rgba(0, 0, 0, 0.26);
    background-color: transparent;
    cursor: not-allowed; }

md-card.md-red-theme {
  border-radius: 2px; }
  md-card.md-red-theme .md-card-image {
    border-radius: 2px 2px 0 0; }

md-checkbox.md-red-theme .md-ripple {
  color: #43a047; }
md-checkbox.md-red-theme.md-checked .md-ripple {
  color: #757575; }
md-checkbox.md-red-theme .md-icon {
  border-color: rgba(0, 0, 0, 0.54); }
md-checkbox.md-red-theme.md-checked .md-icon {
  background-color: rgba(102, 187, 106, 0.87); }
md-checkbox.md-red-theme.md-checked .md-icon:after {
  border-color: #eeeeee; }
md-checkbox.md-red-theme[disabled] .md-icon {
  border-color: rgba(0, 0, 0, 0.26); }
md-checkbox.md-red-theme[disabled].md-checked .md-icon {
  background-color: rgba(0, 0, 0, 0.26); }

md-content.md-red-theme {
  background-color: #ffffff; }

md-dialog.md-red-theme {
  border-radius: 4px;
  background-color: #ffffff; }
  md-dialog.md-red-theme.md-content-overflow .md-actions {
    border-top-color: rgba(0, 0, 0, 0.12); }

md-divider.md-red-theme {
  border-top-color: rgba(0, 0, 0, 0.12); }

md-progress-circular.md-red-theme {
  background-color: transparent; }
  md-progress-circular.md-red-theme .md-inner .md-gap {
    border-top-color: #f44336;
    border-bottom-color: #f44336; }
  md-progress-circular.md-red-theme .md-inner .md-left .md-half-circle, md-progress-circular.md-red-theme .md-inner .md-right .md-half-circle {
    border-top-color: #f44336; }
  md-progress-circular.md-red-theme .md-inner .md-right .md-half-circle {
    border-right-color: #f44336; }
  md-progress-circular.md-red-theme .md-inner .md-left .md-half-circle {
    border-left-color: #f44336; }

md-progress-linear.md-red-theme .md-container {
  background-color: #ffcdd2; }
md-progress-linear.md-red-theme .md-bar {
  background-color: #f44336; }
md-progress-linear.md-red-theme[md-mode=buffer] .md-dashed:before {
  background: radial-gradient(#ffcdd2 0%, #ffcdd2 16%, transparent 42%); }
md-progress-linear.md-red-theme[md-mode=buffer] .md-bar1 {
  background-color: #ffcdd2; }

md-radio-button.md-red-theme .md-off, md-switch.md-red-theme .md-switch-thumb .md-off {
  border-color: rgba(0, 0, 0, 0.54); }
md-radio-button.md-red-theme .md-on, md-switch.md-red-theme .md-switch-thumb .md-on {
  background-color: rgba(102, 187, 106, 0.87); }
md-radio-button.md-red-theme.md-checked .md-off, md-switch.md-red-theme .md-switch-thumb.md-checked .md-off {
  border-color: rgba(102, 187, 106, 0.87); }
md-radio-button.md-red-theme.md-checked .md-ink-ripple, md-switch.md-red-theme .md-switch-thumb.md-checked .md-ink-ripple {
  color: rgba(102, 187, 106, 0.87); }
md-radio-button.md-red-theme .md-container .md-ripple, md-switch.md-red-theme .md-switch-thumb .md-container .md-ripple {
  color: #43a047; }
md-radio-button.md-red-theme[disabled] .md-container .md-off, md-switch.md-red-theme .md-switch-thumb[disabled] .md-container .md-off {
  border-color: rgba(0, 0, 0, 0.26); }
md-radio-button.md-red-theme[disabled] .md-container .md-on, md-switch.md-red-theme .md-switch-thumb[disabled] .md-container .md-on {
  border-color: rgba(0, 0, 0, 0.26); }

md-radio-group.md-red-theme:focus {
  border-color: rgba(0, 0, 0, 0.73); }

md-slider.md-red-theme .md-track {
  background-color: rgba(0, 0, 0, 0.26); }
md-slider.md-red-theme .md-track-fill {
  background-color: #f44336; }
md-slider.md-red-theme .md-thumb:after {
  border-color: #f44336;
  background-color: #f44336; }
md-slider.md-red-theme .md-sign {
  background-color: #f44336; }
  md-slider.md-red-theme .md-sign:after {
    border-top-color: #f44336; }
md-slider.md-red-theme .md-thumb-text {
  color: white; }
md-slider.md-red-theme .md-focus-thumb {
  background-color: rgba(0, 0, 0, 0.54); }
md-slider.md-red-theme .md-focus-ring {
  border-color: rgba(0, 0, 0, 0.12); }
md-slider.md-red-theme .md-disabled-thumb {
  border-color: #ffffff; }
md-slider.md-red-theme.md-min .md-thumb:after {
  background-color: #ffffff; }
md-slider.md-red-theme[disabled] .md-thumb:after {
  border-color: #bdbdbd; }
md-slider.md-red-theme[disabled]:not(.md-min) .md-thumb:after {
  background-color: #bdbdbd; }

.md-subheader.md-red-theme {
  color: rgba(0, 0, 0, 0.54);
  background-color: #ffffff; }
  .md-subheader.md-red-theme.md-primary {
    color: #f44336; }

md-switch.md-red-theme .md-thumb {
  background-color: #fafafa; }
md-switch.md-red-theme .md-bar {
  background-color: #9e9e9e; }
md-switch.md-red-theme.md-checked .md-thumb {
  background-color: #f44336; }
md-switch.md-red-theme.md-checked .md-bar {
  background-color: rgba(244, 67, 54, 0.5); }
md-switch.md-red-theme[disabled] .md-thumb {
  background-color: #bdbdbd; }
md-switch.md-red-theme[disabled] .md-bar {
  background-color: rgba(0, 0, 0, 0.12); }
md-switch.md-red-theme:focus .md-text {
  border-color: black;
  border-style: dotted; }

md-tabs.md-red-theme .md-header {
  background-color: #f44336; }
md-tabs.md-red-theme md-tabs-ink-bar {
  color: #ffff85;
  background: #ffff85; }
md-tabs.md-red-theme md-tab {
  color: #ffcdd2; }
  md-tabs.md-red-theme md-tab.active {
    color: white; }
  md-tabs.md-red-theme md-tab[disabled] {
    color: rgba(0, 0, 0, 0.12); }
  md-tabs.md-red-theme md-tab:focus {
    border-color: rgba(0, 0, 0, 0.73); }
  md-tabs.md-red-theme md-tab .md-ripple-container {
    color: #ffff85; }

md-input-group.md-red-theme input, md-input-group.md-red-theme textarea {
  text-shadow: none; }
  md-input-group.md-red-theme input:-ms-input-placeholder, md-input-group.md-red-theme textarea:-ms-input-placeholder {
    color: rgba(0, 0, 0, 0.26); }
  md-input-group.md-red-theme input::-webkit-input-placeholder, md-input-group.md-red-theme textarea::-webkit-input-placeholder {
    color: rgba(0, 0, 0, 0.26); }
md-input-group.md-red-theme label {
  text-shadow: none;
  color: rgba(0, 0, 0, 0.26); }
md-input-group.md-red-theme input, md-input-group.md-red-theme textarea {
  color: rgba(0, 0, 0, 0.73);
  border-color: rgba(0, 0, 0, 0.12); }
md-input-group.md-red-theme.md-input-focused input, md-input-group.md-red-theme.md-input-focused textarea {
  border-color: #f44336; }
md-input-group.md-red-theme.md-input-focused label {
  color: #f44336; }
md-input-group.md-red-theme.md-input-has-value:not(.md-input-focused) label {
  color: rgba(0, 0, 0, 0.372); }
md-input-group.md-red-theme[disabled] input, md-input-group.md-red-theme[disabled] textarea {
  border-bottom-color: rgba(0, 0, 0, 0.12);
  color: rgba(0, 0, 0, 0.26);
  background-image: linear-gradient(to right, rgba(0, 0, 0, 0.19) 0%, rgba(0, 0, 0, 0.19) 50%, rgba(0, 0, 0, 0) 0%); }

md-toast.md-red-theme {
  background-color: #323232;
  color: white; }
  md-toast.md-red-theme .md-button {
    color: white; }
  md-toast.md-red-theme .md-action {
    color: #ff5252; }

md-toolbar.md-red-theme {
  background-color: #f44336;
  color: white; }
  md-toolbar.md-red-theme .md-button {
    color: white; }

md-tooltip.md-red-theme {
  color: #ffffff; }
  md-tooltip.md-red-theme .md-background {
    background-color: rgba(0, 0, 0, 0.52); }


text:
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Data;
using NServiceKit.Common.Utils;
using NServiceKit.DataAnnotations;
using NServiceKit.Common;
using NServiceKit.OrmLite;

namespace AllDialectsTest
{
    /// A main class.
	class MainClass
	{
        /// The dialects.
		private static List<Dialect> dialects;

        /// The authors.
		private static List<Author> authors;

        /// Main entry-point for this application.
        /// <param name="args">Array of command-line argument strings.</param>
		public static void Main(string[] args)
		{

			bool exit=false;

			dialects = BuildDialectList();
			authors = BuildAuthorList();

			PaintMenu();

			while (!exit)
			{

				Console.WriteLine("Select your option [{0}-{1}] or q to quit  and press ENTER", 1, dialects.Count);
				string option = Console.ReadLine();
				if (string.IsNullOrEmpty(option))
					Console.WriteLine("NO VALID OPTION");
				else if (option.ToUpper() == "Q")
					exit = true;
				else
				{
					int opt;
					if (int.TryParse(option, out opt))
					{
						if (opt >= 1 && opt <= dialects.Count)
							TestDialect(dialects[opt - 1]);
						else
						{
							Console.WriteLine("NO VALID OPTION");
						}

					}
					else
						Console.WriteLine("NO VALID OPTION");
				}
			}

		}

        /// Paints the menu.
		private static void PaintMenu()
		{
			Console.Clear();
			int i=0;
			foreach (Dialect d in dialects)
			{
				Console.WriteLine("{0} {1}", ++i, d.Name);
			}
			Console.WriteLine("q quit");
		}

        /// Builds dialect list.
        /// <returns>A List<Dialect></returns>
		private static List<Dialect> BuildDialectList()
		{
			List<Dialect> l = new List<Dialect>();
			Dialect d = new Dialect() {
				Name = "Sqlite",
				PathToAssembly = "../../../NServiceKit.OrmLite.Sqlite/bin/Debug",
				AssemblyName = "NServiceKit.OrmLite.Sqlite.dll",
				ClassName = "NServiceKit.OrmLite.Sqlite.SqliteOrmLiteDialectProvider",
				InstanceFieldName = "Instance",
				ConnectionString = "~/db.sqlite".MapAbsolutePath()
			};
			l.Add(d);

			d = new Dialect() {
				Name = "SqlServer",
				PathToAssembly = "../../../NServiceKit.OrmLite.SqlServer/bin/Debug",
				AssemblyName = "NServiceKit.OrmLite.SqlServer.dll",
				ClassName = "NServiceKit.OrmLite.SqlServer.SqlServerOrmLiteDialectProvider",
				InstanceFieldName = "Instance",
                ConnectionString = "~/test.mdf".MapAbsolutePath()
			};
			l.Add(d);

			d = new Dialect() {
				Name = "MySql",
				PathToAssembly = "../../../NServiceKit.OrmLite.MySql/bin/Debug",
				AssemblyName = "NServiceKit.OrmLite.MySql.dll",
				ClassName = "NServiceKit.OrmLite.MySql.MySqlDialectProvider",
				InstanceFieldName = "Instance",
				ConnectionString = "Server = 127.0.0.1; Database = ormlite; Uid = root; Pwd = password"
			};
			l.Add(d);

			d = new Dialect() {
				Name = "PostgreSQL",
				PathToAssembly = "../../../NServiceKit.OrmLite.PostgreSQL/bin/Debug",
				AssemblyName = "NServiceKit.OrmLite.PostgreSQL.dll",
				ClassName = "NServiceKit.OrmLite.PostgreSQL.PostgreSQLDialectProvider",
				InstanceFieldName = "Instance",
				ConnectionString = "Server=localhost;Port=5432;User Id=postgres; Password=postgres; Database=ormlite"
			};
			l.Add(d);

			d = new Dialect() {
				Name = "FirebirdSql",
				PathToAssembly = "../../../NServiceKit.OrmLite.Firebird/bin/Debug",
				AssemblyName = "NServiceKit.OrmLite.Firebird.dll",
				ClassName = "NServiceKit.OrmLite.Firebird.FirebirdOrmLiteDialectProvider",
				InstanceFieldName = "Instance",
				ConnectionString = "User=SYSDBA;Password=masterkey;Database=employee.fdb;DataSource=localhost;Dialect=3;charset=ISO8859_1;"
			};
			l.Add(d);

            d = new Dialect() {
                Name = "Oracle",
                PathToAssembly = "../../../NServiceKit.OrmLite.Oracle/bin/Debug",
                AssemblyName = "NServiceKit.OrmLite.Oracle.dll",
                ClassName = "NServiceKit.OrmLite.Oracle.OracleOrmLiteDialectProvider",
                InstanceFieldName = "Instance",
                ConnectionString = "Data Source=localhost:1521/XE;User ID=NServiceKit_test;Password=NServiceKit_test;Unicode=True"
            };
            l.Add(d);

			return l;

		}

        /// Builds author list.
        /// <returns>A List<Author></returns>
		private static List<Author> BuildAuthorList()
		{

			List<Author> a = new List<Author>();
			a.Add(new Author() { Name = "Demis Bellot", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 99.9m, Comments = "CSharp books", Rate = 10, City = "London" });
			a.Add(new Author() { Name = "Angel Colmenares", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 50.0m, Comments = "CSharp books", Rate = 5, City = "Bogota" });
			a.Add(new Author() { Name = "Adam Witco", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 80.0m, Comments = "Math Books", Rate = 9, City = "London" });
			a.Add(new Author() { Name = "Claudia Espinel", Birthday = DateTime.Today.AddYears(-23), Active = true, Earnings = 60.0m, Comments = "Cooking books", Rate = 10, City = "Bogota" });
			a.Add(new Author() { Name = "Libardo Pajaro", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 80.0m, Comments = "CSharp books", Rate = 9, City = "Bogota" });
			a.Add(new Author() { Name = "Jorge Garzon", Birthday = DateTime.Today.AddYears(-28), Active = true, Earnings = 70.0m, Comments = "CSharp books", Rate = 9, City = "Bogota" });
			a.Add(new Author() { Name = "Alejandro Isaza", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 70.0m, Comments = "Java books", Rate = 0, City = "Bogota" });
			a.Add(new Author() { Name = "Wilmer Agamez", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 30.0m, Comments = "Java books", Rate = 0, City = "Cartagena" });
			a.Add(new Author() { Name = "Rodger Contreras", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 90.0m, Comments = "CSharp books", Rate = 8, City = "Cartagena" });
			a.Add(new Author() { Name = "Chuck Benedict", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "CSharp books", Rate = 8, City = "London" });
			a.Add(new Author() { Name = "James Benedict II", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "Java books", Rate = 5, City = "Berlin" });
			a.Add(new Author() { Name = "Ethan Brown", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 45.0m, Comments = "CSharp books", Rate = 5, City = "Madrid" });
			a.Add(new Author() { Name = "Xavi Garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 75.0m, Comments = "CSharp books", Rate = 9, City = "Madrid" });
			a.Add(new Author() { Name = "Luis garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.0m, Comments = "CSharp books", Rate = 10, City = "Mexico", LastActivity= DateTime.Today });
			return a;
		}

        /// Tests dialect.
        /// <param name="dialect">The dialect.</param>
		private static void TestDialect(Dialect dialect)
		{
			Console.Clear();
			Console.WriteLine("Testing expressions for Dialect {0}", dialect.Name);

			OrmLiteConfig.ClearCache();
			OrmLiteConfig.DialectProvider = dialect.DialectProvider;
			SqlExpressionVisitor<Author> ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<Author>();

			using (IDbConnection db = dialect.ConnectionString.OpenDbConnection())
			{
				try
				{
					db.DropTable<Author>();

					var tableExists = OrmLiteConfig.DialectProvider.DoesTableExist(db, typeof(Author).Name);
					Console.WriteLine("Expected:{0} Selected:{1}  {2}", bool.FalseString, tableExists.ToString(), !tableExists ? "OK" : "**************  FAILED ***************");

					db.CreateTable<Author>();

					tableExists = OrmLiteConfig.DialectProvider.DoesTableExist(db, typeof(Author).Name);
					Console.WriteLine("Expected:{0} Selected:{1}  {2}", bool.TrueString, tableExists.ToString(), tableExists ? "OK" : "**************  FAILED ***************");

					db.DeleteAll<Author>();
					Console.WriteLine("Inserting...");
					DateTime t1= DateTime.Now;
					db.InsertAll(authors);
					DateTime t2= DateTime.Now;
					Console.WriteLine("Inserted {0} rows in {1}", authors.Count, t2 - t1);

					Console.WriteLine("Selecting.....");

					int year = DateTime.Today.AddYears(-20).Year;
					var lastDay= new DateTime(year, 12, 31);
					int expected=5;

					ev.Where().Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay);
					Console.WriteLine(ev.ToSelectStatement());
					List<Author> result=db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					result = db.Select<Author>(qry => qry.Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay));
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					result = db.Select<Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					Author a = new Author() { Birthday = lastDay };
					result = db.Select<Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= a.Birthday);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					// select authors from London, Berlin and Madrid : 6
					expected = 6;
					//Sql.In can take params object[]
					var city="Berlin";
					ev.Where().Where(rn => Sql.In(rn.City, "London", "Madrid", city)); //clean prev
					result = db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					result = db.Select<Author>(rn => Sql.In(rn.City, new[] { "London", "Madrid", "Berlin" }));
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					// select authors from Bogota and Cartagena : 7
					expected = 7;
					//... or Sql.In can  take List<Object>
					city = "Bogota";
					List<Object> cities= new List<Object>();
					cities.Add(city);
					cities.Add("Cartagena");
					ev.Where().Where(rn => Sql.In(rn.City, cities));
					result = db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					result = db.Select<Author>(rn => Sql.In(rn.City, "Bogota", "Cartagena"));
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					// select authors which name starts with A
					expected = 3;
					ev.Where().Where(rn => rn.Name.StartsWith("A"));
					result = db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					result = db.Select<Author>(rn => rn.Name.StartsWith("A"));
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					// select authors which name ends with Garzon o GARZON o garzon ( no case sensitive )
					expected = 3;
					var name="GARZON";
					ev.Where().Where(rn => rn.Name.ToUpper().EndsWith(name));
					result = db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					result = db.Select<Author>(rn => rn.Name.ToUpper().EndsWith(name));
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					// select authors which name ends with garzon
					//A percent symbol ("%") in the LIKE pattern matches any sequence of zero or more characters
					//in the string.
					//An underscore ("_") in the LIKE pattern matches any single character in the string.
					//Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching).
					expected = 3;
					ev.Where().Where(rn => rn.Name.EndsWith("garzon"));
					result = db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					result = db.Select<Author>(rn => rn.Name.EndsWith("garzon"));
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					// select authors which name contains  Benedict
					expected = 2;
					name = "Benedict";
					ev.Where().Where(rn => rn.Name.Contains(name));
					result = db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					result = db.Select<Author>(rn => rn.Name.Contains("Benedict"));
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					a.Name = name;
					result = db.Select<Author>(rn => rn.Name.Contains(a.Name));
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					// select authors with Earnings <= 50
					expected = 3;
					var earnings=50;
					ev.Where().Where(rn => rn.Earnings <= earnings);
					result = db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					result = db.Select<Author>(rn => rn.Earnings <= 50);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					// select authors with Rate = 10 and city=Mexio
					expected = 1;
					city = "Mexico";
					ev.Where().Where(rn => rn.Rate == 10 && rn.City == city);
					result = db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					result = db.Select<Author>(rn => rn.Rate == 10 && rn.City == "Mexico");
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					a.City = city;
					result = db.Select<Author>(rn => rn.Rate == 10 && rn.City == a.City);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					//  enough selecting, lets update;
					// set Active=false where rate =0
					expected = 2;
					var rate=0;
					ev.Where().Where(rn => rn.Rate == rate).Update(rn => rn.Active);
					var rows = db.UpdateOnly(new Author() { Active = false }, ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, rows, expected == rows ? "OK" : "**************  FAILED ***************");

					// insert values  only in Id, Name, Birthday, Rate and Active fields
					expected = 4;
					ev.Insert(rn => new { rn.Id, rn.Name, rn.Birthday, rn.Active, rn.Rate });
					db.InsertOnly(new Author() { Active = false, Rate = 0, Name = "Victor Grozny", Birthday = DateTime.Today.AddYears(-18) }, ev);
					db.InsertOnly(new Author() { Active = false, Rate = 0, Name = "Ivan Chorny", Birthday = DateTime.Today.AddYears(-19) }, ev);
					ev.Where().Where(rn => !rn.Active);
					result = db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					//update comment for City == null
					expected = 2;
					ev.Where().Where(rn => rn.City == null).Update(rn => rn.Comments);
					rows = db.UpdateOnly(new Author() { Comments = "No comments" }, ev);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, rows, expected == rows ? "OK" : "**************  FAILED ***************");

					// delete where City is null
					expected = 2;
					rows = db.Delete(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, rows, expected == rows ? "OK" : "**************  FAILED ***************");

					//   lets select  all records ordered by Rate Descending and Name Ascending
					expected = 14;
					ev.Where().OrderBy(rn => new { at = Sql.Desc(rn.Rate), rn.Name }); // clear where condition
					result = db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");
					Console.WriteLine(ev.OrderByExpression);
					var author = result.FirstOrDefault();
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", "Claudia Espinel", author.Name, "Claudia Espinel" == author.Name ? "OK" : "**************  FAILED ***************");

					// select  only first 5 rows ....

					expected = 5;
					ev.Limit(5); // note: order is the same as in the last sentence
					result = db.Select(ev);
					Console.WriteLine(ev.WhereExpression);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					// and finally lets select only Name and City (name will be "UPPERCASED" )

					ev.Select(rn => new { at = Sql.As(rn.Name.ToUpper(), "Name"), rn.City });
					Console.WriteLine(ev.SelectExpression);
					result = db.Select(ev);
					author = result.FirstOrDefault();
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper() == author.Name ? "OK" : "**************  FAILED ***************");

					ev.Select(rn => new { at = Sql.As(rn.Name.ToUpper(), rn.Name), rn.City });
					Console.WriteLine(ev.SelectExpression);
					result = db.Select(ev);
					author = result.FirstOrDefault();
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper() == author.Name ? "OK" : "**************  FAILED ***************");

					//paging :
					ev.Limit(0, 4);// first page, page size=4;
					result = db.Select(ev);
					author = result.FirstOrDefault();
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper() == author.Name ? "OK" : "**************  FAILED ***************");

					ev.Limit(4, 4);// second page
					result = db.Select(ev);
					author = result.FirstOrDefault();
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", "Jorge Garzon".ToUpper(), author.Name, "Jorge Garzon".ToUpper() == author.Name ? "OK" : "**************  FAILED ***************");

					ev.Limit(8, 4);// third page
					result = db.Select(ev);
					author = result.FirstOrDefault();
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", "Rodger Contreras".ToUpper(), author.Name, "Rodger Contreras".ToUpper() == author.Name ? "OK" : "**************  FAILED ***************");

					// select distinct..
					ev.Limit().OrderBy(); // clear limit, clear order for postres
					ev.SelectDistinct(r => r.City);
					expected = 6;
					result = db.Select(ev);
					Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, result.Count, expected == result.Count ? "OK" : "**************  FAILED ***************");

					ev.Select(r=> Sql.As(Sql.Max(r.Birthday), "Birthday"));
					result = db.Select(ev);
					var expectedResult  = authors.Max(r=>r.Birthday);
					Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult,
					                  result[0].Birthday,
					                  expectedResult == result[0].Birthday ? "OK" : "**************  FAILED ***************");

					ev.Select(r=> Sql.As(Sql.Max(r.Birthday), r.Birthday));
					result = db.Select(ev);
					expectedResult  = authors.Max(r=>r.Birthday);
					Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult,
					                  result[0].Birthday,
					                  expectedResult == result[0].Birthday ? "OK" : "**************  FAILED ***************");

					var r1 = db.FirstOrDefault(ev);
					Console.WriteLine("FOD: Expected:{0} Selected {1} {2}",expectedResult,
					                  r1.Birthday,
					                  expectedResult == r1.Birthday ? "OK" : "**************  FAILED ***************");

					var r2 = db.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday) );
					Console.WriteLine("GetScalar DateTime: Expected:{0} Selected {1} {2}",expectedResult,
					                  r2,
					                  expectedResult == r2 ? "OK" : "**************  FAILED ***************");

					ev.Select(r=> Sql.As( Sql.Min(r.Birthday), "Birthday"));
					result = db.Select(ev);
					expectedResult  = authors.Min(r=>r.Birthday);
					Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult,
					                  result[0].Birthday,
					                  expectedResult == result[0].Birthday? "OK" : "**************  FAILED ***************");

					ev.Select(r=> Sql.As( Sql.Min(r.Birthday), r.Birthday));
					result = db.Select(ev);
					expectedResult  = authors.Min(r=>r.Birthday);
					Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult,
					                  result[0].Birthday,
					                  expectedResult == result[0].Birthday? "OK" : "**************  FAILED ***************");

					ev.Select(r=>new{r.City,  MaxResult=Sql.As( Sql.Min(r.Birthday), "Birthday") })
							.GroupBy(r=>r.City)
							.OrderBy(r=>r.City);
					result = db.Select(ev);
					var expectedStringResult= "Berlin";
					Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult,
					                  result[0].City,
					                  expectedStringResult == result[0].City ? "OK" : "**************  FAILED ***************");

					ev.Select(r=>new{r.City,  MaxResult=Sql.As( Sql.Min(r.Birthday), r.Birthday) })
							.GroupBy(r=>r.City)
							.OrderBy(r=>r.City);
					result = db.Select(ev);
					expectedStringResult= "Berlin";
					Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult,
					                  result[0].City,
					                  expectedStringResult == result[0].City ? "OK" : "**************  FAILED ***************");

					r1 = db.FirstOrDefault(ev);
					Console.WriteLine("FOD: Expected:{0} Selected {1} {2}",expectedResult,
					                  r1.City,
					                  expectedStringResult == result[0].City ? "OK" : "**************  FAILED ***************");

					var expectedDecimal= authors.Max(e=>e.Earnings);
					Decimal? r3 = db.GetScalar<Author,Decimal?>(e=> Sql.Max(e.Earnings));
					Console.WriteLine("GetScalar decimal?: Expected:{0} Selected {1} {2}",expectedDecimal,
					                  r3.Value,
					                  expectedDecimal == r3.Value ? "OK" : "**************  FAILED ***************");

					var expectedString= authors.Max(e=>e.Name);
					string r4 = db.GetScalar<Author,String>(e=> Sql.Max(e.Name));

					Console.WriteLine("GetScalar string?: Expected:{0} Selected {1} {2}",expectedString,
					                  r4,
					                  expectedString == r4 ? "OK" : "**************  FAILED ***************");

					var expectedDate= authors.Max(e=>e.LastActivity);
					DateTime? r5 = db.GetScalar<Author,DateTime?>(e=> Sql.Max(e.LastActivity));
					Console.WriteLine("GetScalar datetime?: Expected:{0} Selected {1} {2}",
					                  expectedDate,
					                  r5,
					                  expectedDate == r5 ? "OK" : "**************  FAILED ***************");

					var expectedDate51= authors.Where(e=> e.City=="Bogota").Max(e=>e.LastActivity);
					DateTime? r51 = db.GetScalar<Author,DateTime?>(
						e=>  Sql.Max(e.LastActivity),
					 	e=>  e.City=="Bogota" );

					Console.WriteLine("GetScalar datetime?: Expected:{0} Selected {1} {2}",
					                  expectedDate51,
					                  r51,
					                  expectedDate51 == r51 ? "OK" : "**************  FAILED ***************");

					try{
						var expectedBool= authors.Max(e=>e.Active);
						bool r6 = db.GetScalar<Author,bool>(e=> Sql.Max(e.Active));
						Console.WriteLine("GetScalar bool: Expected:{0} Selected {1} {2}",expectedBool,
					                  r6,
					                  expectedBool == r6 ? "OK" : "**************  FAILED ***************");
					}
					catch(Exception e){
						if(dialect.Name=="PostgreSQL")
							Console.WriteLine("OK PostgreSQL: " + e.Message);
						else
							Console.WriteLine("**************  FAILED *************** " + e.Message);
					}

					// Tests for predicate overloads that make use of the expression visitor
					Console.WriteLine("First author by name (exists)");
					author = db.First<Author>(q => q.Name == "Jorge Garzon");
					Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Jorge Garzon", author.Name, "Jorge Garzon" == author.Name);

					try
					{
						Console.WriteLine("First author by name (does not exist)");
						author = db.First<Author>(q => q.Name == "Does not exist");

						Console.WriteLine("Expected exception thrown, OK? False");
					}
					catch
					{
						Console.WriteLine("Expected exception thrown, OK? True");
					}

					Console.WriteLine("First author or default (does not exist)");
					author = db.FirstOrDefault<Author>(q => q.Name == "Does not exist");
					Console.WriteLine("Expected:null ; OK? {0}", author == null);

					Console.WriteLine("First author or default by city (multiple matches)");
					author = db.FirstOrDefault<Author>(q => q.City == "Bogota");
					Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Angel Colmenares", author.Name, "Angel Colmenares" == author.Name);

					a.City = "Bogota";
					author = db.FirstOrDefault<Author>(q => q.City == a.City);
					Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Angel Colmenares", author.Name, "Angel Colmenares" == author.Name);

					// count test

					var expectedCount= authors.Count();
					long r7 = db.GetScalar<Author,long>(e=> Sql.Count(e.Id));
					Console.WriteLine("GetScalar long: Expected:{0} Selected {1} {2}",expectedCount,
					                  r7,
					                  expectedCount == r7 ? "OK" : "**************  FAILED ***************");

					expectedCount= authors.Count(e=> e.City=="Bogota");
					r7 = db.GetScalar<Author,long>(
						e=>  Sql.Count(e.Id),
					 	e=>  e.City=="Bogota" );

					Console.WriteLine("GetScalar long: Expected:{0} Selected {1} {2}",expectedCount,
					                  r7,
					                  expectedCount == r7 ? "OK" : "**************  FAILED ***************");

                    // more updates.....
                    Console.WriteLine("more updates.....................");
                     ev.Update();// all fields will be updated
                    // select and update
                    expected=1;
                    var rr= db.FirstOrDefault<Author>(rn => rn.Name=="Luis garzon");
                    rr.City="Madrid";
                    rr.Comments="Updated";
                    ev.Where().Where(r=>r.Id==rr.Id); // if omit,  then all records will be updated
                    rows=db.UpdateOnly(rr,ev); // == dbCmd.Update(rr) but it returns void
                    Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, rows, expected == rows ? "OK" : "**************  FAILED ***************");

                    expected=0;
                    ev.Where().Where(r=>r.City=="Ciudad Gotica");
                    rows=db.UpdateOnly(rr, ev);
                    Console.WriteLine("Expected:{0}  Selected:{1}  {2}", expected, rows, expected == rows ? "OK" : "**************  FAILED ***************");

                    expected= db.Select<Author>(x=>x.City=="Madrid").Count;
                    author = new Author(){Active=false};
                    rows=db.UpdateOnly(author, x=>x.Active,  x=>x.City=="Madrid");
                    Console.WriteLine("Expected:{0}  Updated:{1}  {2}", expected, rows, expected == rows ? "OK" : "**************  FAILED ***************");

                    expected= db.Select<Author>(x=>x.Active==false).Count;
                    rows = db.Delete<Author>( x=>x.Active==false);
                    Console.WriteLine("Expected:{0}  Deleted:{1}  {2}", expected, rows, expected == rows ? "OK" : "**************  FAILED ***************");

					DateTime t3= DateTime.Now;
					Console.WriteLine("Expressions test in: {0}", t3 - t2);
					Console.WriteLine("All test in :        {0}", t3 - t1);

				}
				catch (Exception e)
				{
					Console.WriteLine(e.Message);
				}
			}

			Console.WriteLine("Press enter to return to main menu");
			Console.ReadLine();
			PaintMenu();
		}
	}
}


text:
package application_test

import (
	testApplication "github.com/nttlabs/cli/cf/api/applications/fakes"
	"github.com/nttlabs/cli/cf/configuration/core_config"
	"github.com/nttlabs/cli/cf/models"
	testcmd "github.com/nttlabs/cli/testhelpers/commands"
	testconfig "github.com/nttlabs/cli/testhelpers/configuration"
	testreq "github.com/nttlabs/cli/testhelpers/requirements"
	testterm "github.com/nttlabs/cli/testhelpers/terminal"

	. "github.com/nttlabs/cli/cf/commands/application"
	. "github.com/nttlabs/cli/testhelpers/matchers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("stop command", func() {
	var (
		ui                  *testterm.FakeUI
		app                 models.Application
		appRepo             *testApplication.FakeApplicationRepository
		requirementsFactory *testreq.FakeReqFactory
		config              core_config.ReadWriter
	)

	BeforeEach(func() {
		ui = &testterm.FakeUI{}
		config = testconfig.NewRepositoryWithDefaults()
		appRepo = &testApplication.FakeApplicationRepository{}
		requirementsFactory = &testreq.FakeReqFactory{}
	})

	runCommand := func(args ...string) {
		testcmd.RunCommand(NewStop(ui, config, appRepo), args, requirementsFactory)
	}

	It("fails requirements when not logged in", func() {
		runCommand("some-app-name")
		Expect(testcmd.CommandDidPassRequirements).To(BeFalse())
	})

	Context("when logged in and an app exists", func() {
		BeforeEach(func() {
			requirementsFactory.LoginSuccess = true

			app = models.Application{}
			app.Name = "my-app"
			app.Guid = "my-app-guid"
			app.State = "started"
		})

		JustBeforeEach(func() {
			appRepo.ReadReturns.App = app
			requirementsFactory.Application = app
		})

		It("fails with usage when the app name is not given", func() {
			runCommand()
			Expect(ui.FailedWithUsage).To(BeTrue())
		})

		It("stops the app with the given name", func() {
			runCommand("my-app")

			Expect(ui.Outputs).To(ContainSubstrings(
				[]string{"Stopping app", "my-app", "my-org", "my-space", "my-user"},
				[]string{"OK"},
			))

			Expect(requirementsFactory.ApplicationName).To(Equal("my-app"))
			Expect(appRepo.UpdateAppGuid).To(Equal("my-app-guid"))
		})

		It("warns the user when stopping the app fails", func() {
			appRepo.UpdateErr = true
			runCommand("my-app")

			Expect(ui.Outputs).To(ContainSubstrings(
				[]string{"Stopping", "my-app"},
				[]string{"FAILED"},
				[]string{"Error updating app."},
			))
			Expect(appRepo.UpdateAppGuid).To(Equal("my-app-guid"))
		})

		Context("when the app is stopped", func() {
			BeforeEach(func() {
				app.State = "stopped"
			})

			It("warns the user when the app is already stopped", func() {
				runCommand("my-app")

				Expect(ui.Outputs).To(ContainSubstrings([]string{"my-app", "is already stopped"}))
				Expect(appRepo.UpdateAppGuid).To(Equal(""))
			})
		})

		Describe(".ApplicationStop()", func() {
			It("returns the updated app model from ApplicationStop()", func() {
				expectedStoppedApp := app
				expectedStoppedApp.State = "stopped"

				appRepo.UpdateAppResult = expectedStoppedApp
				stopper := NewStop(ui, config, appRepo)
				actualStoppedApp, err := stopper.ApplicationStop(app, config.OrganizationFields().Name, config.SpaceFields().Name)

				Expect(err).NotTo(HaveOccurred())
				Expect(expectedStoppedApp).To(Equal(actualStoppedApp))
			})

			Context("When the app is already stopped", func() {
				BeforeEach(func() {
					app.State = "stopped"
				})

				It("returns the app without updating it", func() {
					stopper := NewStop(ui, config, appRepo)
					updatedApp, err := stopper.ApplicationStop(app, config.OrganizationFields().Name, config.SpaceFields().Name)

					Expect(err).NotTo(HaveOccurred())
					Expect(app).To(Equal(updatedApp))
				})
			})
		})
	})
})


text:
<!--
Copyright 2015 F5 Networks Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# Contributing Guide for f5-common-python
If you have found this that means you you want to help us out. Thanks in advance for lending a hand! This guide should
get you up and running quickly and make it easy for you to contribute. If we don't answer your questions here and you
help or just want to say hi shoot us an email at f5-common-python@f5.com.

## Issues
Creating issues is good, creating good issues is even better. By filing meaningful bug reports will lots of information
 in them helps us figure out what to fix when and how it impacts our users. We like bugs because it means people are
 using our code, and we like fixing them even more.

### Bugs
TODO: What do we want in our bug reports and an example?

### Feature Requests and Enhancements
TODO: What do we want in our feature requests and an example?

## Pull Requests
If you are submitting a pull request you need to make sure that you have done a few things first.

* If an issue doesn't exist, file one.
* Make sure you have tested your code because we are going to do that when when you make your PR. You don't want
_The Hat_ because your request fails unit tests.
* A reasonable set of unit tests is required, and the approver of the pull request is expecting to review them along with the product code.
* Functional tests are nice-to-have but not required to complete a pull request. Note that not having functional tests will make your pull request end up in an integration branch and be held out of the main develop branch until someone writes an appropriate set of tests.
* Clean up your git history;  no one wants to see 75 commits for one issue.
* Use our [commit template](.git-commit-template.txt).
* Use our pull request template.

```
@<reviewer_id>
#### What issues does this address?
Fixes #<issueid>
WIP #<issueid>
...

#### What's this change do?

#### Where should the reviewer start?

#### Any background context?
```

## Testing
Creating tests is pretty straightforward and we need you to help us keep ensure
the quality of our code. We write both our unit tests and functional tests
using [pytest](http://pytest.org). We know it is extra work to write these
tests but the maintainers and consumers of this code appreciate the effort and
writing the tests is pretty easy. Take a look at a few of the test directories
like [f5/bigip/ltm/test](f5/bigip/ltm/test/) if you need help getting started.

Unit tests are located alongside the code, such as [f5/bigip/ltm/test](f5/bigip/ltm/test/).
Functional tests are located at the top level in [test/functional](test/functional/).

Running tests is easy. Here's an example of how to run unit tests.

```
shell
 $ py.test --cov ./f5 --cov-report=html --ignore=test/
 $ open htmlcov/index.html
```

If you are running our functional tests, you will need a real BIG-IP® to run
 them against. You can get one of those pretty easily in [Amazon EC2](https://aws.amazon.com/marketplace/pp/B00JL3UASY/ref=srh_res_product_title?ie=UTF8&sr=0-10&qid=1449332167461).

Here's an example of how to run functional tests.

```
shell
 $ py.test --ignore=f5/ --bigip=1.2.3.4
```

## License

### Apache V2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

### Contributor License Agreement
Individuals or business entities who contribute to this project must have completed and submitted the [F5 Contributor License Agreement](http://f5-openstack-docs.readthedocs.org/en/latest/cla_landing.html) to Openstack_CLA@f5.com prior to their
code submission being included in this project.


text:
class Requirement < ActiveRecord::Base

  include ActionView::Helpers::SanitizeHelper

  has_ancestry
  has_many :responses
  has_many :enumerations, inverse_of: :requirement
  has_many :labels, inverse_of: :requirement
  has_many :resource_contexts
  belongs_to :requirements_template

  accepts_nested_attributes_for :enumerations, allow_destroy: true, reject_if: proc { |attributes| attributes['value'].blank? }
  accepts_nested_attributes_for :labels, allow_destroy: true, reject_if: proc { |attributes| attributes['desc'].blank? }
  default_scope { order('position ASC') }  # requirements should be ordered by position by default, rather than by the id or date

  validates_columns :requirement_type, :obligation
  validates :text_brief, presence: true
  validates :requirements_template_id, presence: true

  #These don't need to be validated if it is a requirement group.
  validates :text_full, presence: true, unless: Proc.new { |x| x.is_group? }
  validates :obligation, presence: true, unless: Proc.new { |x| x.is_group? }
  validates :requirement_type, presence: true, unless: Proc.new { |x| x.is_group? }

  after_save :add_high_position
  after_destroy :close_gap_in_position

  SELECT_FOR_CONTEXT =  'resources.*, resource_contexts.id AS resource_context_id, resource_contexts.institution_id, ' +
                        'resource_contexts.requirements_template_id, resource_contexts.requirement_id'

  def is_group?
    self.group == true
  end

  before_save :validating_to_set_either_subgroup_or_requirement
  before_save :validating_not_to_add_a_child_under_a_leaf
  validate :has_alteast_one_enumeration, on: :create
  validate :has_alteast_one_unit_of_measure, on: :create
  validate :cant_change_requirement_type_on_edit, on: :update

  def validating_to_set_either_subgroup_or_requirement
    parent_id = self.parent_id
    return true if parent_id.nil?
    parent = Requirement.find(parent_id)
    has_children = parent.has_children?
    return true if has_children.nil? || has_children == false
    child = parent.children.first
      if (child.group? == true && self.group? == false)
        errors[:base] <<  "Cannot add a Single Requirement since a Sub Group already exists."
        return false
      elsif (child.group? == false && self.group? == true)
        errors[:base] <<  "Cannot add a Sub Group since a Single Requirement already exists."
        return false
      else
        return true
      end
  end

  def validating_not_to_add_a_child_under_a_leaf
    parent_id = self.parent_id
    return true if parent_id.nil?
    parent = Requirement.find(parent_id)
    if parent.group? == false
      errors[:base] <<  "Cannot add any Requirement or a Sub Group under a Single Requirement."
      return false
    else
      return true
    end
  end

  def response_text(plan)
    unless plan.plan_responses_ids.blank?
      @response = responses.where(id:  [plan.plan_responses_ids]).first
      unless @response.blank?
        if !@response.text_value.blank?
          @html_value = @response.text_value
          @value = strip_tags(@html_value).html_safe.gsub(" ", "").gsub("'", "'") if @html_value
        elsif !@response.numeric_value.blank?
          @value = @response.numeric_value.to_s
        elsif !@response.date_value.blank?
          @value = @response.date_value.to_date.strftime("%m/%d/%Y")
        elsif !@response.enumeration_id.blank?
          @value = @response.enumeration.value
        end
      end
    end
  end

  def response_html(plan)
    unless plan.plan_responses_ids.blank?
      @response = responses.where(id:  [plan.plan_responses_ids]).first
      unless @response == nil
        if !@response.text_value.blank?
          @value = @response.text_value.html_safe
        elsif !@response.numeric_value.blank?
          @value = @response.numeric_value.to_s
        elsif !@response.date_value.blank?
          @value = @response.date_value.to_date.strftime("%m/%d/%Y")
        elsif !@response.enumeration_id.blank?
          @value = @response.enumeration.value
        end
      end
    end
  end

  def has_alteast_one_enumeration
    if self.requirement_type == :enum && self.enumerations.blank?
      errors[:base] << 'Must add at least one Enumeration value'
    end
  end

  def has_alteast_one_unit_of_measure
    if self.requirement_type == :numeric && self.labels.blank?
      errors[:base] << 'Must add a Unit of Measure'
    end
  end

  def cant_change_requirement_type_on_edit
    requirements_template = RequirementsTemplate.find(self.requirements_template_id)
    if requirements_template && requirements_template.active == true
      if self.requirement_type_was != self.requirement_type
        errors[:base] << 'Cannot change Question Type for an existing Requirement of a DMP Template that has been activated.'
      end
    else
      return true
    end
  end

  # gets all the resources, of any kind of attachment that are attached to this requirement
  # as viewed by the institution in the parameter
  def resources(viewing_institution_id)
    template_id = self.requirements_template.id
    Resource.joins(:resource_contexts).
        select(SELECT_FOR_CONTEXT).
        where("resource_contexts.resource_id IS NOT NULL").
        where("resource_contexts.institution_id IS NULL OR resource_contexts.institution_id = ?", viewing_institution_id).
        where("resource_contexts.requirements_template_id IS NULL OR resource_contexts.requirements_template_id = ?", template_id ).
        where("resource_contexts.requirement_id IS NULL OR requirement_id = ?", self.id)
  end

  # gets all the resources that are not customized for a specific institution's viewing.  Levels 1, 2, 3
  def non_customized_resources
    template_id = self.requirements_template.id
    Resource.joins(:resource_contexts).
        select(SELECT_FOR_CONTEXT).
        where("resource_contexts.resource_id IS NOT NULL").
        where("resource_contexts.institution_id IS NULL").
        where("resource_contexts.requirements_template_id IS NULL OR resource_contexts.requirements_template_id = ?", template_id ).
        where("resource_contexts.requirement_id IS NULL OR requirement_id = ?", self.id)
  end

  # global resources for this requirement, Stephen's case #1
  def global_resources
    Resource.joins(:resource_contexts).
        select(SELECT_FOR_CONTEXT).
        where("resource_contexts.institution_id IS NULL").
        where("resource_contexts.requirements_template_id IS NULL").
        where("resource_contexts.requirement_id IS NULL").
        where("resource_contexts.resource_id IS NOT NULL")
  end

  # template resources for this template or template and requirement, Stephen's case #2
  def template_resources
    template_id = self.requirements_template.id
    Resource.joins(:resource_contexts).
        select(SELECT_FOR_CONTEXT).
        where("resource_contexts.institution_id IS NULL").
        where("resource_contexts.requirements_template_id = ?", template_id).
        where("resource_contexts.requirement_id IS NULL").
        where("resource_contexts.resource_id IS NOT NULL")
  end

  # requirement resources for this template or template and requirement, Stephen's case #3
  def requirement_resources
    template_id = self.requirements_template.id
    Resource.joins(:resource_contexts).
        select(SELECT_FOR_CONTEXT).
        where("resource_contexts.institution_id IS NULL").
        where("resource_contexts.requirements_template_id = ?", template_id).
        where("resource_contexts.requirement_id = ?", self.id).
        where("resource_contexts.resource_id IS NOT NULL")
  end

  # institution global resources, Stephen's case #4
  def institution_customization_resources(viewing_institution_id)
    Resource.joins(:resource_contexts).
        select(SELECT_FOR_CONTEXT).
        where("resource_contexts.institution_id = ?", viewing_institution_id).
        where("resource_contexts.requirements_template_id IS NULL").
        where("resource_contexts.requirement_id IS NULL").
        where("resource_contexts.resource_id IS NOT NULL")
  end

  # institution resources for this template, Stephen's case #5
  def template_customization_resources(viewing_institution_id)
    template_id = self.requirements_template.id
    Resource.joins(:resource_contexts).
        select(SELECT_FOR_CONTEXT).
        where("resource_contexts.institution_id = ?", viewing_institution_id).
        where("resource_contexts.requirements_template_id = ?", template_id).
        where("resource_contexts.requirement_id IS NULL").
        where("resource_contexts.resource_id IS NOT NULL")
  end

  # institution resources for this template and requirement, Stephen's case #7
  def requirement_customization_resources(viewing_institution_id)
    template_id = self.requirements_template.id
    Resource.joins(:resource_contexts).
        select(SELECT_FOR_CONTEXT).
        where("resource_contexts.institution_id = ?", viewing_institution_id).
        where("resource_contexts.requirements_template_id = ?", template_id).
        where("resource_contexts.requirement_id = ?", self.id).
        where("resource_contexts.resource_id IS NOT NULL")
  end

  #removes this requirement from the position and set its position to nil
  def remove_from_position
    return if self.position.nil?
    renumber_from = self.position
    self.position = nil
    self.update_column(:position, nil)
    Requirement.where(requirements_template_id: self.requirements_template_id).
                where("position > ?", renumber_from).
                update_all("position = position - 1")
  end

  #positions this requirement before the ID of the other requirement in the order
  def position_before(requirement_id)
    items = Requirement.where(requirements_template_id: self.requirements_template_id).where(id: requirement_id).count
    return if items < 1
    remove_from_position
    before_req = Requirement.find(requirement_id)
    from_position = before_req.position
    Requirement.where(requirements_template_id: before_req.requirements_template_id).
        where("position >= ?", from_position).
        update_all("position = position + 1")
    self.update_column(:position, from_position)
  end

  #positions this requirement after the ID of the other requirement in the order
  def position_after(requirement_id)
    items = Requirement.where(requirements_template_id: self.requirements_template_id).where(id: requirement_id).count
    return if items < 1
    remove_from_position
    after_req = Requirement.find(requirement_id)
    from_position = after_req.position

    Requirement.where(requirements_template_id: after_req.requirements_template_id).
        where("position > ?", from_position).
        update_all("position = position + 1")

    self.update_column(:position, from_position + 1)
  end

  #this is used to add a position to a requirement if it is not set, if position is set then it's ignored
  def add_high_position
    return unless self.position.nil?
    return if self.requirements_template_id.nil?
    rt = self.requirements_template
    m = rt.requirements.maximum(:position)
    if m.nil?
      m = 1
    else
      m += 1
    end
    self.update_column(:position, m)
  end

  def close_gap_in_position
    renumber_from = self.position

    Requirement.where(requirements_template_id: self.requirements_template_id).
        where("position > ?", renumber_from).
        update_all("position = position - 1")
  end

  def self.requirements_with_mandatory_obligation(plan_id, requirements_template_id)
    joins(:responses).
    where("requirements.obligation = ?", :mandatory).
    where("requirements.requirements_template_id = ?", requirements_template_id).
    where("responses.plan_id = ?", plan_id)
  end

  def next_requirement_id
    #first child
    unless self.children.order(:position).blank?
      return self.children.order(:position).first.id
    end

    #or next sibling
    siblings = self.siblings.order(:position).where(requirements_template_id: self.requirements_template_id).pluck(:id)
    next_sib = siblings.index(self.id) + 1
    unless next_sib == siblings.length #unless last sibling
      return siblings[next_sib]
    end

    #for parent's siblings
    item = self.parent
    while !item.nil?
      siblings = item.siblings.order(:position).where(requirements_template_id: item.requirements_template_id).pluck(:id)
      next_sib = siblings.index(item.id) + 1
      unless next_sib == siblings.length #unless last sibling
        return siblings[next_sib]
      end
      item = item.parent
    end

    return nil
  end

  def next_requirement_not_folder

    req = self

    begin
      next_req_id = req.next_requirement_id
      req = Requirement.find(next_req_id) unless next_req_id.nil?
    end until next_req_id.nil? || req.group.nil? || req.group == false

    next_req_id
  end

end