text:
                    bknd-ng-grid
                        (backand.directives.bknd-ng-grid)

                        Grid Example
                        <bknd-ng-grid view-name="viewName" input-style="{'height': 400}" button-groups="buttonGroups" disable-edit-on-dbl-click="disableEditOnDblClick"></bknd-ng-grid>

                    more examples...

                        Binded ng-grid to the Backand REST API

                        This directive provides out-of-the-box CRUD functioality, advanced sorting and filtering

bknd-ng-grid Settings

All settings can be provided as attributes in the bknd-ng-grid or through the query string parameters.

                                view-name
                                (Defaults: null) :
                                A name of a table or view from the database

                                filter-options
                                (Defaults: null) :
                                uses BackAnd REST API filter options: {fieldName, operator, value}

                                input-style
                                (Defaults: null) :
                                css style

bknd-ng-grid Events

                                gridConfigCompleted
                                Emit when the configuration of the grid finishes loading from the Backand REST API and before the configuration of the ng-grid

                                gridDataCompleted
                                Emit when the data of the grid finishes loading from the Backand REST API and before the loading of the rows into ng-grid

                                setCellTemplate
                                Emit when setting the cellTemplate option of ng-grid

                            Markup

                            JavaScript

<div>
    Static Grid Example
    <bknd-ng-grid view-name="'Employees'" input-style="{'height': 400}"></bknd-ng-grid>
</div>
<div data-ng-controller="dynamicGridController">
    Dynamic Grid Example
    <bknd-ng-grid view-name="viewName" input-style="inputStyle"></bknd-ng-grid>
</div>

'use strict';
var backAndControllers  = angular.module('backAnd.controllers');
backAndControllers.controller('dynamicGridController', ['$scope',
    function ($scope)  {
        $scope.viewName  = 'Stores';
        $scope.inputStyle = { 'height': 550 };
    }
])

                    bknd-form
                        (backand.directives.bknd-form)

                        Form Example

                        Binded Form to BackAnd REST API

                        This directive provide you a quick Form connected to your database

bknd-form Settings

All settings can be provided as attributes in the bknd-ng-grid or through the query string parameters.

                                view-name
                                (Defaults: null) :
                                A name of a table or view from the database

                                row-id
                                (Defaults: null) :
                                The row primary key, if provided then the form is in EDIT mode otherwise it is in a CREATE mode.
                                if the primary key of the row has multiple column values then they should be comma delimited in the primary key columns' order

                                default-fields-values
                                (Defaults: null) :
                                Default value for each field: {fieldName, value}

                            Markup

                            JavaScript

<div>
    Static Form Example
    <div bknd-form view-name="'Employees'" row-id="1"></div>
</div>
<div data-ng-controller="dynamicFormController">
    Dynamic Form Example
    <div bknd-form view-name="viewName" row-id="id"></div>
</div>

'use strict';
var backAndControllers  = angular.module('backAnd.controllers');
backAndControllers.controller('dynamicFormController', ['$scope',
    function ($scope)  {
        $scope.viewName  = 'Customers';
        $scope.id  = 1;
    }
])

                    bknd-dashboard
                        (backand.directives.bknd-dashboard)

                        Dashboard Example
                        <bknd-dashboard dashboard-id="1"></bknd-dashboard>

                        Binded dashboard to BackAnd REST API

                        This directive provide you a quick dashboard display based on your settings in the console

bknd-form Settings

All settings can be provided as attributes in the bknd-ng-grid or through the query string parameters.

                                dashboard-id
                                (Defaults: null) :
                                An id of a dashboard from BackAnd REST API configuration

                            Markup

                            JavaScript

<div>
    Dashboard Example
    <bknd-dashboard dashboard-id="1"></bknd-dashboard>
</div>


text:
void ac_printboard();

int ac_gameinit();

void ac_Winner();

void ac_Loser();

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Customises the stock Storefront homepage template to include the sidebar and the boutique_before_homepage_content hook.
 *
 * Template name: Homepage
 *
 * @package storefront
 */

get_header(); ?>

		<?php do_action( 'boutique_before_homepage_content' ); ?>

			<?php do_action( 'homepage' ); ?>

	<?php do_action( 'storefront_sidebar' ); ?>

<?php get_footer(); ?>


text:
import datetime, src, pickle, tkinter.messagebox, time, tkinter
from src.game_utils.utils import turtle, clear_turtle, kill_game, get_random_point, out_of_screen, get_next_point
from src.game_utils.square import create_square
from src.game_utils.game_setup import game_world

def change_food_location(point):
    game_world.food.change_location(point)

def get_food_position():
    return game_world.food.position

def calculate_snake_next_position():
    return game_world.snake.next_position

def get_snake():
    return game_world.snake

def get_point_in_direction(point, direction):
    return get_next_point(point, direction)

def point_snake_up():
    game_world.snake.point_upwards()

def point_snake_down():
    game_world.snake.point_down()

def point_snake_left():
    game_world.snake.point_left()

def point_snake_right():
    game_world.snake.point_right()

def move_snake_head_to_next():
    game_world.snake.move_head_to_next_location()

def clear_screen():
    clear_turtle()

def get_snake_body():
    return game_world.snake.body

def add_next_position_to_snake_body(snake):
    snake.body.append(create_square(snake.x, snake.y))

def game_over():
    """
    - takes care of music
        Stops background music
        Runs the lost sound effect

    - takes care of leader board
        Puts current score to leader board
        Sorts the leader board according to score
        Limits the leader board for five names only
        Saves the leader board

    - Shows a message of game over with score and leader board and asks for playing again
        yes   > Reset and start again
        no    >  End

    :return:  None
    """

    game_world.bck_snd.stop()
    game_world.lose_snd.play()

    src.lb.append([src.name.split()[0]  # first name
                      , game_world.score  # score
                      , datetime.date.today()  # date
                   ])

    src.lb.sort(key=lambda x: x[1], reverse=True)
    src.lb = src.lb[:5]  # maximum names are 5

    strng = 'HighScores:\n'
    for i in range(len(src.lb)):
        strng += "{}) {} : {} \n" \
                 "  Date : {}\n" \
                 "".format(str(i + 1), src.lb[i][0], str(src.lb[i][1]), str(src.lb[i][2]))

    file = open("lb", "wb")
    pickle.dump(src.lb, file)
    file.close()

    if tkinter.messagebox.askquestion("Game Over",
                                          "You have got a Score of {}\n"
                                          " \n"
                                          " {}"
                                          " \n"
                                          " \n"
                                          " Do you want to play again ?".format(
                                              game_world.score, strng)) == "no":
        time.sleep(0.5)
        kill_game()

    else:

        src.move_time = 180
        game_world.reset()

def set_color_string(color):
    turtle.fillcolor(color)

def increase_score():
    """
    -Increases the score
    -Makes score sound
    :return:
    """
    game_world.score += 1
    game_world.win_snd.play()

def reset_score():
    game_world.score = 0

def print_text_to_screen(x, y, text):
    """
    print a string on the screen
    :param x: an int representing the x coordinate of the position of text
    :param y: an int representing the y coordinate of the position of text
    :param text: a string representing the text to be printed on screen
    """
    turtle.setpos((x, y))
    turtle.write(text, move='False', align='center', font=('Arial', 16, 'normal'))

def is_out_of_screen(point):
    """
    Checks if a given point is out of the screen

    :param point: A Point that has x and y coordinates
    :return returns a Boolean, A True or a False
    """
    return out_of_screen(point)

def random_point():
    """
    :return: returns a Point(x,y) on the screen
    """
    return get_random_point()


text:
<!DOCTYPE html>
<?php

// Load Variables
include ("TemplateFiles/doHeader.php");

// Load Display Functions
include ("TemplateFiles/DisplayFunctions.php");

// Load Display Functions
include ("Functions/GetWikiSuggestions.php");

// echo "http://dataranch.net/secondarycategories.php?q=". urlencode($q);
?>

<title>Welcome to Archiver</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta Name="Keywords"
	content="archiver, social archive, twitter archive" />
<meta Name="Description"
	content="Archiving digital society
Because your social media should always be yours!" />
<meta property="og:title" content="Welcome to Archiver" />
<meta property="og:type" content="website" />
<meta property="og:url" content="<?=curPageURL()?>" />
<meta property="og:site_name" content="Archiver" />
<meta property="fb:admins" content="124527214223945" />
<meta property="og:description"
	content="Archiving digital society
Because your social media should always be yours!" />

<link rel="stylesheet" type="text/css" href="CSS/DisplayBitLists.css">
<link rel="stylesheet" type="text/css" href="CSS/Layout.css">
<link rel="stylesheet" type="text/css" href="CSS/Main.css">
<link rel="stylesheet" href="CSS/jquery.fancybox.css?v=2.1.3"
	type="text/css" media="screen" />

<? include("Configuration/FacebookHeader.php"); ?>

The
					Archiver

<?include ("examples/auth.php");?>

<?php include ('mindex.php');?>

Welcome to Archiver

Archiving digital society Because your social media should
						always be yours!

					Archiver is a high availability index of social media data from
					over 200 sources across the web. All data is Creative Commons
					licensed data unless otherwise noted, and is randomly selected and
					spidered using 'Bubba' content spider. Social media data is
					particularly great for deep data analysis, CRM integration, user
					profiling, supplemental content, and search engine keyword
					optimization. Data sources with frequently
					updated content are indexed more frequently (i.e. popular micro
					blogs (Twitter) and news sites). The archive is searchable by keyword
					and location.

					Use the search functionality to the right, or start by browsing categories on the top of the page!

<?include ("TemplateFiles/RightBar.php");?>


text:
//---------------------------------------------------------------------------
// stHistogram.h ...
//
// Author: Marcos Rodrigues Vieira (mrvieira@icmc.usp.br)
// Copyright (c) 2005 GBDI-ICMC-USP
//---------------------------------------------------------------------------
#ifndef stHistogramH
#define stHistogramH

#include <vector.h>

//---------------------------------------------------------------------------
// class stHistogram
//---------------------------------------------------------------------------
template <class ObjectType, class EvaluatorType>
class stHistogram {

   public:

      /**
      * Type of the object.
      */
      typedef ObjectType tObject;

      /**
      * Creates a new instance of this class.
      */
      stHistogram(unsigned int numberOfBins = 100);

      /**
      * Destruct of this class.
      */
      ~stHistogram();

      int Size(){
         return NumberOfBins;
      }//end Size

      int GetNumberOfObjects();

      void Build(EvaluatorType * metricEvaluator);

      void Add(ObjectType * obj);

      double GetBin(unsigned int idx);

      double GetValue(unsigned int idx);

      double GetValueOfBin(double value);

   private:

      vector <tObject *> Objects;

      double * Values;

      double * Bins;

      unsigned int NumberOfBins;

};//end stHistogram

#include "stHistogram.cc"

#endif //end stHistogramH


text:
package com.google.apphosting.vmruntime.jetty9;

/**
 * Interface for checking if an ip address can be trusted.
 */
public interface VmRuntimeTrustedAddressChecker {
  /**
   * Checks if a remote address is trusted for the purposes of handling requests.
   *
   * @param remoteAddr String representation of the remote ip address.
   * @return True if and only if the remote address should be allowed to make requests.
   */
  public boolean isTrustedRemoteAddr(String remoteAddr);
}


text:
Konsole
=======
Prototype Console Application for Kinegenics.
This is based on the O'Reilly [Best Practices Example] (https://github.com/miguelgrinberg/flasky)

# Configuration

## Environment variables

EMAIL_USERNAME - must be set to a valid yahoo email address

EMAIL_PASSWORD - must be set to the password for that email address

There is an activate.bat file that will set this up.

## Flask Configuration

# Create initial database

In a python shell do the following:
```
python fresh_dev_db.py
```

# Run Tests

## With Coverage
```
python manage.py test --coverage
```

## Single Test Suite
```
python -m unittest tests.test_basics.BasicsTestCase
```
FIXME - when doing this it kicks back an error about SERVER not being set

## Single Test Case
```
python -m unittest tests.test_api.APITestCase.test_anonymous
```


text:
package org.inferred.freevisitor.processor;

import static org.inferred.internal.source.ModelUtils.maybeAsTypeElement;

import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Types;

abstract class TypesImpl implements Types {

  @Override
  public boolean isSubtype(TypeMirror t1, TypeMirror t2) {
    return isAssignable(t1, t2);
  }

  @Override
  public boolean isAssignable(TypeMirror t1, TypeMirror t2) {
    TypeElement type2 = maybeAsTypeElement(t2).orNull();
    if (type2 == null || !type2.getTypeParameters().isEmpty()) {
      throw new UnsupportedOperationException("Only non-generic types supported; got " + t2);
    }
    TypeElement supertype = maybeAsTypeElement(t1).orNull();
    while (supertype != null) {
      if (type2.equals(supertype)) {
        return true;
      }
      if (type2.getKind() == ElementKind.INTERFACE) {
        for (TypeMirror iface : supertype.getInterfaces()) {
          if (type2.equals(maybeAsTypeElement(iface).orNull())) {
            return true;
          }
        }
      }
      supertype = maybeAsTypeElement(supertype.getSuperclass()).orNull();
    }
    return false;
  }
}


text:
require 'spec_helper'

describe DocxFormMerger do
  it 'has a version number' do
    expect(DocxFormMerger::VERSION).not_to be nil
  end

  # it 'does something useful' do
  #   expect(false).to eq(true)
  # end
end


text:
package ninja.joshdavis;

import static org.junit.Assert.*;
import org.junit.Test;

/**
 * Unit test for App.
 */
public class AppTest {
    @Test
    public void AppFrameTest() {
        AppFrame frame = new AppFrame();
        assertNotNull(frame);
    }
    @Test
    public void FileListPaneTest() {
        FileListPane srcFileListPane= new FileListPane();
        assertNotNull(srcFileListPane);
    }
    @Test
    public void EditorTest() {
        Editor mrEd = new Editor();
        assertNotNull(mrEd);
        mrEd.setSearchString("foo");
        mrEd.setReplaceString("baz");

        String str = mrEd.edit("foobarfoo");
        assertEquals("bazbarfoo", str);

        mrEd.setGlobalSearch(true);
        str = mrEd.edit("foobarfoo");
        assertEquals("bazbarbaz", str);

        mrEd.setCaseInsensitiveSearch(true);
        str = mrEd.edit("FoobarfOo");
        assertEquals("bazbarbaz", str);

        mrEd.setCaseInsensitiveSearch(false);
        mrEd.setLiteralSearch(false);
        mrEd.setSearchString("f.o");
        str = mrEd.edit("foobarfao");
        assertEquals("bazbarbaz", str);

        mrEd.setLiteralSearch(true);
        mrEd.setSearchString("foo");
        mrEd.setReplaceString("\\$1");
        str = mrEd.edit("foobarfoo");
        assertEquals("$1bar$1", str);

        mrEd.setLiteralSearch(false);
        mrEd.setSearchString("([0-9]+)foo([0-9]+)");

        mrEd.setReplaceString("$1bar$2");
        str = mrEd.edit("123foo456");
        assertEquals("123bar456", str);

        mrEd.setSearchString("([0-9]+)foo([0-9]+)");
        mrEd.setReplaceString("$1bar\\$2");//Must escape $ and \ to get literal
        str = mrEd.edit("123foo456");
        assertEquals("123bar$2", str);
    }
}


text:
package org.citygml4j.core.model.generics;

import org.citygml4j.core.model.core.AbstractGenericAttribute;

public class UriAttribute extends AbstractGenericAttribute<String> {

    public UriAttribute() {
    }

    public UriAttribute(String name, String value) {
        super(name, value);
    }
}


text:
package org.apache.deltaspike.test.testcontrol.uc011;

import javax.enterprise.context.RequestScoped;

@RequestScoped
public class InterceptionResultStorage
{
    private boolean intercepted;

    public void markAsIntercepted()
    {
        this.intercepted = true;
    }

    public boolean isInterceptionDetected()
    {
        return intercepted;
    }
}


text:
<?php

require_once dirname( __FILE__ ) . '/../AbstractTestCase.php';

/**
 * Unit tests for class {@link PHP_ChangeCoverage_Report_Factory}.
 *
 * @category   QualityAssurance
 * @package    PHP_ChangeCoverage
 * @subpackage Report
 * @author     Manuel Pichler <mapi@pdepend.org>
 * @copyright  2010 Manuel Pichler. All rights reserved.
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: @package_version@
 * @link       http://pdepend.org/
 */
class PHP_ChangeCoverage_Report_FactoryUnitTest extends PHP_ChangeCoverage_AbstractTestCase
{
    /**
     * testFactoryThrowsExceptionWhenReportFileDoesNotExist
     *
     * @return void
     * @covers PHP_ChangeCoverage_Report_Factory
     * @group report
     * @group unittest
     * @expectedException RuntimeException
     */
    public function testFactoryThrowsExceptionWhenReportFileDoesNotExist()
    {
        $fileName = $this->createDirectory( 'coverage' ) . '/report.xml';

        $factory = new PHP_ChangeCoverage_Report_Factory();
        $factory->createReport( $fileName );
    }

    /**
     * testFactoryThrowsExceptionForUnsupportedReportFormat
     *
     * @return void
     * @covers PHP_ChangeCoverage_Report_Factory
     * @group report
     * @group unittest
     * @expectedException RuntimeException
     */
    public function testFactoryThrowsExceptionForUnsupportedReportFormat()
    {
        $fileName = $this->createFile( 'report.xml', '<coverage><report/></coverage>' );

        $factory = new PHP_ChangeCoverage_Report_Factory();
        $factory->createReport( $fileName );
    }

    /**
     * testFactoryCreatesCloverReportForCloverReportFormat
     *
     * @return void
     * @covers PHP_ChangeCoverage_Report_Factory
     * @group report
     * @group unittest
     */
    public function testFactoryCreatesCloverReportForCloverReportFormat()
    {
        $fileName = $this->createFile( 'report.xml', '<coverage><project/></coverage>' );

        $factory = new PHP_ChangeCoverage_Report_Factory();
        $report  = $factory->createReport( $fileName );
    }
}


text:
package org.olat.course.nodes.en;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.olat.basesecurity.BaseSecurity;
import org.olat.basesecurity.BaseSecurityManager;
import org.olat.core.commons.persistence.DBFactory;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.translator.Translator;
import org.olat.core.id.Identity;
import org.olat.core.logging.Tracing;
import org.olat.core.manager.BasicManager;
import org.olat.core.util.coordinate.CoordinatorManager;
import org.olat.core.util.coordinate.SyncerExecutor;
import org.olat.core.util.mail.MailHelper;
import org.olat.core.util.mail.MailTemplate;
import org.olat.core.util.mail.MailerResult;
import org.olat.core.util.mail.MailerWithTemplate;
import org.olat.core.util.resource.OresHelper;
import org.olat.course.groupsandrights.CourseGroupManager;
import org.olat.course.nodes.ENCourseNode;
import org.olat.course.properties.CoursePropertyManager;
import org.olat.group.BusinessGroup;
import org.olat.group.BusinessGroupManager;
import org.olat.group.BusinessGroupManagerImpl;
import org.olat.group.ui.BGConfigFlags;
import org.olat.group.ui.BGMailHelper;
import org.olat.properties.Property;
import org.olat.testutils.codepoints.server.Codepoint;

/**
 * Description:

 * Business-logic of enrollemnt
 *

 * Handle enroll and cancel-enrollment
 *

 * Initial Date: Nov 11, 2006
 *
 * @author Christian Guretzki
 */
public class EnrollmentManager extends BasicManager {
	// TODO with spring
	static final EnrollmentManager enrollmentManager = new EnrollmentManager();
	// Managers TODO inject with spring
	private final BaseSecurity securityManager;
	private final BusinessGroupManager businessGroupManager;

	/**
	 * @param moduleConfiguration
	 * @param ureq
	 * @param wControl
	 * @param userCourseEnv
	 * @param enNode
	 */
	private EnrollmentManager() {
		this.securityManager = BaseSecurityManager.getInstance();
		this.businessGroupManager = BusinessGroupManagerImpl.getInstance();
	}

	public static EnrollmentManager getInstance() {
		return enrollmentManager;
	}

	public EnrollStatus doEnroll(final Identity identity, final BusinessGroup group, final ENCourseNode enNode, final CoursePropertyManager coursePropertyManager,
			final WindowControl wControl, final Translator trans, final List groupNames, final List areaNames, final CourseGroupManager cgm) {
		final EnrollStatus enrollStatus = new EnrollStatus();
		if (Tracing.isDebugEnabled(this.getClass())) {
			Tracing.logDebug("doEnroll", this.getClass());
		}
		// check if the user is already enrolled (user can be enrooled only in one group)
		if ((getBusinessGroupWhereEnrolled(identity, groupNames, areaNames, cgm) == null)
				&& (getBusinessGroupWhereInWaitingList(identity, groupNames, areaNames, cgm) == null)) {
			if (Tracing.isDebugEnabled(this.getClass())) {
				Tracing.logDebug("Identity is not enrolled identity=" + identity.getName() + "  group=" + group.getName(), this.getClass());
				// 1. Check if group has max size defined. If so check if group is full
				// o_clusterREVIEW cg please review it - also where does the group.getMaxParticipants().equals("") come from??
				// and: why can't we just have a group here and a max participants count and an identity to enrol?
				// the group was chosen, so why do we need the groupNames and areaNames here???
			}

			Codepoint.codepoint(EnrollmentManager.class, "beforeDoInSync");
			CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(group, new SyncerExecutor() {
				@Override
				public void execute() {
					Tracing.logInfo("doEnroll start: group=" + OresHelper.createStringRepresenting(group), identity.getName(), EnrollmentManager.class);
					Codepoint.codepoint(EnrollmentManager.class, "doInSync1");
					// 6_1_0-RC15: reload group object here another node might have changed this in the meantime
					final BusinessGroup reloadedGroup = (BusinessGroup) DBFactory.getInstance().loadObject(group, true);
					if (reloadedGroup.getMaxParticipants() != null && !reloadedGroup.getMaxParticipants().equals("")) {
						final int participantsCounter = securityManager.countIdentitiesOfSecurityGroup(reloadedGroup.getPartipiciantGroup());

						Tracing.logInfo("doEnroll - participantsCounter: " + participantsCounter + ", maxParticipants: " + reloadedGroup.getMaxParticipants().intValue(),
								identity.getName(), EnrollmentManager.class);
						if (participantsCounter >= reloadedGroup.getMaxParticipants().intValue()) {
							// already full, show error and updated choose page again
							if (!reloadedGroup.getWaitingListEnabled().booleanValue()) {
								// No Waiting List => List is full
								enrollStatus.setErrorMessage(trans.translate("error.group.full"));
							} else {
								final boolean done = addUserToWaitingList(identity, reloadedGroup, enNode, coursePropertyManager, wControl, trans);
								enrollStatus.setIsInWaitingList(done);
							}
						} else {
							final boolean done = addUserToParticipantList(identity, reloadedGroup, enNode, coursePropertyManager, wControl, trans);
							Codepoint.codepoint(EnrollmentManager.class, "doInSync2");
							enrollStatus.setIsEnrolled(done);
							Tracing.logInfo("doEnroll - setIsEnrolled ", identity.getName(), EnrollmentManager.class);
						}
					} else {
						if (Tracing.isDebugEnabled(this.getClass())) {
							Tracing.logDebug("doEnroll beginTransaction", this.getClass());
						}
						final boolean done = addUserToParticipantList(identity, reloadedGroup, enNode, coursePropertyManager, wControl, trans);
						enrollStatus.setIsEnrolled(done);
						if (Tracing.isDebugEnabled(this.getClass())) {
							Tracing.logDebug("doEnroll committed", this.getClass());
						}
					}
					Tracing.logInfo("doEnroll end", identity.getName(), EnrollmentManager.class);
				}
			});// end of doInSync
			Codepoint.codepoint(EnrollmentManager.class, "afterDoInSync");
		} else {
			enrollStatus.setErrorMessage(trans.translate("error.group.already.enrolled"));
		}
		if (Tracing.isDebugEnabled(this.getClass())) {
			Tracing.logDebug("doEnroll finished", this.getClass());
		}
		return enrollStatus;
	}

	public void doCancelEnrollment(final Identity identity, final BusinessGroup enrolledGroup, final ENCourseNode enNode,
			final CoursePropertyManager coursePropertyManager, final WindowControl wControl, final Translator trans) {
		if (Tracing.isDebugEnabled(this.getClass())) {
			Tracing.logDebug("doCancelEnrollment", this.getClass());
		}
		// 1. Remove group membership, fire events, do loggin etc.
		final BGConfigFlags flags = BGConfigFlags.createLearningGroupDefaultFlags();

		CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(enrolledGroup, new SyncerExecutor() {
			@Override
			public void execute() {
				// Remove participant. This will also check if a waiting-list with auto-close-ranks is configurated
				// and move the users accordingly
				businessGroupManager.removeParticipantAndFireEvent(identity, identity, enrolledGroup, flags, false);
				Tracing.logInfo("doCancelEnrollment in group " + enrolledGroup, identity.getName(), EnrollmentManager.class);
				// 2. Remove enrollmentdate property
				// only remove last time date, not firsttime
				final Property lastTime = coursePropertyManager.findCourseNodeProperty(enNode, identity, null, ENCourseNode.PROPERTY_RECENT_ENROLLMENT_DATE);
				if (lastTime != null) {
					coursePropertyManager.deleteProperty(lastTime);
				}
			}
		});

		// 3. Send notification mail
		final MailTemplate mailTemplate = BGMailHelper.createRemoveMyselfMailTemplate(enrolledGroup, identity);
		final MailerWithTemplate mailer = MailerWithTemplate.getInstance();
		final MailerResult mailerResult = mailer.sendMail(identity, null, null, mailTemplate, null);
		MailHelper.printErrorsAndWarnings(mailerResult, wControl, trans.getLocale());
	}

	public void doCancelEnrollmentInWaitingList(final Identity identity, final BusinessGroup enrolledWaitingListGroup, final ENCourseNode enNode,
			final CoursePropertyManager coursePropertyManager, final WindowControl wControl, final Translator trans) {
		// 1. Remove group membership, fire events, do loggin etc.
		CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(enrolledWaitingListGroup, new SyncerExecutor() {
			@Override
			public void execute() {
				businessGroupManager.removeFromWaitingListAndFireEvent(identity, identity, enrolledWaitingListGroup, false);
				// 2. Remove enrollmentdate property
				// only remove last time date, not firsttime
				final Property lastTime = coursePropertyManager.findCourseNodeProperty(enNode, identity, null, ENCourseNode.PROPERTY_RECENT_WAITINGLIST_DATE);
				if (lastTime != null) {
					coursePropertyManager.deleteProperty(lastTime);
				}
			}
		});

		// 3. Send notification mail
		final MailTemplate mailTemplate = BGMailHelper.createRemoveWaitinglistMailTemplate(enrolledWaitingListGroup, identity);
		final MailerWithTemplate mailer = MailerWithTemplate.getInstance();
		final MailerResult mailerResult = mailer.sendMail(identity, null, null, mailTemplate, null);
		MailHelper.printErrorsAndWarnings(mailerResult, wControl, trans.getLocale());
	}

	// Helper Methods
	// ////////////////
	/**
	 * @param identity
	 * @param groupNames
	 * @return BusinessGroup in which the identity is enrolled, null if identity is nowhere enrolled.
	 */
	protected BusinessGroup getBusinessGroupWhereEnrolled(final Identity identity, final List groupNames, final List areaNames, final CourseGroupManager cgm) {
		Iterator iterator = groupNames.iterator();
		// 1. check in groups
		while (iterator.hasNext()) {
			final String groupName = (String) iterator.next();
			final List groups = cgm.getParticipatingLearningGroupsFromAllContexts(identity, groupName);
			if (groups.size() > 0) {
				// Usually it is only possible to be in one group. However,
				// theoretically the
				// admin can put the user in a second enrollment group or the user could
				// theoretically be in a second group context. For now, we only look for
				// the first
				// group. All groups found after the first one are disgarded.
				return (BusinessGroup) groups.get(0);
			}
		}
		// 2. check in areas
		iterator = areaNames.iterator();
		while (iterator.hasNext()) {
			final String areaName = (String) iterator.next();
			final List groups = cgm.getParticipatingLearningGroupsInAreaFromAllContexts(identity, areaName);
			if (groups.size() > 0) {
				// Usually it is only possible to be in one group. However,
				// theoretically the
				// admin can put the user in a second enrollment group or the user could
				// theoretically be in a second group context. For now, we only look for
				// the first
				// group. All groups found after the first one are disgarded.
				return (BusinessGroup) groups.get(0);
			}
		}
		return null; //
	}

	/**
	 * @param identity
	 * @param groupNames
	 * @return true if this identity is any waiting-list group in this course that has a name that is in the group names list
	 */
	protected BusinessGroup getBusinessGroupWhereInWaitingList(final Identity identity, final List groupNames, final List areaNames, final CourseGroupManager cgm) {
		final List groups = loadGroupsFromNames(groupNames, areaNames, cgm);
		BusinessGroup businessGroup;
		// loop over all business-groups
		for (final Iterator iter = groups.iterator(); iter.hasNext();) {
			businessGroup = (BusinessGroup) iter.next();
			if (securityManager.isIdentityInSecurityGroup(identity, businessGroup.getWaitingGroup())) { return businessGroup; }
		}
		return null;
	}

	/**
	 * @param groupNames
	 * @return a list of business groups from any of the courses group contexts that match the names from the groupNames list. If a groupname is not found it won't be in
	 *         the list. So groupNames.size() can very well by different than loadGroupsFromNames().size()
	 */
	protected List loadGroupsFromNames(final List groupNames, final List areaNames, final CourseGroupManager cgm) {
		final List groups = new ArrayList();
		// 1. add groups
		Iterator iterator = groupNames.iterator();
		while (iterator.hasNext()) {
			final String groupName = (String) iterator.next();
			final List mygroups = cgm.getLearningGroupsFromAllContexts(groupName);
			for (final Iterator it = mygroups.iterator(); it.hasNext();) {
				final BusinessGroup bg = (BusinessGroup) it.next();
				if (!groups.contains(bg)) {
					groups.add(bg);
				}
			}
		}
		// add groups from areas
		iterator = areaNames.iterator();
		while (iterator.hasNext()) {
			final String areaName = (String) iterator.next();
			final List mygroups = cgm.getLearningGroupsInAreaFromAllContexts(areaName);
			for (final Iterator it = mygroups.iterator(); it.hasNext();) {
				final BusinessGroup bg = (BusinessGroup) it.next();
				if (!groups.contains(bg)) {
					groups.add(bg);
				}
			}
		}
		return groups;
	}

	/**
	 * Check if in any business-group a waiting-list is configured.
	 *
	 * @param groups
	 * @return true : YES, there are waiting-list

	 *         false: NO, no waiting-list
	 */
	protected boolean hasAnyWaitingList(final List groups) {
		for (final Iterator iter = groups.iterator(); iter.hasNext();) {
			final BusinessGroup businessGroup = (BusinessGroup) iter.next();
			if (businessGroup.getWaitingListEnabled().booleanValue()) { return true; }
		}
		return false;
	}

	// /////////////////
	// Private Methods
	// /////////////////
	private boolean addUserToParticipantList(final Identity identity, final BusinessGroup group, final ENCourseNode enNode,
			final CoursePropertyManager coursePropertyManager, final WindowControl wControl, final Translator trans) {
		CoordinatorManager.getInstance().getCoordinator().getSyncer().assertAlreadyDoInSyncFor(group);
		// 1. Add user to group, fire events, do loggin etc.
		final BGConfigFlags flags = BGConfigFlags.createLearningGroupDefaultFlags();
		businessGroupManager.addParticipantAndFireEvent(identity, identity, group, flags, false);
		// 2. Set first enrollment date
		final String nowString = Long.toString(System.currentTimeMillis());
		Property firstTime = coursePropertyManager.findCourseNodeProperty(enNode, identity, null, ENCourseNode.PROPERTY_INITIAL_ENROLLMENT_DATE);
		if (firstTime == null) {
			// create firsttime
			firstTime = coursePropertyManager.createCourseNodePropertyInstance(enNode, identity, null, ENCourseNode.PROPERTY_INITIAL_ENROLLMENT_DATE, null, null,
					nowString, null);
			coursePropertyManager.saveProperty(firstTime);
		}
		// 3. Set enrollmentdate property
		Property thisTime = coursePropertyManager.findCourseNodeProperty(enNode, identity, null, ENCourseNode.PROPERTY_RECENT_ENROLLMENT_DATE);
		if (thisTime == null) {
			// create firsttime
			thisTime = coursePropertyManager.createCourseNodePropertyInstance(enNode, identity, null, ENCourseNode.PROPERTY_RECENT_ENROLLMENT_DATE, null, null,
					nowString, null);
			coursePropertyManager.saveProperty(thisTime);
		} else {
			thisTime.setStringValue(nowString);
			coursePropertyManager.updateProperty(thisTime);
		}
		// 4. Send notification mail
		final MailTemplate mailTemplate = BGMailHelper.createAddMyselfMailTemplate(group, identity);
		final MailerWithTemplate mailer = MailerWithTemplate.getInstance();
		final MailerResult mailerResult = mailer.sendMail(identity, null, null, mailTemplate, null);
		MailHelper.printErrorsAndWarnings(mailerResult, wControl, trans.getLocale());

		return true;
	}

	private boolean addUserToWaitingList(final Identity identity, final BusinessGroup group, final ENCourseNode enNode,
			final CoursePropertyManager coursePropertyManager, final WindowControl wControl, final Translator trans) {
		CoordinatorManager.getInstance().getCoordinator().getSyncer().assertAlreadyDoInSyncFor(group);
		// 1. Add user to group, fire events, do loggin etc.
		businessGroupManager.addToWaitingListAndFireEvent(identity, identity, group, false);
		// 2. Set first waiting-list date
		final String nowString = Long.toString(System.currentTimeMillis());
		Property firstTime = coursePropertyManager.findCourseNodeProperty(enNode, identity, null, ENCourseNode.PROPERTY_INITIAL_WAITINGLIST_DATE);
		if (firstTime == null) {
			// create firsttime
			firstTime = coursePropertyManager.createCourseNodePropertyInstance(enNode, identity, null, ENCourseNode.PROPERTY_INITIAL_WAITINGLIST_DATE, null, null,
					nowString, null);
			coursePropertyManager.saveProperty(firstTime);
		}
		// 3. Set waiting-list date property
		Property thisTime = coursePropertyManager.findCourseNodeProperty(enNode, identity, null, ENCourseNode.PROPERTY_RECENT_WAITINGLIST_DATE);
		if (thisTime == null) {
			// create firsttime
			thisTime = coursePropertyManager.createCourseNodePropertyInstance(enNode, identity, null, ENCourseNode.PROPERTY_RECENT_WAITINGLIST_DATE, null, null,
					nowString, null);
			coursePropertyManager.saveProperty(thisTime);
		} else {
			thisTime.setStringValue(nowString);
			coursePropertyManager.updateProperty(thisTime);
		}
		// 4. Send notification mail
		final MailTemplate mailTemplate = BGMailHelper.createAddWaitinglistMailTemplate(group, identity);
		final MailerWithTemplate mailer = MailerWithTemplate.getInstance();
		final MailerResult mailerResult = mailer.sendMail(identity, null, null, mailTemplate, null);
		MailHelper.printErrorsAndWarnings(mailerResult, wControl, trans.getLocale());

		return true;
	}

}


text:
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Automation;
using Microsoft.VisualStudio.Shell.Interop;

namespace TestUtilities.UI {
    public class AzureCloudServicePublishDialog : AutomationDialog {
        public AzureCloudServicePublishDialog(VisualStudioApp app, AutomationElement element)
            : base(app, element) {
        }

        public static AzureCloudServicePublishDialog FromDte(VisualStudioApp app) {
            var publishDialogHandle = app.OpenDialogWithDteExecuteCommand("Build.PublishSelection");
            return new AzureCloudServicePublishDialog(app, AutomationElement.FromHandle(publishDialogHandle));
        }

        public AzureManageSubscriptionsDialog SelectManageSubscriptions() {
            WaitForInputIdle();

            // <Manage...> is different from other list item, selecting it
            // using SelectItem will throw COMException
            // This is what the cloud service team did in their tests for their
            // combo box special items that bring up dialogs.
            AccountComboBox.ClickItem("<Manage...>");

            return new AzureManageSubscriptionsDialog(App, AutomationElement.FromHandle(App.WaitForDialogToReplace(Element)));
        }

        public AzureCloudServiceCreateDialog SelectCreateNewService() {
            WaitForInputIdle();

            // <Create New...> is different from other list item, selecting it
            // using SelectItem will throw COMException
            // This is what the cloud service team did in their tests for their
            // combo box special items that bring up dialogs.
            ServiceComboBox.ClickItem("<Create New...>");

            return new AzureCloudServiceCreateDialog(App, AutomationElement.FromHandle(App.WaitForDialogToReplace(Element)));
        }

        public void ClickPublish() {
            // Wait for the publish button to be enabled
            // It will not be enabled until all combo boxes have a valid
            // selection, such as the storage account combo box.
            WaitFor(PublishButton, btn => btn.Element.Current.IsEnabled);

            WaitForInputIdle();
            WaitForClosed(TimeSpan.FromSeconds(10.0), () => PublishButton.Click());
        }

        public void ClickNext() {
            WaitForInputIdle();
            WaitForClosed(TimeSpan.FromSeconds(10.0), () => ClickButtonByAutomationId("PART_NextCommandSource"));
        }

        private Button PublishButton {
            get {
                return new Button(FindByAutomationId("PART_FinishCommandSource"));
            }
        }

        private ComboBox AccountComboBox {
            get {
                return new ComboBox(FindByAutomationId("accountCombo"));
            }
        }

        private ComboBox ServiceComboBox {
            get {
                return new ComboBox(FindByAutomationId("ServiceComboBox"));
            }
        }
    }
}


text:
using System.Diagnostics.Contracts;
using Qoollo.Concierge.Attributes;

namespace Qoollo.Concierge.UniversalExecution.Decorators
{
    internal class ActionsExecutableDecorator : IExecutable
    {
        private readonly FluentExecutor _executor;

        public ActionsExecutableDecorator(FluentExecutor executor)
        {
            Contract.Requires(executor != null);
            _executor = executor;
        }

        public void Dispose()
        {
            Stop();
        }

        public void Start()
        {
            _executor.Start();
        }

        public void Stop()
        {
            if (_executor.Stop != null)
                _executor.Stop();
        }

        [StartupParametersHandler]
        public void StartupMethod(string[] keys)
        {
            if (_executor.Init != null)
                _executor.Init(keys);
        }
    }
}


text:
from . import decorators, ldap, stats, string

__all__ = ['decorators', 'ldap', 'stats', 'string']


text:
package httptest

import (
	"io"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
	"go.uber.org/fx/docs/internal/test"
)

func TestPostSuccess(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc("/success", func(w http.ResponseWriter, r *http.Request) {
		_, err := io.Copy(w, r.Body)
		assert.NoError(t, err, "copy request body")
	})
	mux.HandleFunc("/failure", func(w http.ResponseWriter, r *http.Request) {
		http.NotFound(w, r)
	})

	srv := httptest.NewServer(mux)
	defer srv.Close()

	t.Run("success", func(t *testing.T) {
		got := PostSuccess(t, srv.URL+"/success", "hello")
		assert.Equal(t, "hello", got)
	})

	t.Run("failure", func(t *testing.T) {
		result := test.WithFake(t, func(t test.T) {
			PostSuccess(t, srv.URL+"/failure", "hello")
		})
		assert.True(t, result.Failed, "test should fail")
		assert.Len(t, result.Errors, 1)
		assert.Contains(t, result.Errors[0], "status code did not match")
	})
}


text:
#if ENABLE_GETSOCIAL_CHAT

using GetSocialSdk.Core;
using System;

namespace GetSocialSdk.Chat
{
    /// <summary>
    /// Represents chat message.
    /// </summary>
    public sealed class ChatMessage
    {
        internal ChatMessage(User sender, string guid, DateTime timestamp, bool wasSentByMe, ChatMessageContent content)
        {
            this.sender = sender;
            this.guid = guid;
            this.timestamp = timestamp;
            this.wasSentByMe = wasSentByMe;
            this.content = content;
        }

        private readonly User sender;
        private readonly string guid;
        private readonly DateTime timestamp;
        private readonly bool wasSentByMe;
        private readonly ChatMessageContent content;

        /// <summary>
        /// Gets the sender of the message.
        /// </summary>
        /// <value>Returns the user that has sent the message</value>
        public User Sender
        {
            get { return sender; }
        }

        /// <summary>
        /// Gets the GUID of the message.
        /// </summary>
        /// <value>The GUID of the message.</value>
        public string Guid
        {
            get { return guid; }
        }

        /// <summary>
        /// Gets the timestamp of the message.
        /// </summary>
        /// <value>The timestamp of the message.</value>
        public DateTime Timestamp
        {
            get { return timestamp; }
        }

        /// <summary>
        /// Gets a value indicating whether this <see cref="GetSocialSdk.Chat.ChatMessage"/> was sent by me.
        /// </summary>
        /// <value><c>true</c> if was sent by me; otherwise, <c>false</c>.</value>
        public bool WasSentByMe
        {
            get { return wasSentByMe; }
        }

        /// <summary>
        /// Gets the content of the message.
        /// </summary>
        /// <value>The content of the message.</value>
        public ChatMessageContent Content
        {
            get { return content; }
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents the current <see cref="GetSocialSdk.Chat.ChatMessage"/>.
        /// </summary>
        /// <returns>A <see cref="System.String"/> that represents the current <see cref="GetSocialSdk.Chat.ChatMessage"/>.</returns>
        public override string ToString()
        {
            return string.Format("[ChatMessage: Sender={0}, Guid={1}, Timestamp={2}, WasSentByMe={3}, Content={4}]", Sender, Guid, Timestamp.ToString("U"), WasSentByMe, Content);
        }
    }
}
#endif


text:
import networkx as nx
import pandas as pd

PATH_MAP_ADJACENCY_INIT = "map_adjacency_init.xlsx"

PATH_RECLICS = "relics.xlsx"

PATH_TABLETS = "tablets.xlsx"

class Board():
	# Rules, p 11, "Tokens and Enmity"
	# There is no limit to the number of reputation and fortune tokens
	# The enmity tokens are limited to 8 per player.

	def __init__(self, game):
		"""
		This object contains a list of all the coordinates for the SeaFall game
		board stored in hexgrid_keys.

		locked_chest_state: ref page 2. Keeps track of what locked chests have been opened.
		"""
		try:
			df_map_adjacency = pd.read_excel(PATH_MAP_ADJACENCY_INIT)

		except Exception as e:
			print("Error {}".format(e))
			print("Cannot open *{}*!".format(PATH_MAP_ADJACENCY_INIT))

		try:
			df_relics = pd.read_excel(PATH_RELICS)

		except Exception as e:
			print("Error {}".format(e))
			print("Cannot open *{}*!".format(PATH_RELICS))

		try:
			df_tablets = pd.read_excel(PATH_TABLETS)

		except Exception as e:
			print("Error {}".format(e))
			print("Cannot open *{}*!".format(PATH_TABLETS))

		self.map = nx.from_pandas.adjacency(df, create_using=nx.DiGraph())
		self.locked_chest_state = 0

	def get_valid_moves(self):

		return self.valid_moves

	def sail(self, player, ship, destination):

		return True

class Curses():
	def __init__(self):
		self.curse_types = [
		'',
		''
		]

		self.curse_distribution = [1, 1]

class DamageDeck():
	def __init__(self):
		self.stage

class Ship():
	# Rules, pg 8, "Province Boards" also inlcude information about ships
	def __init__(self):
		self.curses = []
		# damage, a list of damage cards
		self.damage = []
		# hold, a list of objects with max length hold
		self.hold = []
		# upgrades, a list of upgrade objects of max length 2
		self.upgrades = []
		# values (explore, hold, raid, sail)
		self._values = (1, 1, 1, 1)
		# vmax is the maximum number values can reach for (explore, hold, raid,
		# sail)
		self._vmax = (5, 5, 5, 5)
		# the name of the ship
		self.name = ''

	@property
	def values(self):
		return self._values

	@values.setter
	def values(self, values):
		if not isinstance(values, tuple):
			err_str = ("Not a valid data type. The data type should be a tuple"
					   " of 4 length.")
			raise ValueError(err_str)
		elif len(values) != 4:
			err_str = ("Not a valid data type. The data type should be a tuple"
					   " of 4 length.")
			raise ValueError(err_str)

		for val, vmax in zip(values, self.vmax):
			if val > vmax:
				raise ValueError("A ship value exceeds its max.")

		self._values = values

	@property
	def vmax(self):
		return self._vmax

	@vmax.setter
	def vmax(self, vmax_tuple):
		if not isinstance(vmax_tuple, tuple):
			err_str = ("Not a valid data type. The data type should be a tuple"
					   " of 4 length.")
			raise ValueError(err_str)
		elif len(vmax_tuple) != 4:
			err_str = ("Not a valid data type. The data type should be a tuple"
					   " of 4 length.")
			raise ValueError(err_str)

		for val, vmax in zip((5, 5, 5, 5), vmax_tuple):
			if val > vmax:
				raise ValueError("The maximum ship values are never less than (5, 5, 5, 5).")

		self._vmax = vmax

class Region():
	def __init__(self):
		# Rules, pg 7, "Garrison"
		self.garrison = 0
		pass

class ProvinceBoard():
	# Rules, pg 8, "Province Boards"
	def __init__(self):
		self.active_advisor = None
		self.at_war_with
		self.building_sites = []
		self.council_room = []
		self.home_enmity
		self.fields = (4, 4)
		ship0 = Ship()
		ship0.values = (2, 3, 2, 2)
		ship1 = Ship()
		ship1.values = (3, 2, 2, 2)
		self.ships = (ship0, ship1)
		self.treasure_room = []
		self.vault = 0
		self.warehouse = []

	def end_of_game():
		return True

class Province():
	def __init__(self):
		pass

class Colony(Region):
	def __init__(self):
		pass

class Island(Region):
	def __init__(self):
		self.name = None
		self.garrison

class Upgrade():
'''
locked_chest: ref page 2. This number
'''
	def __init__(self):
		self.locked_chest = 0
		pass

class Relic():
	def __init__(self):
		pass

class Tablet():
	def __init__(self):
		pass

class Goods():
	# Rules, p 12, "Islands Produce"
	# Goods are supply limited.
	valid_goods = {
		"iron",
		"linen",
		"spice",
		"wood"
		}

	goods_supply = [
		"iron", "iron", "iron", "iron", "iron",
		"iron", "iron", "iron", "iron", "iron",
		"linen", "linen", "linen", "linen", "linen",
		"linen", "linen", "linen", "linen", "linen",
		"spice", "spice", "spice", "spice", "spice",
		"spice", "spice", "spice", "spice", "spice",
		"wood", "wood", "wood", "wood", "wood",
		"wood", "wood", "wood", "wood", "wood"
	]

	# Goods.goods_supply.remove("iron") to remove to first match of iron from the list of goods in the supply

	def __init__(self):
		pass

class DicePool():
	def __init__(self):
		pass

class Dice():
	def __init__(self):
		pass

class Advisor():
	def __init__(self):
		pass

class SideBoard():
	def __init__(self):
		pass

class Structure():
	def __init__(self):
		pass

class Leader():
	# Rules, pg 6, "Leader Cards"
	def __init__(self, appellation=None, fortune=0, improvement=None,
				 name=None, reputation=0, title=None):
		# Rules, pg 6, "Leader Cards"
		# appellation is an ability a leader earns at the start of a campaign
		# or as a game end upgrade.
		self.appellation = appellation
		# Rules, pg 3, "Fortune Tokens"
		# the number of fortune tokens a player has at the begining of a game
		self.fortune = fortune
		# improvement is one of a number of stickers that boosts the effect of
		# a particular guild.
		self.improvement = improvement
		# The name of the leader as given by the player
		self.name = name
		# Rules, pg 3, "Reputation Tokens"
		# the number of reputation tokens a player has at the beginnig of a
		# game.
		self.reputation = reputation
		# Rules, pg 6, "Titles"
		# title, the province rank in the overall campaign based on total
		# glory.
		self.title = title

class Site():
	def __init__(self, dangerous=False, defense=0, explored=False):
		# Rules, pg 10, "Dangerous Sites"
		self.dangerous = dangerous
		# Rules, pg 10, "Starting an Endeavor"
		# Rules, pg 7, "Defense"
		self.defense = defense
		self.explored = explored
		self.enmity = 0

class HomeHarbor(Region):
	def __init__(self):
		pass

class UpgradeSheet():
	def __init__(self):
		pass

class Enmity():
	def __init__(self):
		pass

class IslandSiteGood(Site):
	def __init__(self, dangerous=False, defense=0, good='Food'):
		super().__init__(dangerous=dangerous, defense=defense)
		self._good = good

	@property
	def good(self):
		return self._good

	@good.setter
	def good(self, good):
		if not isinstance(values, tuple):
			err_str = ("Not a valid data type. The data type should be a tuple"
					" of 4 length.")
			raise ValueError(err_str)
		elif len(values) != 4:
			err_str = ("Not a valid data type. The data type should be a tuple"
					" of 4 length.")
			raise ValueError(err_str)

		for val, vmax in zip(values, self.vmax):
			if val > vmax:
				raise ValueError("A ship value exceeds its max.")

		self._good = good

class IslandSiteMine(Site):
	def __init__(self, dangerous=False, defense=0, gold=0):
		super().__init__(dangerous=dangerous, defense=defense)
		self.gold = gold

class IslandSiteDocks(Site):
	def __init__(self):
		pass

class IslandSiteMarket(Site):
	def __init__(self):
		pass

class IslandSiteTomb(Site):
	def __init__(self):
		pass


text:
[CmdletBinding()]
param()

. $PSScriptRoot\..\..\..\Tests\lib\Initialize-Test.ps1
. $PSScriptRoot\MockVariable.ps1
. $PSScriptRoot\..\Utility.ps1
. $PSScriptRoot\MockHelper.ps1

$extensionName="WinRMCustomScriptExtension"

# Test 1 "Should throw Resource group name is null"
Assert-Throws {
    $response = Validate-CustomScriptExecutionStatus -resourceGroupName $null -vmName $vm0Name -extensionName $extensionName
} -MessagePattern "AFC_SetCustomScriptExtensionFailed *"

# Test 2 "Should throw when VM name is null"
Assert-Throws {
    $response =  Validate-CustomScriptExecutionStatus -resourceGroupName $validRG -vmName $null -extensionName $extensionName
} -MessagePattern "AFC_SetCustomScriptExtensionFailed *"

# Test 3 "Should throw when VM name is invalid"
Assert-Throws {
    $response = Validate-CustomScriptExecutionStatus -resourceGroupName $validRG -vmName $invalidMachineName -extensionName $extensionName
} -MessagePattern "AFC_SetCustomScriptExtensionFailed *"

# Test 4 "Should throw Extension name is null"
Assert-Throws {
    $response = Validate-CustomScriptExecutionStatus -resourceGroupName $validRG -vmName $vm0Name -extensionName $null
} -MessagePattern "AFC_SetCustomScriptExtensionFailed *"

# Test 5 "should throw when Extension name is invalid"
$invalidExtensionName="InvalidWinRMCustomScriptExtension"
Assert-Throws {
    $response =  Validate-CustomScriptExecutionStatus -resourceGroupName $validRG -vmName $vm0Name -extensionName $invalidExtensionName
} -MessagePattern "AFC_SetCustomScriptExtensionFailed *"

# Test 6 "Should not throw" "For valid values, if previous extension deployed successfully"
Register-Mock Remove-AzureMachineCustomScriptExtension { return @{}}
$vmInstanceViews[$vm0Name]["Extensions"]=$extensions

Validate-CustomScriptExecutionStatus -resourceGroupName $validRG -vmName $vm0Name -extensionName $extensionName
Assert-WasCalled Remove-AzureMachineCustomScriptExtension -Times 0

# Test 7 "Should throw for valid values, if previous extension failed to deploy"
$extensions[0]["SubStatuses"][1]["Message"]="Extension script execution failed."
$vmInstanceViews[$vm0Name]["Extensions"]=$extensions

Assert-Throws {
    Validate-CustomScriptExecutionStatus -resourceGroupName $validRG -vmName $vm0Name -extensionName $extensionName
} -MessagePattern "AFC_SetCustomScriptExtensionFailed *"
Assert-WasCalled Remove-AzureMachineCustomScriptExtension -Times 1

# Test 8 "For valid values, if previous extension failed to provision"
Unregister-Mock Remove-AzureMachineCustomScriptExtension
Register-Mock Remove-AzureMachineCustomScriptExtension { return @{}}
$extensions[0]["SubStatuses"][1]["Message"]="Failed to apply the extension."
$vmInstanceViews[$vm0Name]["Extensions"]=$extensions

Assert-Throws {
    Validate-CustomScriptExecutionStatus -resourceGroupName $validRG -vmName $vm0Name -extensionName $extensionName
} -MessagePattern "AFC_SetCustomScriptExtensionFailed *"
Assert-WasCalled Remove-AzureMachineCustomScriptExtension -Times 1

#Clean the extension
$vmInstanceViews[$vm0Name]["Extensions"]=@()


text:
<?php

namespace IceClaws\CoreBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class IceClawsCoreBundle extends Bundle
{
}


text:
class DSP : public Processor {
public:
  enum : bool { Threaded = false };
  alwaysinline void step(unsigned clocks);
  alwaysinline void synchronize_smp();

  uint8 read(uint8 addr);
  void write(uint8 addr, uint8 data);

  void enter();
  void power();
  void reset();

  void channel_enable(unsigned channel, bool enable);

  DSP();

private:
  SPC_DSP spc_dsp;
  int16 samplebuffer[8192];
  bool channel_enabled[8];
};

extern DSP dsp;


text:
from __future__ import absolute_import

import contextlib
import copy
import functools
import time

from oslo_utils import strutils
import six
import sqlalchemy as sa
from sqlalchemy import exc as sa_exc
from sqlalchemy import pool as sa_pool
from sqlalchemy import sql

from taskflow import exceptions as exc
from taskflow import logging
from taskflow.persistence.backends.sqlalchemy import migration
from taskflow.persistence.backends.sqlalchemy import tables
from taskflow.persistence import base
from taskflow.persistence import models
from taskflow.types import failure
from taskflow.utils import eventlet_utils
from taskflow.utils import misc

LOG = logging.getLogger(__name__)

# NOTE(harlowja): This is all very similar to what oslo-incubator uses but is
# not based on using oslo.cfg and its global configuration (which should not be
# used in libraries such as taskflow).
#
# TODO(harlowja): once oslo.db appears we should be able to use that instead
# since it's not supposed to have any usage of oslo.cfg in it when it
# materializes as a library.

# See: http://dev.mysql.com/doc/refman/5.0/en/error-messages-client.html
MY_SQL_CONN_ERRORS = (
    # Lost connection to MySQL server at '%s', system error: %d
    '2006',
    # Can't connect to MySQL server on '%s' (%d)
    '2003',
    # Can't connect to local MySQL server through socket '%s' (%d)
    '2002',
)
MY_SQL_GONE_WAY_AWAY_ERRORS = (
    # Lost connection to MySQL server at '%s', system error: %d
    '2006',
    # Lost connection to MySQL server during query
    '2013',
    # Commands out of sync; you can't run this command now
    '2014',
    # Can't open shared memory; no answer from server (%lu)
    '2045',
    # Lost connection to MySQL server at '%s', system error: %d
    '2055',
)

# See: http://www.postgresql.org/docs/9.1/static/errcodes-appendix.html
POSTGRES_CONN_ERRORS = (
    # connection_exception
    '08000',
    # connection_does_not_exist
    '08003',
    # connection_failure
    '08006',
    # sqlclient_unable_to_establish_sqlconnection
    '08001',
    # sqlserver_rejected_establishment_of_sqlconnection
    '08004',
    # Just couldn't connect (postgres errors are pretty weird)
    'could not connect to server',
)
POSTGRES_GONE_WAY_AWAY_ERRORS = (
    # Server terminated while in progress (postgres errors are pretty weird).
    'server closed the connection unexpectedly',
    'terminating connection due to administrator command',
)

# These connection urls mean sqlite is being used as an in-memory DB.
SQLITE_IN_MEMORY = ('sqlite://', 'sqlite:///', 'sqlite:///:memory:')

# Transacation isolation levels that will be automatically applied, we prefer
# strong read committed isolation levels to avoid merging and using dirty
# data...
#
# See: http://en.wikipedia.org/wiki/Isolation_(database_systems)
DEFAULT_TXN_ISOLATION_LEVELS = {
    'mysql': 'READ COMMITTED',
    'postgresql': 'READ COMMITTED',
    'postgres': 'READ COMMITTED',
}

def _log_statements(log_level, conn, cursor, statement, parameters, *args):
    if LOG.isEnabledFor(log_level):
        LOG.log(log_level, "Running statement '%s' with parameters %s",
                statement, parameters)

def _in_any(reason, err_haystack):
    """Checks if any elements of the haystack are in the given reason."""
    for err in err_haystack:
        if reason.find(six.text_type(err)) != -1:
            return True
    return False

def _is_db_connection_error(reason):
    return _in_any(reason, list(MY_SQL_CONN_ERRORS + POSTGRES_CONN_ERRORS))

def _as_bool(value):
    if isinstance(value, bool):
        return value
    # This is different than strutils, but imho is an acceptable difference.
    if value is None:
        return False
    # NOTE(harlowja): prefer strictness to avoid users getting accustomed
    # to passing bad values in and this *just working* (which imho is a bad
    # habit to encourage).
    return strutils.bool_from_string(value, strict=True)

def _thread_yield(dbapi_con, con_record):
    """Ensure other greenthreads get a chance to be executed.

    If we use eventlet.monkey_patch(), eventlet.greenthread.sleep(0) will
    execute instead of time.sleep(0).

    Force a context switch. With common database backends (eg MySQLdb and
    sqlite), there is no implicit yield caused by network I/O since they are
    implemented by C libraries that eventlet cannot monkey patch.
    """
    time.sleep(0)

def _set_sql_mode(sql_mode, dbapi_con, connection_rec):
    """Set the sql_mode session variable.

    MySQL supports several server modes. The default is None, but sessions
    may choose to enable server modes like TRADITIONAL, ANSI,
    several STRICT_* modes and others.

    Note: passing in '' (empty string) for sql_mode clears
    the SQL mode for the session, overriding a potentially set
    server default.
    """
    cursor = dbapi_con.cursor()
    cursor.execute("SET SESSION sql_mode = %s", [sql_mode])

def _ping_listener(dbapi_conn, connection_rec, connection_proxy):
    """Ensures that MySQL connections checked out of the pool are alive.

    Modified + borrowed from: http://bit.ly/14BYaW6.
    """
    try:
        dbapi_conn.cursor().execute('select 1')
    except dbapi_conn.OperationalError as ex:
        if _in_any(six.text_type(ex.args[0]), MY_SQL_GONE_WAY_AWAY_ERRORS):
            LOG.warn('Got mysql server has gone away', exc_info=True)
            raise sa_exc.DisconnectionError("Database server went away")
        elif _in_any(six.text_type(ex.args[0]), POSTGRES_GONE_WAY_AWAY_ERRORS):
            LOG.warn('Got postgres server has gone away', exc_info=True)
            raise sa_exc.DisconnectionError("Database server went away")
        else:
            raise

class _Alchemist(object):
    """Internal <-> external row <-> objects + other helper functions.

    NOTE(harlowja): for internal usage only.
    """
    def __init__(self, tables):
        self._tables = tables

    @staticmethod
    def convert_flow_detail(row):
        return models.FlowDetail.from_dict(dict(row.items()))

    @staticmethod
    def convert_book(row):
        return models.LogBook.from_dict(dict(row.items()))

    @staticmethod
    def convert_atom_detail(row):
        row = dict(row.items())
        atom_cls = models.atom_detail_class(row.pop('atom_type'))
        return atom_cls.from_dict(row)

    def atom_query_iter(self, conn, parent_uuid):
        q = (sql.select([self._tables.atomdetails]).
             where(self._tables.atomdetails.c.parent_uuid == parent_uuid))
        for row in conn.execute(q):
            yield self.convert_atom_detail(row)

    def flow_query_iter(self, conn, parent_uuid):
        q = (sql.select([self._tables.flowdetails]).
             where(self._tables.flowdetails.c.parent_uuid == parent_uuid))
        for row in conn.execute(q):
            yield self.convert_flow_detail(row)

    def populate_book(self, conn, book):
        for fd in self.flow_query_iter(conn, book.uuid):
            book.add(fd)
            self.populate_flow_detail(conn, fd)

    def populate_flow_detail(self, conn, fd):
        for ad in self.atom_query_iter(conn, fd.uuid):
            fd.add(ad)

class SQLAlchemyBackend(base.Backend):
    """A sqlalchemy backend.

    Example configuration::

        conf = {
            "connection": "sqlite:////tmp/test.db",
        }
    """
    def __init__(self, conf, engine=None):
        super(SQLAlchemyBackend, self).__init__(conf)
        if engine is not None:
            self._engine = engine
            self._owns_engine = False
        else:
            self._engine = self._create_engine(self._conf)
            self._owns_engine = True
        self._validated = False

    @staticmethod
    def _create_engine(conf):
        # NOTE(harlowja): copy the internal one so that we don't modify it via
        # all the popping that will happen below.
        conf = copy.deepcopy(conf)
        engine_args = {
            'echo': _as_bool(conf.pop('echo', False)),
            'convert_unicode': _as_bool(conf.pop('convert_unicode', True)),
            'pool_recycle': 3600,
        }
        if 'idle_timeout' in conf:
            idle_timeout = misc.as_int(conf.pop('idle_timeout'))
            engine_args['pool_recycle'] = idle_timeout
        sql_connection = conf.pop('connection')
        e_url = sa.engine.url.make_url(sql_connection)
        if 'sqlite' in e_url.drivername:
            engine_args["poolclass"] = sa_pool.NullPool

            # Adjustments for in-memory sqlite usage.
            if sql_connection.lower().strip() in SQLITE_IN_MEMORY:
                engine_args["poolclass"] = sa_pool.StaticPool
                engine_args["connect_args"] = {'check_same_thread': False}
        else:
            for (k, lookup_key) in [('pool_size', 'max_pool_size'),
                                    ('max_overflow', 'max_overflow'),
                                    ('pool_timeout', 'pool_timeout')]:
                if lookup_key in conf:
                    engine_args[k] = misc.as_int(conf.pop(lookup_key))
        if 'isolation_level' not in conf:
            # Check driver name exact matches first, then try driver name
            # partial matches...
            txn_isolation_levels = conf.pop('isolation_levels',
                                            DEFAULT_TXN_ISOLATION_LEVELS)
            level_applied = False
            for (driver, level) in six.iteritems(txn_isolation_levels):
                if driver == e_url.drivername:
                    engine_args['isolation_level'] = level
                    level_applied = True
                    break
            if not level_applied:
                for (driver, level) in six.iteritems(txn_isolation_levels):
                    if e_url.drivername.find(driver) != -1:
                        engine_args['isolation_level'] = level
                        break
        else:
            engine_args['isolation_level'] = conf.pop('isolation_level')
        # If the configuration dict specifies any additional engine args
        # or engine arg overrides make sure we merge them in.
        engine_args.update(conf.pop('engine_args', {}))
        engine = sa.create_engine(sql_connection, **engine_args)
        log_statements = conf.pop('log_statements', False)
        if _as_bool(log_statements):
            log_statements_level = conf.pop("log_statements_level",
                                            logging.BLATHER)
            sa.event.listen(engine, "before_cursor_execute",
                            functools.partial(_log_statements,
                                              log_statements_level))
        checkin_yield = conf.pop('checkin_yield',
                                 eventlet_utils.EVENTLET_AVAILABLE)
        if _as_bool(checkin_yield):
            sa.event.listen(engine, 'checkin', _thread_yield)
        if 'mysql' in e_url.drivername:
            if _as_bool(conf.pop('checkout_ping', True)):
                sa.event.listen(engine, 'checkout', _ping_listener)
            mode = None
            if 'mysql_sql_mode' in conf:
                mode = conf.pop('mysql_sql_mode')
            if mode is not None:
                sa.event.listen(engine, 'connect',
                                functools.partial(_set_sql_mode, mode))
        return engine

    @property
    def engine(self):
        return self._engine

    def get_connection(self):
        conn = Connection(self)
        if not self._validated:
            try:
                max_retries = misc.as_int(self._conf.get('max_retries', None))
            except TypeError:
                max_retries = 0
            conn.validate(max_retries=max_retries)
            self._validated = True
        return conn

    def close(self):
        # NOTE(harlowja): Only dispose of the engine if we actually own the
        # engine in the first place. If the user passed in their own engine
        # we should not be disposing it on their behalf...
        if self._owns_engine:
            self._engine.dispose()
        self._validated = False

class Connection(base.Connection):
    def __init__(self, backend):
        self._backend = backend
        self._engine = backend.engine
        self._metadata = sa.MetaData()
        self._tables = tables.fetch(self._metadata)
        self._converter = _Alchemist(self._tables)

    @property
    def backend(self):
        return self._backend

    def validate(self, max_retries=0):

        def verify_connect(failures):
            try:
                # See if we can make a connection happen.
                #
                # NOTE(harlowja): note that even though we are connecting
                # once it does not mean that we will be able to connect in
                # the future, so this is more of a sanity test and is not
                # complete connection insurance.
                with contextlib.closing(self._engine.connect()):
                    pass
            except sa_exc.OperationalError as ex:
                if _is_db_connection_error(six.text_type(ex.args[0])):
                    failures.append(failure.Failure())
                    return False
            return True

        failures = []
        if verify_connect(failures):
            return

        # Sorry it didn't work out...
        if max_retries <= 0:
            failures[-1].reraise()

        # Go through the exponential backoff loop and see if we can connect
        # after a given number of backoffs (with a backoff sleeping period
        # between each attempt)...
        attempts_left = max_retries
        for sleepy_secs in misc.ExponentialBackoff(max_retries):
            LOG.warn("SQL connection failed due to '%s', %s attempts left.",
                     failures[-1].exc, attempts_left)
            LOG.info("Attempting to test the connection again in %s seconds.",
                     sleepy_secs)
            time.sleep(sleepy_secs)
            if verify_connect(failures):
                return
            attempts_left -= 1

        # Sorry it didn't work out...
        failures[-1].reraise()

    def upgrade(self):
        try:
            with contextlib.closing(self._engine.connect()) as conn:
                # NOTE(imelnikov): Alembic does not support SQLite,
                # and we don't recommend to use SQLite in production
                # deployments, so migrations are rarely needed
                # for SQLite. So we don't bother about working around
                # SQLite limitations, and create the database directly from
                # the tables when it is in use...
                if 'sqlite' in self._engine.url.drivername:
                    self._metadata.create_all(bind=conn)
                else:
                    migration.db_sync(conn)
        except sa_exc.SQLAlchemyError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Failed upgrading database version")

    def clear_all(self):
        try:
            logbooks = self._tables.logbooks
            with self._engine.begin() as conn:
                conn.execute(logbooks.delete())
        except sa_exc.DBAPIError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Failed clearing all entries")

    def update_atom_details(self, atom_detail):
        try:
            atomdetails = self._tables.atomdetails
            with self._engine.begin() as conn:
                q = (sql.select([atomdetails]).
                     where(atomdetails.c.uuid == atom_detail.uuid))
                row = conn.execute(q).first()
                if not row:
                    raise exc.NotFound("No atom details found with uuid"
                                       " '%s'" % atom_detail.uuid)
                e_ad = self._converter.convert_atom_detail(row)
                self._update_atom_details(conn, atom_detail, e_ad)
            return e_ad
        except sa_exc.SQLAlchemyError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Failed updating atom details"
                                 " with uuid '%s'" % atom_detail.uuid)

    def _insert_flow_details(self, conn, fd, parent_uuid):
        value = fd.to_dict()
        value['parent_uuid'] = parent_uuid
        conn.execute(sql.insert(self._tables.flowdetails, value))
        for ad in fd:
            self._insert_atom_details(conn, ad, fd.uuid)

    def _insert_atom_details(self, conn, ad, parent_uuid):
        value = ad.to_dict()
        value['parent_uuid'] = parent_uuid
        value['atom_type'] = models.atom_detail_type(ad)
        conn.execute(sql.insert(self._tables.atomdetails, value))

    def _update_atom_details(self, conn, ad, e_ad):
        e_ad.merge(ad)
        conn.execute(sql.update(self._tables.atomdetails)
                     .where(self._tables.atomdetails.c.uuid == e_ad.uuid)
                     .values(e_ad.to_dict()))

    def _update_flow_details(self, conn, fd, e_fd):
        e_fd.merge(fd)
        conn.execute(sql.update(self._tables.flowdetails)
                     .where(self._tables.flowdetails.c.uuid == e_fd.uuid)
                     .values(e_fd.to_dict()))
        for ad in fd:
            e_ad = e_fd.find(ad.uuid)
            if e_ad is None:
                e_fd.add(ad)
                self._insert_atom_details(conn, ad, fd.uuid)
            else:
                self._update_atom_details(conn, ad, e_ad)

    def update_flow_details(self, flow_detail):
        try:
            flowdetails = self._tables.flowdetails
            with self._engine.begin() as conn:
                q = (sql.select([flowdetails]).
                     where(flowdetails.c.uuid == flow_detail.uuid))
                row = conn.execute(q).first()
                if not row:
                    raise exc.NotFound("No flow details found with"
                                       " uuid '%s'" % flow_detail.uuid)
                e_fd = self._converter.convert_flow_detail(row)
                self._converter.populate_flow_detail(conn, e_fd)
                self._update_flow_details(conn, flow_detail, e_fd)
            return e_fd
        except sa_exc.SQLAlchemyError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Failed updating flow details with"
                                 " uuid '%s'" % flow_detail.uuid)

    def destroy_logbook(self, book_uuid):
        try:
            logbooks = self._tables.logbooks
            with self._engine.begin() as conn:
                q = logbooks.delete().where(logbooks.c.uuid == book_uuid)
                r = conn.execute(q)
                if r.rowcount == 0:
                    raise exc.NotFound("No logbook found with"
                                       " uuid '%s'" % book_uuid)
        except sa_exc.DBAPIError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Failed destroying logbook '%s'" % book_uuid)

    def save_logbook(self, book):
        try:
            logbooks = self._tables.logbooks
            with self._engine.begin() as conn:
                q = (sql.select([logbooks]).
                     where(logbooks.c.uuid == book.uuid))
                row = conn.execute(q).first()
                if row:
                    e_lb = self._converter.convert_book(row)
                    self._converter.populate_book(conn, e_lb)
                    e_lb.merge(book)
                    conn.execute(sql.update(logbooks)
                                 .where(logbooks.c.uuid == e_lb.uuid)
                                 .values(e_lb.to_dict()))
                    for fd in book:
                        e_fd = e_lb.find(fd.uuid)
                        if e_fd is None:
                            e_lb.add(fd)
                            self._insert_flow_details(conn, fd, e_lb.uuid)
                        else:
                            self._update_flow_details(conn, fd, e_fd)
                    return e_lb
                else:
                    conn.execute(sql.insert(logbooks, book.to_dict()))
                    for fd in book:
                        self._insert_flow_details(conn, fd, book.uuid)
                    return book
        except sa_exc.DBAPIError:
            exc.raise_with_cause(
                exc.StorageFailure,
                "Failed saving logbook '%s'" % book.uuid)

    def get_logbook(self, book_uuid, lazy=False):
        try:
            logbooks = self._tables.logbooks
            with contextlib.closing(self._engine.connect()) as conn:
                q = (sql.select([logbooks]).
                     where(logbooks.c.uuid == book_uuid))
                row = conn.execute(q).first()
                if not row:
                    raise exc.NotFound("No logbook found with"
                                       " uuid '%s'" % book_uuid)
                book = self._converter.convert_book(row)
                if not lazy:
                    self._converter.populate_book(conn, book)
                return book
        except sa_exc.DBAPIError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Failed getting logbook '%s'" % book_uuid)

    def get_logbooks(self, lazy=False):
        gathered = []
        try:
            with contextlib.closing(self._engine.connect()) as conn:
                q = sql.select([self._tables.logbooks])
                for row in conn.execute(q):
                    book = self._converter.convert_book(row)
                    if not lazy:
                        self._converter.populate_book(conn, book)
                    gathered.append(book)
        except sa_exc.DBAPIError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Failed getting logbooks")
        for book in gathered:
            yield book

    def get_flows_for_book(self, book_uuid, lazy=False):
        gathered = []
        try:
            with contextlib.closing(self._engine.connect()) as conn:
                for fd in self._converter.flow_query_iter(conn, book_uuid):
                    if not lazy:
                        self._converter.populate_flow_detail(conn, fd)
                    gathered.append(fd)
        except sa_exc.DBAPIError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Failed getting flow details in"
                                 " logbook '%s'" % book_uuid)
        for flow_details in gathered:
            yield flow_details

    def get_flow_details(self, fd_uuid, lazy=False):
        try:
            flowdetails = self._tables.flowdetails
            with self._engine.begin() as conn:
                q = (sql.select([flowdetails]).
                     where(flowdetails.c.uuid == fd_uuid))
                row = conn.execute(q).first()
                if not row:
                    raise exc.NotFound("No flow details found with uuid"
                                       " '%s'" % fd_uuid)
                fd = self._converter.convert_flow_detail(row)
                if not lazy:
                    self._converter.populate_flow_detail(conn, fd)
                return fd
        except sa_exc.SQLAlchemyError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Failed getting flow details with"
                                 " uuid '%s'" % fd_uuid)

    def get_atom_details(self, ad_uuid):
        try:
            atomdetails = self._tables.atomdetails
            with self._engine.begin() as conn:
                q = (sql.select([atomdetails]).
                     where(atomdetails.c.uuid == ad_uuid))
                row = conn.execute(q).first()
                if not row:
                    raise exc.NotFound("No atom details found with uuid"
                                       " '%s'" % ad_uuid)
                return self._converter.convert_atom_detail(row)
        except sa_exc.SQLAlchemyError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Failed getting atom details with"
                                 " uuid '%s'" % ad_uuid)

    def get_atoms_for_flow(self, fd_uuid):
        gathered = []
        try:
            with contextlib.closing(self._engine.connect()) as conn:
                for ad in self._converter.atom_query_iter(conn, fd_uuid):
                    gathered.append(ad)
        except sa_exc.DBAPIError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Failed getting atom details in flow"
                                 " detail '%s'" % fd_uuid)
        for atom_details in gathered:
            yield atom_details

    def close(self):
        pass


text:
set -e
echo "Installing Kyle McKeans's git config"
cp "$PWD/git/gitconfig" "$HOME/.gitconfig"
echo "Kyle McKean's git config installed"


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.kubernetesconfiguration.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** Statuses of objects deployed by the user-specified kustomizations from the git repository. */
@Fluent
public final class ObjectStatusDefinition {
    /*
     * Name of the applied object
     */
    @JsonProperty(value = "name")
    private String name;

    /*
     * Namespace of the applied object
     */
    @JsonProperty(value = "namespace")
    private String namespace;

    /*
     * Kind of the applied object
     */
    @JsonProperty(value = "kind")
    private String kind;

    /*
     * Compliance state of the applied object showing whether the applied
     * object has come into a ready state on the cluster.
     */
    @JsonProperty(value = "complianceState")
    private FluxComplianceState complianceState;

    /*
     * Object reference to the Kustomization that applied this object
     */
    @JsonProperty(value = "appliedBy")
    private ObjectReferenceDefinition appliedBy;

    /*
     * List of Kubernetes object status conditions present on the cluster
     */
    @JsonProperty(value = "statusConditions")
    private List<ObjectStatusConditionDefinition> statusConditions;

    /*
     * Additional properties that are provided from objects of the HelmRelease
     * kind
     */
    @JsonProperty(value = "helmReleaseProperties")
    private HelmReleasePropertiesDefinition helmReleaseProperties;

    /**
     * Get the name property: Name of the applied object.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: Name of the applied object.
     *
     * @param name the name value to set.
     * @return the ObjectStatusDefinition object itself.
     */
    public ObjectStatusDefinition withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the namespace property: Namespace of the applied object.
     *
     * @return the namespace value.
     */
    public String namespace() {
        return this.namespace;
    }

    /**
     * Set the namespace property: Namespace of the applied object.
     *
     * @param namespace the namespace value to set.
     * @return the ObjectStatusDefinition object itself.
     */
    public ObjectStatusDefinition withNamespace(String namespace) {
        this.namespace = namespace;
        return this;
    }

    /**
     * Get the kind property: Kind of the applied object.
     *
     * @return the kind value.
     */
    public String kind() {
        return this.kind;
    }

    /**
     * Set the kind property: Kind of the applied object.
     *
     * @param kind the kind value to set.
     * @return the ObjectStatusDefinition object itself.
     */
    public ObjectStatusDefinition withKind(String kind) {
        this.kind = kind;
        return this;
    }

    /**
     * Get the complianceState property: Compliance state of the applied object showing whether the applied object has
     * come into a ready state on the cluster.
     *
     * @return the complianceState value.
     */
    public FluxComplianceState complianceState() {
        return this.complianceState;
    }

    /**
     * Set the complianceState property: Compliance state of the applied object showing whether the applied object has
     * come into a ready state on the cluster.
     *
     * @param complianceState the complianceState value to set.
     * @return the ObjectStatusDefinition object itself.
     */
    public ObjectStatusDefinition withComplianceState(FluxComplianceState complianceState) {
        this.complianceState = complianceState;
        return this;
    }

    /**
     * Get the appliedBy property: Object reference to the Kustomization that applied this object.
     *
     * @return the appliedBy value.
     */
    public ObjectReferenceDefinition appliedBy() {
        return this.appliedBy;
    }

    /**
     * Set the appliedBy property: Object reference to the Kustomization that applied this object.
     *
     * @param appliedBy the appliedBy value to set.
     * @return the ObjectStatusDefinition object itself.
     */
    public ObjectStatusDefinition withAppliedBy(ObjectReferenceDefinition appliedBy) {
        this.appliedBy = appliedBy;
        return this;
    }

    /**
     * Get the statusConditions property: List of Kubernetes object status conditions present on the cluster.
     *
     * @return the statusConditions value.
     */
    public List<ObjectStatusConditionDefinition> statusConditions() {
        return this.statusConditions;
    }

    /**
     * Set the statusConditions property: List of Kubernetes object status conditions present on the cluster.
     *
     * @param statusConditions the statusConditions value to set.
     * @return the ObjectStatusDefinition object itself.
     */
    public ObjectStatusDefinition withStatusConditions(List<ObjectStatusConditionDefinition> statusConditions) {
        this.statusConditions = statusConditions;
        return this;
    }

    /**
     * Get the helmReleaseProperties property: Additional properties that are provided from objects of the HelmRelease
     * kind.
     *
     * @return the helmReleaseProperties value.
     */
    public HelmReleasePropertiesDefinition helmReleaseProperties() {
        return this.helmReleaseProperties;
    }

    /**
     * Set the helmReleaseProperties property: Additional properties that are provided from objects of the HelmRelease
     * kind.
     *
     * @param helmReleaseProperties the helmReleaseProperties value to set.
     * @return the ObjectStatusDefinition object itself.
     */
    public ObjectStatusDefinition withHelmReleaseProperties(HelmReleasePropertiesDefinition helmReleaseProperties) {
        this.helmReleaseProperties = helmReleaseProperties;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (appliedBy() != null) {
            appliedBy().validate();
        }
        if (statusConditions() != null) {
            statusConditions().forEach(e -> e.validate());
        }
        if (helmReleaseProperties() != null) {
            helmReleaseProperties().validate();
        }
    }
}