text:
from django.contrib import admin

from gigs.models import Gig, SignUp
# Register your models here.

admin.site.register(Gig)
admin.site.register(SignUp)

redpajama_set_name: RedPajamaGithub


text:
package com.wixpress.guineapig.entities;

import com.google.common.collect.ImmutableList;
import com.natpryce.makeiteasy.Maker;
import com.wixpress.petri.experiments.domain.Experiment;
import com.wixpress.petri.experiments.domain.ExperimentBuilder;
import com.wixpress.petri.experiments.domain.ExperimentSnapshotBuilder;
import com.wixpress.petri.laboratory.dsl.ExperimentMakers;
import org.joda.time.DateTime;

import static com.natpryce.makeiteasy.MakeItEasy.a;
import static com.natpryce.makeiteasy.MakeItEasy.with;
import static com.wixpress.petri.experiments.domain.ExperimentBuilder.anExperiment;
import static com.wixpress.petri.experiments.domain.ExperimentSnapshotBuilder.anExperimentSnapshot;
import static com.wixpress.petri.laboratory.dsl.TestGroupMakers.TEST_GROUPS_WITH_FIRST_ALWAYS_WINNING;

/**
 * @author: talyag
 * @since: 12/23/13
 */
public class ExperimentBuilders {

    private static final String SOME_SCOPE = "someScope";

    public static ExperimentBuilder createActiveEditorExperiment(String key) {
        return aLastUpdatedExperiment()
                .withExperimentSnapshot(
                        commonExperimentSnapshotBuilder(key)
                                .withScopes(ImmutableList.of(SOME_SCOPE))
                                .build()
                );
    }

    public static ExperimentBuilder createActiveEditorExperimentNotFromSpec(String key) {
        return aLastUpdatedExperiment()
                .withExperimentSnapshot(
                        commonExperimentSnapshotBuilder(key)
                                .withScopes(ImmutableList.of(SOME_SCOPE))
                                .withFromSpec(false)
                                .build()
                );
    }

    public static ExperimentBuilder createTerminatedEditorExperiment(String key) {
        return aLastUpdatedExperiment()
                .withExperimentSnapshot(commonExperimentSnapshotBuilder(key)
                                .withScopes(ImmutableList.of(SOME_SCOPE))
                                .withStartDate(new DateTime().minusHours(2))
                                .withEndDate(new DateTime().minusHours(1))
                                .build()
                );
    }

    private static ExperimentSnapshotBuilder commonExperimentSnapshotBuilder(String key) {
        return anExperimentSnapshot()
                .withKey(key)
                .withGroups(TEST_GROUPS_WITH_FIRST_ALWAYS_WINNING)
                .withFeatureToggle(true)
                .withStartDate(new DateTime().minusHours(1))
                .withEndDate(new DateTime().plusHours(1))
                .withOnlyForLoggedInUsers(true);
    }

    private static ExperimentBuilder aLastUpdatedExperiment() {
        return anExperiment()
                .withLastUpdated(new DateTime());
    }

    public static Maker<Experiment> createFuture() {
        return a(ExperimentMakers.Experiment,
                with(ExperimentMakers.startDate, new DateTime().plusHours(1)),
                with(ExperimentMakers.endDate, new DateTime().plusHours(2)));
    }
}


text:
A simple python client for the Icelandic government authentication service Íslykill (www.islykill.is)
You must apply for access before using this library.

Usage
=====

Just remember to set the `username`, `password` and `service_id` as your own.
`service_id` is the ID you are given from the national registry of Iceland (www.skra.is), e.g. for
www.betraisland.is the id is `betraisland.is` and the Íslykill authentication url is
`https://innskraning.island.is/?id=betraisland.is`

    >>> import islykill
    >>> islykill.username = "Your-username-here"
    >>> islykill.password = "Your-password-here"
    >>> islykill.service_id = "dev.roddfolksins.is"
    >>> token = 'Some-received-token' # the token received from island.is
    >>> ip_address = '1.1.1.1' # remote user ip address
    >>> result = islykill.generate_saml_from_token(token, ip_address)
    >>> print result
    {'ssn': '1234567890', 'ip_address': '1.1.1.1', 'name': u'Jon Jonsson'}

If an error occurs, the result from `generate_saml_from_token` will return a dictionary with the
key "error" with the body of the error as value, e.g.

    >>> print result
    {'error': 'HTTPError = 500'}

500 usually mean that you can make the request again immediately, just a glitch in the
webservice.

    >>> print result
    {'error': 'Unable to find SAML assertion from token.'}

"Unable to find SAML assertion from token" means that the token is invalid or expired somehow,
which means the user has to authenticate again.


text:
import { Component, Input, Output, ViewChild, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { AssetService } from '../../shared/services/asset.service';
import { FormFields } from '../../shared/interfaces/forms.interface';
import { WzFormComponent } from '../../shared/components/wz-form/wz.form.component';
import { WzToastComponent } from '../../shared/components/wz-toast/wz.toast.component';
import { CurrentUser } from '../../shared/services/current-user.model';
import { User} from '../../shared/interfaces/user.interface';
import { Subscription } from 'rxjs/Rx';

@Component({
  moduleId: module.id,
  selector: 'asset-share',
  templateUrl: 'asset-share.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class AssetShareComponent implements OnDestroy {
  @Input() currentUser: CurrentUser;
  @Input() uiState: any;
  @Input() config: any;
  @Input() assetThumbnailUrl: any;
  @Input() assetName: any;
  @Input() assetId: any;
  @Output() close = new EventEmitter();

  public assetLinkIsShowing: boolean = false;
  public assetShareLink: any = '';
  public serverErrors: any;
  public formItems: Array<any> = [];
  public user: User;
  private userSubscription: Subscription;

  @ViewChild(WzFormComponent) private wzForm: WzFormComponent;
  @ViewChild(WzToastComponent) private wzToast: WzToastComponent;

  constructor(
    currentUser: CurrentUser,
    private asset: AssetService,
    private changeDetector: ChangeDetectorRef) {
      this.userSubscription = currentUser.data.subscribe((user: User) => this.user = user);
  }

  public ngOnDestroy() {
    this.userSubscription.unsubscribe();
  }

  public closeAssetShare(): void {
    this.close.emit();
  }

  public showShareLink(assetId: any) {
    // we need to pass ISO formatted time stamps for the start and end time.
    let shareLink: any = {};
    let endDate = new Date();
    endDate.setDate(endDate.getDate() + 10);
    shareLink.accessEndDate = this.IsoFormatLocalDate(endDate);
    shareLink.accessStartDate = this.IsoFormatLocalDate(new Date());
    shareLink.accessInfo = assetId;
    shareLink.type = 'asset';

    this.asset.createShareLink(shareLink).take(1).subscribe((res) => {
      this.assetShareLink = `${window.location.href};share_key=${res.apiKey}`;
      this.changeDetector.markForCheck();
    });
    this.assetLinkIsShowing = !this.assetLinkIsShowing;
  }

  public createShareLink(shareLink: any, assetId: any): void {
    let endDate = new Date();
    endDate.setDate(endDate.getDate() + 10);
    shareLink.accessEndDate = this.IsoFormatLocalDate(endDate);
    shareLink.accessStartDate = this.IsoFormatLocalDate(new Date());
    shareLink.accessInfo = assetId;
    shareLink.type = 'asset';
    shareLink.recipientEmails = (shareLink.recipientEmails) ? shareLink.recipientEmails.split(/\s*,\s*|\s*;\s*/) : [];
    if (shareLink.copyMe) {
      shareLink.recipientEmails.push(this.user.emailAddress);
    }
    this.asset.createShareLink(shareLink).take(1).subscribe((res) => {
      this.success();
      this.wzToast.show();
    }, this.error.bind(this));
  }

  public success(): void {
    this.formItems = this.clearForm();
    this.wzForm.resetForm();
    this.changeDetector.markForCheck();
    this.closeAssetShare();
  }

  private clearForm() {
    return this.formItems
      .map((field: FormFields) => {
        field.value = '';
        if (field.type === 'tags') field.tags = [];
        return field;
      });
  }

  private error(error: any) {
    this.serverErrors = error.json();
    this.changeDetector.markForCheck();
  }

  // we need to submit date/timestamps in ISO format. This does that.
  private IsoFormatLocalDate(date: any) {
    var d = date,
      tzo = -d.getTimezoneOffset(),
      dif = tzo >= 0 ? '+' : '-',
      pad = function (num: any) {
        var norm = Math.abs(Math.floor(num));
        return (norm < 10 ? '0' : '') + norm;
      };
    return d.getFullYear()
      + '-' + pad(d.getMonth() + 1)
      + '-' + pad(d.getDate())
      + 'T' + pad(d.getHours())
      + ':' + pad(d.getMinutes())
      + ':' + pad(d.getSeconds())
      + dif + pad(tzo / 60)
      + ':' + pad(tzo % 60);
  }
}


text:
import Ember from 'ember';

const {
  assert
} = Ember;

export default Ember.Mixin.create({

  _invokeFind(database, opts) {
    assert(`override _invokeFind and don't call super ${this} ${database} ${opts}`, false);
  },

  __find(database, model) {
    let opts = this.get('find');
    assert(`Query._find should not be called when find returns ${opts}`, !!opts);

    if(!opts.hasOwnProperty('model')) {
      opts.model = model;
    }

    return this._invokeFind(database, opts);
  },

});


text:
A wrapper of sorts for go commands, meant to emulate the behavior of multiple executables without the size penalty
of having several go binaries for small tasks.

Non-hidden/deprecated commands added to `commands/cmdo.go`'s `RootCmd` can have stubs/shims created in a directory,
allowing them to be invoked directly. An example could be taking `cmdo foo` subcommand, and by running:
`cmdo install ~/bin --force` you'd have have: `~/bin/foo`. Hurray!

#### TODO

- [ ] Better documentation
- [ ] Example commands *(that aren't silly-one and silly-two)*
- [ ] Tests
- [ ] Colors
- [ ] Maintenance commands
  - [ ] Status: View list of available commands, status (installed/not) of each.
  - [ ] Remove: Check that shims are generated by us, provide ability to remove.
- [ ] Ability to force generating shims for specific platform, or both.
- [ ] Include/Exclude filters instead of skiplist.


text:
import './test_plan_list_item.html';
import { Template } from 'meteor/templating';

/**
 * Template Helpers
 */
Template.TestPlanListItem.helpers({});

/**
 * Template Event Handlers
 */
Template.TestPlanListItem.events({});

/**
 * Template Created
 */
Template.TestPlanListItem.onCreated(() => {
});

/**
 * Template Rendered
 */
Template.TestPlanListItem.onRendered(()=> {
  var instance = Template.instance();

  // make this draggable
  instance.$(".center-pole-list-selectable").draggable({
    revert  : true,
    distance: 5,
    start(event, ui) {
      ui.helper.addClass("in-drag");
    },
    stop(event, ui) {
      ui.helper.removeClass("in-drag");
    }
  });
});

/**
 * Template Destroyed
 */
Template.TestPlanListItem.onDestroyed(() => {

});


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic
    Public Module PredefinedPreprocessorSymbols

        Friend Const CurrentVersionNumber = 15.3

        ''' <summary>
        ''' Adds predefined preprocessor symbols VBC_VER and TARGET to given list of preprocessor symbols if not included yet.
        ''' </summary>
        ''' <param name="kind">The Output kind to derive the value of TARGET symbol from.</param>
        ''' <param name="symbols">A collection of KeyValue pairs representing existing symbols.</param>
        ''' <returns>Array of symbols that include VBC_VER and TARGET.</returns>
        Public Function AddPredefinedPreprocessorSymbols(kind As OutputKind, symbols As IEnumerable(Of KeyValuePair(Of String, Object))) As ImmutableArray(Of KeyValuePair(Of String, Object))
            Return AddPredefinedPreprocessorSymbols(kind, symbols.AsImmutableOrNull())
        End Function

        ''' <summary>
        ''' Adds predefined preprocessor symbols VBC_VER and TARGET to given list of preprocessor symbols if not included yet.
        ''' </summary>
        ''' <param name="kind">The Output kind to derive the value of TARGET symbol from.</param>
        ''' <param name="symbols">An parameter array of KeyValue pairs representing existing symbols.</param>
        ''' <returns>Array of symbols that include VBC_VER and TARGET.</returns>
        Public Function AddPredefinedPreprocessorSymbols(kind As OutputKind, ParamArray symbols As KeyValuePair(Of String, Object)()) As ImmutableArray(Of KeyValuePair(Of String, Object))
            Return AddPredefinedPreprocessorSymbols(kind, symbols.AsImmutableOrNull())
        End Function

        ''' <summary>
        ''' Adds predefined preprocessor symbols VBC_VER and TARGET to given list of preprocessor symbols if not included yet.
        ''' </summary>
        ''' <param name="kind">The Output kind to derive the value of TARGET symbol from.</param>
        ''' <param name="symbols">An ImmutableArray of KeyValue pairs representing existing symbols.</param>
        ''' <returns>Array of symbols that include VBC_VER and TARGET.</returns>
        Public Function AddPredefinedPreprocessorSymbols(kind As OutputKind, symbols As ImmutableArray(Of KeyValuePair(Of String, Object))) As ImmutableArray(Of KeyValuePair(Of String, Object))
            If Not kind.IsValid Then
                Throw New ArgumentOutOfRangeException(NameOf(kind))
            End If

            Const CompilerVersionSymbol = "VBC_VER"
            Const TargetSymbol = "TARGET"

            If symbols.IsDefault Then
                symbols = ImmutableArray(Of KeyValuePair(Of String, Object)).Empty
            End If

            If symbols.FirstOrDefault(Function(entry) IdentifierComparison.Equals(entry.Key, CompilerVersionSymbol)).Key Is Nothing Then
                ' This number should always line up with the current version of the compilerString
                symbols = symbols.Add(New KeyValuePair(Of String, Object)(CompilerVersionSymbol, CurrentVersionNumber))
            End If

            If symbols.FirstOrDefault(Function(entry) IdentifierComparison.Equals(entry.Key, TargetSymbol)).Key Is Nothing Then
                symbols = symbols.Add(New KeyValuePair(Of String, Object)(TargetSymbol, GetTargetString(kind)))
            End If

            Return symbols
        End Function

        Friend Function GetTargetString(kind As OutputKind) As String
            Select Case kind
                Case OutputKind.ConsoleApplication
                    Return "exe"

                Case OutputKind.DynamicallyLinkedLibrary
                    Return "library"

                Case OutputKind.NetModule
                    Return "module"

                Case OutputKind.WindowsApplication
                    Return "winexe"

                Case OutputKind.WindowsRuntimeApplication
                    Return "appcontainerexe"

                Case OutputKind.WindowsRuntimeMetadata
                    Return "winmdobj"

                Case Else
                    Throw ExceptionUtilities.UnexpectedValue(kind)
            End Select
        End Function
    End Module
End Namespace


text:
<?php
/**
 * A musical group, such as a band, an orchestra, or a choir. Can also be a solo musician.
 *
 * @see    http://schema.org/MusicGroup
*/
abstract class TypeMusicGroup extends TypePerformingGroup
{
	/**
	 * The Schema.org Type Scope
	 *
	 * @var string
	 */
	protected static $scope = 'https://schema.org/MusicGroup';

	/**
	 * A music album. Supersedes albums.
	 * Expected Type: MusicAlbum
	 *
	 * @var	array
	 */
	protected static $album = array('value' => 'album',
		'expectedTypes' => array('MusicAlbum')
	);

	/**
	 * Genre of the creative work or group.
	 * Expected Type: Text
	 *
	 * @var	array
	 */
	protected static $genre = array('value' => 'genre',
		'expectedTypes' => array('Text')
	);

	/**
	 * A music recording (track)—usually a single song. If an ItemList is given, the list should contain items of type MusicRecording. Supersedes tracks.
	 * Expected Type: ItemList, MusicRecording
	 *
	 * @var	array
	 */
	protected static $track = array('value' => 'track',
		'expectedTypes' => array('ItemList', 'MusicRecording')
	);

	/**
	 * Return the 'album' Property value
	 *
	 * @return	string
	 */
	public static function pAlbum()
	{
		return self::getValue(self::$album);
	}

	/**
	 * Return the 'genre' Property value
	 *
	 * @return	string
	 */
	public static function pGenre()
	{
		return self::getValue(self::$genre);
	}

	/**
	 * Return the 'track' Property value
	 *
	 * @return	string
	 */
	public static function pTrack()
	{
		return self::getValue(self::$track);
	}
}


text:
using GeckoUBL.Ubl21.Udt;

namespace GeckoUBL.Ubl21.Cac
{
	/// <remarks/>
	[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
	[System.SerializableAttribute()]
	[System.Diagnostics.DebuggerStepThroughAttribute()]
	[System.ComponentModel.DesignerCategoryAttribute("code")]
	[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
	[System.Xml.Serialization.XmlRootAttribute("ExchangeRate", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", IsNullable=false)]
	public class ExchangeRateType {
		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public CodeType SourceCurrencyCode { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public RateType SourceCurrencyBaseRate { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public CodeType TargetCurrencyCode { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public RateType TargetCurrencyBaseRate { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public IdentifierType ExchangeMarketID { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public RateType CalculationRate { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public CodeType MathematicOperatorCode { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public DateType Date { get; set; }

		/// <remarks/>
		public ContractType ForeignExchangeContract { get; set; }
	}
}


text:
'use strict';

// Setting up route
angular.module('users').config(['$stateProvider', 'AUTH_LEVEL',
	function($stateProvider, AUTH_LEVEL) {
		// Users state routing
		$stateProvider.
		state('unauthorized', {
			url: '/unauthorized',
			templateUrl: 'modules/users/views/unauthorized.client.view.html',
      accessLevel: AUTH_LEVEL.public
		}).
		state('profile', {
			url: '/settings/profile',
			templateUrl: 'modules/users/views/settings/edit-profile.client.view.html',
      accessLevel: AUTH_LEVEL.student
		}).
		state('password', {
			url: '/settings/password',
			templateUrl: 'modules/users/views/settings/change-password.client.view.html',
      accessLevel: AUTH_LEVEL.student
		}).
		state('signup', {
			url: '/signup',
			templateUrl: 'modules/users/views/authentication/signup.client.view.html',
      accessLevel: AUTH_LEVEL.public
		}).
		state('signin', {
			url: '/signin?failure',
			templateUrl: 'modules/users/views/authentication/signin.client.view.html',
      accessLevel: AUTH_LEVEL.public
		}).
		state('forgot', {
			url: '/password/forgot',
			templateUrl: 'modules/users/views/password/forgot-password.client.view.html',
      accessLevel: AUTH_LEVEL.public
		}).
		state('reset-invalid', {
			url: '/password/reset/invalid',
			templateUrl: 'modules/users/views/password/reset-password-invalid.client.view.html',
      accessLevel: AUTH_LEVEL.public
		}).
		state('reset-success', {
			url: '/password/reset/success',
			templateUrl: 'modules/users/views/password/reset-password-success.client.view.html',
      accessLevel: AUTH_LEVEL.public
		}).
		state('reset', {
			url: '/password/reset/:token',
			templateUrl: 'modules/users/views/password/reset-password.client.view.html',
      accessLevel: AUTH_LEVEL.public
		});
	}
]);


text:
package com.codegans.ai.cup2016.decision;

import com.codegans.ai.cup2016.action.Action;
import com.codegans.ai.cup2016.navigator.GameMap;
import model.Building;
import model.Game;
import model.LivingUnit;
import model.Wizard;

import java.util.Collection;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.lang.StrictMath.PI;
import static java.lang.StrictMath.abs;

/**
 * JavaDoc here
 *
 * @author Victor Polischuk
 * @since 14.11.2016 21:08
 */
public class DangerousBattleMoveDecision extends AbstractBattleMoveDecision {
    private static final double PADDING = 5;

    public DangerousBattleMoveDecision(int priority) {
        super(priority);
    }

    @Override
    protected Stream<Action> moveToKill(LivingUnit enemy, Wizard self, GameMap map, Game game, Collection<LivingUnit> units) {
        Collection<LivingUnit> enemies = units.stream().filter(GameMap::isEnemy)
                .filter(e -> isDanger(game, self, e, PADDING, SAFE_COOL_DOWN))
                .collect(Collectors.toList());
        long friends = units.stream().filter(GameMap::isFriend)
                .filter(e -> Double.compare(self.getDistanceTo(e), self.getCastRange()) <= 0)
                .filter(e -> Double.compare(abs(self.getAngleTo(e)), PI / 2) <= 0)
                .count();

        if (enemies.size() > 1 && friends < enemies.size()) {
            LOG.printf("Retreat!!! Enemies around: %d. Friends around: %d%n", enemies.size(), friends);

            return retreat(self, enemy, game, map, priority);
        }

        Optional<Building> optional = map.towers()
                .filter(GameMap::isEnemy)
                .filter(e -> Double.compare(self.getDistanceTo(e), e.getAttackRange() + self.getRadius() + PADDING) <= 0)
                .findAny();

        if (optional.isPresent()) {
            Building tower = optional.get();

            double distance = tower.getAttackRange() + self.getRadius() + PADDING - self.getDistanceTo(tower);

            double tickRequired = distance / game.getWizardBackwardSpeed();

            if (tower.getRemainingActionCooldownTicks() >= tickRequired && tower.getRemainingActionCooldownTicks() < tickRequired * 2) {
                LOG.printf("Retreat!!! Tower ticks remain: %d%n", tower.getRemainingActionCooldownTicks(), enemies.size(), friends);

                return retreat(self, enemy, game, map, priority);
            }
        }

        return Stream.empty();
    }
}


text:
package org.jclouds.scriptbuilder.statements.chef;

import static org.jclouds.scriptbuilder.domain.Statements.createOrOverwriteFile;
import static org.jclouds.scriptbuilder.domain.Statements.exec;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

import java.io.IOException;

import org.jclouds.scriptbuilder.domain.OsFamily;
import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.scriptbuilder.domain.chef.DataBag;
import org.jclouds.scriptbuilder.domain.chef.Role;
import org.jclouds.scriptbuilder.domain.chef.RunList;
import org.testng.annotations.Test;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;

/**
 * Unit tests for the {@link ChefSoloTest} statement.
 */
@Test(groups = "unit", testName = "ChefSoloTest")
public class ChefSoloTest {

   public void testCreateDefaultSoloConfiguration() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      ChefSolo solo = ChefSolo.builder().build();

      solo.createSoloConfiguration(statements);
      ImmutableList<Statement> statementList = statements.build();

      assertEquals(statementList.size(), 3);
      assertEquals(statementList.get(0), exec("{md} " + ChefSolo.DEFAULT_SOLO_PATH));
      assertEquals(statementList.get(1), exec("{md} " + ChefSolo.DEFAULT_SOLO_PATH + "/cookbooks"));

      Statement expected = createOrOverwriteFile(
            ChefSolo.DEFAULT_SOLO_PATH + "/solo.rb",
            ImmutableSet.of("file_cache_path \"" + ChefSolo.DEFAULT_SOLO_PATH + "\"", //
                  "cookbook_path [\"" + ChefSolo.DEFAULT_SOLO_PATH + "/cookbooks\"]", "role_path \""
                        + ChefSolo.DEFAULT_SOLO_PATH + "/roles\"", "data_bag_path \"" + ChefSolo.DEFAULT_SOLO_PATH
                        + "/data_bags\""));

      assertEquals(statementList.get(2).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));
   }

   public void testCreateCustomSoloConfiguration() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      ChefSolo solo = ChefSolo.builder().fileCachePath("/tmp").cookbookPath("/tmp/foo").cookbookPath("/tmp/bar")
            .rolePath("/tmp/roles").dataBagPath("/tmp/databags").build();

      solo.createSoloConfiguration(statements);
      ImmutableList<Statement> statementList = statements.build();

      assertEquals(statementList.size(), 4);
      assertEquals(statementList.get(0), exec("{md} /tmp"));
      assertEquals(statementList.get(1), exec("{md} /tmp/foo"));
      assertEquals(statementList.get(2), exec("{md} /tmp/bar"));

      Statement expected = createOrOverwriteFile("/tmp/solo.rb", ImmutableSet.of("file_cache_path \"/tmp\"", //
            "cookbook_path [\"/tmp/foo\",\"/tmp/bar\"]", "role_path \"/tmp/roles\"", "data_bag_path \"/tmp/databags\""));

      assertEquals(statementList.get(3).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));
   }

   public void testCreateDefaultNodeConfiguration() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      ChefSolo solo = ChefSolo.builder().build();

      solo.createNodeConfiguration(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + "/node.json",
            ImmutableSet.of("{\"run_list\":[]}"));

      assertEquals(statementList.size(), 1);
      assertEquals(statementList.get(0).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));
   }

   public void testCreateNodeConfigurationWithJsonAttributes() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      ChefSolo solo = ChefSolo.builder().jsonAttributes("{\"foo\":\"bar\"}").build();

      solo.createNodeConfiguration(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + "/node.json",
            ImmutableSet.of("{\"foo\":\"bar\",\"run_list\":[]}"));

      assertEquals(statementList.size(), 1);
      assertEquals(statementList.get(0).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));
   }

   public void testCreateNodeConfigurationWithRunList() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      RunList runlist = RunList.builder().recipe("foo").role("bar").build();
      ChefSolo solo = ChefSolo.builder().runlist(runlist).build();

      solo.createNodeConfiguration(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + "/node.json",
            ImmutableSet.of("{\"run_list\":[\"recipe[foo]\",\"role[bar]\"]}"));

      assertEquals(statementList.size(), 1);
      assertEquals(statementList.get(0).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));
   }

   public void testCreateNodeConfigurationWithJsonAttributesAndRunList() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      RunList runlist = RunList.builder().recipe("foo").role("bar").build();
      ChefSolo solo = ChefSolo.builder().jsonAttributes("{\"foo\":\"bar\"}").runlist(runlist).build();

      solo.createNodeConfiguration(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + "/node.json",
            ImmutableSet.of("{\"foo\":\"bar\",\"run_list\":[\"recipe[foo]\",\"role[bar]\"]}"));

      assertEquals(statementList.size(), 1);
      assertEquals(statementList.get(0).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));
   }

   public void testCreateRolesIfNecessaryWithDefaultValues() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      ChefSolo solo = ChefSolo.builder().build();

      solo.createRolesIfNecessary(statements);
      ImmutableList<Statement> statementList = statements.build();

      assertTrue(statementList.isEmpty());
   }

   public void testCreateRolesIfNecessaryWithOneRole() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      RunList runlist = RunList.builder().recipe("bar").build();
      Role role = Role.builder().name("foo").runlist(runlist).build();
      ChefSolo solo = ChefSolo.builder().defineRole(role).build();

      solo.createRolesIfNecessary(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + "/roles/" + role.getName() + ".json",
            ImmutableSet.of(role.toJsonString()));

      assertEquals(statementList.size(), 2);
      assertEquals(statementList.get(0), exec("{md} " + ChefSolo.DEFAULT_SOLO_PATH + "/roles"));
      assertEquals(statementList.get(1).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));
   }

   public void testCreateRolesIfNecessaryWithOneRoleAndCustomPath() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      RunList runlist = RunList.builder().recipe("bar").build();
      Role role = Role.builder().name("foo").runlist(runlist).build();
      ChefSolo solo = ChefSolo.builder().rolePath("/tmp/roles").defineRole(role).build();

      solo.createRolesIfNecessary(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expected = createOrOverwriteFile("/tmp/roles/" + role.getName() + ".json",
            ImmutableSet.of(role.toJsonString()));

      assertEquals(statementList.size(), 2);
      assertEquals(statementList.get(0), exec("{md} /tmp/roles"));
      assertEquals(statementList.get(1).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));
   }

   public void testCreateRolesIfNecessaryWithMultipleRoleAndCustomPath() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      Role roleFoo = Role.builder().name("foo").runlist(RunList.builder().recipe("foo").build()).build();
      Role roleBar = Role.builder().name("bar").runlist(RunList.builder().recipe("bar").build()).build();
      ChefSolo solo = ChefSolo.builder().rolePath("/tmp/roles").defineRole(roleFoo).defineRole(roleBar).build();

      solo.createRolesIfNecessary(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expectedFoo = createOrOverwriteFile("/tmp/roles/" + roleFoo.getName() + ".json",
            ImmutableSet.of(roleFoo.toJsonString()));
      Statement expectedBar = createOrOverwriteFile("/tmp/roles/" + roleBar.getName() + ".json",
            ImmutableSet.of(roleBar.toJsonString()));

      assertEquals(statementList.size(), 3);
      assertEquals(statementList.get(0), exec("{md} /tmp/roles"));
      assertEquals(statementList.get(1).render(OsFamily.UNIX), expectedFoo.render(OsFamily.UNIX));
      assertEquals(statementList.get(2).render(OsFamily.UNIX), expectedBar.render(OsFamily.UNIX));
   }

   public void testCreateDatabagsIfNecessaryWithDefaultValues() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      ChefSolo solo = ChefSolo.builder().build();

      solo.createDatabagsIfNecessary(statements);
      ImmutableList<Statement> statementList = statements.build();

      assertTrue(statementList.isEmpty());
   }

   public void testCreateDatabagsIfNecessaryWithOneDatabag() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      DataBag databag = DataBag.builder().name("foo").item("item", "{\"foo\":\"bar\"}").build();
      ChefSolo solo = ChefSolo.builder().defineDataBag(databag).build();

      solo.createDatabagsIfNecessary(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + "/data_bags/foo/item.json",
            ImmutableSet.of("{\"foo\":\"bar\"}"));

      assertEquals(statementList.size(), 3);
      assertEquals(statementList.get(0), exec("{md} " + ChefSolo.DEFAULT_SOLO_PATH + "/data_bags"));
      assertEquals(statementList.get(1), exec("{md} " + ChefSolo.DEFAULT_SOLO_PATH + "/data_bags/" + databag.getName()));
      assertEquals(statementList.get(2).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));
   }

   public void testCreateDatabagsIfNecessaryWithOneDatabagAndCustomPath() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      DataBag databag = DataBag.builder().name("foo").item("item", "{\"foo\":\"bar\"}").build();
      ChefSolo solo = ChefSolo.builder().dataBagPath("/tmp/databags").defineDataBag(databag).build();

      solo.createDatabagsIfNecessary(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expected = createOrOverwriteFile("/tmp/databags/foo/item.json", ImmutableSet.of("{\"foo\":\"bar\"}"));

      assertEquals(statementList.size(), 3);
      assertEquals(statementList.get(0), exec("{md} /tmp/databags"));
      assertEquals(statementList.get(1), exec("{md} /tmp/databags/" + databag.getName()));
      assertEquals(statementList.get(2).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));
   }

   public void testCreateDatabagsIfNecessaryWithOneDatabagWithMultipleItemsAndCustomPath() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      DataBag databag = DataBag.builder().name("foo").item("item1", "{\"foo\":\"bar\"}")
            .item("item2", "{\"bar\":\"foo\"}").build();
      ChefSolo solo = ChefSolo.builder().dataBagPath("/tmp/databags").defineDataBag(databag).build();

      solo.createDatabagsIfNecessary(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expectedItem1 = createOrOverwriteFile("/tmp/databags/foo/item1.json",
            ImmutableSet.of("{\"foo\":\"bar\"}"));
      Statement expectedItem2 = createOrOverwriteFile("/tmp/databags/foo/item2.json",
            ImmutableSet.of("{\"bar\":\"foo\"}"));

      assertEquals(statementList.size(), 4);
      assertEquals(statementList.get(0), exec("{md} /tmp/databags"));
      assertEquals(statementList.get(1), exec("{md} /tmp/databags/" + databag.getName()));
      assertEquals(statementList.get(2).render(OsFamily.UNIX), expectedItem1.render(OsFamily.UNIX));
      assertEquals(statementList.get(3).render(OsFamily.UNIX), expectedItem2.render(OsFamily.UNIX));
   }

   public void testCreateDatabagsIfNecessaryWithMultipleDatabagsAndCustomPath() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      DataBag databagFoo = DataBag.builder().name("foo").item("itemFoo", "{\"foo\":\"bar\"}").build();
      DataBag databagBar = DataBag.builder().name("bar").item("itemBar", "{\"bar\":\"foo\"}").build();
      ChefSolo solo = ChefSolo.builder().dataBagPath("/tmp/databags").defineDataBag(databagFoo)
            .defineDataBag(databagBar).build();

      solo.createDatabagsIfNecessary(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expectedFoo = createOrOverwriteFile("/tmp/databags/foo/itemFoo.json",
            ImmutableSet.of("{\"foo\":\"bar\"}"));
      Statement expectedBar = createOrOverwriteFile("/tmp/databags/bar/itemBar.json",
            ImmutableSet.of("{\"bar\":\"foo\"}"));

      assertEquals(statementList.size(), 5);
      assertEquals(statementList.get(0), exec("{md} /tmp/databags"));
      assertEquals(statementList.get(1), exec("{md} /tmp/databags/" + databagFoo.getName()));
      assertEquals(statementList.get(2).render(OsFamily.UNIX), expectedFoo.render(OsFamily.UNIX));
      assertEquals(statementList.get(3), exec("{md} /tmp/databags/" + databagBar.getName()));
      assertEquals(statementList.get(4).render(OsFamily.UNIX), expectedBar.render(OsFamily.UNIX));
   }

   public void testCreateDatabagsIfNecessaryWithMultipleDatabagsAndMultipleItemsAndCustomPath() {
      ImmutableList.Builder<Statement> statements = ImmutableList.builder();
      DataBag databagFoo = DataBag.builder().name("foo").item("itemFoo", "{\"foo\":\"bar\"}").build();
      DataBag databagBar = DataBag.builder().name("bar").item("itemBar", "{\"bar\":\"foo\"}")
            .item("extra", "{\"extra\":[]}").build();
      ChefSolo solo = ChefSolo.builder().dataBagPath("/tmp/databags").defineDataBag(databagFoo)
            .defineDataBag(databagBar).build();

      solo.createDatabagsIfNecessary(statements);
      ImmutableList<Statement> statementList = statements.build();

      Statement expectedFoo = createOrOverwriteFile("/tmp/databags/foo/itemFoo.json",
            ImmutableSet.of("{\"foo\":\"bar\"}"));
      Statement expectedBar = createOrOverwriteFile("/tmp/databags/bar/itemBar.json",
            ImmutableSet.of("{\"bar\":\"foo\"}"));
      Statement expectedExtra = createOrOverwriteFile("/tmp/databags/bar/extra.json", ImmutableSet.of("{\"extra\":[]}"));

      assertEquals(statementList.size(), 6);
      assertEquals(statementList.get(0), exec("{md} /tmp/databags"));
      assertEquals(statementList.get(1), exec("{md} /tmp/databags/" + databagFoo.getName()));
      assertEquals(statementList.get(2).render(OsFamily.UNIX), expectedFoo.render(OsFamily.UNIX));
      assertEquals(statementList.get(3), exec("{md} /tmp/databags/" + databagBar.getName()));
      assertEquals(statementList.get(4).render(OsFamily.UNIX), expectedBar.render(OsFamily.UNIX));
      assertEquals(statementList.get(5).render(OsFamily.UNIX), expectedExtra.render(OsFamily.UNIX));
   }

   @Test(expectedExceptions = UnsupportedOperationException.class, expectedExceptionsMessageRegExp = "windows not yet implemented")
   public void testChefSoloInWindows() {
      ChefSolo.builder().cookbooksArchiveLocation("/tmp/cookbooks").build().render(OsFamily.WINDOWS);
   }

   public void testChefWoloWithDefaultConfiguration() throws IOException {
      String script = ChefSolo.builder().build().render(OsFamily.UNIX);
      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()
            + "chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname`\n");
   }

   public void testChefWoloWithNodeName() throws IOException {
      String script = ChefSolo.builder().nodeName("foo").build().render(OsFamily.UNIX);
      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()
            + "chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N foo\n");
   }

   public void testChefSoloWithGroup() throws IOException {
      String script = ChefSolo.builder().group("foo").build().render(OsFamily.UNIX);
      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()
            + "chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -g foo\n");
   }

   public void testChefSoloWithInterval() throws IOException {
      String script = ChefSolo.builder().interval(15).build().render(OsFamily.UNIX);
      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()
            + "chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -i 15\n");
   }

   public void testChefSoloWithLogLevel() throws IOException {
      String script = ChefSolo.builder().logLevel("debug").build().render(OsFamily.UNIX);
      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()
            + "chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -l debug\n");
   }

   public void testChefSoloWithLogFile() throws IOException {
      String script = ChefSolo.builder().logFile("/var/log/solo.log").build().render(OsFamily.UNIX);
      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()
            + "chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -L /var/log/solo.log\n");
   }

   public void testChefSoloWithCookbooksLocation() throws IOException {
      String script = ChefSolo.builder().cookbooksArchiveLocation("/tmp/cookbooks").build().render(OsFamily.UNIX);
      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()
            + "chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -r /tmp/cookbooks\n");
   }

   public void testChefSoloWithSplay() throws IOException {
      String script = ChefSolo.builder().splay(15).build().render(OsFamily.UNIX);
      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()
            + "chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -s 15\n");
   }

   public void testChefSoloWithUser() throws IOException {
      String script = ChefSolo.builder().user("foo").build().render(OsFamily.UNIX);
      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()
            + "chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -u foo\n");
   }

   private static String createConfigFile() {
      return "mkdir -p /var/chef\nmkdir -p /var/chef/cookbooks\ncat > /var/chef/solo.rb <<-'END_OF_JCLOUDS_FILE'\n"
            + "\tfile_cache_path \"/var/chef\"\n\tcookbook_path [\"/var/chef/cookbooks\"]\n"
            + "\trole_path \"/var/chef/roles\"\n\tdata_bag_path \"/var/chef/data_bags\"\nEND_OF_JCLOUDS_FILE\n";
   }

   private static String createNodeFile() {
      return "cat > /var/chef/node.json <<-'END_OF_JCLOUDS_FILE'\n\t{\"run_list\":[]}\nEND_OF_JCLOUDS_FILE\n";
   }

   private static String checkSoloExists() {
      return "if ! hash chef-solo 2>/dev/null; then\necho 'chef-solo not found. Please, install Chef first'\nexit 1\nfi\n";
   }

}


text:
/* $Id: memcache_queue.c,v 1.4 2008/08/16 10:15:54 tony2001 Exp $ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "memcache_queue.h"

void mmc_queue_push(mmc_queue_t *queue, void *ptr) {
	if (queue->len >= queue->alloc) {
		int increase = 1 + MMC_QUEUE_PREALLOC;
		queue->alloc += increase;
		queue->items = erealloc(queue->items, sizeof(*queue->items) * queue->alloc);

		/* move tail segment downwards */
		if (queue->head < queue->tail) {
			memmove(queue->items + queue->tail + increase, queue->items + queue->tail, (queue->alloc - queue->tail - increase) * sizeof(*queue->items));
			queue->tail += increase;
		}
	}

	if (queue->len) {
		queue->head++;

		if (queue->head >= queue->alloc) {
			queue->head = 0;
		}
	}

	queue->items[queue->head] = ptr;
	queue->len++;
}

void *mmc_queue_pop(mmc_queue_t *queue) {
	if (queue->len) {
		void *ptr;

		ptr = queue->items[queue->tail];
		queue->len--;

		if (queue->len) {
			queue->tail++;

			if (queue->tail >= queue->alloc) {
				queue->tail = 0;
			}
		}

		return ptr;
	}
	return NULL;
}

int mmc_queue_contains(mmc_queue_t *queue, void *ptr) {
	if (queue != NULL) {
		int i;

		for (i=0; i < queue->len; i++) {
			if (mmc_queue_item(queue, i) == ptr) {
				return 1;
			}
		}
	}

	return 0;
}

void mmc_queue_free(mmc_queue_t *queue) {
	if (queue->items != NULL) {
		efree(queue->items);
	}
	memset(queue, 0, sizeof(*queue));
}

void mmc_queue_copy(mmc_queue_t *source, mmc_queue_t *target) {
	if (target->alloc != source->alloc) {
		target->alloc = source->alloc;
		erealloc(target->items, sizeof(*target->items) * target->alloc);
	}

	memcpy(target->items, source->items, sizeof(*source->items) * source->alloc);
	target->head = source->head;
	target->tail = source->tail;
	target->len = source->len;
}

void mmc_queue_remove(mmc_queue_t *queue, void *ptr) {
	void *item;
	mmc_queue_t original = *queue;
	mmc_queue_release(queue);

	while ((item = mmc_queue_pop(&original)) != NULL) {
		if (item != ptr) {
			mmc_queue_push(queue, item);
		}
	}

	mmc_queue_free(&original);
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */


text:
package io.getquill.context.ndbc.postgres

import io.getquill.context.sql.encoding.ArrayEncodingBaseSpec

class ArrayNdbcPostgresEncodingSpec extends ArrayEncodingBaseSpec {

  val ctx = testContext
  import ctx._

  val q = quote(query[ArraysTestEntity])

  "Support all sql base types and `Traversable` implementers" in {
    get(ctx.run(q.insertValue(lift(e))))
    val actual = get(ctx.run(q)).head
    actual mustEqual e
    baseEntityDeepCheck(actual, e)
  }

  "Support Traversable encoding basing on MappedEncoding" in {
    val wrapQ = quote(querySchema[WrapEntity]("ArraysTestEntity"))
    get(ctx.run(wrapQ.insertValue(lift(wrapE))))
    get(ctx.run(wrapQ)).head mustBe wrapE
  }

  override protected def beforeEach(): Unit = {
    get(ctx.run(q.delete))
    ()
  }
}


text:
package au.com.southsky.jfreesane;

/**
 * This enum describes the capabilities possessed by an option. See <a
 * href="http://www.sane-project.org/html/doc011.html#s4.2.9.7">Sane Standard v1.0.4 section
 * 4.2.9.7</a> the official description of these values.
 *
 * @author James Ring (sjr@jdns.org)
 */
enum OptionCapability implements SaneEnum {
  /**
   * The option value may be set in software.
   */
  SOFT_SELECT(1),

  /**
   * This option may be selected by the user on the scanner (e.g. by flipping a switch).
   */
  HARD_SELECT(2),

  /**
   * This option may be read in software.
   */
  SOFT_DETECT(4),

  /**
   * The option is not directly supported by the scanner but is emulated by the SANE backend.
   */
  EMULATED(8),

  /**
   * The option value may be automatically set by the SANE backend if desired.
   */
  AUTOMATIC(16),

  /**
   * The option is inactive.
   */
  INACTIVE(32),

  /**
   * The option is intended for advanced users.
   */
  ADVANCED(64);

  private final int capBit;

  OptionCapability(int capBit) {
    this.capBit = capBit;
  }

  @Override
  public int getWireValue() {
    return capBit;
  }
}


text:
/*****************************************************************************
 OSSLDSAKeyPair.h

 OpenSSL DSA key-pair class
 *****************************************************************************/

#ifndef _SOFTHSM_V2_OSSLDSAKEYPAIR_H
#define _SOFTHSM_V2_OSSLDSAKEYPAIR_H

#include "config.h"
#include "AsymmetricKeyPair.h"
#include "OSSLDSAPublicKey.h"
#include "OSSLDSAPrivateKey.h"

class OSSLDSAKeyPair : public AsymmetricKeyPair
{
public:
	// Set the public key
	void setPublicKey(OSSLDSAPublicKey& publicKey);

	// Set the private key
	void setPrivateKey(OSSLDSAPrivateKey& privateKey);

	// Return the public key
	virtual PublicKey* getPublicKey();
	virtual const PublicKey* getConstPublicKey() const;

	// Return the private key
	virtual PrivateKey* getPrivateKey();
	virtual const PrivateKey* getConstPrivateKey() const;

private:
	// The public key
	OSSLDSAPublicKey pubKey;

	// The private key
	OSSLDSAPrivateKey privKey;
};

#endif // !_SOFTHSM_V2_OSSLDSAKEYPAIR_H


text:
<?php

class RefAkdRuangAktif extends \Phalcon\Mvc\Model
{

    /**
     *
     * @var integer
     * @Primary
     * @Column(type="integer", length=10, nullable=false)
     */
    public $ps_id;

    /**
     *
     * @var string
     * @Primary
     * @Column(type="string", length=4, nullable=false)
     */
    public $thn_akd;

    /**
     *
     * @var string
     * @Primary
     * @Column(type="string", length=3, nullable=false)
     */
    public $session_id;

    /**
     *
     * @var integer
     * @Primary
     * @Column(type="integer", length=10, nullable=false)
     */
    public $ruang_id;

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'ref_akd_ruang_aktif';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return RefAkdRuangAktif[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return RefAkdRuangAktif
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

}


text:
'use strict';

const assert = require('assert');
const fs = require('fs');

const jsdom = require('jsdom');

const prepareLabData = require('../../../../report/html/renderer/psi.js');
const Util = require('../../../../report/html/renderer/util.js');
const I18n = require('../../../../report/html/renderer/i18n.js');
const DOM = require('../../../../report/html/renderer/dom.js');
const CategoryRenderer = require('../../../../report/html/renderer/category-renderer.js');
const DetailsRenderer = require('../../../../report/html/renderer/details-renderer.js');
const CriticalRequestChainRenderer =
    require('../../../../report/html/renderer/crc-details-renderer.js');

const sampleResultsStr = fs.readFileSync(__dirname + '/../../../results/sample_v2.json', 'utf-8');
const sampleResultsRoundtripStr = fs.readFileSync(
  __dirname + '/../../../../../proto/sample_v2_round_trip.json',
  'utf-8'
);

const TEMPLATE_FILE = fs.readFileSync(
  __dirname + '/../../../../report/html/templates.html',
  'utf8'
);

/* eslint-env jest */

describe('DOM', () => {
  let document;
  beforeAll(() => {
    global.Util = Util;
    global.Util.i18n = new I18n('en', {...Util.UIStrings});

    global.DOM = DOM;
    global.CategoryRenderer = CategoryRenderer;
    global.DetailsRenderer = DetailsRenderer;

    // Delayed so that CategoryRenderer is in global scope
    const PerformanceCategoryRenderer =
        require('../../../../report/html/renderer/performance-category-renderer.js');
    global.PerformanceCategoryRenderer = PerformanceCategoryRenderer;
    global.CriticalRequestChainRenderer = CriticalRequestChainRenderer;

    const {window} = new jsdom.JSDOM(TEMPLATE_FILE);
    document = window.document;
  });

  afterAll(() => {
    global.Util.i18n = undefined;
    global.Util = undefined;
    global.DOM = undefined;
    global.CategoryRenderer = undefined;
    global.DetailsRenderer = undefined;
    global.PerformanceCategoryRenderer = undefined;
    global.CriticalRequestChainRenderer = undefined;
  });

  describe('psi prepareLabData helpers', () => {
    describe('prepareLabData', () => {
      it('succeeds with LHResult object (roundtrip) input', () => {
        const roundTripLHResult = /** @type {LH.Result} */ JSON.parse(sampleResultsRoundtripStr);
        const result = prepareLabData(roundTripLHResult, document);

        // sanity check that the report exists and has some content
        assert.ok(result.perfCategoryEl instanceof document.defaultView.Element);
        assert.ok(result.perfCategoryEl.outerHTML.length > 50000, 'perfCategory HTML is populated');
        assert.ok(!result.perfCategoryEl.outerHTML.includes('lh-permalink'),
            'PSI\'s perfCategory HTML doesn\'t include a lh-permalink element');
        // Assume using default locale.
        const title = result.perfCategoryEl.querySelector('.lh-audit-group--metrics')
          .querySelector('.lh-audit-group__title').textContent;
        assert.equal(title, Util.UIStrings.labDataTitle);
      });

      it('succeeds with stringified LHResult input', () => {
        const result = prepareLabData(sampleResultsStr, document);
        assert.ok(result.scoreGaugeEl instanceof document.defaultView.Element);
        assert.equal(result.scoreGaugeEl.querySelector('.lh-gauge__wrapper').href, '');
        assert.ok(result.scoreGaugeEl.outerHTML.includes('<svg'), 'score gauge comes with SVG');

        assert.ok(result.perfCategoryEl instanceof document.defaultView.Element);
        assert.ok(result.perfCategoryEl.outerHTML.length > 50000, 'perfCategory HTML is populated');
        assert.ok(!result.perfCategoryEl.outerHTML.includes('lh-permalink'),
            'PSI\'s perfCategory HTML doesn\'t include a lh-permalink element');

        assert.equal(typeof result.finalScreenshotDataUri, 'string');
        assert.ok(result.finalScreenshotDataUri.startsWith('data:image/jpeg;base64,'));
      });

      it('throws if there is no perf category', () => {
        const lhrWithoutPerf = JSON.parse(sampleResultsStr);
        delete lhrWithoutPerf.categories.performance;
        const lhrWithoutPerfStr = JSON.stringify(lhrWithoutPerf);

        assert.throws(() => {
          prepareLabData(lhrWithoutPerfStr, document);
        }, /no performance category/i);
      });

      it('throws if there is no category groups', () => {
        const lhrWithoutGroups = JSON.parse(sampleResultsStr);
        delete lhrWithoutGroups.categoryGroups;
        const lhrWithoutGroupsStr = JSON.stringify(lhrWithoutGroups);

        assert.throws(() => {
          prepareLabData(lhrWithoutGroupsStr, document);
        }, /no category groups/i);
      });

      it('includes custom title and description', () => {
        const {perfCategoryEl} = prepareLabData(sampleResultsStr, document);
        const metricsGroupEl = perfCategoryEl.querySelector('.lh-audit-group--metrics');

        // Assume using default locale.
        // Replacing markdown because ".textContent" will be post-markdown.
        const expectedDescription = Util.UIStrings.lsPerformanceCategoryDescription
          .replace('[Lighthouse](https://developers.google.com/web/tools/lighthouse/)', 'Lighthouse');

        // Assume using default locale.
        const title = metricsGroupEl.querySelector('.lh-audit-group__title').textContent;
        const description =
          metricsGroupEl.querySelector('.lh-audit-group__description').textContent;
        assert.equal(title, Util.UIStrings.labDataTitle);
        assert.equal(description, expectedDescription);
      });
    });
  });

  describe('_getFinalScreenshot', () => {
    it('gets a datauri as a string', () => {
      const datauri = prepareLabData(sampleResultsStr, document).finalScreenshotDataUri;
      assert.equal(typeof datauri, 'string');
      assert.ok(datauri.startsWith('data:image/jpeg;base64,'));
    });

    it('returns null if there is no final-screenshot audit', () => {
      const clonedResults = JSON.parse(sampleResultsStr);
      delete clonedResults.audits['final-screenshot'];
      const LHResultJsonString = JSON.stringify(clonedResults);
      const datauri = prepareLabData(LHResultJsonString, document).finalScreenshotDataUri;
      assert.equal(datauri, null);
    });
  });
});


text:
using Merchello.Core.Models;
using Merchello.Core.Models.Rdbms;

namespace Merchello.Core.Persistence.Mappers
{
    internal sealed class ProductOptionMapper : MerchelloBaseMapper
    {

        public ProductOptionMapper()
        {
            BuildMap();
        }

        internal override void BuildMap()
        {
            if (!PropertyInfoCache.IsEmpty) return;

            CacheMap<ProductOption, ProductOptionDto>(src => src.Key, dto => dto.Key);
            CacheMap<ProductOption, ProductOptionDto>(src => src.Name, dto => dto.Name);
            CacheMap<ProductOption, ProductOptionDto>(src => src.DetachedContentTypeKey, dto => dto.DetachedContentTypeKey);
            CacheMap<ProductOption, ProductOptionDto>(src => src.Required, dto => dto.Required);
            CacheMap<ProductOption, ProductOptionDto>(src => src.Shared, dto => dto.Shared);
            CacheMap<ProductOption, ProductOptionDto>(src => src.UiOption, dto => dto.UiOption);
            CacheMap<ProductOption, ProductOptionDto>(src => src.UpdateDate, dto => dto.UpdateDate);
            CacheMap<ProductOption, ProductOptionDto>(src => src.CreateDate, dto => dto.CreateDate);
        }
    }
}


text:
<!DOCTYPE html>

<title>Login</title>

Gallery

  Your openid could not be resolved.

Login with your openid

  <form method="POST" action="authenticate">
    <input id="openid_identifier" name="openid_identifier" type="text" size=80/>
    <input class="btn" type="submit" value="send"/>
  </form>


text:
package com.bill.crawler.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bill.crawler.config.IConfig;
import com.bill.crawler.config.SystemConfig;
import com.bill.crawler.global.SiteConst;
import com.bill.crawler.model.Author;
import com.bill.crawler.seed.ISeedGenerator;
import com.bill.crawler.site.fs.*;
import com.bill.crawler.site.cto.*;
import com.bill.crawler.site.common.*;
import com.bill.crawler.site.csdn.*;
import com.bill.crawler.utility.FilterUtil;
import com.bill.crawler.utility.LogUtil;

import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;

public class SiteManager {
	private static SiteManager instance = new SiteManager();

	private List<String> siteList;

	public static SiteManager getInstance() {
		return instance;
	}

	private SiteManager() {
		this.siteList = new ArrayList<String>();
		this.siteList.add(SiteConst.SITE_51CTO);
		this.siteList.add(SiteConst.SITE_CSDN);
		this.siteList.add(SiteConst.SITE_COMMON);
		this.siteList.add(SiteConst.SITE_FS);
	}

	public void launchCrawlers() {
		SiteConfReader.readSysConfig();
		if (SystemConfig.getBasePath() == null) {
			LogUtil.logger.error("system config has error!");
			return;
		}

		for (String site : siteList) {
			createCrawlers(SiteConst.CONF_PATH + site + FilterUtil.XML_SUFFIX, site);
		}
	}

	private void createCrawlers(String resource, String site) {
		List<Author> authorList = SiteConfReader.readSiteConfig(resource, site);
		if (authorList == null || authorList.size() == 0) {
			LogUtil.logger.info("no author in site" + site);
		} else {
			Author author = null;
			for (int i = 0; i < authorList.size(); i++) {
				author = authorList.get(i);
				boolean isValid = author.validate(site);

				if(isValid){
					createSingleCrawler(site, author);
				}else{
					LogUtil.logger.info("author with account " + author.getAccount() + " is not valid");
				}

			}
		}
	}

	private void createSingleCrawler(String site, Author author) {
		IConfig config = null;
		ISeedGenerator seedGenerator = null;
		Class crawlerClass = null;
		if (site.equals(SiteConst.SITE_51CTO)) {
			seedGenerator = new CtoSeedGenerator(author);
			config = new CtoConfig(author);
			crawlerClass = CtotPageHandler.class;
		} else if (site.equals(SiteConst.SITE_CSDN)) {
			seedGenerator = new CSDNSeedGenerator(author);
			config = new CSDNConfig(author);
			crawlerClass = CSDNPageHandler.class;
		} else if (site.equals(SiteConst.SITE_FS)) {
			seedGenerator = new FSSeedGenerator(author);
			config = new FSConfig(author);
			crawlerClass = FSPageHandler.class;
		} else if (site.equals(SiteConst.SITE_COMMON)) {
			seedGenerator = new CommonSeedGenerator(author);
			config = new CommonConfig(author);
			crawlerClass = CommonPageHandler.class;
		} else {
			return;
		}

		config.setPerformanceLevel(SystemConfig.getCrawlingPerformanceLevel());
		startCrawler(config, seedGenerator, author, crawlerClass);
	}

	private void startCrawler(IConfig siteConfig, ISeedGenerator seedGenerator, Author author, Class crawlerClass) {
		CrawlConfig coreConfig = siteConfig.getConfig();

		PageFetcher pageFetcher = new PageFetcher(coreConfig);
		RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
		RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);

		CrawlController controller = null;
		try {
			controller = new CrawlController(coreConfig, pageFetcher, robotstxtServer);
		} catch (Exception e) {
			LogUtil.logger.error(e.toString());
		}

		for (String item : seedGenerator.getSeeds()) {
			controller.addSeed(item);
		}

		Map<String, Object> customMap = new HashMap<String, Object>();
		customMap.put("author", author);
		customMap.put("config", siteConfig);

		controller.setCustomData(customMap);

		//controller.startNonBlocking(crawler.getClass(), siteConfig.getThreadNum());
		controller.startNonBlocking(crawlerClass, 1);

		if(SystemConfig.isEnableConcurrentCrawling() == false){
			controller.waitUntilFinish();
		}
	}

}


text:
namespace Thinktecture.IdentityServer.Core.Services.Default
{
    /// <summary>
    /// View loaded that loads HTML templates from the embedded assets.
    /// </summary>
    public class EmbeddedAssetsViewLoader : IViewLoader
    {
        /// <summary>
        /// Loads the HTML for the named view.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public string Load(string name)
        {
            return AssetManager.LoadLayoutWithPage(name);
        }
    }
}


text:
/**
 *
 */
package uk.ac.manchester.cs.pronto.events;

import uk.ac.manchester.cs.pronto.exceptions.EventHandlingException;

/**
 * @author Pavel Klinov
 *
 * pklinov@cs.man.ac.uk, pklinov@clarkparsia.com
 */
public interface EventHandlerWithFeedback<T> extends ReasoningEventHandler {

	public T handleEventWithFeedback(ReasoningEvent event) throws EventHandlingException;
}


text:
package au.com.williamhill.flywheel.remote;

import java.net.*;
import java.util.*;
import java.util.concurrent.*;

import org.slf4j.*;

import com.obsidiandynamics.socketx.*;

import au.com.williamhill.flywheel.frame.*;

public final class RemoteNode implements AutoCloseable {
  private static final Logger LOG = LoggerFactory.getLogger(RemoteNode.class);

  private final XClient<?> client;

  private final Wire wire;

  private final List<RemoteNexus> nexuses = new CopyOnWriteArrayList<>();

  public RemoteNode(XClientFactory<?> clientFactory, XClientConfig config, Wire wire) throws Exception {
    this.client = clientFactory.create(config);
    this.wire = wire;
  }

  public RemoteNexus open(URI uri, RemoteNexusHandler handler) throws Exception {
    if (LOG.isDebugEnabled()) LOG.debug("Connecting to {}", uri);
    final RemoteNexus nexus = new RemoteNexus(RemoteNode.this);
    final EndpointAdapter<XEndpoint> adapter = new EndpointAdapter<>(RemoteNode.this, nexus, handler);
    client.connect(uri, adapter);
    nexuses.add(nexus);
    return nexus;
  }

  void addNexus(RemoteNexus nexus) {
    nexuses.add(nexus);
  }

  void removeNexus(RemoteNexus nexus) {
    nexuses.remove(nexus);
  }

  /**
   *  Obtains the currently connected nexuses.
   *
   *  @return List of nexuses.
   */
  public List<RemoteNexus> getNexuses() {
    return Collections.unmodifiableList(new ArrayList<>(nexuses));
  }

  Wire getWire() {
    return wire;
  }

  @Override
  public void close() throws Exception {
    client.close();
  }

  public static RemoteNodeBuilder builder() {
    return new RemoteNodeBuilder();
  }
}


text:
require 'gosu'

module Kawaii
  class ContentManager

    attr_accessor :root, :images

    def initialize window, root
      @window = window
      @root = root
      @images = {}
    end

    def clear
      @images.clear
    end

    # loads an image and caches it for further use
    # if an image has been loaded it is just being returned
    def load_image(path, tileable = false)
      if !@images[path]
        @images[path] = Gosu::Image.new(@window, "#{@root}/#{path}", tileable)
      end
      @images[path]
    end

    def load_tiled_images(path, cell_size)
      if !@images[path]
        @images[path] = Gosu::Image.load_tiles(@window, "#{@root}/#{path}", cell_size, cell_size, true)
      end
      @images[path]
    end
  end
end


text:
import os
from ansible.utils import template
from ansible import utils
from ansible import errors
from ansible.runner.return_data import ReturnData

class ActionModule(object):

    TRANSFERS_FILES = False

    def __init__(self, runner):
        self.runner = runner

    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):

        if not module_args:
            result = dict(failed=True, msg="No source file given")
            return ReturnData(conn=conn, comm_ok=True, result=result)

        source = module_args
        source = template.template(self.runner.basedir, source, inject)

        if '_original_file' in inject:
            source = utils.path_dwim_relative(inject['_original_file'], 'vars', source, self.runner.basedir)
        else:
            source = utils.path_dwim(self.runner.basedir, source)

        if os.path.exists(source):
            data = utils.parse_yaml_from_file(source, vault_password=self.runner.vault_pass)
            if data and type(data) != dict:
                raise errors.AnsibleError("%s must be stored as a dictionary/hash" % source)
            elif data is None:
                data = {}
            result = dict(ansible_facts=data)
            return ReturnData(conn=conn, comm_ok=True, result=result)
        else:
            result = dict(failed=True, msg="Source file not found.", file=source)
            return ReturnData(conn=conn, comm_ok=True, result=result)


text:
class Shoji

  autoload :Excel, 'shoji/excel'
  autoload :CSV, 'shoji/csv'
  autoload :TSV, 'shoji/tsv'
  autoload :ODS, 'shoji/ods'

  class_eval do
    [:foreach, :foreach_hash, :valid_file?, :valid_content?, :rows, :row_size].each do |meth|
      eval <<EOL
def self.#{meth}(*args, &block)
  klass = class_from_params(*args, &block)
  klass.send(:#{meth}, *args, &block)
end
EOL
    end
  end

  def initialize(filename, opts = {}, &block)
    @filename = filename
    @opts = opts
    if block_given?
      yield(self)
    end
  end
  def foreach(opts = {}, &block)
    self.clcass.foreach(@filename, opts, &block)
  end
  def valid_file?(opts = {})
    self.class.valid_file?(@filename, opts)
  end
  def valid_content?(opts = {})
    self.class.valid_content?(@filename, opts)
  end

  def row_size(opts = {})
    self.class.row_size(@filename, opts)
  end
  def rows(opts = {})
    self.class.rows(@filename, opts)
  end

  private
  def self.detect_class_from_filename_or_content(filename)
    klass = detect_class_from_filename(filename)
    return klass if klass
    detect_class_from_content(filename)
  end
  def self.detect_class_from_filename(filename)
    @@ext2class ||= build_ext2class
    @@ext2class[File.extname(filename).upcase]
  end
  def self.build_ext2class
    {
      '.XLS' => Shoji::Excel,
      '.CSV' => Shoji::CSV,
      '.TSV' => Shoji::TSV,
      '.ODS' => Shoji::ODS
    }
  end
  def self.detect_class_from_content(filename)
    if binary_file? filename
      # Try to check valid xls.
      return Shoji::Excel if Shoji::Excel.valid_file? filename
    else
      line = first_line(filename)
      case line
      when /\t/ then Shoji::TSV
      when /,/ then Shoji::CSV
      else
        nil
      end
    end
  end
  def self.class_from_params(*args)
    filename = args[0]
    opts = args[1] || {}
    case opts[:type]
    when nil, :auto then detect_class_from_filename_or_content(filename)
    when :excel, :xls then Shoji::Excel
    when :csv then Shoji::CSV
    when :tsv, :tabtext, :tab_text, :tab then Shoji::TSV
    else "Unexpected type value=#{opts[:type]}"
    end
  end
  def self.binary_file?(filename)
    buf = nil
    File.open(filename, 'rb') do |f|
      buf = f.read(256)
    end
    buf.index("\0") ? true : false
  end
  def self.first_line(filename)
    line = nil
    File.foreach(filename, encoding: 'BINARY') do |l|
      line = l
      break
    end
    line
  end
end


text:
const { readFileSync, existsSync, unlinkSync } = require('fs');
const toSpec = require('./tap');
const babel = require('babel-core');
const getRc = require('jsdoctap/lib/get-babelrc');
const req = require('require-from-string');

const removeBOM = (res) => {
    if (res.charCodeAt(0) === 0xFEFF)
        res = res.substr(1);
    return res
}

const runTests = (filename, withExtra) => {
    const content = readFileSync(filename, 'utf8');
    const spec = toSpec(process.cwd(), filename, content, withExtra);
    const testPlusCode = content + spec;
    const { babelRc, isPackage } = getRc(filename);
    const opts = { extends: babelRc }
    const transformed = babel.transform(testPlusCode, opts).code;
    req(removeBOM(transformed), filename);
    process.on('exit', () => {
        if (isPackage && existsSync(babelRc)) {
            unlinkSync(babelRc);
        }
    })
}

module.exports = runTests;


text:
describe('transform.js', function () {
    'use strict';

    var expect = require('expect.js');
    var transform = require('../lib/transform');

    var data;

    before(function (done) {
        var fs = require('fs');
        var parseJs = require('../lib/parse-js');
        var path = require('path');
        var filePath = path.resolve(__dirname, './fixture/block.js');

        fs.readFile(filePath, {encoding: 'utf8'}, function (err, content) {
            if (err) {
                throw err;
            }

            data = parseJs(content);
            done();
        });
    });

    describe('parseArguments()', function () {
        it('', function () {});
    });

    describe('parseComments()', function () {
        it('', function () {});
    });

    describe('parseMethods()', function () {
        it('', function () {});
    });

    describe('parseName()', function () {
        it('', function () {});
    });

    describe('transform()', function () {
        var ast;

        before(function () {
            ast = transform.transform(data);
        });

        it('returns an object', function () {
            expect(ast).to.be.an('object');
        });

        it('returns an object with instance[] key', function () {
            expect(ast).to.have.key('instance');
            expect(ast.instance).to.be.an('array');
        });

        it('returns an object with klass[] key', function () {
            expect(ast).to.have.key('klass');
            expect(ast.klass).to.be.an('array');
        });
    });
});


text:
Router.configure({
  layoutTemplate: 'layout'
});

Router.route('/', function(){
  this.render('resultsList');
});

Router.route('/result', function(){
  this.render('table');
});


text:
<?php

namespace Aindong\Pluggables\Facades;

use Illuminate\Support\Facades\Facade;

class Pluggable extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'pluggables';
    }
}


text:
We welcome contributions to BlueOak Server.  Follow this guide for reporting bugs or making code changes.

## Bugs
Bugs can be handled by submitting pull requests or opening issues in our GitHub Repository.

## Pull Requests
* Pull requests must follow style guidelines.  Run `npm run lint` to validate style.
* Ensure tests pass, both unit tests (`npm test`) and functional tests (`npm run test-integration`).
* Add new tests as necessary.
* [Pull requests](http://help.github.com/send-pull-requests/) should be made to the master branch.

# Code of Conduct
Always follow the [code of conduct](CODE_OF_CONDUCT.md).


text:
package com.github.mrvilkaman.presentationlayer.resolution.toolbar;

import com.github.mrvilkaman.presentationlayer.activities.BaseActivityView;
import com.github.mrvilkaman.presentationlayer.resolution.drawer.LeftDrawerHelper;
import com.github.mrvilkaman.presentationlayer.resolution.fragments.FragmentResolver;
import com.github.mrvilkaman.presentationlayer.resolution.navigation.NavigationResolver;
import com.github.mrvilkaman.testsutils.BaseTestCase;

import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;

import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class MyToolbarResolverCallbackTest extends BaseTestCase {

	@Mock FragmentResolver fragmentManager;
	@Mock LeftDrawerHelper drawerHelper;
	@Mock BaseActivityView activityView;
	@Mock ToolbarResolver toolbarResolver;
	@Mock NavigationResolver navigationResolver;
	private MyToolbarResolverCallback callback;

	@Override
	public void init() {
		callback = new MyToolbarResolverCallback(fragmentManager, drawerHelper, activityView,
				toolbarResolver, navigationResolver);
	}

	@Test
	public void testOnClickHome_rootScreenAndRootActivity() {
		// Arrange
		when(fragmentManager.isRootScreen()).thenReturn(true);
		when(activityView.isTaskRoot()).thenReturn(true);

		// Act
		callback.onClickHome();

		// Assert
		verify(drawerHelper).open();
		verify(navigationResolver, never()).onBackPressed();
		verify(activityView, never()).hideKeyboard();
	}

	@Test
	public void testOnClickHome_rootScreenAndNotRootActivity() {
		// Arrange
		when(fragmentManager.isRootScreen()).thenReturn(true);
		when(activityView.isTaskRoot()).thenReturn(false);

		// Act
		callback.onClickHome();

		// Assert
		verify(drawerHelper,never()).open();
		verify(navigationResolver).onBackPressed();
		verify(activityView).hideKeyboard();
	}

	@Test
	public void testOnClickHome_notRootScreen() {
		// Arrange
		when(fragmentManager.isRootScreen()).thenReturn(false);

		// Act
		callback.onClickHome();

		// Assert
		verify(drawerHelper, never()).open();
		InOrder inOrder = Mockito.inOrder(navigationResolver, activityView);
		inOrder.verify(navigationResolver)
				.onBackPressed();
		inOrder.verify(activityView)
				.hideKeyboard();
	}

	@Test
	public void testUpdateIcon_notRootScreen() {
		// Arrange
		when(fragmentManager.isRootScreen()).thenReturn(false);

		// Act
		callback.updateIcon();

		// Assert
		verify(toolbarResolver).showBackIcon();
		verify(toolbarResolver, never()).showHomeIcon();
	}

	@Test
	public void testUpdateIcon_RootScreenAndRootActivity() {
		// Arrange
		when(fragmentManager.isRootScreen()).thenReturn(true);
		when(activityView.isTaskRoot()).thenReturn(true);

		// Act
		callback.updateIcon();

		// Assert
		verify(toolbarResolver, never()).showBackIcon();
		verify(toolbarResolver).showHomeIcon();
	}

	@Test
	public void testUpdateIcon_RootScreenAndNotRootActivity() {
		// Arrange
		when(fragmentManager.isRootScreen()).thenReturn(true);
		when(activityView.isTaskRoot()).thenReturn(false);

		// Act
		callback.updateIcon();

		// Assert
		verify(toolbarResolver,never()).updateIcon();
		verify(toolbarResolver).showBackIcon();
	}

	@Test
	public void testUpdateIcon_withoutToolbar_notRootScreen() {
		// Arrange
		callback = new MyToolbarResolverCallback(fragmentManager, drawerHelper, activityView,
				null, navigationResolver);
		when(fragmentManager.isRootScreen()).thenReturn(false);

		// Act
		callback.updateIcon();

		// Assert
		verify(fragmentManager, never()).isRootScreen();
		verify(toolbarResolver, never()).showBackIcon();
		verify(toolbarResolver, never()).showHomeIcon();
	}

	@Test
	public void testUpdateIcon_withoutToolbar_RootScreen() {
		// Arrange
		callback = new MyToolbarResolverCallback(fragmentManager, drawerHelper, activityView,
				null, navigationResolver);
		when(fragmentManager.isRootScreen()).thenReturn(true);

		// Act
		callback.updateIcon();

		// Assert
		verify(fragmentManager, never()).isRootScreen();
		verify(toolbarResolver, never()).showBackIcon();
		verify(toolbarResolver, never()).showHomeIcon();
	}

}