text:
extern "Java"
{
  namespace java
  {
    namespace awt
    {
        class Component;
        class Graphics;
    }
  }
  namespace javax
  {
    namespace swing
    {
      namespace plaf
      {
        namespace metal
        {
            class MetalIconFactory$FileChooserUpFolderIcon;
        }
      }
    }
  }
}

class javax::swing::plaf::metal::MetalIconFactory$FileChooserUpFolderIcon : public ::javax::swing::plaf::metal::MetalIconFactory$FileChooserNewFolderIcon
{

public:
  MetalIconFactory$FileChooserUpFolderIcon();
  virtual void paintIcon(::java::awt::Component *, ::java::awt::Graphics *, jint, jint);
  static ::java::lang::Class class$;
};

#endif // __javax_swing_plaf_metal_MetalIconFactory$FileChooserUpFolderIcon__


text:
<?php
/**
 * Created by PhpStorm.
 * User: Christabel
 * Date: 3/27/14
 * Time: 1:07 AM
 */

namespace CB\GrantBundle\Controller;

use CB\GrantBundle\Entity\GrantCycleInstance;
use CB\GrantBundle\Entity\PhaseInstance;
use CB\GrantBundle\Form\Model\ProjectToCycleType;
use CB\GrantBundle\Form\Model\SelectTemplateType;
use CB\GrantBundle\Form\Type\GrantCycleInstanceType;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class GrantInstanceController extends Controller {
    /*
    public function viewAction($id) {
        $em = $this->getDoctrine()->getManager();
        $grantCycle = $em->getRepository('CBGrantBundle:GrantCycle')->find($id);
        $cycleInstance = $grantCycle->getGrantCycleInstance();

        return $this->render('CBGrantBundle:Default:AllGrantInstances.html.twig', array(
           'cycleInstance' => $cycleInstance,
           'grantCycle' => $grantCycle,
        ));
    }*/

    public function viewAction($user, $grant, $project) {
        $em = $this->getDoctrine()->getManager();
        $grantCycle = $em->getRepository('CBGrantBundle:GrantCycleInstance')->find($grant);
        $projectObject = $em->getRepository('CBProjectBundle:Project')->find($project);

        if($user === 'funder') {
            return $this->render('CBGrantBundle:Funder:GrantInstancePermalink.html.twig', array(
                'instance'=>$grantCycle
            ));
        } else {
            return $this->render('CBGrantBundle:Proponent:GrantInstancePermalink.html.twig', array(
                'project'=>$projectObject,
                'instance'=>$grantCycle
            ));
        }

    }

    // id = grant id
    public function selectAction($id, Request $request) {
        $em = $this->getDoctrine()->getManager();
        $grant = $em->getRepository('CBGrantBundle:Grant')->find($id);

        $templateType = new SelectTemplateType();
        $templateType->setChoices($grant->getGrantCycle());
        $form = $this->createForm($templateType);
        $form->handleRequest($request);

        if($form->isValid()) {
            $data = $form['template']->getData();

            return $this->redirect($this->generateUrl('cb_create_grant_instance', array(
                'id'=>$data,
            )));
        } else {

            return $this->render('CBMainBundle:Default:CreateForm.html.twig', array(
                'form'=>$form->createView(),
                'title'=>'Select Template for this Instance'
            ));

        }

        /*
        $em = $this->getDoctrine()->getManager();
        $grantCycle = $em->getRepository('CBGrantBundle:GrantCycle')->find($id);

        $grantCycleInstance= new GrantCycleInstance();
        $phases = $grantCycle->getPhase();

        $phaseInstances = new ArrayCollection();

        foreach( $phases as $phase ) {

            $phaseInstance = new PhaseInstance();
            $phaseInstances[] = $phaseInstance;
            $phaseInstance->setPhase($phase);

            if( $phase != $phases->first() ) {
                $phaseInstances->prev()->setNextPhaseInstance($phaseInstance);
                $phaseInstance->setPreviousPhaseInstance($phaseInstances->prev());
            }
            $grantCycleInstance->addPhaseInstance($phaseInstance);
        }

        $instanceForm = $this->createForm(new GrantCycleInstanceType(), $grantCycleInstance);
        $instanceForm->handleRequest($request);

        if($instanceForm->isValid()) {
            $grantCycleInstance->setGrantCycle($grantCycle);

            $areas = $grantCycleInstance->getResearchArea();
            foreach($grantCycleInstance->getResearchArea() as $area) {
                if($researchArea = $this->getDoctrine()->getRepository('CBGrantBundle:ResearchArea')->find($area->getResearchAreaTag())) {
                    $areas[] = $researchArea;
                    $grantCycleInstance->removeResearchAreon($area);
                }
            }

            $em = $this->getDoctrine()->getManager();
            $em->persist($grantCycleInstance);
            $em->flush();

            return $this->redirect($this->generateUrl('cb_grant_instance', array('id'=>$id)));
        } else {

            return $this->render('CBGrantBundle:Default:CreateGrantInstance.html.twig', array(
                'form'=>$instanceForm->createView(),
            ));
        }
        */
    }

    // id - grant cycle id
    public function createAction ($id, Request $request) {
        $em = $this->getDoctrine()->getManager();
        $grantCycle = $em->getRepository('CBGrantBundle:GrantCycle')->find($id);

        $grantCycleInstance = new GrantCycleInstance();
        $phases = $grantCycle->getPhase();
        $phaseInstances = new ArrayCollection();

        $i = 0;
        $len = count($phases);
        foreach( $phases as $phase ) {

            $phaseInstance = new PhaseInstance();
            $phaseInstances[] = $phaseInstance;
            $phaseInstance->setPhase($phase);

            if ($i != 0) {
                // not first
                $phaseInstance->setPreviousPhaseInstance($phaseInstances->get($i-1));
                $phaseInstances->get($i-1)->setNextPhaseInstance($phaseInstance);
            }
            $i++;

            $grantCycleInstance->addPhaseInstance($phaseInstance);
        }

        $form = $this->createForm(new GrantCycleInstanceType(), $grantCycleInstance);
        $form->handleRequest($request);

        if($form->isValid()) {

            $grantCycleInstance->setGrantCycle($grantCycle);

            $areas = $grantCycleInstance->getResearchArea();
            foreach($grantCycleInstance->getResearchArea() as $area) {
                if($researchArea = $em->getRepository('CBGrantBundle:ResearchArea')->find($area->getResearchAreaTag())) {
                    $areas[] = $researchArea;
                    $grantCycleInstance->removeResearchAreon($area);
                }
            }

            $em->persist($grantCycleInstance);
            $em->flush();

            return $this->redirect($this->generateUrl('cb_grant_permalink', array(
                'id'=>$grantCycle->getGrant()->getGrantId(),
                'user'=>'funder'
            )));
        } else {

            return $this->render('CBMainBundle:Default:CreateForm.html.twig', array(
                'form'=>$form->createView(),
            ));

        }
    }

    public function addProjectAction($id, Request $request) {

        $em =  $this->getDoctrine()->getManager();
        // grant cycle instance id
        $instance = $em->getRepository('CBGrantBundle:GrantCycleInstance')->find($id);

        $formType = new ProjectToCycleType();
        $formType->setChoices($this->findProjects($em));

        $form = $this->createForm($formType);
        $form->handleRequest($request);

        if($form->isValid()) {
            $projectIds = $form['project']->getData();

            foreach( $projectIds as $pid ) {
                $project = $em->getRepository('CBProjectBundle:Project')->find($pid);
                $instance->addProject($project);
            }

            $em->persist($instance);
            $em->flush();

            return $this->redirect($this->generateUrl('cb_dashboard'));
        } else {

            return $this->render('CBMainBundle:Default:CreateForm.html.twig', array(
                'form'=>$form->createView(),
            ));
        }

    }

    private function findProjects($em) {
        $proponentObjects = $em->getRepository('CBProjectBundle:Proponent')->findByAccountId($this->getUser()->getAccountId());

        $projects = new ArrayCollection();

        foreach($proponentObjects as $object) {
            $projects[] = $object->getProject();
        }

        return $projects;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.IO;
using System;
using Aspose.Email.Mail;
using Aspose.Email.Outlook;
using Aspose.Email.Pop3;
using Aspose.Email;
using Aspose.Email.Mime;
using Aspose.Email.Imap;
using System.Configuration;
using System.Data;
using Aspose.Email.Mail.Bounce;

namespace Aspose.Email.Examples.CSharp.Email
{
    class SaveMessageAsDraft
    {
        public static void Run()
        {
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_Email();
            string dstEmail = dataDir + "New-Draft.msg";

            // Create a new instance of MailMessage class
            MailMessage message = new MailMessage();

            // Set sender information
            message.From = "from@domain.com";

            // Add recipients
            message.To.Add("to1@domain.com");
            message.To.Add("to2@domain.com");

            // Set subject of the message
            message.Subject = "New message created by Aspose.Email";

            // Set Html body of the message
            message.IsBodyHtml = true;
            message.HtmlBody = "This line is in bold.

This line is in blue color";

            // Create an instance of MapiMessage and load the MailMessag instance into it
            MapiMessage mapiMsg = MapiMessage.FromMailMessage(message);

            // Set the MapiMessageFlags as UNSENT and FROMME
            mapiMsg.SetMessageFlags(MapiMessageFlags.MSGFLAG_UNSENT | MapiMessageFlags.MSGFLAG_FROMME);

            // Save the MapiMessage to disk
            mapiMsg.Save(dstEmail);

            Console.WriteLine(Environment.NewLine + "Created draft MSG at " + dstEmail);
        }
    }
}


text:
package org.javasimon.console;

/**
 * Exception raised during action execution
 *
 * @author gquintana
 */
public class ActionException extends Exception {
	public static final long serialVersionUID=1;
	public ActionException(String message, Throwable cause) {
		super(message, cause);
	}

	public ActionException(String message) {
		super(message);
	}
}


text:
import datetime

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
from django import forms
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

import json

from library.models import Book, Reader, User, Borrowing
from library.forms import SearchForm, LoginForm, RegisterForm, ResetPasswordForm

def index(request):
    context = {
        'searchForm': SearchForm(),
    }
    return render(request, 'library/index.html', context)

def user_login(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('/')

    state = None

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = auth.authenticate(username=username, password=password)

        if user:
            if user.is_active:
                auth.login(request, user)
                return HttpResponseRedirect('/')
            else:
                return HttpResponse(u'Your account is disabled.')
        else:
            state = 'not_exist_or_password_error'

    context = {
        'loginForm': LoginForm(),
        'state': state,
    }

    return render(request, 'library/login.html', context)

def user_register(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('/')

    registerForm = RegisterForm()

    state = None
    if request.method == 'POST':
        registerForm = RegisterForm(request.POST, request.FILES)
        password = request.POST.get('password', '')
        repeat_password = request.POST.get('re_password', '')
        if password == '' or repeat_password == '':
            state = 'empty'
        elif password != repeat_password:
            state = 'repeat_error'
        else:
            username = request.POST.get('username', '')
            name = request.POST.get('name', '')
            if User.objects.filter(username=username):
                state = 'user_exist'
            else:
                new_user = User.objects.create(username=username)
                new_user.set_password(password)
                new_user.save()
                new_reader = Reader.objects.create(user=new_user, name=name, phone=int(username))
                new_reader.photo = request.FILES['photo']
                new_reader.save()
                state = 'success'

                auth.login(request, new_user)

                context = {
                    'state': state,
                    'registerForm': registerForm,
                }
                return render(request, 'library/register.html', context)

    context = {
        'state': state,
        'registerForm': registerForm,
    }

    return render(request, 'library/register.html', context)

@login_required
def set_password(request):
    user = request.user
    state = None
    if request.method == 'POST':
        old_password = request.POST.get('old_password', '')
        new_password = request.POST.get('new_password', '')
        repeat_password = request.POST.get('repeat_password', '')

        if user.check_password(old_password):
            if not new_password:
                state = 'empty'
            elif new_password != repeat_password:
                state = 'repeat_error'
            else:
                user.set_password(new_password)
                user.save()
                state = 'success'

    context = {
        'state': state,
        'resetPasswordForm': ResetPasswordForm(),
    }

    return render(request, 'library/set_password.html', context)

@login_required
def user_logout(request):
    auth.logout(request)
    return HttpResponseRedirect('/')

def profile(request):
    if not request.user.is_authenticated:
        return HttpResponseRedirect('/login')

    id = request.user.id
    try:
        reader = Reader.objects.get(user_id=id)
    except Reader.DoesNotExist:
        return HttpResponse('no this id reader')

    borrowing = Borrowing.objects.filter(reader=reader).exclude(date_returned__isnull=False)

    context = {
        'state': request.GET.get('state', None),
        'reader': reader,
        'borrowing': borrowing,
    }
    return render(request, 'library/profile.html', context)

def reader_operation(request):
    if not request.user.is_authenticated:
        return HttpResponseRedirect('/login')

    action = request.GET.get('action', None)

    if action == 'return_book':
        id = request.GET.get('id', None)
        if not id:
            return HttpResponse('no id')
        b = Borrowing.objects.get(pk=id)
        b.date_returned = datetime.date.today()
        if b.date_returned > b.date_due_to_returned:
            b.amount_of_fine = (b.date_returned - b.date_due_to_returned).total_seconds() / 24 / 3600 * 0.1
        b.save()

        r = Reader.objects.get(user=request.user)
        r.max_borrowing += 1
        r.save()

        bk = Book.objects.get(ISBN=b.ISBN_id)
        bk.quantity += 1
        bk.save()

        return HttpResponseRedirect('/profile?state=return_success')

    elif action == 'renew_book':
        id = request.GET.get('id', None)
        if not id:
            return HttpResponse('no id')
        b = Borrowing.objects.get(pk=id)
        if (b.date_due_to_returned - b.date_issued) < datetime.timedelta(60):
            b.date_due_to_returned += datetime.timedelta(30)
            b.save()

        return HttpResponseRedirect('/profile?state=renew_success')

    return HttpResponseRedirect('/profile')

def book_search(request):
    search_by = request.GET.get('search_by', '书名')
    books = []
    current_path = request.get_full_path()

    keyword = request.GET.get('keyword', u'_书目列表')

    if keyword == u'_书目列表':
        books = Book.objects.all()
    else:
        if search_by == u'书名':
            keyword = request.GET.get('keyword', None)
            books = Book.objects.filter(title__contains=keyword).order_by('-title')[0:50]
        elif search_by == u'ISBN':
            keyword = request.GET.get('keyword', None)
            books = Book.objects.filter(ISBN__contains=keyword).order_by('-title')[0:50]
        elif search_by == u'作者':
            keyword = request.GET.get('keyword', None)
            books = Book.objects.filter(author__contains=keyword).order_by('-title')[0:50]

    paginator = Paginator(books, 5)
    page = request.GET.get('page', 1)

    try:
        books = paginator.page(page)
    except PageNotAnInteger:
        books = paginator.page(1)
    except EmptyPage:
        books = paginator.page(paginator.num_pages)

    # ugly solution for &page=2&page=3&page=4
    if '&page' in current_path:
        current_path = current_path.split('&page')[0]

    context = {
        'books': books,
        'search_by': search_by,
        'keyword': keyword,
        'current_path': current_path,
        'searchForm': SearchForm(),
    }
    return render(request, 'library/search.html', context)

def book_detail(request):
    ISBN = request.GET.get('ISBN', None)
    print(ISBN)
    if not ISBN:
        return HttpResponse('there is no such an ISBN')
    try:
        book = Book.objects.get(pk=ISBN)
    except Book.DoesNotExist:
        return HttpResponse('there is no such an ISBN')

    action = request.GET.get('action', None)
    state = None

    if action == 'borrow':

        if not request.user.is_authenticated:
            state = 'no_user'
        else:
            reader = Reader.objects.get(user_id=request.user.id)
            if reader.max_borrowing > 0:
                reader.max_borrowing -= 1
                reader.save()

                bk = Book.objects.get(pk=ISBN)
                bk.quantity -= 1
                bk.save()

                issued = datetime.date.today()
                due_to_returned = issued + datetime.timedelta(30)

                b = Borrowing.objects.create(
                    reader=reader,
                    ISBN=bk,
                    date_issued=issued,
                    date_due_to_returned=due_to_returned)

                b.save()
                state = 'success'
                return HttpResponseRedirect('/profile?state=borrow_success')
            else:
                state = 'upper_limit'

    context = {
        'state': state,
        'book': book,
    }
    return render(request, 'library/book_detail.html', context)

def statistics(request):
    borrowing = Borrowing.objects.all()
    readerInfo = {}
    for r in borrowing:
        if r.reader.name not in readerInfo:
            readerInfo[r.reader.name] = 1
        else:
            readerInfo[r.reader.name] += 1

    bookInfo = {}
    for r in borrowing:
        if r.ISBN.title not in bookInfo:
            bookInfo[r.ISBN.title] = 1
        else:
            bookInfo[r.ISBN.title] += 1

    readerData = list(sorted(readerInfo, key=readerInfo.__getitem__, reverse=True))[0:10]
    bookData = list(sorted(bookInfo, key=bookInfo.__getitem__, reverse=True))[0:5]

    readerAmountData = [readerInfo[x] for x in readerData]

    bookAmountData = [bookInfo[x] for x in bookData]

    context = {
        'readerData': readerData,
        'readerAmountData': readerAmountData,
        'bookData': bookData,
        'bookAmountData': bookAmountData,
    }
    return render(request, 'library/statistics.html', context)

def about(request):
    return render(request, 'library/about.html', {})


text:
using UnityEngine;
using System.Collections;

public class LaserTurret : Turret {
	// laser specific settings
	public Laser LaserPrefab;

	public float LaserMaxRange = 100f;

    public float LaserLifetime = 1f;

	public override void Shoot ()
	{
		if (!canFire()) return;

		// Figure out the angle the bullet will be shot in
		// Angle = Spread + Turret Rotation
		float angleSpread = Random.Range(-Spread/2, Spread/2);
		float currentTurretRotation = this.transform.rotation.eulerAngles.y;

		Quaternion LaserRotation = Quaternion.Euler(0f, angleSpread + currentTurretRotation, 0f);

		Laser laserEntity = (Laser)Instantiate(LaserPrefab, this.transform.position, LaserRotation);
		laserEntity.transform.parent = this.transform;
		laserEntity.maxLength = LaserMaxRange;

        laserEntity.Lifetime = LaserLifetime;

	}

	public override float getAproxRange ()
	{
		return LaserMaxRange;
	}
}


text:
"""
test_gp_wideband
----------------------------------

Tests for WidebandTimingModel.
"""

import unittest

import numpy as np

from enterprise.pulsar import Pulsar
from enterprise.signals import white_signals, gp_signals, parameter, selections, signal_base
from enterprise.signals.selections import Selection
from tests.enterprise_test_data import datadir

class TestWidebandTimingModel(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        """Setup the Pulsar object."""

        cls.psr = Pulsar(
            datadir + "/J1832-0836_NANOGrav_12yv3.wb.gls.par", datadir + "/J1832-0836_NANOGrav_12yv3.wb.tim"
        )

    def test_wideband(self):
        ms = white_signals.MeasurementNoise(selection=Selection(selections.by_backend))

        dm = gp_signals.WidebandTimingModel(
            dmefac=parameter.Uniform(0.9, 1.1),
            dmefac_selection=Selection(selections.by_backend),
            log10_dmequad=parameter.Uniform(-7.0, 0.0),
            log10_dmequad_selection=Selection(selections.by_backend),
            dmjump=parameter.Normal(0, 1),
            dmjump_selection=Selection(selections.by_frontend),
            dmjump_ref=None,
            name="wideband_timing_model",
        )

        model = ms + dm

        pta = signal_base.PTA([model(self.psr)])

        ps = parameter.sample(pta.params)

        pta.get_lnlikelihood(ps)

        dmtiming = pta.pulsarmodels[0].signals[1]

        msg = "DMEFAC masks do not cover the data."
        assert np.all(sum(dmtiming._dmefac_masks) == 1), msg

        msg = "DMEQUAD masks do not cover the data."
        assert np.all(sum(dmtiming._log10_dmequad_masks) == 1), msg

        msg = "DMJUMP masks do not cover the data."
        assert np.all(sum(dmtiming._dmjump_masks) == 1), msg

        # start with zero DMEFAC, DMEQUAD, and DMJUMP
        # p0 = {par.name: (1 if "dmefac" in par.name else 0) for par in dmtiming.params}
        p0 = {}
        for par in dmtiming.params:
            if "dmefac" in par.name:
                p0[par.name] = 1.0
            elif "dmequad" in par.name:
                p0[par.name] = -1e40  # np.inf breaks the masking trick
            else:
                p0[par.name] = 0.0

        pta.get_lnlikelihood(params=p0)

        phi0 = dmtiming.get_phi(params=p0)
        dl0 = dmtiming.get_delay(params=p0)

        dm_flags, dme_flags = np.array(self.psr.flags["pp_dm"], "d"), np.array(self.psr.flags["pp_dme"], "d")

        delays = np.zeros_like(self.psr.toas)

        check = 0
        for index, par in enumerate(self.psr.fitpars):
            if "DMX" not in par:
                msg = "Problem with unbound timing parameters"
                assert phi0[index] == 1e40, msg
            else:
                dmx = self.psr.dmx[par]
                which = (dmx["DMXR1"] <= (self.psr.stoas / 86400)) & ((self.psr.stoas / 86400) < dmx["DMXR2"])
                check += which

                avgdm = np.sum(dm_flags[which] / dme_flags[which] ** 2) / np.sum(1.0 / dme_flags[which] ** 2)
                vardm = 1.0 / np.sum(1.0 / dme_flags[which] ** 2)

                msg = "Priors do not match"
                assert np.allclose(vardm, phi0[index]), msg

                delays[which] = (avgdm - self.psr.dm - dmx["DMX"]) / (2.41e-4 * self.psr.freqs[which] ** 2)

        msg = "Not all TOAs are covered by DMX"
        assert np.all(check == 1)

        msg = "Delays do not match"
        assert np.allclose(dl0, delays), msg

        # sample DMEFACs and DMEQUADs randomly
        # p1 = {par.name: (parameter.sample(par)[par.name] if "dmefac" in par.name else 0) for par in dmtiming.params}
        p1 = {
            par.name: (parameter.sample(par)[par.name] if "dmefac" in par.name or "dmequad" in par.name else 0)
            for par in dmtiming.params
        }

        pta.get_lnlikelihood(params=p1)

        phi1 = dmtiming.get_phi(params=p1)
        dl1 = dmtiming.get_delay(params=p1)

        sel = Selection(selections.by_backend)(self.psr)
        msg = "Problem making selection"
        assert np.all(sum(m for m in sel.masks.values()) == 1), msg

        dme_flags_var = dme_flags.copy()

        for key, mask in sel.masks.items():
            dmefac = p1["J1832-0836_" + key + "_dmefac"]
            log10_dmequad = p1["J1832-0836_" + key + "_log10_dmequad"]
            dmequad = 10**log10_dmequad
            dme_flags_var[mask] *= dmefac
            dme_flags_var[mask] = (dme_flags_var[mask] ** 2 + dmequad**2) ** 0.5

        for index, par in enumerate(self.psr.fitpars):
            if "DMX" not in par:
                msg = "Problem with unbound timing parameters"
                assert phi1[index] == 1e40, msg
            else:
                dmx = self.psr.dmx[par]
                which = (dmx["DMXR1"] <= (self.psr.stoas / 86400)) & ((self.psr.stoas / 86400) < dmx["DMXR2"])

                avgdm = np.sum(dm_flags[which] / dme_flags_var[which] ** 2) / np.sum(1.0 / dme_flags_var[which] ** 2)
                vardm = 1.0 / np.sum(1.0 / dme_flags_var[which] ** 2)

                msg = "Priors do not match"
                assert np.allclose(vardm, phi1[index]), msg

                delays[which] = (avgdm - self.psr.dm - dmx["DMX"]) / (2.41e-4 * self.psr.freqs[which] ** 2)

        msg = "Delays do not match"
        assert np.allclose(dl1, delays), msg

class TestGPSignalsPint(TestWidebandTimingModel):
    @classmethod
    def setUpClass(cls):
        """Setup the Pulsar object."""

        cls.psr = Pulsar(
            datadir + "/J1832-0836_NANOGrav_12yv3.wb.gls.par",
            datadir + "/J1832-0836_NANOGrav_12yv3.wb.tim",
            timing_package="pint",
        )

    def test_wideband(self):
        # PINT Pulsar object needs to include dm information

        pass


text:
/*eslint-env node, mocha */
'use strict'

const chai            = require('chai')
const chaiAsPromised  = require('chai-as-promised')
const spies           = require('chai-spies')
const mongoose        = require('mongoose')
const mockgoose       = require('mockgoose')
const Collection      = require('../../../collection')
const VersionControl  = require('../../../lib/version-control')
const collectionDefs  = require('../../fixtures/collections')

const expect = chai.expect
const fixtures = {
	definitions: {
		test1: {
			singular: 'Test1',
			fields: {
				'field1': {
					label: 'Field1',
					schemaType: { type: String }
				},
				'field2': {
					label: 'Field2',
					schemaType: {
						type: mongoose.Schema.Types.ObjectId,
						ref: 'User'
					}
				},
				'field3': {
					label: 'name',
					schemaType: {
						first: { label: 'first', type: String },
						last: { label: 'last', type: String }
					}
				},
				'field4': {
					label: 'values',
					schemaType: [{ type: String }]
				}
			}
		},
		user: {
			singular: 'User',
			fields: {
				'name': {
					label: 'Name',
					schemaType: { type: String }
				}
			}
		}
	}
}

chai.use(chaiAsPromised)
chai.use(spies)

describe('Collection', function() {

	let factory = {
		connection: null,
		getInstanceWithModel: function() {
			return { model: {} }
		}
	}

	describe('constructor()', function() {
		beforeEach(function(done) {
			mockgoose(mongoose)
				.then(() => {
					mongoose.connect('mongodb://testing', err => {
						factory.connection = mongoose.connection
						done(err)
					})
				})
		})

		afterEach(function(done) {
			delete mongoose.connection.models['Test1']
			delete mongoose.connection.models['User']
			mongoose.unmock(done)
		})

		it('should set the collection name', function() {
			const testCollection = new Collection('test1', fixtures.definitions.test1, factory)
			expect(testCollection.name).to.equal('test1')
		})

		it('should set the definition', function() {
			const testCollection = new Collection('test1', fixtures.definitions.test1, factory)
			expect(testCollection.definition).to.be.instanceof(Object)
		})

		it('should set the model name to the singular property', function() {
			const testCollection = new Collection('test1', fixtures.definitions.test1, factory)
			expect(testCollection.modelName).to.equal(fixtures.definitions.test1.singular)
		})

		it('should set the population fields', function() {
			const testCollection = new Collection('test1', fixtures.definitions.test1, factory)
			const populationFields = testCollection.populationFields
			expect(populationFields).to.be.instanceof(Array)
			expect(populationFields).to.eql(['field2'])
		})

		it('should add version control methods to documents by default', function() {
			const usersCollection = new Collection('users', collectionDefs.users, factory)

			return usersCollection.model
				.create({
					_id: mongoose.Types.ObjectId(),
					username: 'testDoc',
					email: 'test@doc.com'
				})
				.then(doc => {
					expect(doc).to.respondTo('getVersions')
					expect(doc).to.respondTo('getLatestVersion')
					expect(doc).to.respondTo('getDiffs')
					expect(doc).to.respondTo('getLatestDiff')
					expect(doc).to.respondTo('saveVersion')
					expect(doc).to.respondTo('restoreVersion')
				})
		})

		it('should not add version control methods to documents when disabled', function() {
			const def = Object.assign({}, collectionDefs.users, { versioned: false })
			const usersCollection = new Collection('users', def, factory)

			return usersCollection.model
				.create({
					_id: mongoose.Types.ObjectId(),
					username: 'testDoc',
					email: 'test@doc.com'
				})
				.then(doc => {
					expect(doc).to.not.respondTo('getVersions')
					expect(doc).to.not.respondTo('getLatestVersion')
					expect(doc).to.not.respondTo('getDiffs')
					expect(doc).to.not.respondTo('getLatestDiff')
					expect(doc).to.not.respondTo('saveVersion')
					expect(doc).to.not.respondTo('restoreVersion')
				})
		})
	})

	describe('isValidDefinition()', function() {
		it('should return true for a valid definition', function() {
			expect(Collection.isValidDefinition({
				singular: 'Users',
				fields: {}
			})).to.be.true

			expect(Collection.isValidDefinition({
				singular: 'Users',
				fields: {
					name: {
						label: 'Name',
						schemaType: { type: String }
					}
				}
			})).to.be.true
		})

		it('should return false when `singular` is missing', function() {
			let errors = []
			expect(Collection.isValidDefinition({
				fields: {}
			}, errors)).to.be.false

			expect(errors).to.have.length(2)
		})

		it('should return false when `fields` is missing', function() {
			let errors = []
			expect(Collection.isValidDefinition({
				singular: 'Test'
			}, errors)).to.be.false

			expect(errors).to.have.length(2)
		})
	})

	describe('isValidField()', function() {
		it('should return true for valid field definition', function() {
			let errors = []
			expect(Collection.isValidField({
				label: 'Text',
				schemaType: { type: String }
			}, 'test', errors)).to.be.true
		})

		it('should return false for when `label` is missing', function() {
			let errors = []
			expect(Collection.isValidField({
				schemaType: { type: String }
			}, 'test', errors)).to.be.false
			expect(errors).to.have.length(2)
		})

		it('should return false for when `schemaType` is missing', function() {
			let errors = []
			expect(Collection.isValidField({
				label: 'Text'
			}, 'test', errors)).to.be.false

			expect(errors).to.have.length(2)
		})
	})

	describe('isValidFieldRef()', function() {
		it('should return true for valid field definition', function() {
			let errors = []
			expect(Collection.isValidFieldRef({
				label: 'Text',
				schemaType: {
					type: mongoose.Schema.Types.ObjectId,
					ref: 'User'
				}
			}, 'test', ['User'], errors)).to.be.true
		})

		it('should return false for when `ref` is not a collection', function() {
			let errors = []
			expect(Collection.isValidFieldRef({
				label: 'Text',
				schemaType: {
					type: mongoose.Schema.Types.ObjectId,
					ref: 'User'
				}
			}, 'test', ['Test'], errors)).to.be.false

			expect(errors).to.have.length(1)
		})
	})

	describe('getFieldRef()', function() {
		it('should return the ref when schemaType is an object', function() {
			expect(Collection.getFieldRef({
				schemaType: { type: String, ref: 'TestRef' }
			})).to.equal('TestRef')
		})

		it('should return the ref when schemaType is an array', function() {
			expect(Collection.getFieldRef({
				schemaType: [{ type: String, ref: 'TestRef' }]
			})).to.equal('TestRef')
		})

		it('should return undefined when no ref', function() {
			expect(Collection.getFieldRef({
				schemaType: { type: String }
			})).to.be.undefined
		})
	})

	describe('getField()', function() {
		beforeEach(function(done) {
			mockgoose(mongoose)
				.then(() => {
					mongoose.connect('mongodb://testing', err => {
						factory.connection = mongoose.connection
						done(err)
					})
				})
		})

		afterEach(function(done) {
			delete mongoose.connection.models['Test1']
			mongoose.unmock(done)
		})

		it('should return a field object', function() {
			const testCollection = new Collection('test1', fixtures.definitions.test1, factory)
			const field = testCollection.getField('field1')
			expect(field).to.be.instanceof(Object)
		})

		it('should return a field object with referenceModel', function() {
			const testCollection = new Collection('test1', fixtures.definitions.test1, factory)
			const field = testCollection.getField('field2')
			expect(field).to.be.instanceof(Object)
			expect(field).to.haveOwnProperty('referenceModel')
		})

		it('should flatten the field if nested and enabled', function() {
			const testCollection = new Collection('test1', fixtures.definitions.test1, factory)
			const field3 = testCollection.getField('field3', true)
			expect(field3).to.be.instanceof(Array)
			expect(field3).to.have.deep.property('[0].name', 'field3.first')
			expect(field3).to.have.deep.property('[1].name', 'field3.last')
			expect(field3).to.have.deep.property('[1].flattened', true)
		})

		it('should not flatten fields that store arrays of values', function() {
			const testCollection = new Collection('test1', fixtures.definitions.test1, factory)
			const field4 = testCollection.getField('field4', true)
			expect(field4).to.be.instanceof(Object)
			expect(field4.name).to.eql('field4')
		})
	})

	describe('getFields()', function() {
		beforeEach(function(done) {
			mockgoose(mongoose)
				.then(() => {
					mongoose.connect('mongodb://testing', err => {
						factory.connection = mongoose.connection
						done(err)
					})
				})
		})

		afterEach(function(done) {
			delete mongoose.connection.models['Test1']
			mongoose.unmock(done)
		})

		it('should return all field definitions', function() {
			const testCollection = new Collection('test1', fixtures.definitions.test1, factory)
			const fields = testCollection.getFields()
			expect(fields).to.be.instanceOf(Object)
			expect(fields).to.haveOwnProperty('field1')
			expect(fields).to.haveOwnProperty('field2')
		})

		it('should flatten all nested fields if enabled', function() {
			const testCollection = new Collection('test1', fixtures.definitions.test1, factory)
			const fields = testCollection.getFields(true)

			expect(fields).to.be.instanceOf(Object)
			expect(fields).to.haveOwnProperty('field1')
			expect(fields).to.haveOwnProperty('field2')

			expect(fields).to.haveOwnProperty('field3.first')
			expect(fields).to.haveOwnProperty('field3.last')
			expect(fields['field3.first']).to.haveOwnProperty('label')
			expect(fields['field3.first']).to.haveOwnProperty('name')
			expect(fields['field3.first']).to.haveOwnProperty('schemaType')
			expect(fields['field3.first']).to.haveOwnProperty('flattened')
			expect(fields['field3.last']).to.haveOwnProperty('flattened')
		})
	})

	describe('inflateFields()', function() {
		beforeEach(function(done) {
			mockgoose(mongoose)
				.then(() => {
					mongoose.connect('mongodb://testing', err => {
						factory.connection = mongoose.connection
						done(err)
					})
				})
		})

		afterEach(function(done) {
			delete mongoose.connection.models['Test1']
			mongoose.unmock(done)
		})

		it('should expand flattened fields', function() {
			const testCollection = new Collection('test1', fixtures.definitions.test1, factory)
			const fieldsFlat = {
				'field1': {
					label: 'Field1',
					schemaType: { type: String }
				},
				'field2': {
					label: 'Field2',
					schemaType: {
						type: mongoose.Schema.Types.ObjectId,
						ref: 'User'
					}
				},
				'field3.first': {
					flattened: true,
					label: 'first',
					schemaType: { type: String }
				},
				'field3.last': {
					flattened: true,
					label: 'last',
					schemaType: { type: String }
				}
			}
			const fieldsExpanded = testCollection.inflateFields(fieldsFlat)

			expect(fieldsExpanded).to.have.deep.property('field1.name', 'field1')
			expect(fieldsExpanded).to.have.deep.property('field2.name', 'field2')
			expect(fieldsExpanded).to.have.deep.property('field3.name', 'field3')
			expect(fieldsExpanded).to.have.deep.property('field3.label', 'name')
		})
	})

	describe('getFieldTypeName()', function() {
		beforeEach(function(done) {
			mockgoose(mongoose)
				.then(() => {
					mongoose.connect('mongodb://testing', err => {
						factory.connection = mongoose.connection
						done(err)
					})
				})
		})

		afterEach(function(done) {
			delete mongoose.connection.models['Test1']
			mongoose.unmock(done)
		})

		it('should return the type name if schemaType is object', function() {
			const testCollection = new Collection('test1', {
				singular: 'Test1',
				fields: {
					field1: {
						label: 'name',
						schemaType: { name: 'stringType', type: String }
					},
					field2: {
						label: 'email',
						schemaType: [{ name: 'emailType', type: String }]
					}
				}
			}, factory)

			expect(testCollection.getFieldTypeName('field1')).to.equal('stringType')
		})

		it('should return the type name if schemaType is array', function() {
			const testCollection = new Collection('test1', {
				singular: 'Test1',
				fields: {
					field1: {
						label: 'name',
						schemaType: { name: 'stringType', type: String }
					},
					field2: {
						label: 'email',
						schemaType: [{ name: 'emailType', type: String }]
					}
				}
			}, factory)

			expect(testCollection.getFieldTypeName('field2')).to.equal('emailType')
		})
	})

	describe('getFieldTypes()', function() {
		beforeEach(function(done) {
			mockgoose(mongoose)
				.then(() => {
					mongoose.connect('mongodb://testing', err => {
						factory.connection = mongoose.connection
						done(err)
					})
				})
		})

		afterEach(function(done) {
			delete mongoose.connection.models['Test1']
			mongoose.unmock(done)
		})

		it('should return an array of type values', function() {
			const testCollection = new Collection('test1', {
				singular: 'Test1',
				fields: {
					field1: {
						label: 'name',
						schemaType: { name: 'stringType', type: String }
					},
					field2: {
						label: 'email',
						schemaType: [{ name: 'emailType', type: mongoose.Schema.Types.String }]
					},
					field3: {
						label: 'full name',
						schemaType: {
							first: { name: 'text', label: 'First', type: String },
							last: { name: 'text', label: 'Last', type: String }
						}
					}
				}
			}, factory)

			expect(testCollection.getFieldTypes('field1')).to.eql([
				'field1',
				'stringType',
				'String'
			])
			expect(testCollection.getFieldTypes('field2')).to.eql([
				'field2',
				'emailType',
				'String'
			])
		})

		it('should include "COMPLEX" for fields with nested values', function() {
			const testCollection = new Collection('test1', {
				singular: 'Test1',
				fields: {
					field1: {
						label: 'name',
						schemaType: { name: 'stringType', type: String }
					},
					field2: {
						label: 'email',
						schemaType: [{ name: 'emailType', type: mongoose.Schema.Types.String }]
					},
					field3: {
						label: 'full name',
						schemaType: {
							first: { name: 'text', label: 'First', type: String },
							last: { name: 'text', label: 'Last', type: String }
						}
					}
				}
			}, factory)

			expect(testCollection.getFieldTypes('field3')).to.eql([
				'field3',
				'COMPLEX'
			])
		})
	})

	describe('getMeta()', function() {
		beforeEach(function(done) {
			mockgoose(mongoose)
				.then(() => {
					mongoose.connect('mongodb://testing', err => {
						factory.connection = mongoose.connection
						done(err)
					})
				})
		})

		afterEach(function(done) {
			delete mongoose.connection.models['User']
			delete mongoose.connection.models['Post']
			mongoose.unmock(done)
		})

		it('should return the meta property specified', function() {
			const collectionWithMeta = new Collection('users', collectionDefs.users, factory)

			expect(collectionWithMeta.getMeta('description'))
				.to.equal(collectionDefs.users.meta.description)
		})

		it('should return all meta data if none specified', function() {
			const collectionWithMeta = new Collection('users', collectionDefs.users, factory)

			expect(collectionWithMeta.getMeta()).to.eql(collectionDefs.users.meta)
			expect(collectionWithMeta.getMeta()).to.not.equal(collectionDefs.users.meta)

			expect(collectionWithMeta.meta).to.eql(collectionDefs.users.meta)
		})

		it('should return undefined if property does not exist', function() {
			const collectionWithMeta = new Collection('users', collectionDefs.users, factory)

			expect(collectionWithMeta.getMeta('foo')).to.be.undefined
		})

		it('should return undefined if no metadata exists', function() {
			const collectionWithoutMeta = new Collection('posts', collectionDefs.posts, factory)

			expect(collectionWithoutMeta.getMeta()).to.be.undefined
			expect(collectionWithoutMeta.getMeta('description')).to.be.undefined

			expect(collectionWithoutMeta.meta).to.be.undefined
		})
	})

	describe('defaultField()', function() {
		beforeEach(function(done) {
			mockgoose(mongoose)
				.then(() => {
					mongoose.connect('mongodb://testing', err => {
						factory.connection = mongoose.connection
						done(err)
					})
				})
		})

		afterEach(function(done) {
			delete mongoose.connection.models['Test1']
			delete mongoose.connection.models['Test2']
			mongoose.unmock(done)
		})

		it('should return the definition property `defaultField` if present', function() {
			const testCollection1 = new Collection('test1', {
				singular: 'Test1',
				fields: {
					name: {
						label: 'name',
						schemaType: { name: 'stringType', type: String }
					}
				},
				defaultField: 'name'
			}, factory)

			expect(testCollection1.defaultField).to.eql('name')
		})

		it('should return `_id` if `defaultField` is not defined', function() {
			const testCollection2 = new Collection('test2', {
				singular: 'Test2',
				fields: {
					email: {
						label: 'email',
						schemaType: { name: 'stringType', type: String }
					}
				}
			}, factory)

			expect(testCollection2.defaultField).to.eql('_id')
		})
	})

	describe('addField()', function() {
		beforeEach(function(done) {
			mockgoose(mongoose)
				.then(() => {
					mongoose.connect('mongodb://testing', err => {
						factory.connection = mongoose.connection
						done(err)
					})
				})
		})

		afterEach(function(done) {
			delete mongoose.connection.models['Collection']
			mongoose.unmock(done)
		})

		it('should add a new path to the schema', function() {
			const coll = new Collection('coll', {
				singular: 'Collection',
				fields: {
					field1: {
						label: 'Field1',
						schemaType: String
					}
				}
			}, factory)

			coll.addField('field2', 'Field2', String)

			expect(coll.schema.path('field2')).to.not.be.undefined
		})

		it('should add a field to the collection definition', function() {
			const coll = new Collection('coll', {
				singular: 'Collection',
				fields: {
					field1: {
						label: 'Field1',
						schemaType: String
					}
				}
			}, factory)

			coll.addField('field2', 'Field2', String)

			expect(coll.definition).to.have.deep.property('fields.field2')
			expect(coll.definition.fields.field2).to.have.property('label', 'Field2')
			expect(coll.definition.fields.field2).to.have.property('schemaType', String)
		})
	})

	describe('attachHook', function () {
		beforeEach(function(done) {
			mockgoose(mongoose)
				.then(() => {
					mongoose.connect('mongodb://testing', err => {
						factory.connection = mongoose.connection
						done(err)
					})
				})
		})

		afterEach(function(done) {
			delete mongoose.connection.models['User']
			mongoose.unmock(done)
		})

		it('should add a pre hook', function() {
			const users = new Collection('users', collectionDefs.users, factory)
			const hook = chai.spy((next) => { next() })

			users.attachHook('pre', 'save', hook)
			return users.create({
				username: 'testUser',
				email: 'test@testerson.com'
			}).then(() => {
				expect(hook).to.have.been.called.exactly.once
			})
		})

		it('should add a post hook', function() {
			const users = new Collection('users', collectionDefs.users, factory)
			const hook = chai.spy((doc, next) => { next() })

			users.attachHook('post', 'save', hook)
			return users.model.create({
				username: 'testUser',
				email: 'test@testerson.com'
			}).then(() => {
				expect(hook).to.have.been.called.exactly.once
			})
		})

		it('should throw an error if `when` is not "pre" or "post"', function() {
			const users = new Collection('users', collectionDefs.users, factory)
			const hook = chai.spy((doc, next) => { next() })
			const fn = () => { users.attachHook('foo', 'save', hook) }

			expect(fn).to.throw('Must include "pre" or "post" when attaching a hook')
		})
	})

	describe('CRUD operations', function() {
		let ids = [
			new mongoose.Types.ObjectId(),
			new mongoose.Types.ObjectId()
		]

		describe('readById()', function() {
			beforeEach(function(done) {
				mockgoose(mongoose)
					.then(() => {
						mongoose.connect('mongodb://testing', err => {
							factory.connection = mongoose.connection
							done(err)
						})
					})
			})

			afterEach(function(done) {
				delete mongoose.connection.models['posts']
				mongoose.unmock(done)
			})

			it('should return a promise', function() {
				const usersCollection = new Collection('users', collectionDefs.users, factory)

				expect(usersCollection.readById(12345)).to.be.instanceof(Promise)
			})

			it('should return a query', function() {
				const usersCollection = new Collection('users', collectionDefs.users, factory)

				expect(usersCollection.readById(12345, null, null, true)).to.be.instanceof(mongoose.Query)
			})

			it('should resolve with a single document', function() {
				const usersCollection = new Collection('users', collectionDefs.users, factory)

				return usersCollection.model
					.create([
						{
							_id: ids[0],
							username: 'testDoc',
							email: 'test@doc.com'
						},
						{
							_id: ids[1],
							username: 'johndoe',
							email: 'jdoe@gmail.com'
						}
					])
					.then(() => {
						return usersCollection.readById(ids[0].toString())
					})
					.then(result => {
						expect(result).to.have.property('username', 'testDoc')
						expect(result).to.have.property('email', 'test@doc.com')
					})
			})

			it('should include populated fields with resolved document', function() {
				const usersCollection = new Collection('users', collectionDefs.users, factory)
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return usersCollection.model
					.create([
						{
							_id: ids[0],
							username: 'testDoc',
							email: 'test@doc.com'
						},
						{
							_id: ids[1],
							username: 'johndoe',
							email: 'jdoe@gmail.com'
						}
					])
					.then(() => {
						return postsCollection.model
							.create({
								title: 'Test Post',
								author: ids[0]
							})
					})
					.then(doc => {
						return postsCollection.readById(doc._id, null, true)
					})
					.then(result => {
						expect(result).to.have.deep.property('author.username', 'testDoc')
						expect(result).to.have.deep.property('author.email', 'test@doc.com')
					})
			})

			it('should not include fields where `select` is false in document', function() {
				const usersCollection = new Collection('users', collectionDefs.users, factory)
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return usersCollection.model
					.create([
						{
							_id: ids[0],
							username: 'testDoc',
							email: 'test@doc.com'
						},
						{
							_id: ids[1],
							username: 'johndoe',
							email: 'jdoe@gmail.com'
						}
					])
					.then(() => {
						return postsCollection.model
							.create({
								title: 'Test Post',
								author: ids[0]
							})
					})
					.then(doc => {
						return postsCollection.readById(doc._id, null, true)
					})
					.then(post => {
						expect(post.version).to.be.undefined
					})
			})

			it('should include selected fields when overriding `select` from schema', function() {
				const usersCollection = new Collection('users', collectionDefs.users, factory)
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return usersCollection.model
					.create([
						{
							_id: ids[0],
							username: 'testDoc',
							email: 'test@doc.com'
						},
						{
							_id: ids[1],
							username: 'johndoe',
							email: 'jdoe@gmail.com'
						}
					])
					.then(() => {
						return postsCollection.model
							.create({
								title: 'Test Post',
								author: ids[0]
							})
					})
					.then(doc => {
						return postsCollection.readById(doc._id, '+version', true)
					})
					.then(post => {
						expect(post.version).to.equal(1)
					})
			})

			it('should resolve with null when no matching id', function() {
				const usersCollection = new Collection('users', collectionDefs.users, factory)
				const result = usersCollection.readById(new mongoose.Types.ObjectId())

				return expect(result).to.eventually.be.null
			})
		})

		describe('create()', function() {
			beforeEach(function(done) {
				mockgoose(mongoose)
					.then(() => {
						mongoose.connect('mongodb://testing', err => {
							factory.connection = mongoose.connection
							done(err)
						})
					})
			})

			afterEach(function(done) {
				delete mongoose.connection.models['posts']
				mongoose.unmock(done)
			})

			it('should return a promise', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				const result = postsCollection.create({
					title: 'Test 1',
					content: 'Test 1 content',
					author: ids[0]
				})

				expect(result).to.be.instanceof(Promise)
			})

			it('should resolve with the new document', function() {
				const usersCollection = new Collection('users', collectionDefs.users, factory)
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return usersCollection.model
					.create([
						{
							_id: ids[0],
							username: 'testDoc',
							email: 'test@doc.com'
						},
						{
							_id: ids[1],
							username: 'johndoe',
							email: 'jdoe@gmail.com'
						}
					])
					.then(() => {
						return postsCollection
							.create({
								title: 'Test 2',
								content: 'Test 2 content',
								author: ids[0]
							})
					})
					.then(result => {
						expect(result).to.have.deep.property('title', 'Test 2')
						expect(result).to.have.deep.property('content', 'Test 2 content')
						expect(result).to.have.deep.property('author.username', 'testDoc')
						expect(result).to.have.property('_id')
					})
			})

			it('should reject with validation errors', function(done) {
				const usersCollection = new Collection('users', collectionDefs.users, factory)
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return usersCollection.model
					.create([
						{
							_id: ids[0],
							username: 'testDoc',
							email: 'test@doc.com'
						},
						{
							_id: ids[1],
							username: 'johndoe',
							email: 'jdoe@gmail.com'
						}
					])
					.then(() => {
						return postsCollection
							.create({
								content: 'No title content',
								author: ids[0]
							})
					})
					.then(() => done(true))
					.catch(err => {
						expect(err).to.have.deep.property('errors.title')
						done()
					})
			})

			it('should create a document version for the new document', function() {
				const usersCollection = new Collection('users', collectionDefs.users, factory)
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return usersCollection.model
					.create([
						{
							_id: ids[0],
							username: 'testDoc',
							email: 'test@doc.com'
						},
						{
							_id: ids[1],
							username: 'johndoe',
							email: 'jdoe@gmail.com'
						}
					])
					.then(() => {
						return postsCollection
							.create({
								title: 'Test 2',
								content: 'Test 2 content',
								author: ids[0]
							})
					})
					.then(doc => {
						return VersionControl.getVersions(doc._id)
					})
					.then(versions => {
						expect(versions).to.have.length(1)
						expect(versions[0].doc).to.have.property('title', 'Test 2')
					})
			})
		})

		describe('update()', function() {
			beforeEach(function(done) {
				mockgoose(mongoose)
					.then(() => {
						mongoose.connect('mongodb://testing', err => {
							factory.connection = mongoose.connection
							done(err)
						})
					})
			})

			afterEach(function(done) {
				delete mongoose.connection.models['posts']
				mongoose.unmock(done)
			})

			it('should return a promise', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create({
						title: 'Initial Document',
						content: '',
						author: ids[0]
					})
					.then(() => {
						const result = postsCollection.update([
							{ title: 'test1', content: '', author: ids[0] }
						])

						expect(result).to.be.instanceof(Promise)
					})
			})

			it('should resolve with the updated collection', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create({
						title: 'Initial Document',
						content: '',
						author: ids[0]
					})
					.then(() => {
						return postsCollection.update([
							{ title: 'test1', content: '', author: ids[0] }
						])
					})
					.then(result => {
						expect(result).to.be.instanceof(Array)
						expect(result).to.have.deep.property('[0].title', 'test1')
						expect(result).to.have.deep.property('[0].content', '')
					})
			})

			it('should overwrite the existing documents', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create({
						title: 'Initial Document',
						content: '',
						author: ids[0]
					})
					.then(() => {
						return postsCollection.update([
							{ title: 'test2', content: '', author: ids[0] }
						])
					})
					.then(() => {
						return postsCollection.model.find().exec()
					})
					.then(result => {
						expect(result).to.be.instanceof(Array)
						expect(result).to.have.length(1)
						expect(result).to.not.have.deep.property('[0].title', 'test1')
						expect(result).to.have.deep.property('[0].title', 'test2')
					})
			})

			it('should reject with validation errors', function(done) {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create({
						title: 'Initial Document',
						content: '',
						author: ids[0]
					})
					.then(() => {
						return postsCollection.update([
							{ content: '', author: ids[0] }
						])
					})
					.then(() => {
						done(true)
					})
					.catch(err => {
						expect(err).to.have.deep.property('errors.title')
						done()
					})
			})

			it('should create a new document version record for each document', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create({
						title: 'Initial Document',
						content: '',
						author: ids[0]
					})
					.then(() => {
						return postsCollection.update([
							{ title: 'test2', content: '', author: ids[0] },
							{ title: 'test3', content: '', author: ids[0] }
						])
					})
					.then(docs => {
						const promises = docs.map(doc => {
							return VersionControl.getVersions(doc._id)
						})

						return Promise.all(promises)
					})
					.then(versions => {
						expect(versions).to.have.length(2)
						expect(versions[0]).to.have.length(1)
						expect(versions[1]).to.have.length(1)
						expect(versions[0][0].doc).to.have.property('title', 'test2')
						expect(versions[1][0].doc).to.have.property('title', 'test3')
					})
			})
		})

		describe('updateById()', function() {
			beforeEach(function(done) {
				mockgoose(mongoose)
					.then(() => {
						mongoose.connect('mongodb://testing', err => {
							factory.connection = mongoose.connection
							done(err)
						})
					})
			})

			afterEach(function(done) {
				delete mongoose.connection.models['posts']
				mongoose.unmock(done)
			})

			it('should return a promise', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create({
						title: 'Update Document',
						content: '',
						author: ids[0]
					})
					.then(doc => {
						const result = postsCollection.updateById(doc._id, {
							content: 'test1'
						})

						expect(result).to.be.instanceof(Promise)
					})
			})

			it('should resolve with the updated document', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create({
						title: 'Update Document',
						content: '',
						author: ids[0]
					})
					.then(doc => {
						return postsCollection.updateById(doc._id, {
							content: 'test1'
						})
					})
					.then(result => {
						expect(result).to.have.deep.property('title', 'Update Document')
						expect(result).to.have.deep.property('content', 'test1')
					})
			})

			it('should reject with validation errors', function(done) {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create({
						title: 'Update Document',
						content: '',
						author: ids[0]
					})
					.then(doc => {
						return postsCollection.updateById(doc._id, {
							content: 'foobar'
						})
					})
					.then(() => {
						done(true)
					})
					.catch(err => {
						expect(err).to.have.deep.property('errors.content')
						expect(err).to.have.deep.property('errors.content.message', 'content must not equal foobar')
						done()
					})
			})

			it('should store a new document version', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create({
						title: 'Update Document',
						content: '',
						author: ids[0]
					})
					.then(doc => {
						return postsCollection.updateById(doc._id, {
							content: 'test1'
						})
					})
					.then(doc => {
						return VersionControl.getVersions(doc._id)
					})
					.then(versions => {
						expect(versions).to.have.length(1)
						expect(versions[0].doc).to.have.property('content', 'test1')

						return postsCollection.updateById(versions[0].version.documentId, {
							content: 'test2'
						})
					})
					.then(doc => {
						return VersionControl.getVersions(doc._id)
					})
					.then(versions => {
						expect(versions).to.have.length(2)
						expect(versions[0].doc).to.have.property('content', 'test2')
						expect(versions[1].doc).to.have.property('content', 'test1')
					})
			})
		})

		describe('del()', function() {
			beforeEach(function(done) {
				mockgoose(mongoose)
					.then(() => {
						mongoose.connect('mongodb://testing', err => {
							factory.connection = mongoose.connection
							done(err)
						})
					})
			})

			afterEach(function(done) {
				delete mongoose.connection.models['posts']
				mongoose.unmock(done)
			})

			it('should return a promise', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create([
						{
							title: 'Delete1',
							author: ids[0]
						},
						{
							title: 'Delete2',
							author: ids[0]
						}
					])
					.then(() => {
						const result = postsCollection.del()

						expect(result).to.eventually.be.instanceof(Promise)
					})
			})

			it('should resolve with the deleted documents', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create([
						{
							title: 'Delete1',
							author: ids[0]
						},
						{
							title: 'Delete2',
							author: ids[0]
						}
					])
					.then(() => {
						return postsCollection.del()
					})
					.then(result => {
						expect(result).to.have.length(2)
						expect(result).to.have.deep.property('[0].title', 'Delete1')
						expect(result).to.have.deep.property('[1].title', 'Delete2')
					})
			})

			it('should delete all documents from the collection', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create([
						{
							title: 'Delete1',
							author: ids[0]
						},
						{
							title: 'Delete2',
							author: ids[0]
						}
					])
					.then(() => {
						return postsCollection.del()
					})
					.then(function() {
						return postsCollection.model.find().exec()
					})
					.then(docs => {
						expect(docs).to.be.empty
					})
			})
		})

		describe('delById()', function() {
			beforeEach(function(done) {
				mockgoose(mongoose)
					.then(() => {
						mongoose.connect('mongodb://testing', err => {
							factory.connection = mongoose.connection
							done(err)
						})
					})
			})

			afterEach(function(done) {
				delete mongoose.connection.models['posts']
				mongoose.unmock(done)
			})

			it('should return a promise', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create([
						{
							title: 'Delete1',
							author: ids[0]
						}
					])
					.then(doc => {
						const result = postsCollection.delById(doc._id)

						expect(result).to.be.instanceof(Promise)
					})
			})

			it('should resolve with the deleted document', function() {
				const postsCollection = new Collection('posts', collectionDefs.posts, factory)

				return postsCollection.model
					.create({
						title: 'Delete1',
						content: '',
						author: ids[0]
					})
					.then(doc => {
						return postsCollection.delById(doc._id)
					})
					.then(result => {
						expect(result).to.have.deep.property('title', 'Delete1')
					})
			})
		})
	})

})


text:
'use strict'

var _ = require('lodash')
var OpParser = require('./operator_parser')

module.exports = function (seneca) {
  var StandardQuery = seneca.export('standard-query/utils')

  function parseExtendedExpression (sTypes, currentName, currentValue, params, values) {
    function parseComplexSelectOperator (sTypes, currentName, currentValue, params, values) {
      var result = {}

      result.processed = _.every(currentValue, function (opVal, op) {
        if (!OpParser[op]) {
          result.err = 'This operator is not yet implemented: ' + op
          return false
        }
        var err = OpParser[op](currentName, opVal, params, values, sTypes)
        if (err) {
          result.err = err
          return false
        }

        return true
      })

      return result
    }

    var result = StandardQuery.parseExpression(sTypes, currentName, currentValue, params, values)

    if (!result.processed && _.isObject(currentValue)) {
      result = parseComplexSelectOperator(sTypes, currentName, currentValue, params, values)
      if (result.err) {
        return result
      }
    }

    return result
  }

  function buildQueryFromExpression (entp, queryParameters, sTypes, values) {
    return StandardQuery.buildQueryFromExpressionCustom(entp, queryParameters, sTypes, values, parseExtendedExpression)
  }

  function selectstm (qent, q, sTypes, done) {
    StandardQuery.selectstmCustom(qent, q, sTypes, buildQueryFromExpression, done)
  }

  function buildSelectStatement (qent, q, sTypes, done) {
    return StandardQuery.buildSelectStatementCustom(qent, q, sTypes, selectstm, StandardQuery.selectstmOr, done)
  }

  return {
    selectstm: selectstm,
    fixPrepStatement: StandardQuery.fixPrepStatement,
    selectstmOr: StandardQuery.selectstmOr,
    buildSelectStatement: buildSelectStatement
  }
}


text:
package in.twizmwaz.cardinal.util;

import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.match.Match;
import in.twizmwaz.cardinal.module.GameObjective;
import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.modules.chatChannels.TeamChannel;
import in.twizmwaz.cardinal.module.modules.hill.HillObjective;
import in.twizmwaz.cardinal.module.modules.team.TeamModule;
import in.twizmwaz.cardinal.module.modules.wools.WoolObjective;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;

public class TeamUtils {

    public static TeamModule getTeamWithFewestPlayers(Match match) {
        TeamModule result = null;
        double percent = Double.POSITIVE_INFINITY;
        for (TeamModule team : getTeams()) {
            if (!team.isObserver() && (team.size() / (double) team.getMax()) < percent) {
                result = team;
                percent = team.size() / (double) team.getMax();
            }
        }
        return result;
    }

    public static TeamModule getTeamByName(String name) {
        if (name == null) return null;
        for (TeamModule team : GameHandler.getGameHandler().getMatch().getModules().getModules(TeamModule.class)) {
            if (team.getName().replaceAll(" ", "").toLowerCase().startsWith(name.replaceAll(" ", "").toLowerCase())) {
                return team;
            }
        }
        return null;
    }

    public static TeamModule getTeamById(String id) {
        for (TeamModule team : GameHandler.getGameHandler().getMatch().getModules().getModules(TeamModule.class)) {
            if (team.getId().replaceAll(" ", "").equalsIgnoreCase(id.replaceAll(" ", ""))) {
                return team;
            }
        }
        for (TeamModule team : GameHandler.getGameHandler().getMatch().getModules().getModules(TeamModule.class)) {
            if (team.getId().replaceAll(" ", "").toLowerCase().startsWith(id.replaceAll(" ", "").toLowerCase())) {
                return team;
            }
        }
        for (TeamModule team : GameHandler.getGameHandler().getMatch().getModules().getModules(TeamModule.class)) {
            if (team.getId().replaceAll(" ", "-").equalsIgnoreCase(id.replaceAll(" ", "-"))) {
                return team;
            }
        }
        for (TeamModule team : GameHandler.getGameHandler().getMatch().getModules().getModules(TeamModule.class)) {
            if (team.getId().replaceAll(" ", "-").toLowerCase().startsWith(id.replaceAll(" ", "-").toLowerCase())) {
                return team;
            }
        }
        return null;
    }

    public static TeamModule getTeamByPlayer(Player player) {
        for (TeamModule team : GameHandler.getGameHandler().getMatch().getModules().getModules(TeamModule.class)) {
            if (team.contains(player)) {
                return team;
            }
        }
        return null;
    }

    public static ModuleCollection<TeamModule> getTeams() {
        return GameHandler.getGameHandler().getMatch().getModules().getModules(TeamModule.class);
    }

    public static ModuleCollection<GameObjective> getObjectives(TeamModule team) {
        ModuleCollection<GameObjective> objectives = new ModuleCollection<>();
        for (GameObjective objective : GameHandler.getGameHandler().getMatch().getModules().getModules(GameObjective.class)) {
            if (objective instanceof WoolObjective) {
                if (objective.getTeam() == team) {
                    objectives.add(objective);
                }
            } else if (objective.getTeam() != team && !(objective instanceof HillObjective)) {
                objectives.add(objective);
            }
        }
        return objectives;
    }

    public static ModuleCollection<GameObjective> getShownObjectives(TeamModule team) {
        ModuleCollection<GameObjective> objectives = new ModuleCollection<>();
        for (GameObjective objective : getObjectives(team)) {
            if (objective.showOnScoreboard()) {
                objectives.add(objective);
            }
        }
        return objectives;
    }

    public static TeamChannel getTeamChannel(TeamModule team) {
        for (TeamChannel channel : GameHandler.getGameHandler().getMatch().getModules().getModules(TeamChannel.class)) {
            if (channel.getTeam() == team) return channel;
        }
        return null;
    }

    public static ChatColor getTeamColorByPlayer(OfflinePlayer player) {
        if (player.isOnline()) {
            TeamModule team = getTeamByPlayer(player.getPlayer());
            if (team != null) return team.getColor();
            else return ChatColor.DARK_AQUA;
        } else return ChatColor.DARK_AQUA;
    }

    public static boolean teamsReady() {
        for (TeamModule team : getTeams()) {
            if (!team.isReady()) return false;
        }
        return true;
    }

    public static boolean teamsNoObsReady() {
        for (TeamModule team : getTeams()) {
            if (!team.isReady() && !team.isObserver()) return false;
        }
        return true;
    }
}


text:
class Admin::ContactsController < AdminController
  before_action :load_contact, only: %i[edit update clone delete destroy]
  helper_method :search

  def new
    @contact = Contact.new
  end

  def index
    @contacts = search.results.includes(:contact_groups, :organisation).by_title
  end

  def edit; end

  def update
    if @contact.update(contact_params)
      redirect_to successful_update_url, notice: "Contact successfully updated"
    else
      render :edit
    end
  end

  def clone
    cloned_contact = Admin::CloneContact.new(@contact).clone
    flash.notice = "Contact cloned"
    redirect_to edit_admin_contact_path(cloned_contact)
  end

  def create
    contact_creator = Admin::CreateContact.new(contact_params)
    if contact_creator.save
      redirect_to admin_contacts_path, notice: "Contact successfully created"
    else
      @contact = contact_creator.contact
      render :new
    end
  end

  def delete; end

  def destroy
    if (valid_path = redirect_path(params[:redirect_url]))
      if Admin::DestroyAndRedirectContact.new(@contact, valid_path).destroy_and_redirect
        flash.notice = "Contact successfully deleted"
        redirect_to admin_contacts_path
      else
        flash.alert = @contact.errors.full_messages.to_sentence
        redirect_to delete_admin_contact_path
      end
    else
      flash.alert = "Invalid redirect URL. Redirects must be internal links, e.g. /world"
      redirect_to delete_admin_contact_path
    end
  end

private

  def redirect_path(url)
    uri = URI.parse(url)
    return uri.path if uri.host.nil?

    redirect_host = if uri.host.match(/^www\./)
                      uri.host
                    else
                      "www.#{uri.host}"
                    end
    website_root_host = URI(Plek.website_root).host
    uri.path if redirect_host == website_root_host
  rescue URI::InvalidURIError
    false
  end

  def successful_update_url
    if params[:tab].present?
      [:admin, @contact, params[:tab].to_sym]
    else
      [:edit, :admin, @contact]
    end
  end

  def load_contact
    @contact = Contact.find(params[:id])
  end

  def search
    @search ||= ContactsSearch.new search_params
  end

  def search_params
    return {} unless params.key? :contacts_search

    params.require(:contacts_search).permit(:q, :organisation_id)
  end

  def contact_params
    params.require(:contact).permit(
      { contact_group_ids: [] },
      :organisation_id,
      :description,
      :popularity,
      :before_you_contact_us,
      :contact_information,
      :title,
      :more_info_contact_form,
      :more_info_webchat,
      :more_info_email_address,
      :more_info_post_address,
      :more_info_phone_number,
      :online_transaction_link,
      :online_transaction_description,
      :quick_link_1,
      :quick_link_title_1,
      :quick_link_description_1,
      :quick_link_2,
      :quick_link_title_2,
      :quick_link_description_2,
      :quick_link_3,
      :quick_link_title_3,
      :quick_link_description_3,
      :query_response_time,
      related_contact_ids: [],
    )
  end
end


text:
var root = ui("caixilist");
var page = sm("do_Page");
root.setMapping({
	"caixititle.text":"title",
	"caixititle.tag":"index",
	"caixititle.fontColor" : "fontColor",
	"caixilist.bgColor" : "bgColor",
	"caixititle.fontStyle" : "fontStyle"
});

var _title=ui("caixititle");
var caixititle=ui("caixititle");
var caixilist=ui("caixilist");
page.on("caixiColor",function(index){
	if(_title.tag==index){
		caixititle.fontColor="E6852DFF";
		caixititle.fontStyle="bold";
		caixilist.bgColor="F6F6F6FF";
	}else{
		caixititle.fontColor="555555FF";
		caixititle.fontStyle="normal";
		caixilist.bgColor="F6F6F600";
	}
});


text:
                    Item
                    Quantity
                    Price

 0" >

                        Your cart is empty.

                    {{product.name}}
                    {{product.quantity}}
                    {{product.price * product.quantity | currency}}

                            <button
                                    class="btn btn-primary" type="button"
                                    ng-click="addItem(product)">+</button>
                            <button
                                    class="btn btn-inverse" type="button"
                                    ng-click="removeItem(product)">-</button>

                    Total
                    {{getTotalCount()}}
                    {{getTotalPrice() | currency}}
                    <button
                            class="btn btn-success" type="button" ng-show="getTotalCount() >0"
                            >Buy</button>


text:
using BootstrapTable.Support;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;

namespace BootstrapTable.Controls
{
    /// <summary>
    /// Build a BootstrapTable control.
    /// </summary>
    internal partial class TableBuilderT<TModel> : TableBuilder, IColumnBuilderT<TModel>
    {
        /// <exclude/>
        public TableBuilderT(string id = null, string url = null, TablePaginationOption sidePagination = TablePaginationOption.none, object htmlAttributes = null)
            : base(id, url, sidePagination, htmlAttributes)
        {
            typeof(TModel).GetSortedProperties().ToDictionary(x => x.Name, x => x).ForEach(pair =>
            {
                DisplayAttribute display = pair.Value.GetCustomAttribute<DisplayAttribute>();
                HiddenInputAttribute hidden = pair.Value.GetCustomAttribute<HiddenInputAttribute>();

                if (hidden == null || hidden.DisplayValue == true)
                {
                    if (display == null || display.GetAutoGenerateField() == null || display.AutoGenerateField == true)
                    {
                        if (display != null && !string.IsNullOrEmpty(display.GetName()))
                            Column(display.GetName(), pair.Key);
                        else
                            Column(pair.Key.SplitCamelCase(), pair.Key);
                    }
                }
            });
        }

        #region ITableApply
        /// <inheritDoc/>
        new public ITableBuilderT<TModel> ApplyToTable(string name, object value)
        {
            base.ApplyToTable(name, value);
            return this;
        }

        /// <inheritDoc/>
        public new ITableBuilderT<TModel> ApplyToColumns(ColumnOption option)
        {
            base.ApplyToColumns(option);
            return this;
        }

        /// <inheritDoc/>
        new public ITableBuilderT<TModel> Apply(params TableOption[] options)
        {
            base.Apply(options);
            return this;
        }

        /// <inheritDoc/>
        new public ITableBuilderT<TModel> Apply(TableOption option, object value)
        {
            base.Apply(option, value);
            return this;
        }

        /// <inheritDoc/>
        new public ITableBuilderT<TModel> Apply(TableOption option, object[] value)
        {
            base.Apply(option, value);
            return this;
        }

        /// <inheritDoc/>
        new public ITableBuilderT<TModel> Cease(params TableOption[] options)
        {
            base.Cease(options);
            return this;
        }

        /// <inheritDoc/>
        new public ITableBuilderT<TModel> Columns(params string[] columns)
        {
            base.Columns(columns);
            return this;
        }
        #endregion //ITableApply

        #region IColumnApply
        /// <inheritDoc/>
        public new IColumnBuilderT<TModel> Apply(ColumnOption option, object[] value)
        {
            base.Apply(option, value);
            return this;
        }

        /// <inheritDoc/>
        IColumnBuilderT<TModel> IColumnApply<IColumnBuilderT<TModel>>.Apply(ColumnOption option, object value)
        {
            base.Apply(option, value);
            return this;
        }

        /// <inheritDoc/>
        IColumnBuilderT<TModel> IColumnApply<IColumnBuilderT<TModel>>.Apply(params ColumnOption[] options)
        {
            base.Apply(options);
            return this;
        }

        /// <inheritDoc/>
        public new IColumnBuilderT<TModel> Cease(params ColumnOption[] options)
        {
            base.Cease(options);
            return this;
        }
        #endregion //IColumnApply

        #region ITableBuilderT
        /// <inheritDoc/>
        public IColumnBuilderT<TModel> Apply<TProperty>(Expression<Func<TModel, TProperty>> expression, ColumnOption option, object[] value)
        {
            ApplyToColumnT(expression, option.FieldName(), string.Format("[{0}]", string.Join(",", value)));
            return this;
        }

        /// <inheritDoc/>
        public IColumnBuilderT<TModel> Apply<TProperty>(Expression<Func<TModel, TProperty>> expression, ColumnOption option, object value)
        {
            ApplyToColumnT(expression, option.FieldName(), value);
            return this;
        }

        /// <inheritDoc/>
        public IColumnBuilderT<TModel> Apply<TProperty>(Expression<Func<TModel, TProperty>> expression, params ColumnOption[] options)
        {
            options.ForEach(option =>
            {
                ApplyToColumnT(expression, option.FieldName(), option.FieldValue() ?? true.ToStringLower());
            });
            return this;
        }

        /// <inheritDoc/>
        public IColumnBuilderT<TModel> Cease<TProperty>(Expression<Func<TModel, TProperty>> expression, params ColumnOption[] options)
        {
            options.ForEach(option =>
            {
                ApplyToColumnT(expression, option.FieldName(), option.FieldValue() ?? false.ToStringLower());
            });
            return this;
        }

        /// <inheritDoc/>
        public IColumnBuilderT<TModel> Column<TProperty>(Expression<Func<TModel, TProperty>> expression)
        {
            SetColumnByTitle(expression.GetDisplayName());
            return this;
        }
        #endregion //ITableBuilderT

        /// <exclude/>
        protected IColumnBuilderT<TModel> ApplyToColumnT<TProperty>(Expression<Func<TModel, TProperty>> expression, string name, object value)
        {
            if (!SetColumnByTitle(expression.GetDisplayName()))
                throw new ArgumentException("Column not found!");
            base.ApplyToColumn(name, value);
            return this;
        }
    }
}


text:
layout: default
state: sa
title: South Australia - 24 Hour Snapshot - NEMOBS
---

South Australia

24 Hour Snapshot

		{% include 24hour_snapshot.html %}
		{% include sidebar_menu.html %}


text:
#include <boost/statechart/event.hpp>
#include <boost/statechart/state_machine.hpp>

#include <boost/config.hpp>

#ifdef BOOST_HAS_DECLSPEC
  #ifdef BOOST_STATECHART_TEST_DYNAMIC_LINK
    #ifdef BOOST_STATECHART_TEST_DLL_EXPORT
      #define BOOST_STATECHART_DECL __declspec(dllexport)
    #else
      #define BOOST_STATECHART_DECL __declspec(dllimport)
    #endif
  #endif
#endif

#ifndef BOOST_STATECHART_DECL
  #define BOOST_STATECHART_DECL
#endif

namespace sc = boost::statechart;

#ifdef BOOST_MSVC
#  pragma warning( push )
   // class X needs to have dll-interface to be used by clients of class Y
#  pragma warning( disable: 4251 )
   // non dll-interface class X used as base for dll-interface class
#  pragma warning( disable: 4275 )
#endif

struct BOOST_STATECHART_DECL EvX : sc::event< EvX > {};
struct BOOST_STATECHART_DECL EvY : sc::event< EvY > {};

struct Initial;
struct BOOST_STATECHART_DECL TuTest : sc::state_machine< TuTest, Initial >
{
  void initiate();
  void unconsumed_event( const sc::event_base & );
};

#ifdef BOOST_MSVC
#  pragma warning( pop )
#endif

#endif


text:
#pragma once

#include <QtWidgets/QDialog>
#include <QtWidgets/QListWidgetItem>
#include <QtCore/QModelIndex>

#include <qrkernel/ids.h>

#include "models/models.h"

namespace Ui
{
class ReferenceList;
}

namespace qReal
{
class MainWindow;
}

/** @brief ReferenceList is a widget which allows to edit reference properties
*
* Shows all the logical elements of needed type and sets reference property to chosen value
*/

class ReferenceList : public QDialog
{
	Q_OBJECT

public:
	ReferenceList(qReal::MainWindow *mainWindow, const QPersistentModelIndex &index
			, const QString &refType, const QStringList &currentValue, int role, QWidget *parent = 0);
	~ReferenceList();

public slots:
	void activateElement(QListWidgetItem *);

signals:
	/// emitted when OK pressed
	void referenceSet(const QStringList &newValue, const QPersistentModelIndex &index, int role);

private slots:
	void valueChanged();
	void restoreSelected();

private:
	void loadList(const QString &refType);
	void addItem(const qReal::Id &element);

	void highlightCurrentValue(const QStringList &currentValue);
	QStringList getNewValue() const;

	void initConnections();

	Ui::ReferenceList *mUi;

	QPersistentModelIndex mIndex;
	int mRole;

	qReal::MainWindow *mWindow;
};


text:
/* Legacy variables. Discontinue to use these: */
/**
 * Convert font-size from px to rem with px fallback
 * @param $size - the value in pixel you want to convert
 * e.g. p {@include fontSize(12px);}
 * courtesy of https://github.com/stubbornella/oocss/blob/master/oocss/src/components/utils/_fontSize.scss
 */
/* line 3, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus {
    width: 100%;
    table-layout: fixed;
    margin-bottom: 10px;
}

/* line 7, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus thead th, #syllabus td {
    text-align: left;
    font-size: 14px;
    font-size: 0.875rem;
}

/* line 14, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus tr.date.date_passed > td, #syllabus tr.date.date_passed > th {
    background-color: #F5F5F5;
}

/* line 18, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus tr.date .day_date {
    white-space: nowrap;
}

/* line 21, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus tr.date td.details {
    padding-right: 0;
}

/* line 23, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus tr.date td.details td {
    border: none;
    background-color: transparent;
}

/* line 28, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus tr.date table.detail_list {
    width: 100%;
}

/* line 31, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus tr.date table.detail_list td.dates {
    white-space: nowrap;
    padding-right: 7px;
    text-align: right;
}

/* line 37, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus tr.date table.detail_list td.not_last {
    border-bottom: 1px solid #C7CDD1;
}

/* line 40, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus tr.date table.detail_list tr.related_event {
    background-color: #E5F2F8;
}

/* line 45, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus tr.date.date_passed td, #syllabus tr.date.date_passed th {
    background-color: #F5F5F5;
}

/* line 48, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus tr.date.date_passed.details {
    color: #444;
}

/* line 55, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus tr.date.related td, #syllabus tr.date.related th, #syllabus tr.date.selected td, #syllabus tr.date.selected th {
    background-color: #E5F2F8;
}

/* line 60, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#syllabus .special_date_title {
    color: #999;
    font-size: 12px;
    font-size: 0.75rem;
}

/* line 66, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
.name > i {
    padding-right: 6px;
}

/* line 70, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#toggle_special_dates_in_syllabus {
    float: right;
}

/* line 71, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#toggle_special_dates_in_syllabus.hidden span.hide {
    display: none;
}

/* line 74, /home/gorana/Documents/github/koturato/canvas-lms/app/stylesheets/bundles/syllabus.scss */
#toggle_special_dates_in_syllabus.shown span.show {
    display: none;
}

/* line 13, app/stylesheets/vendor/bootstrap/_mixins.scss */
#syllabus_links:before, #syllabus_links:after {
    display: table;
    content: "";
    line-height: 0;
}

/* line 21, app/stylesheets/vendor/bootstrap/_mixins.scss */
#syllabus_links:after {
    clear: both;
}


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
Acta Micropalaeontol Sin 9 (2): 194.

#### Original name
null

### Remarks
null


text:
(function () {

	angular.module('app').controller('UserController', UserController);

	function UserController($scope, authenticationService) {
		$scope.user = authenticationService.currentUser();
	}

} ());


text:
% Copyright 2011. All rights reserved.
% Institute of Measurement and Control Systems
% Karlsruhe Institute of Technology, Germany

% This file is part of libicp.
% Authors: Andreas Geiger

% libicp is free software; you can redistribute it and/or modify it under the
% terms of the GNU General Public License as published by the Free Software
% Foundation; either version 3 of the License, or any later version.

% libicp is distributed in the hope that it will be useful, but WITHOUT ANY
% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
% PARTICULAR PURPOSE. See the GNU General Public License for more details.

% You should have received a copy of the GNU General Public License along with
% libicp; if not, write to the Free Software Foundation, Inc., 51 Franklin
% Street, Fifth Floor, Boston, MA 02110-1301, USA

% libicp demo file for MATLAB

dbstop error; clear variables; close all;
disp('================================');

% create model
[X,Y] = meshgrid(-2:.25:2,-2:.25:2);
Z = 5 * X .* exp(-X.^2-Y.^2);
M = [X(:) Y(:) Z(:)]';

% transform model yielding the template
rx = 0.3;
Tr = [1 0 0 -2; 0 cos(rx) -sin(rx) 1;0 sin(rx) cos(rx) 0;0 0 0 1];
T  = Tr(1:3,1:3)*M + Tr(1:3,4)*ones(1,size(M,2));

% fit template to model
% - init with identity transformation (eye(4))
% - no outlier rejection step (-1)
% - use point-to-plane fitting
Tr_fit = icpMex(M,T,eye(4),-1,'point_to_plane');
T_fit  = Tr_fit(1:3,1:3)*T + Tr_fit(1:3,4)*ones(1,size(T,2));

% plot
figure,axis equal,hold on; ms=8; lw=2; fs=16;
plot3(M(1,:),M(2,:),M(3,:),'or','MarkerSize',ms,'LineWidth',lw);
plot3(T(1,:),T(2,:),T(3,:),'sg','MarkerSize',ms,'LineWidth',lw);
plot3(T_fit(1,:),T_fit(2,:),T_fit(3,:),'xb','MarkerSize',ms,'LineWidth',lw);
legend('model','template','fitted template','Location','NorthEast');
set(gca,'FontSize',fs);
view(20,20);


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">MonTransit Maritime Bus</string>
    <string name="app_desc">Données des autobus de Maritime Bus pour MonTransit.</string>
</resources>


text:
package org.apache.sling.osgi.installer.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.Sequence;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.service.packageadmin.PackageAdmin;

/** Test the BundleResourceProcessor */
public class BundleResourceProcessorTest {

    private Mockery mockery;
    private Sequence sequence;
    private static int counter;

    static class TestStorage extends Storage {
        int saveCounter;

        TestStorage(File f) throws IOException {
            super(f);
        }

        @Override
        protected void saveToFile() throws IOException {
            super.saveToFile();
            saveCounter++;
        }
    }

    @org.junit.Before public void setup() {
        mockery = new Mockery();
        sequence = mockery.sequence(getClass().getSimpleName());
    }

    @org.junit.Test public void testNothing() {

    }

    /** Disabled for now - too complex, gets in the way of osgiworker changes */
    public void TODO_DISABLED_testInstall() throws Exception {

        final OsgiControllerImpl c = new OsgiControllerImpl();
        final BundleContext bc = mockery.mock(BundleContext.class);
        Utilities.setField(c, "bundleContext", bc);
        final PackageAdmin pa = mockery.mock(PackageAdmin.class);
        final TestStorage s = new TestStorage(Utilities.getTestFile());
        Utilities.setStorage(c, s);
        final Bundle b = mockery.mock(Bundle.class);
        final Bundle [] bundles = { b };
        final long bundleId = 1234;
        final String uri = "/test/bundle.jar";
        final MockInstallableData data = new MockInstallableData(uri, "some data");

        // We'll try installing a bundle, re-installing to cause
        // it to be updated, and removing
        mockery.checking(new Expectations() {{
            allowing(pa).refreshPackages(null);
            allowing(pa).resolveBundles(null);
            allowing(b).start();
            allowing(b).getSymbolicName();
            will(returnValue(bundleId + "-name"));
            allowing(b).getBundleId();
            will(returnValue(bundleId));
            allowing(b).getState();
            allowing(bc).getBundle(bundleId);
            will(returnValue(b));
            allowing(bc).getBundles();
            will(returnValue(bundles));
            allowing(b).getLocation();
            will(returnValue(uri));
            allowing(bc).addFrameworkListener(with(any(FrameworkListener.class)));
            allowing(bc).getDataFile(with(any(String.class)));
            will(returnValue(getDataFile()));

            one(bc).installBundle(
            		with(equal(OsgiControllerImpl.getResourceLocation(uri))),
            		with(any(InputStream.class)));
            inSequence(sequence);
            will(returnValue(b));

            allowing(bc).getBundle(bundleId);
            inSequence(sequence);
            will(returnValue(b));

            one(b).stop();
            inSequence(sequence);

            one(b).update(with(any(InputStream.class)));
            inSequence(sequence);

            one(b).uninstall();
            inSequence(sequence);
        }});

        // Do the calls and check some stuff on the way
        final BundleResourceProcessor p = new BundleResourceProcessor(bc, pa, new MockStartLevel());
        final OsgiResourceProcessorList proc = new OsgiResourceProcessorList(bc, null, null, null);
        proc.clear();
        proc.add(p);
        Utilities.setField(c, "processors", proc);
        assertFalse("Before install, uri must not be in list", c.getInstalledUris().contains(uri));

        // Need to send framework events to p
        // TODO: this test is getting too complicated... ;-)
        class FEThread extends Thread {
        	boolean active = true;
        	public FEThread() {
        		setDaemon(true);
        		start();
			}
        	public void run() {
        		while(active) {
        			try {
        				Thread.sleep(1000L);
        			} catch(InterruptedException iex) {
        				active = false;
        			}
        			p.frameworkEvent(new FrameworkEvent(FrameworkEvent.PACKAGES_REFRESHED, b, null));
        		}
        	}
        };
        FEThread t = new FEThread();

        // do the actual testing
        c.scheduleInstallOrUpdate(uri, data);
        c.executeScheduledOperations();
        assertTrue("After install, uri must be in list", c.getInstalledUris().contains(uri));
        assertEquals("Digest must have been stored", data.getDigest(), c.getDigest(uri));
        assertEquals("Storage data has been saved during install", 1, s.saveCounter);

        data.setDigest("digest is now different");
        c.scheduleInstallOrUpdate(uri, data);
        c.executeScheduledOperations();
        assertTrue("After update, uri must be in list", c.getInstalledUris().contains(uri));
        assertEquals("Digest must have been updated", data.getDigest(), c.getDigest(uri));
        assertEquals("Storage data has been saved during update", 2, s.saveCounter);

        c.scheduleUninstall(uri);
        c.executeScheduledOperations();
        assertFalse("After uninstall, uri must not be in list", c.getInstalledUris().contains(uri));
        assertEquals("Digest must be gone", null, c.getDigest(uri));
        assertFalse("After getLastModified, uri must not be in list", c.getInstalledUris().contains(uri));
        assertEquals("Storage data has been saved during uninstall", 3, s.saveCounter);

        // And verify expectations
        mockery.assertIsSatisfied();
        t.active = false;
    }

    static File getDataFile() throws IOException {
        return File.createTempFile(BundleResourceProcessor.class.getSimpleName() + (++counter),".tmp");
    }
}


text:
module Makitzo; module Logging
  class Blackhole
    def with_host(host, &block); yield; end
    def log_command(status); end
    def overall_success!; end
    def overall_error!; end
    def error(msg); end
    def success(msg); end
    def notice(msg); end
    def warn(msg); end
    def info(msg); end
    def debug(msg); end
    def collector?; false; end
    def result; ""; end
  end
end; end


text:
DELETE FROM cw_addons WHERE addon = 'anti_scrapping_robot';
REPLACE INTO `cw_addons` (`addon`, `descr`, `active`, `status`, `parent`,`version`,`orderby`)
VALUES ('anti_scrapping_robot', 'Anti Scrapping Robot', 1, 1, '', '0.1', 0);

INSERT INTO `cw_config_categories` (`config_category_id`, `category`, `is_local`) VALUES (NULL, 'anti_scrapping_robot', '0');
SET @config_category_id = LAST_INSERT_ID();
INSERT INTO `cw_config` (`name`, `comment`, `value`, `config_category_id`, `orderby`, `type`, `defvalue`, `variants`)
VALUES ('scrapper_user_agent_likes', 'Scraper user agent likes', '', @config_category_id, '10', 'textarea', '', '');
INSERT INTO `cw_config` (`name`, `comment`, `value`, `config_category_id`, `orderby`, `type`, `defvalue`, `variants`)
VALUES ('scrapper_ips', 'Scraper IPs', '', @config_category_id, '20', 'textarea', '', '');
INSERT INTO `cw_config` (`name`, `comment`, `value`, `config_category_id`, `orderby`, `type`, `defvalue`, `variants`)
VALUES ('percent_for_price_change', 'Percent for price change', '0', @config_category_id, '30', 'numeric', '0', '');

INSERT INTO `cw_languages` (`code`, `name`, `value`, `tooltip`, `topic`) VALUES ('EN', 'addon_name_anti_scrapping_robot', 'Anti Scrapping Robot', '', 'Addons');


text:
from django.conf import settings

def get_current_path(request):
    return {'current_path': request.get_full_path(), 'current_host': request.get_host()}

def get_settings(request):
    return {'SITE_ROOT': settings.SITE_ROOT}