text:
gmavenplus-intellij-plugin
==========================

IntelliJ Plugin which supports new [GMavenPlus](https://github.com/groovy/GMavenPlus) Groovy Maven Plugin

See http://plugins.jetbrains.com/plugin/7442


text:
package com.github.richardballard.packplanner.pack.assembler;

import com.github.richardballard.packplanner.executionparams.ExecutionParams;
import com.github.richardballard.packplanner.item.Item;
import com.github.richardballard.packplanner.item.ItemQuantity;
import com.github.richardballard.packplanner.item.order.FillType;
import com.github.richardballard.packplanner.item.order.SortOrder;
import com.github.richardballard.packplanner.pack.Pack;
import com.github.richardballard.packplanner.pack.PackId;
import com.google.common.collect.ImmutableList;
import net.jcip.annotations.ThreadSafe;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

/**
 * Main entry point for translating a list of {@link ItemQuantity} instances into a list of {@link Pack} instances.
 */
@ThreadSafe
public class PackAssembler {

    @NotNull
    private final EquivalentItemGrouper equivalentItemGrouper;

    @NotNull
    private final Function<? super SortOrder, FillType> fillTypeFromSortOrderFunction;

    public PackAssembler(@NotNull final EquivalentItemGrouper equivalentItemGrouper,
                         @NotNull final Function<? super SortOrder, FillType> fillTypeFromSortOrderFunction) {
        assert equivalentItemGrouper != null;
        assert fillTypeFromSortOrderFunction != null;

        this.equivalentItemGrouper = equivalentItemGrouper;
        this.fillTypeFromSortOrderFunction = fillTypeFromSortOrderFunction;
    }

    @NotNull
    public ImmutableList<Pack> assemblePacks(@NotNull final ExecutionParams executionParams) {
        assert executionParams != null;

        // get the groups of equivalent items
        final ImmutableList<EquivalentItemGroup> equivalentItemGroups
                = equivalentItemGrouper.groupItems(executionParams.getSortOrder(),
                                                   executionParams.getItemQuantities());

        final List<Pack> packs = new ArrayList<>(32);

        final FillType fillType = fillTypeFromSortOrderFunction.apply(executionParams.getSortOrder());
        assert fillType != null;

        // while there are any that are not empty
        while(equivalentItemGroups.stream().anyMatch(equivalentItemGroup -> !equivalentItemGroup.isEmpty())) {
            final SinglePackBuilder packBuilder = new SinglePackBuilder(executionParams.getMaxPiecesPerPack(),
                                                                        executionParams.getMaxWeightPerPackKg());
            final Iterator<EquivalentItemGroup> groupIt = equivalentItemGroups.iterator();
            while(groupIt.hasNext()) {
                final EquivalentItemGroup group = groupIt.next();

                // fill up the pack builder from the group
                while(packBuilder.hasAvailability() && !group.isEmpty()) {
                    final Optional<Item> bestFit = group.removeBestFit(packBuilder.getAvailableWeightKg());

                    // if it found a fit from this group
                    if(bestFit.isPresent()) {
                        packBuilder.addSingleItem(bestFit.get());
                    }
                    else {
                        if(fillType == FillType.STRICTLY_ADHERE_TO_ORDER) {
                            // at this point the group doesn't have a fit and we don't want to pull items in out of order

                            // if there are still more items in the group (it's just that they don't fit in our available weight)
                            if(!group.isEmpty()) {
                                // mark the pack builder as unavailable so we will break the current loop and stow the current pack away
                                packBuilder.markAsUnavailable();
                            }
                        }

                        // didn't find a fit in this group so break loop and go to the next group
                        break;
                    }
                }
            }

            // we've either been through all the groups or the pack is full
            packs.add(new Pack(new PackId(packs.size() + 1),
                               packBuilder.getItemQuantities()));
        }

        return ImmutableList.copyOf(packs);
    }
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var common_1 = require('@angular/common');
var router_1 = require('@angular/router');
var form_component_1 = require("./form.component");
var auth_guard_1 = require("../_guards/auth.guard");
var forms_1 = require('@angular/forms');
var routes = [{ path: '', component: form_component_1.FormComponent, canActivate: [auth_guard_1.AuthGuard] }];
var FormModule = (function () {
    function FormModule() {
    }
    FormModule = __decorate([
        core_1.NgModule({
            imports: [
                common_1.CommonModule,
                router_1.RouterModule.forChild(routes),
                forms_1.FormsModule
            ],
            declarations: [
                form_component_1.FormComponent
            ],
            providers: []
        }),
        __metadata('design:paramtypes', [])
    ], FormModule);
    return FormModule;
}());
exports.FormModule = FormModule;
//# sourceMappingURL=form.module.js.map


text:
package com.planets.game.model.repo;

import com.planets.app.model.AppUser;
import com.planets.game.model.Game;

public interface GameRepoCustom {

	public Game create(Long id);

	public Game create(AppUser owner, int planetLimit, int shipLimit);

	public void delete(Game game);

}


text:
package org.wso2.developerstudio.eclipse.ds.provider;

import java.util.Collection;
import java.util.List;

import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.common.util.ResourceLocator;

import org.eclipse.emf.ecore.EStructuralFeature;

import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.FeatureMapUtil;
import org.eclipse.emf.ecore.xml.type.XMLTypeFactory;
import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.emf.edit.provider.ViewerNotification;

import org.wso2.developerstudio.eclipse.ds.DsFactory;
import org.wso2.developerstudio.eclipse.ds.DsPackage;
import org.wso2.developerstudio.eclipse.ds.ResultMapping;

/**
 * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.ds.ResultMapping} object.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public class ResultMappingItemProvider extends ItemProviderAdapter implements
                                                                  IEditingDomainItemProvider,
                                                                  IStructuredItemContentProvider,
                                                                  ITreeItemContentProvider,
                                                                  IItemLabelProvider,
                                                                  IItemPropertySource {
	/**
     * This constructs an instance from a factory and a notifier.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */
	public ResultMappingItemProvider(AdapterFactory adapterFactory) {
        super(adapterFactory);
    }

	/**
     * This returns the property descriptors for the adapted class.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */

	@Override
	public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
        if (itemPropertyDescriptors == null) {
            super.getPropertyDescriptors(object);

            addDefaultNamespacePropertyDescriptor(object);
            addElementNamePropertyDescriptor(object);
            addRowNamePropertyDescriptor(object);
            addUseColumnNumbersPropertyDescriptor(object);
            addEscapeNonPrintableCharPropertyDescriptor(object);
            addXsltPathPropertyDescriptor(object);
            addOutputTypePropertyDescriptor(object);
        }
        return itemPropertyDescriptors;
    }

	/**
     * This adds a property descriptor for the Default Namespace feature.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */
	protected void addDefaultNamespacePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_ResultMapping_defaultNamespace_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_ResultMapping_defaultNamespace_feature", "_UI_ResultMapping_type"),
                 DsPackage.Literals.RESULT_MAPPING__DEFAULT_NAMESPACE,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 null,
                 null));
    }

	/**
     * This adds a property descriptor for the Element Name feature.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */
	protected void addElementNamePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_ResultMapping_elementName_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_ResultMapping_elementName_feature", "_UI_ResultMapping_type"),
                 DsPackage.Literals.RESULT_MAPPING__ELEMENT_NAME,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 null,
                 null));
    }

	/**
     * This adds a property descriptor for the Row Name feature.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */
	protected void addRowNamePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_ResultMapping_rowName_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_ResultMapping_rowName_feature", "_UI_ResultMapping_type"),
                 DsPackage.Literals.RESULT_MAPPING__ROW_NAME,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 null,
                 null));
    }

	/**
     * This adds a property descriptor for the Use Column Numbers feature.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */
	protected void addUseColumnNumbersPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_ResultMapping_useColumnNumbers_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_ResultMapping_useColumnNumbers_feature", "_UI_ResultMapping_type"),
                 DsPackage.Literals.RESULT_MAPPING__USE_COLUMN_NUMBERS,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE,
                 null,
                 null));
    }

	/**
     * This adds a property descriptor for the Escape Non Printable Char feature.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */
	protected void addEscapeNonPrintableCharPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_ResultMapping_escapeNonPrintableChar_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_ResultMapping_escapeNonPrintableChar_feature", "_UI_ResultMapping_type"),
                 DsPackage.Literals.RESULT_MAPPING__ESCAPE_NON_PRINTABLE_CHAR,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE,
                 null,
                 null));
    }

	/**
     * This adds a property descriptor for the Xslt Path feature.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */
	protected void addXsltPathPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_ResultMapping_xsltPath_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_ResultMapping_xsltPath_feature", "_UI_ResultMapping_type"),
                 DsPackage.Literals.RESULT_MAPPING__XSLT_PATH,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 null,
                 null));
    }

	/**
     * This adds a property descriptor for the Output Type feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addOutputTypePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_ResultMapping_outputType_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_ResultMapping_outputType_feature", "_UI_ResultMapping_type"),
                 DsPackage.Literals.RESULT_MAPPING__OUTPUT_TYPE,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 null,
                 null));
    }

    /**
	 * This specifies how to implement {@link #getChildren} and is used to
	 * deduce an appropriate feature for an
	 * {@link org.eclipse.emf.edit.command.AddCommand},
	 * {@link org.eclipse.emf.edit.command.RemoveCommand} or
	 * {@link org.eclipse.emf.edit.command.MoveCommand} in
	 * {@link #createCommand}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 *
	 * @generated NOT
	 */

	@Override
	public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
		if (childrenFeatures == null) {
			super.getChildrenFeatures(object);
			// childrenFeatures.add(DsPackage.Literals.RESULT_MAPPING__MIXED);
			childrenFeatures.add(DsPackage.Literals.RESULT_MAPPING__ELEMENT);
			childrenFeatures.add(DsPackage.Literals.RESULT_MAPPING__ATTRIBUTE);
			childrenFeatures.add(DsPackage.Literals.RESULT_MAPPING__CALL_QUERY);
		}
		return childrenFeatures;
	}

	/**
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */

	@Override
	protected EStructuralFeature getChildFeature(Object object, Object child) {
        // Check the type of the specified child object and return the proper feature to use for
        // adding (see {@link AddCommand}) it as a child.

        return super.getChildFeature(object, child);
    }

	/**
	 * This returns ResultMapping.gif.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 *
	 * @generated NOT
	 */

	public Object getImage(Object object) {
		return overlayImage(object, getResourceLocator().getImage("wso2/result"));
	}

	/**
	 * This returns the label text for the adapted class.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 *
	 * @generated NOT
	 */

	public String getText(Object object) {
		String label = ((ResultMapping) object).getElementName();
		String type = " (" + getString("_UI_ResultMapping_type") + ")";
		return label != null ? label.toString() + type : type;

	}

	/**
     * This handles model notifications by calling {@link #updateChildren} to update any cached
     * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */

	@Override
	public void notifyChanged(Notification notification) {
        updateChildren(notification);

        switch (notification.getFeatureID(ResultMapping.class)) {
            case DsPackage.RESULT_MAPPING__DEFAULT_NAMESPACE:
            case DsPackage.RESULT_MAPPING__ELEMENT_NAME:
            case DsPackage.RESULT_MAPPING__ROW_NAME:
            case DsPackage.RESULT_MAPPING__USE_COLUMN_NUMBERS:
            case DsPackage.RESULT_MAPPING__ESCAPE_NON_PRINTABLE_CHAR:
            case DsPackage.RESULT_MAPPING__XSLT_PATH:
            case DsPackage.RESULT_MAPPING__OUTPUT_TYPE:
                fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
                return;
            case DsPackage.RESULT_MAPPING__MIXED:
            case DsPackage.RESULT_MAPPING__ELEMENT:
            case DsPackage.RESULT_MAPPING__ATTRIBUTE:
            case DsPackage.RESULT_MAPPING__CALL_QUERY:
                fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
                return;
        }
        super.notifyChanged(notification);
    }

	/**
     * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
     * that can be created under this object.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */

	@Override
	protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
        super.collectNewChildDescriptors(newChildDescriptors, object);

        newChildDescriptors.add
            (createChildParameter
                (DsPackage.Literals.RESULT_MAPPING__MIXED,
                 FeatureMapUtil.createEntry
                    (XMLTypePackage.Literals.XML_TYPE_DOCUMENT_ROOT__COMMENT,
                     "")));

        newChildDescriptors.add
            (createChildParameter
                (DsPackage.Literals.RESULT_MAPPING__MIXED,
                 FeatureMapUtil.createEntry
                    (XMLTypePackage.Literals.XML_TYPE_DOCUMENT_ROOT__TEXT,
                     "")));

        newChildDescriptors.add
            (createChildParameter
                (DsPackage.Literals.RESULT_MAPPING__MIXED,
                 FeatureMapUtil.createEntry
                    (XMLTypePackage.Literals.XML_TYPE_DOCUMENT_ROOT__PROCESSING_INSTRUCTION,
                     XMLTypeFactory.eINSTANCE.createProcessingInstruction())));

        newChildDescriptors.add
            (createChildParameter
                (DsPackage.Literals.RESULT_MAPPING__MIXED,
                 FeatureMapUtil.createEntry
                    (XMLTypePackage.Literals.XML_TYPE_DOCUMENT_ROOT__CDATA,
                     "")));

        newChildDescriptors.add
            (createChildParameter
                (DsPackage.Literals.RESULT_MAPPING__MIXED,
                 FeatureMapUtil.createEntry
                    (DsPackage.Literals.RESULT_MAPPING__ELEMENT,
                     DsFactory.eINSTANCE.createElementMapping())));

        newChildDescriptors.add
            (createChildParameter
                (DsPackage.Literals.RESULT_MAPPING__MIXED,
                 FeatureMapUtil.createEntry
                    (DsPackage.Literals.RESULT_MAPPING__ATTRIBUTE,
                     DsFactory.eINSTANCE.createAttributeMapping())));

        newChildDescriptors.add
            (createChildParameter
                (DsPackage.Literals.RESULT_MAPPING__MIXED,
                 FeatureMapUtil.createEntry
                    (DsPackage.Literals.RESULT_MAPPING__CALL_QUERY,
                     DsFactory.eINSTANCE.createCallQuery())));

        newChildDescriptors.add
            (createChildParameter
                (DsPackage.Literals.RESULT_MAPPING__ELEMENT,
                 DsFactory.eINSTANCE.createElementMapping()));

        newChildDescriptors.add
            (createChildParameter
                (DsPackage.Literals.RESULT_MAPPING__ATTRIBUTE,
                 DsFactory.eINSTANCE.createAttributeMapping()));

        newChildDescriptors.add
            (createChildParameter
                (DsPackage.Literals.RESULT_MAPPING__CALL_QUERY,
                 DsFactory.eINSTANCE.createCallQuery()));
    }

	/**
     * This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */
	@Override
	public String getCreateChildText(Object owner, Object feature, Object child,
	                                 Collection<?> selection) {
        Object childFeature = feature;
        Object childObject = child;

        if (childFeature instanceof EStructuralFeature && FeatureMapUtil.isFeatureMap((EStructuralFeature)childFeature)) {
            FeatureMap.Entry entry = (FeatureMap.Entry)childObject;
            childFeature = entry.getEStructuralFeature();
            childObject = entry.getValue();
        }

        boolean qualify =
            childFeature == DsPackage.Literals.RESULT_MAPPING__ELEMENT ||
            childFeature == DsPackage.Literals.RESULT_MAPPING__ATTRIBUTE ||
            childFeature == DsPackage.Literals.RESULT_MAPPING__CALL_QUERY;

        if (qualify) {
            return getString
                ("_UI_CreateChild_text2",
                 new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) });
        }
        return super.getCreateChildText(owner, feature, child, selection);
    }

	/**
     * Return the resource locator for this item provider's resources.
     * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
     * @generated
     */

	@Override
	public ResourceLocator getResourceLocator() {
        return DsEditPlugin.INSTANCE;
    }

}


text:
<?php
	require '../../include/common/core.inc.php';
	require '../../include/common/loggedinT.php';
	require '../../adminpanel/include/common/dbhelper.inc.php';
	require '../../include/modules/teacher/teacher.inc.php';

	$db = new dbHelper;
	$db->ud_connectToDB();

	$banner = true;
	if(isset($_GET['subjectID']) && !empty($_GET['subjectID']))
	{
		$courseID = $_GET['subjectID'];
	}
	else
	{
		header('location:index.php');
	}
	$course = array();
	$result = $db->ud_getQuery('SELECT * FROM `ud_subject` s JOIN `ud_subjects_users` u ON s.subjectID = u.subjectID WHERE u.subjectID = '.$courseID.' AND u.userID = '.$_SESSION['userID']);
	if( $db->ud_getRowCountResult($result)==0)
	{
		header('location:index.php');
	}
	else
	{
		$course = $db->ud_mysql_fetch_assoc($result);
		updateAcc($course['subjectID']);

		//	Category
		$result = $db->ud_getQuery('SELECT * FROM `ud_subject_category` c LEFT JOIN (SELECT questionCatID,count(questionID) FROM `ud_question` GROUP BY questionCatID) x ON c.categoryID = x.questionCatID WHERE c.userID = \''.$_SESSION['userID'].'\' AND c.subjectID = \''.$course['subjectID'].'\'');
		$category = $db->ud_mysql_fetch_assoc_all($result);
	}

?>
<!DOCTYPE html>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title><?php echo $_SESSION['userLogin'] ?> - Home</title>

<meta content="" name="description" />
<meta content="" name="keywords" />
<meta content="" name="author" />

<?php require '../../include/header/foundation.php'; ?>
<?php require '../../include/header/datatable.php'; ?>

<?php require '../../include/header/headerT.php'; ?>

Add/Modify Category

			<input type="text" name="category" placeholder="Category Title"/>

			<div class="radius button" style="height:32px;" id="add-category" rowcount="<?php echo sizeof($category); ?>">Add

						#
						Category
						Count
						Action

				<?php
				for($i=0;$i<sizeof($category);$i++)
				{
					if(empty($category[$i]['count(questionID)']))
					{
						$category[$i]['count(questionID)'] = '-';
					}
				?>

<?php echo ($i+1); ?>

<?php echo $category[$i]['category'] ?>

						<?php echo $category[$i]['count(questionID)']; ?>

							<?php
								if($category[$i]['categoryDefault'] == 1)
								{
									echo '-';
								}
								else
								{

							?>
							<div class="category-id" id="<?php echo $category[$i]['categoryID'] ?>" row="<?php echo ($i+1); ?>">
								<input type="button" class="edit-button">
								<input type="button" class="delete-button">

							<?php
								}
							?>

				<?php
				}
				?>

<?php require '../../include/footer/footerT.php'; ?>


text:
Aria.classDefinition({
    $classpath : "test.aria.core.io.FormSubmit",
    $extends : "aria.jsunit.TestCase",
    $dependencies : ["test.aria.core.test.IOFilterSample", "aria.utils.Dom", "aria.utils.String", "aria.utils.Xml"],
    $constructor : function () {
        this.$TestCase.constructor.call(this);
        this.request = {};
    },
    $prototype : {
        /**
         * Adds listeners when test is run
         */
        setUp : function () {
            aria.core.IO.$on({
                '*' : this.checkEvent,
                'request' : this.onEvent,
                'response' : this.onEvent,
                scope : this
            });
            this.eventsState = 0;
        },

        /**
         * Resets any transport configuration, removes any listeners, and removes timers.
         */
        tearDown : function () {
            // make sure the form is removed from the DOM:
            aria.utils.Dom.replaceHTML("TESTAREA", "");

            aria.core.IO.$unregisterListeners(this);
            this.url = null;

            // Check that we didn't forget any timer on IO
            var timers = 0, id;
            for (id in aria.core.IO._poll) {
                if (aria.core.IO._poll.hasOwnProperty(id)) {
                    timers += 1;
                }
            }
            for (id in aria.core.IO._timeOut) {
                if (aria.core.IO._timeOut.hasOwnProperty(id)) {
                    timers += 1;
                }
            }

            this.request = {};

            this.assertEquals(timers, 0, "Undisposed timers on aria.core.IO");
        },

        /**
         * Event catcher for a specific url.
         * @param {Object} evt
         */
        onEvent : function (evt) {
            if (evt.req.url == this.url) {
                // we only catch events which come for the specified URL
                try {
                    if (evt.name == 'request') {
                        this.assertTrue(this.eventsState === 0);
                        this.eventsState = 1;
                    } else if (evt.name == 'response') {
                        this.assertTrue(this.eventsState === 1);
                        this.eventsState = 2;
                    }
                } catch (ex) {}
            }
        },

        /**
         * Used to test failed call of asyncFormSubmit (no form)
         */
        testAsyncFormSubmissionWithoutForm : function () {
            this._setFormRequestObject("testAsyncFormSubmissionWithoutForm", {
                success : false
            });
            this.request.callback.onerror = this._testAsyncFormSubmissionWithoutForm;
            aria.core.IO.asyncFormSubmit(this.request);
        },

        /**
         * Attempts to make a form submission when there is no html form defined in the page.
         */
        _testAsyncFormSubmissionWithoutForm : function () {
            this.assertErrorInLogs(aria.core.IO.MISSING_FORM);
            this.notifyTestEnd("testAsyncFormSubmissionWithoutForm");
        },

        /**
         * Makes a form submission using an html form element in the request
         */
        testAsyncFormSubmissionWithForm : function () {
            this._injectForm();
            this._setFormRequestObject("testAsyncFormSubmissionWithForm", {
                success : true
            });
            this.request.form = aria.utils.Dom.getElementById(this.request.formId);
            delete this.request.formId;
            aria.core.IO.asyncFormSubmit(this.request);
        },

        /**
         * Makes a form submission, expecting an XML response.
         */
        testAsyncFormSubmissionXmlResponse : function () {
            this._injectForm();
            this._setFormRequestObject("testAsyncFormSubmissionXmlResponse", {
                success : true,
                expectsXml : true
            });
            this.request.url = Aria.rootFolderPath + "test/aria/core/test/TestFile.xml";
            aria.core.IO.asyncFormSubmit(this.request);
        },

        /**
         * Makes a form submission using a form name in the request
         */
        testAsyncFormSubmissionWithFormId : function () {
            this._injectForm();
            this._setFormRequestObject("testAsyncFormSubmissionWithFormId", {
                success : true
            });
            aria.core.IO.asyncFormSubmit(this.request);
        },

        /**
         * Uses a timeout to test the request abort
         */
        testAsyncFormSubmissionWithTimeout : function () {
            this._injectForm();
            aria.core.IO.$onOnce({
                "abortEvent" : {
                    fn : this._ioAbortWithTimeout,
                    scope : this,
                    args : {
                        testName : "testAsyncFormSubmissionWithTimeout"
                    }
                }
            });

            aria.core.IO.asyncFormSubmit({
                formId : "simulateAsyncFormSubmit",
                callback : {
                    fn : this._failWithTimeout,
                    onerror : this._abortWithTimeout,
                    scope : this,
                    args : {
                        testName : "testAsyncFormSubmissionWithTimeout"
                    }
                },
                timeout : 1
            });
        },

        _failWithTimeout : function (args) {
            this.assertTrue(false, "Form shouldn't be submitted");
        },

        _abortWithTimeout : function (response, args) {
            this.assertEquals(response.status, 0);
            this.assertEquals(response.statusText, aria.core.IO.TIMEOUT_ERROR);
            this.assertEquals(response.req.formId, "simulateAsyncFormSubmit");
            this.assertTrue(this.__abortEventCalled, "Evento was not raised");

            // Wait a little buit just to check that the response callback is not called
            aria.core.Timer.addCallback({
                fn : function () {
                    this.notifyTestEnd(args.testName);
                },
                scope : this
            });
        },

        _ioAbortWithTimeout : function () {
            this.__abortEventCalled = true;
        },

        /**
         * Uses a filter for the request and the response to change the type of request to use a different transport.
         * Also changes the timeout, url, and the response status.
         */
        testAsyncFormSubmissionWithFilter : function () {
            this._injectForm();
            this._setFormRequestObject("testAsyncFormSubmissionWithFilter", {
                success : false
            });

            // add a filter to change the type of request to use a different transport
            aria.core.IOFiltersMgr.addFilter({
                classpath : "test.aria.core.test.IOFilterSample",
                initArgs : {
                    onRequest : function (req) {
                        delete req.form;// remove formId will be treated as a file request using the local
                        // transport
                        req.timeout = 1000;// change timeout from the default of 6 secs to 1 sec to speed up the test
                        req.url = req.url + "x";// change url to a non existent file
                    },
                    onResponse : function (req) {
                        req.res.status = -1;// changing the response status
                    }
                }
            });
            aria.core.IO.asyncFormSubmit(this.request);
        },

        /**
         * Helper to set the request object
         * @param {String} testName
         * @protected
         */
        _setFormRequestObject : function (testName, expectedResult) {
            this.request = {
                formId : "simulateAsyncFormSubmit",
                callback : {
                    fn : this._testFormHandlerSuccess,
                    onerror : this._testFormHandlerError,
                    scope : this,
                    args : {
                        testName : testName,
                        expectedResult : expectedResult
                    }
                }
            };
        },

        /**
         * Helper to create the mock form
         * @protected
         */
        _injectForm : function () {
            aria.utils.Dom.replaceHTML("TESTAREA", "<form enctype='multipart/form-data' name='simulateAsyncFormSubmit' id='simulateAsyncFormSubmit' method='POST' action='"
                    + Aria.rootFolderPath
                    + "test/aria/core/test/TestFile.html'><input type='text' id='simulateAsyncFileUpload' name='simulateAsyncFileUpload' value='test.txt' style='-moz-opacity:0;filter:alpha(opacity: 0);opacity: 0;'></form>");
        },

        /**
         * Callback used when request was successful
         * @param {Object} request
         * @protected
         */
        _testFormHandlerSuccess : function (response, args) {
            try {
                var expectedResult = args.expectedResult;
                this.assertTrue(expectedResult.success, "Expecting a failure and got a success.");
                this.assertTrue(response.status === 200);
                this.assertTrue(aria.utils.Type.isString(response.responseText), "responseText must be a string");
                if (expectedResult.expectsXml) {
                    var docElement = response.responseXML.documentElement;
                    this.assertTrue(docElement.nodeName == "response");
                    var json = aria.utils.Xml.convertXmlNodeToJson(docElement);
                    this.assertTrue(json.content1 == "<Hello world!>");
                } else {
                    this.assertTrue(aria.utils.String.trim(response.responseText) == "Test file content. <=<  >=>.Tags: <b>in a <b> tag</b>.");
                }
                this._removeFilter();
                this.notifyTestEnd(args.testName);
            } catch (e) {
                this.handleAsyncTestError(e);
            }
        },

        /**
         * Callback used when request failed
         * @param {Object} request
         * @protected
         */
        _testFormHandlerError : function (response, args) {
            try {
                var expectedResult = args.expectedResult;
                this.assertFalse(expectedResult.success, "Expecting a success and got a failure.");
                this.assertTrue(response.status === -1);
                this._removeFilter();
                this.notifyTestEnd(args.testName);
            } catch (e) {
                this.handleAsyncTestError(e);
            }
        },

        /**
         * Removes a filter when there is one present
         * @protected
         */
        _removeFilter : function () {
            if (aria.core.IOFiltersMgr.isFilterPresent("test.aria.core.test.IOFilterSample")) {
                var res = aria.core.IOFiltersMgr.removeFilter("test.aria.core.test.IOFilterSample");
                this.assertTrue(res);
            }
        }
    }
});


text:
package org.apache.struts2.views.freemarker.tags;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.components.Component;
import org.apache.struts2.components.OptionTransferSelect;

import com.opensymphony.xwork2.util.ValueStack;

/**
 * @see OptionTransferSelect
 */
public class OptionTransferSelectModel extends TagModel {

    public OptionTransferSelectModel(ValueStack stack, HttpServletRequest req, HttpServletResponse res) {
        super(stack, req, res);
    }

    protected Component getBean() {
        return new OptionTransferSelect(stack, req, res);
    }

}


text:
package org.apache.jackrabbit.oak.plugins.document;

import java.io.Closeable;
import java.io.IOException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.jackrabbit.oak.commons.FixturesHelper;
import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore;
import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBDataSourceFactory;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBDataSourceWrapper;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBDocumentStore;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBOptions;
import org.apache.jackrabbit.oak.plugins.document.util.MongoConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

import static org.apache.jackrabbit.oak.commons.FixturesHelper.Fixture.DOCUMENT_MEM;
import static org.apache.jackrabbit.oak.commons.FixturesHelper.Fixture.DOCUMENT_NS;
import static org.apache.jackrabbit.oak.commons.FixturesHelper.Fixture.DOCUMENT_RDB;

public abstract class DocumentStoreFixture {

    private static final Logger LOG = LoggerFactory.getLogger(DocumentStoreFixture.class);

    public static final DocumentStoreFixture MEMORY = new MemoryFixture();
    public static final DocumentStoreFixture MONGO = new MongoFixture();

    public static final DocumentStoreFixture RDB_DB2 = new RDBFixture("RDB-DB2", System.getProperty("rdb-db2-jdbc-url",
            "jdbc:db2://localhost:50000/OAK"), System.getProperty("rdb-db2-jdbc-user", "oak"), System.getProperty(
            "rdb-db2-jdbc-passwd", "geheim"));
    public static final DocumentStoreFixture RDB_DERBY = new RDBFixture("RDB-Derby(embedded)", System.getProperty(
            "rdb-derby-jdbc-url", "jdbc:derby:./target/derby-ds-test;create=true"),
            System.getProperty("rdb-derby-jdbc-user", "sa"), System.getProperty("rdb-derby-jdbc-passwd", ""));
    public static final DocumentStoreFixture RDB_H2 = new RDBFixture("RDB-H2(file)", System.getProperty("rdb-h2-jdbc-url",
            "jdbc:h2:file:./target/h2-ds-test"), System.getProperty("rdb-h2-jdbc-user", "sa"), System.getProperty(
            "rdb-h2-jdbc-passwd", ""));
    public static final DocumentStoreFixture RDB_MSSQL = new RDBFixture("RDB-MSSql", System.getProperty("rdb-mssql-jdbc-url",
            "jdbc:sqlserver://localhost:1433;databaseName=OAK"), System.getProperty("rdb-mssql-jdbc-user", "sa"),
            System.getProperty("rdb-mssql-jdbc-passwd", "geheim"));
    public static final DocumentStoreFixture RDB_MYSQL = new RDBFixture("RDB-MySQL", System.getProperty("rdb-mysql-jdbc-url",
            "jdbc:mysql://localhost:3306/oak"), System.getProperty("rdb-mysql-jdbc-user", "root"), System.getProperty(
            "rdb-mysql-jdbc-passwd", "geheim"));
    public static final DocumentStoreFixture RDB_ORACLE = new RDBFixture("RDB-Oracle", System.getProperty("rdb-oracle-jdbc-url",
            "jdbc:oracle:thin:@localhost:1521:orcl"), System.getProperty("rdb-oracle-jdbc-user", "system"), System.getProperty(
            "rdb-oracle-jdbc-passwd", "geheim"));
    public static final DocumentStoreFixture RDB_PG = new RDBFixture("RDB-Postgres", System.getProperty("rdb-postgres-jdbc-url",
            "jdbc:postgresql:oak"), System.getProperty("rdb-postgres-jdbc-user", "postgres"), System.getProperty(
            "rdb-postgres-jdbc-passwd", "geheim"));

    public static final String TABLEPREFIX = "dstest_";

    public static List<Object[]> getFixtures() {
        List<Object[]> fixtures = Lists.newArrayList();
        if (FixturesHelper.getFixtures().contains(DOCUMENT_MEM)) {
            fixtures.add(new Object[] { new DocumentStoreFixture.MemoryFixture() });
        }

        DocumentStoreFixture mongo = new DocumentStoreFixture.MongoFixture();
        if (FixturesHelper.getFixtures().contains(DOCUMENT_NS) && mongo.isAvailable()) {
            fixtures.add(new Object[] { mongo });
        }

        DocumentStoreFixture rdb = new DocumentStoreFixture.RDBFixture();
        if (FixturesHelper.getFixtures().contains(DOCUMENT_RDB) && rdb.isAvailable()) {
            fixtures.add(new Object[] { rdb });
        }
        return fixtures;
    }

    public abstract String getName();

    public abstract DocumentStore createDocumentStore(DocumentMK.Builder builder);

    public DocumentStore createDocumentStore(int clusterId) {
        return createDocumentStore(new DocumentMK.Builder().setClusterId(clusterId));
    }

    public DocumentStore createDocumentStore() {
        return createDocumentStore(new DocumentMK.Builder().setClusterId(1));
    }

    public boolean isAvailable() {
        return true;
    }

    // get underlying datasource if RDB persistence
    public DataSource getRDBDataSource() {
        return null;
    }

    // return false if the multiple instances will not share the same persistence
    public boolean hasSinglePersistence() {
        return true;
    }

    public String toString() {
        return getClass().getSimpleName() + ": "+ getName();
    }

    public void dispose() throws Exception {
    }

    public static class MemoryFixture extends DocumentStoreFixture {

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

        @Override
        public DocumentStore createDocumentStore(DocumentMK.Builder builder) {
            return new MemoryDocumentStore();
        }

        @Override
        public boolean hasSinglePersistence() {
            return false;
        }
    }

    public static class RDBFixture extends DocumentStoreFixture {

        DataSource dataSource;
        DocumentStore store1, store2;
        String name;
        RDBOptions options = new RDBOptions().tablePrefix(TABLEPREFIX).dropTablesOnClose(true);

        public RDBFixture() {
            // default RDB fixture
            this("RDB-H2(file)", "jdbc:h2:file:./target/ds-test2", "sa", "");
        }

        public RDBFixture(String name, String url, String username, String passwd) {
            this.name = name;
            try {
                dataSource = new RDBDataSourceWrapper(RDBDataSourceFactory.forJdbcUrl(url, username, passwd));
            } catch (Exception ex) {
                LOG.info("Database instance not available at " + url + ", skipping tests...", ex);
            }
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public DocumentStore createDocumentStore(DocumentMK.Builder builder) {
            if (builder.getClusterId() == 1) {
                store1 = new RDBDocumentStore(dataSource, builder, options);
                return store1;
            } else if (builder.getClusterId() == 2) {
                store2 = new RDBDocumentStore(dataSource, builder, options);
                return store2;
            } else {
                throw new RuntimeException("expect clusterId == 1 or == 2");
            }
        }

        @Override
        public boolean isAvailable() {
            return dataSource != null;
        }

        @Override
        public DataSource getRDBDataSource() {
            return dataSource;
        }

        @Override
        public void dispose() {
            if (dataSource instanceof Closeable) {
                try {
                    ((Closeable)dataSource).close();
                }
                catch (IOException ignored) {
                }
            }
        }

        public void setRDBOptions(RDBOptions options) {
            this.options = options;
        }
    }

    public static class MongoFixture extends DocumentStoreFixture {
        protected List<MongoConnection> connections = Lists.newArrayList();

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

        @Override
        public DocumentStore createDocumentStore(DocumentMK.Builder builder) {
            try {
                MongoConnection connection = MongoUtils.getConnection();
                connections.add(connection);
                return new MongoDocumentStore(connection.getMongoClient(),
                        connection.getDatabase(), builder);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public boolean isAvailable() {
            return MongoUtils.isAvailable();
        }

        @Override
        public void dispose() {
            try {
                MongoUtils.dropCollections(MongoUtils.DB);
            } catch (Exception ignore) {
            }
            for (MongoConnection c : connections) {
                try {
                    c.close();
                } catch (IllegalStateException e) {
                    // may happen when connection is already closed (OAK-7447)
                }
            }
            connections.clear();
        }
    }
}


text:
using ColladaXna.Base;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;

namespace Base_Tests
{

    ///
    ///This is a test class for ColladaModelTest and is intended
    ///to contain all ColladaModelTest Unit Tests
    ///
    [TestClass()]
    public class ColladaModelTest
    {

        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion

        ///
        ///A test for ColladaModel Constructor
        ///
        [TestMethod()]
        public void ColladaModelConstructorTest()
        {
            string filename = TestDataLoader.GetTestFilePath("APC_animation.DAE");
            Assert.IsTrue(File.Exists(filename), (new FileInfo(filename).FullName) + " does not exist");

            ColladaModel target = new ColladaModel(filename);
        }
    }
}


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2014 Danny Sale and Michael Lawson
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function HARP_Opt(inputFile)
%HARP_Opt Horizontal Axis Rotor Performance Optimization.
%  _   _  ___ ____________        _____       _
% | | | |/ _ \| ___ | ___ \      |  _  |     | |
% | |_| / /_\ | |_/ | |_/ /      | | | |_ __ | |_
% |  _  |  _  |    /|  __/       | | | | '_ \| __|
% | | | | | | | |\ \| |          \ \_/ | |_) | |_
% \_| |_\_| |_\_| \_\_|           \___/| .__/ \__|
%                         ______       | |
%                        |______|      |_|
%
%   HARP_Opt(inputFile) executes the HARP_Opt code for the input file
%   named by the string inputFile (with the file extension included).
%
%   If using the compiled version of HARP_Opt (because you do not have
%   access to the required toolboxes) type the command:
%   HARP_Opt.exe inputFile
%   at the command prompt, where inputFile is the input file.

% Add the source code directory
if ~isdeployed
    % Everything in this directory is maintained by the HARP_Opt developers
    addpath([pwd filesep 'Source']);
    % These are external dependencies of HARP_Opt
    addpath([pwd filesep 'Source' filesep 'akima']);
    addpath([pwd filesep 'Source' filesep 'fminsearchbnd']);
    addpath([pwd filesep 'Source' filesep 'psopt']);
    addpath([pwd filesep 'Source' filesep 'xlwrite']);
        javaaddpath([pwd filesep 'Source' filesep 'xlwrite' filesep 'poi_library/poi-3.8-20120326.jar']);
        javaaddpath([pwd filesep 'Source' filesep 'xlwrite' filesep 'poi_library/poi-ooxml-3.8-20120326.jar']);
        javaaddpath([pwd filesep 'Source' filesep 'xlwrite' filesep 'poi_library/poi-ooxml-schemas-3.8-20120326.jar']);
        javaaddpath([pwd filesep 'Source' filesep 'xlwrite' filesep 'poi_library/xmlbeans-2.3.0.jar']);
        javaaddpath([pwd filesep 'Source' filesep 'xlwrite' filesep 'poi_library/dom4j-1.6.1.jar']);
end

% Add debug points
% dbstop HARP_Opt 97
% dbstop HARP_Opt_init 7
% dbstop optAero 9
% dbstop optStruct 1
% dbstop find_pitch 65
% dbstop outputFun_GA.m 128
% dbstop optFitness 4
% dbstop writeOupFileXLS 21

% Read the data and initialize the required variables
[BLADE,CAV,ENV,OPT,SIM,TURB,WTP] = HARP_Opt_Init(inputFile);

% Initialize the optimization algorithms
% Read the input file and set the opt algorithm options
[OPT.options]   = parseOptimizationOptions(SIM.optFile);
optPlotFun      = {};
optCustomOutput = [];
switch OPT.ALG
    case 'GradientSearch'
        if OPT.PLOT_ITER
            optPlotFun        = {@optimplotx,@optimplotfunccount,@optimplotfval,@optimplotconstrviolation,@optimplotstepsize,@optimplotfirstorderopt};
%             optCustomOutput = @(x,optimValues,state) outputGradientSearch(x, optimValues, state, otherInputs?);
        end
        OPT.options = optimset(OPT.options, ...
                              'OutputFcns', optCustomOutput, ...
                              'PlotFcns',   optPlotFun, ...
                              'TypicalX',   OPT.x0);

    case 'PatternSearch'
        if OPT.PLOT_ITER
            optPlotFun        = {@psplotbestf, @psplotmeshsize ,@psplotfuncount, @psplotbestx};
%             optCustomOutput = @(optimvalues, options, flag) outputPatternSearch(optimvalues, options, flag, otherInputs?);
%             optCustomOutput = @(options, state, flag) outputFun_GA(options, state, flag, ...
%                                                                    BLADE,CAV,ENV,OPT,SIM,TURB,WTP);
        end
        OPT.options = psoptimset(OPT.options, ...
                                'OutputFcns', optCustomOutput, ...
                                'PlotFcns',   optPlotFun);

    case 'ParticleSwarm'
        % find a feasible initial population
        initPop      = constrainedRandomVector(OPT.options.PopulationSize,OPT.lb,OPT.ub,OPT.Aineq,OPT.bineq);
        initPop(:,1) = OPT.x0(:); % include our "modified" Glauert optimum blade in the initial population

        if OPT.PLOT_ITER
            optPlotFun        = {@psoplotbestf};
%             optCustomOutput = @(optimvalues, options, flag) outputParticleSwarm(optimvalues, options, flag, otherInputs?);
        end
        OPT.options = psooptimset(OPT.options, ...
                                 'OutputFcns',        optCustomOutput, ...
                                 'PlotFcns',          optPlotFun, ...
                                 'InitialPopulation', initPop');

    case 'GeneticAlgorithm'
        % find a feasible initial population
        initPop      = constrainedRandomVector(OPT.options.PopulationSize,OPT.lb,OPT.ub,OPT.Aineq,OPT.bineq);
        initPop(:,1) = OPT.x0(:); % include our "modified" Glauert optimum blade in the initial population

        if OPT.PLOT_ITER
            optPlotFun      = {@gaplotbestf, @gaplotbestindiv, @gaplotdistance, @gaplotmaxconstr, @gaplotscores};
            optCustomOutput = @(options, state, flag) outputFun_GA(options, state, flag, ...
                                                                   BLADE,CAV,ENV,OPT,SIM,TURB,WTP);
        end
        OPT.options = gaoptimset(OPT.options, ...
                                'OutputFcns',        optCustomOutput, ...
                                'PlotFcns',          optPlotFun, ...
                                'InitialPopulation', initPop');

    case 'MOGeneticAlgorithm'
        % find a feasible initial population
        initPop      = constrainedRandomVector(OPT.options.PopulationSize,OPT.lb,OPT.ub,OPT.Aineq,OPT.bineq);
        initPop(:,1) = OPT.x0(:); % include our "modified" Glauert optimum blade in the initial population

        if OPT.PLOT_ITER
            optPlotFun      = {@gaplotpareto};
            optCustomOutput = @(options, state, flag) outputFun_custom(options, state, flag, ...
                                                                       BLADE,CAV,ENV,OPT,SIM,TURB,WTP);
        end
        OPT.options = gaoptimset(OPT.options, ...
                                'OutputFcns',        optCustomOutput, ...
                                'PlotFcns',          optPlotFun, ...
                                'InitialPopulation', initPop');

end

% need a function to accept variable inputs from the various optimization
% algorithms.  Unfortunately, each algorithm uses non-standard definitions
% for state, flag, optimvalues
% but really, all I need is
% (x,optimValues?,state) = the fitness values
% (flag) = the current state of the algorithm
% (others) = variables defined outside the scope of the optimization algorithms functions
% switch OPT.ALG
%     case 'GradientSearch'
%         optCustomOutput = @(x,optimValues,state) outputGradientSearch(x, optimValues, state, otherInputs?);
%         options =
%         state   =
%         flag    =
%     case 'PatternSearch'
%         optCustomOutput = @(optimvalues, options, flag) outputPatternSearch(optimvalues, options, flag, otherInputs?);
%         options =
%         state   =
%         flag    =
%     case 'ParticleSwarm'
%         optCustomOutput = @(optimvalues, options, flag) outputParticleSwarm(optimvalues, options, flag, otherInputs?);
%         options =
%         state   =
%         flag    =
%     case 'GeneticAlgorithm'
%         optCustomOutput = @(options, state, flag) outputFun_GA(options, state, flag, ...
%                             'InitialPopulation', initPop');
%         options =
%         state   =
%         flag    =
%     case 'MOGeneticAlgorithm'
%         optCustomOutput = @(options, state, flag) outputFun_GA(options, state, flag, ...
%                                                                BLADE,CAV,ENV,OPT,SIM,TURB,WTP);
%         options =
%         state   =
%         flag    =
%     otherwise
%
% end

%% Run the optimization
switch OPT.ALG
    case 'GradientSearch';     [OPT.xBest, OPT.fval, OPT.exitflag, OPT.output]                                =       fmincon(OPT.objective, OPT.x0,      OPT.Aineq, OPT.bineq, [], [], OPT.lb, OPT.ub, [], OPT.options);
    case 'PatternSearch';      [OPT.xBest, OPT.fval, OPT.exitflag, OPT.output]                                = patternsearch(OPT.objective, OPT.x0,      OPT.Aineq, OPT.bineq, [], [], OPT.lb, OPT.ub, [], OPT.options);
    case 'ParticleSwarm';      [OPT.xBest, OPT.fval, OPT.exitflag, OPT.output, OPT.finalPop, OPT.finalScores] =           pso(OPT.objective, OPT.numVars, OPT.Aineq, OPT.bineq, [], [], OPT.lb, OPT.ub, [], OPT.options);
    case 'GeneticAlgorithm';   [OPT.xBest, OPT.fval, OPT.exitFlag, OPT.output, OPT.finalPop, OPT.finalScores] =            ga(OPT.objective, OPT.numVars, OPT.Aineq, OPT.bineq, [], [], OPT.lb, OPT.ub, [], OPT.options);
    case 'MOGeneticAlgorithm'; [OPT.xBest, OPT.fval, OPT.exitFlag, OPT.output, OPT.finalPop, OPT.finalScores] =    gamultiobj(OPT.objective, OPT.numVars, OPT.Aineq, OPT.bineq, [], [], OPT.lb, OPT.ub,     OPT.options);
    otherwise
        error('ERROR: Unrecognized value for OPT.ALG');
end

%% postProcessing
HARP_Opt_PostProcess(BLADE,CAV,ENV,OPT,SIM,TURB,WTP);

%% Final clean-up
fprintf(1, ['HARP_Opt version ' SIM.version ' terminated normally for case ' SIM.tag '.\n']);
diary OFF
fclose all;
close all;

end % function HARP_Opt


text:
"""Salt worker main test module."""
from __future__ import (absolute_import, division, print_function,
                        unicode_literals, with_statement)

import os
import sys

import pytest

from watchmaker.exceptions import InvalidValue
from watchmaker.workers.salt import SaltBase, SaltLinux, SaltWindows

try:
    from unittest.mock import MagicMock, call, patch
except ImportError:
    from mock import MagicMock, call, patch

@pytest.fixture
def saltworker_client():
    """Return salt worker arguments."""
    system_params = {}
    salt_config = {}

    return SaltBase(system_params, **salt_config)

@pytest.fixture
def saltworker_base_salt_args():
    """Return base arguments for salt-call."""
    return [
        '--log-file', 'salt_call.debug.log',
        '--log-file-level', 'debug',
        '--log-level', 'error',
        '--out', 'quiet',
        '--return', 'local'
    ]

def test_default_valid_environments(saltworker_client):
    """
    Ensure valid_environment checks work as expected.

    Args:
        saltworker_client: (:obj:`src.workers.SaltBase`)

    """
    # test that the defaults work
    assert saltworker_client.before_install() is None

def test_bogus_environment(saltworker_client):
    """
    Ensure a bogus environment throws InvalidValue.

    Args:
        saltworker_client: (:obj:`src.workers.SaltBase`)

    """
    # ensure InvalidValue is raised when a bogus environment type is selected
    with pytest.raises(InvalidValue):
        saltworker_client.ent_env = "bogus"
        saltworker_client.valid_envs = [None, "dev", "test", "prod"]
        saltworker_client.before_install()

def test_valid_environment(saltworker_client):
    """
    Ensure that an environment within valid_environments works as expected.

    Args:
        saltworker_client: (:obj:`src.workers.SaltBase`)

    """
    saltworker_client.ent_env = "dev"
    saltworker_client.valid_envs = [None, "dev", "test", "prod"]
    assert saltworker_client.before_install() is None

def test_salt_client_defaults():
    """
    Check SaltClient default values.

    Args:
        saltworker_client: (:obj:`src.workers.SaltBase`)

    """
    system_params = {}
    salt_config = {}

    saltworker_client = SaltBase(system_params, **salt_config)
    assert saltworker_client.salt_states == 'highstate'

def test_salt_client_none():
    """
    Check SaltClient handles None values properly.

    Args:
        saltworker_client: (:obj:`src.workers.SaltBase`)

    """
    system_params = {}
    salt_config = {
        'salt_states': None
    }

    saltworker_client = SaltBase(system_params, **salt_config)
    assert saltworker_client.salt_states == ''

def test_salt_client_explicit_value():
    """
    Check SaltClient handles explicit values properly.

    Args:
        saltworker_client: (:obj:`src.workers.SaltBase`)

    """
    system_params = {}
    salt_config = {
        'salt_states': 'foo'
    }

    saltworker_client = SaltBase(system_params, **salt_config)
    assert saltworker_client.salt_states == 'foo'

def test_process_states_highstate(
    saltworker_client,
    saltworker_base_salt_args,
):
    """
    Run process_states with "highstate".

    Args:
        saltworker_client: (:obj:`src.workers.SaltBase`)

    """
    # setup
    states = 'highstate'
    exclude = None

    saltworker_client.run_salt = MagicMock(return_value={'retcode': 0})
    saltworker_client.salt_state_args = saltworker_base_salt_args

    expected = saltworker_client.salt_state_args + ['state.highstate']

    # test
    saltworker_client.process_states(states, exclude)

    # assertions
    saltworker_client.run_salt.assert_called_with(
        expected,
        log_pipe='stderr',
        raise_error=False
    )
    assert saltworker_client.run_salt.call_count == 1

def test_process_states_multiple_states(
    saltworker_client,
    saltworker_base_salt_args,
):
    """
    Run process_states with "foo,bar".

    Args:
        saltworker_client: (:obj:`src.workers.SaltBase`)

    """
    # setup
    states = 'foo,bar'
    exclude = None

    saltworker_client.run_salt = MagicMock(return_value={'retcode': 0})
    saltworker_client.salt_state_args = saltworker_base_salt_args

    expected = saltworker_client.salt_state_args + ['state.sls', 'foo,bar']

    # test
    saltworker_client.process_states(states, exclude)

    # assertions
    saltworker_client.run_salt.assert_called_with(
        expected,
        log_pipe='stderr',
        raise_error=False
    )
    assert saltworker_client.run_salt.call_count == 1

def test_process_states_multiple_states_case_sensitive(
    saltworker_client,
    saltworker_base_salt_args,
):
    """
    Run process_states with "Foo,bAR".

    Args:
        saltworker_client: (:obj:`src.workers.SaltBase`)

    """
    # setup
    states = 'Foo,bAR'
    exclude = None

    saltworker_client.run_salt = MagicMock(return_value={'retcode': 0})
    saltworker_client.salt_state_args = saltworker_base_salt_args

    expected = saltworker_client.salt_state_args + ['state.sls', 'Foo,bAR']

    # test
    saltworker_client.process_states(states, exclude)

    # assertions
    saltworker_client.run_salt.assert_called_with(
        expected,
        log_pipe='stderr',
        raise_error=False
    )
    assert saltworker_client.run_salt.call_count == 1

def test_process_states_highstate_extra_states(
    saltworker_client,
    saltworker_base_salt_args,
):
    """
    Run process_states with "highstate,foo,bar".

    Args:
        saltworker_client: (:obj:`src.workers.SaltBase`)

    """
    # setup
    states = 'highstate,foo,bar'
    exclude = None

    saltworker_client.run_salt = MagicMock(return_value={'retcode': 0})
    saltworker_client.salt_state_args = saltworker_base_salt_args

    call_1 = saltworker_client.salt_state_args + ['state.highstate']
    call_2 = saltworker_client.salt_state_args + ['state.sls', 'foo,bar']

    calls = [
        call(call_1, log_pipe='stderr', raise_error=False),
        call(call_2, log_pipe='stderr', raise_error=False),
    ]

    # test
    saltworker_client.process_states(states, exclude)

    # assertions
    saltworker_client.run_salt.assert_has_calls(calls)
    assert saltworker_client.run_salt.call_count == len(calls)

@patch.dict(os.environ, {"systemdrive": "C:",
                         "ProgramFiles": "C:\\Program Files"})
def test_windows_missing_prepdir():
    """Ensure that error raised when missing prep directory."""
    system_params = {}
    salt_config = {}

    system_params["logdir"] = "logdir"
    system_params["workingdir"] = "workingdir"

    with pytest.raises(KeyError, match="prepdir"):
        SaltWindows(system_params, **salt_config)

@patch.dict(os.environ, {"systemdrive": "C:",
                         "ProgramFiles": "C:\\Program Files"})
def test_windows_missing_logdir():
    """Ensure that error raised when missing log directory."""
    system_params = {}
    salt_config = {}

    system_params["prepdir"] = "prepdir"
    system_params["workingdir"] = "workingdir"

    with pytest.raises(KeyError, match="logdir"):
        SaltWindows(system_params, **salt_config)

@patch.dict(os.environ, {"systemdrive": "C:",
                         "ProgramFiles": "C:\\Program Files"})
def test_windows_missing_workingdir():
    """Ensure that error raised when missing working directory."""
    system_params = {}
    salt_config = {}

    system_params["logdir"] = "logdir"
    system_params["prepdir"] = "prepdir"

    with pytest.raises(KeyError, match="workingdir"):
        SaltWindows(system_params, **salt_config)

@patch.dict(os.environ, {"systemdrive": "C:",
                         "ProgramFiles": "C:\\Program Files"})
def test_windows_defaults():
    """Ensure that default values are populated as expected."""
    system_params = {}
    salt_config = {}

    system_params["prepdir"] = "8cbda638-6b60-5628-870b-40fdf8add9f8"
    system_params["logdir"] = "21fa57e2-9302-5934-978d-4ae40d5a2a55"
    system_params["workingdir"] = "c990ee27-ff12-5d7e-9957-1d27d114c0ff"

    salt_config["installer_url"] = "5de41ea1-902c-5e7c-ae86-89587057c6b3"
    salt_config["ash_role"] = "b116b3e1-ee3f-5a83-9dd1-3d01d0d5e343"

    win_salt = SaltWindows(system_params, **salt_config)

    # assertions ===================
    assert win_salt.installer_url == salt_config["installer_url"]
    assert win_salt.ash_role == salt_config["ash_role"]
    assert win_salt.salt_call == os.sep.join(("C:", "Salt", "salt-call.bat"))
    assert win_salt.salt_wam_root == os.sep.join(
        (system_params["prepdir"], "Salt"))
    assert win_salt.salt_conf_path == os.sep.join(
        (system_params["prepdir"], "Salt", "conf")
    )
    assert win_salt.salt_srv == os.sep.join(
        (system_params["prepdir"], "Salt", "srv"))
    assert win_salt.salt_win_repo == os.sep.join(
        (system_params["prepdir"], "Salt", "srv", "winrepo")
    )
    assert win_salt.salt_log_dir == system_params["logdir"]
    assert win_salt.salt_working_dir == system_params["workingdir"]
    assert win_salt.salt_working_dir_prefix == "Salt-"

    assert win_salt.salt_base_env == os.sep.join((win_salt.salt_srv, "states"))
    assert win_salt.salt_formula_root == os.sep.join(
        (win_salt.salt_srv, "formulas"))
    assert win_salt.salt_pillar_root == os.sep.join(
        (win_salt.salt_srv, "pillar"))
    assert win_salt.salt_conf["file_client"] == "local"
    assert win_salt.salt_conf["hash_type"] == "sha512"
    assert win_salt.salt_conf["pillar_roots"] == {
        "base": [str(os.sep.join((win_salt.salt_srv, "pillar")))]
    }
    assert win_salt.salt_conf["pillar_merge_lists"]
    assert win_salt.salt_conf["conf_dir"] == os.sep.join(
        (system_params["prepdir"], "Salt", "conf")
    )
    assert win_salt.salt_conf["winrepo_source_dir"] == "salt://winrepo"
    assert win_salt.salt_conf["winrepo_dir"] == os.sep.join(
        (system_params["prepdir"], "Salt", "srv", "winrepo", "winrepo")
    )

@patch.dict(os.environ, {"systemdrive": "C:",
                         "ProgramFiles": "C:\\Program Files"})
def test_windows_install(saltworker_base_salt_args):
    """Ensure that install runs as expected."""
    system_params = {}
    salt_config = {}
    system_params["prepdir"] = "0dcd877d-56cb-50c2-954a-80d1084b2216"
    system_params["logdir"] = "647c2a49-baf9-511b-a17a-d6ebf0edd91c"
    system_params["workingdir"] = "3d6ab2ef-09ad-59f1-a365-ee5f22c95c79"

    salt_config["installer_url"] = "20c913cf-d825-533e-8649-4ab2fed5d9c1"
    salt_config["ash_role"] = "f1d27775-9a3d-5e87-ab42-a79ac329ae4b"

    saltworker_win = SaltWindows(system_params, **salt_config)

    saltworker_win._prepare_for_install = MagicMock(return_value=None)
    saltworker_win.salt_state_args = saltworker_base_salt_args
    saltworker_win._install_package = MagicMock(return_value=None)
    saltworker_win.service_stop = MagicMock(return_value=None)
    saltworker_win._build_salt_formula = MagicMock(return_value=None)
    saltworker_win.service_disable = MagicMock(return_value=True)
    saltworker_win._set_grain = MagicMock(return_value=None)
    saltworker_win.process_grains = MagicMock(return_value=None)
    saltworker_win.run_salt = MagicMock(return_value={"retcode": 0})
    saltworker_win.working_dir = system_params["workingdir"]
    saltworker_win.cleanup = MagicMock(return_value=None)

    run_salt_calls = [
        call("pkg.refresh_db"),
        call(
            saltworker_win.salt_state_args + ['state.highstate'],
            log_pipe='stderr',
            raise_error=False
        ),
    ]

    # test
    saltworker_win.install()

    # assertions ===================
    assert saltworker_win._prepare_for_install.call_count == 1
    assert saltworker_win._install_package.call_count == 1
    saltworker_win.service_stop.assert_called_with("salt-minion")
    saltworker_win._build_salt_formula.assert_called_with(
        saltworker_win.salt_srv)
    saltworker_win.service_disable.assert_called_with("salt-minion")
    saltworker_win._set_grain.assert_called_with(
        "ash-windows", {"lookup": {"role": salt_config["ash_role"]}}
    )
    assert saltworker_win.process_grains.call_count == 1
    assert saltworker_win.run_salt.call_count == len(run_salt_calls)
    saltworker_win.run_salt.assert_has_calls(run_salt_calls)
    assert saltworker_win.cleanup.call_count == 1

@patch.dict(os.environ, {"systemdrive": "C:",
                         "ProgramFiles": "C:\\Program Files"})
@patch("os.path.isfile", MagicMock(return_value=False))
def test_windows_salt_call_old():
    """Ensure old path is tested."""
    salt_path = os.sep.join(("C:", 'Salt', 'salt-call.bat'))
    assert SaltWindows._get_salt_call() == salt_path

@patch.dict(os.environ, {"systemdrive": "C:",
                         "ProgramFiles": "C:\\Program Files"})
@patch("os.path.isfile", MagicMock(return_value=True))
def test_windows_salt_call_new():
    """Ensure new path is tested."""
    salt_path = os.sep.join(("C:\\Program Files", 'Salt Project',
                             'Salt', 'salt-call.bat'))
    assert SaltWindows._get_salt_call() == salt_path

@patch.dict(os.environ, {"systemdrive": "C:",
                         "ProgramFiles": "C:\\Program Files"})
@patch("codecs.open", autospec=True)
@patch("os.makedirs", autospec=True)
@patch("yaml.safe_dump", autospec=True)
def test_windows_prep_install(mock_safe, mock_makedirs, mock_codec):
    """Ensure that prep portion of install runs as expected."""
    system_params = {}
    salt_config = {}
    system_params["prepdir"] = "ac2bf0c3-7985-569f-bfbd-3a8d8a13ce7d"
    system_params["logdir"] = "5b0976f8-fcbc-50af-9459-8060589e70d9"
    system_params["workingdir"] = "860f630a-f85d-5ed2-bd7a-bbdb48a53b2b"

    salt_config["installer_url"] = "5f0c8635-4a10-5802-8145-732052a0b44b"
    salt_config["ash_role"] = "fddc3dc3-3684-5924-bf55-bb1dbc4e4c08"

    saltworker_win = SaltWindows(system_params, **salt_config)

    saltworker_win.create_working_dir = MagicMock(
        return_value=system_params["workingdir"]
    )
    saltworker_win._prepare_for_install()

    # assertions ===================
    saltworker_win.create_working_dir.assert_called_with(
        system_params["workingdir"], "Salt-"
    )
    mock_makedirs.assert_called_with(saltworker_win.salt_conf_path)
    mock_codec.assert_called_with(
        os.path.join(saltworker_win.salt_conf_path, "minion"),
        "w", encoding="utf-8"
    )
    mock_safe.assert_called_with(
        saltworker_win.salt_conf,
        mock_codec.return_value.__enter__(),
        default_flow_style=False,
    )

def test_linux_computer_name_none():
    """Test that Pythonic None can be used without error rather than 'None'."""
    # setup ========================
    system_params = {}
    salt_config = {}
    system_params["prepdir"] = "662f1bdb-5992-5f8f-87d6-15c4de958b7b"
    system_params["logdir"] = "76b74ceb-e81d-5fac-b293-0d7d45901ef7"
    system_params["workingdir"] = "4e6a1827-1d3b-5612-a7fd-f6fed00b5a2f"

    # try "normal" first, with a value. try with none below.
    salt_config["computer_name"] = "5f0c8635-4a10-5802-8145-732052a0b44b"

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)

    saltworker_lx._set_grain = MagicMock(return_value=None)
    saltworker_lx.run_salt = MagicMock(
        return_value={"retcode": 0, "stdout": b"", "stderr": b""}
    )

    saltworker_lx.process_grains()

    # assertions ===================
    assert saltworker_lx._set_grain.call_count == 3
    saltworker_lx._set_grain.assert_called_with(
        'name-computer', {'computername': salt_config["computer_name"]})

    # tried "normal" first, with a value, above. now, trying with none.
    salt_config["computer_name"] = None

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)

    saltworker_lx._set_grain = MagicMock(return_value=None)
    saltworker_lx.run_salt = MagicMock(
        return_value={"retcode": 0, "stdout": b"", "stderr": b""}
    )

    saltworker_lx.process_grains()

    # assertions ===================
    assert saltworker_lx._set_grain.call_count == 2

@patch("codecs.open", autospec=True)
@patch("os.makedirs", autospec=True)
@patch("yaml.safe_dump", autospec=True)
def test_linux_salt_debug_log_none(mock_safe, mock_makedirs, mock_codec):
    """Test that Pythonic None can be used without error rather than 'None'."""
    # setup ========================
    system_params = {}
    salt_config = {}
    system_params["prepdir"] = "d6f194e9-7cbc-5c89-9c9c-7ad43faf8a7b"
    system_params["logdir"] = "9523029a-b7a9-50a1-83c8-d0a1b39f496f"
    system_params["workingdir"] = "f92163af-f801-5880-983a-aeb880c94a0b"

    # try "normal" first, with a value. try with none below.
    salt_config["salt_debug_log"] = "211aba6a-72f3-5659-85ce-22fc3854da2e"

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)
    saltworker_lx.create_working_dir = MagicMock(return_value=None)
    saltworker_lx._prepare_for_install()

    # assertions ===================
    assert saltworker_lx.salt_debug_logfile == salt_config["salt_debug_log"]

    # tried "normal" first, with a value, above. now, trying with none.
    salt_config["salt_debug_log"] = None

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)
    saltworker_lx.create_working_dir = MagicMock(return_value=None)
    saltworker_lx._prepare_for_install()

    # assertions ===================
    assert saltworker_lx.salt_debug_logfile == os.sep.join(
        (system_params["logdir"], 'salt_call.debug.log'))

@pytest.mark.skipif(sys.version_info < (3, 4),
                    reason="Not supported in this Python version.")
@patch("codecs.open", autospec=True)
@patch("os.walk", autospec=True)
@patch("yaml.safe_dump", autospec=True)
@patch("yaml.safe_load", autospec=True)
@patch("watchmaker.utils.copytree", autospec=True)
def test_linux_salt_content_none(
        mock_copytree, mock_yload, mock_ydump, mock_os, mock_codec):
    """Test that Pythonic None can be used without error rather than 'None'."""
    # setup ========================
    system_params = {}
    salt_config = {}
    system_params["prepdir"] = "1868795c-7d47-5d4d-9021-941b449967af"
    system_params["logdir"] = "e88611fe-d444-5951-bb20-4d7508ed7a0c"
    system_params["workingdir"] = "f671935d-6669-50d1-a63c-157799cd13cb"

    salt_config["salt_content"] = None

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)

    saltworker_lx.retrieve_file = MagicMock(return_value=None)
    saltworker_lx.extract_contents = MagicMock(return_value=None)

    saltworker_lx._build_salt_formula("c6295b26-c043-5cd8-aa83-e3aab9df263c")

    # assertions ===================
    assert saltworker_lx.retrieve_file.call_count == 0
    assert saltworker_lx.extract_contents.call_count == 0
    assert mock_codec.call_count == 1
    assert mock_os.call_count == 2
    assert mock_ydump.call_count == 1
    assert mock_yload.call_count == 1
    assert mock_copytree.call_count > 1

@pytest.mark.skipif(sys.version_info < (3, 4),
                    reason="Not supported in this Python version.")
@patch("codecs.open", autospec=True)
@patch("os.walk", autospec=True)
@patch("yaml.safe_dump", autospec=True)
@patch("yaml.safe_load", autospec=True)
@patch("watchmaker.utils.copytree", autospec=True)
@patch("glob.glob", autospec=True)
@patch("watchmaker.utils.copy_subdirectories", autospec=True)
def test_linux_salt_content_path_none(
        mock_copysubdirs, mock_glob, mock_copytree, mock_yload,
        mock_ydump, mock_os, mock_codec):
    """Test that Pythonic None can be used without error rather than 'None'."""
    # setup ========================
    system_params = {}
    salt_config = {}
    system_params["prepdir"] = "4504257a-76d0-49bd-9d04-53c1459b7156"
    system_params["logdir"] = "045143d6-0e87-497f-a11a-5eebb1ec7edf"
    system_params["workingdir"] = "83f16e7b-c2cf-482b-93c8-32a558f6ded6"

    salt_config["salt_content"] = "33691f8e-e245-4be2-827b-2fa727600fb4.zip"
    salt_config["salt_content_path"] = None

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)
    saltworker_lx.working_dir = system_params["workingdir"]

    saltworker_lx.retrieve_file = MagicMock(return_value=None)
    saltworker_lx.extract_contents = MagicMock(return_value=None)

    saltworker_lx._build_salt_formula("e8d7398e-49fa-4eb9-8f8b-22c9d3fdb7f7")

    # assertions ===================
    assert saltworker_lx.retrieve_file.call_count == 1
    assert saltworker_lx.extract_contents.call_count == 1
    assert mock_copysubdirs.call_count == 1
    assert mock_codec.call_count == 1
    assert mock_os.call_count == 1
    assert mock_ydump.call_count == 1
    assert mock_yload.call_count == 1
    assert mock_copytree.call_count > 1
    assert mock_glob.call_count == 0

@pytest.mark.skipif(sys.version_info < (3, 4),
                    reason="Not supported in this Python version.")
@patch("codecs.open", autospec=True)
@patch("os.walk", autospec=True)
@patch("yaml.safe_dump", autospec=True)
@patch("yaml.safe_load", autospec=True)
@patch("watchmaker.utils.copytree", autospec=True)
@patch("glob.glob", autospec=True)
def test_linux_salt_content_path(
        mock_glob, mock_copytree, mock_yload,
        mock_ydump, mock_os, mock_codec):
    """Ensure that files from salt_content_path are retrieved correctly."""
    # setup ========================
    system_params = {}
    salt_config = {}
    system_params["prepdir"] = "96003f32-5808-4ef8-a573-763b7f47ba9d"
    system_params["logdir"] = "0585f9d7-ed0e-4a1b-ac0d-2b10a245a0eb"
    system_params["workingdir"] = "35f411db-355b-4953-ae31-d6f592753e58"

    salt_config["salt_content"] = "d002be6e-645d-4f58-97c9-8335df0ff5e4.zip"
    salt_config["salt_content_path"] = "05628e08-f1be-474d-8c12-5bb6517fc5f9"

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)

    saltworker_lx.retrieve_file = MagicMock(return_value=None)
    saltworker_lx.extract_contents = MagicMock(return_value=None)
    saltworker_lx.working_dir = system_params["workingdir"]
    mock_glob.return_value = ['05628e08-f1be-474d-8c12-5bb6517fc5f9/87a2324d']

    saltworker_lx._build_salt_formula("8822e968-deea-410f-9b6e-d25a36c512d1")

    # assertions ===================
    assert saltworker_lx.retrieve_file.call_count == 1
    assert saltworker_lx.extract_contents.call_count == 1
    assert mock_codec.call_count == 1
    assert mock_os.call_count == 3
    assert mock_ydump.call_count == 1
    assert mock_yload.call_count == 1
    assert mock_copytree.call_count > 1
    assert mock_glob.call_count == 1

def test_linux_ou_path_none():
    """Test that Pythonic None can be used without error rather than 'None'."""
    # setup ========================
    system_params = {}
    salt_config = {}
    system_params["prepdir"] = "dba0f4db-3851-54b0-b2f7-bfff6bb8bbf5"
    system_params["logdir"] = "f9d62bf8-7ffe-58a8-9ad9-2d21a430e52b"
    system_params["workingdir"] = "0a5e5983-3d95-58b3-92a8-c4673902b47d"

    # try "normal" first, with a value. try with none below.
    salt_config["ou_path"] = "b547b63d-31e8-50b0-a97f-761ac8279319"

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)

    saltworker_lx._set_grain = MagicMock(return_value=None)
    saltworker_lx.run_salt = MagicMock(
        return_value={"retcode": 0, "stdout": b"", "stderr": b""}
    )

    saltworker_lx.process_grains()

    # assertions ===================
    assert saltworker_lx._set_grain.call_count == 3
    saltworker_lx._set_grain.assert_called_with(
        'join-domain', {'oupath': salt_config["ou_path"]})

    # tried "normal" first, with a value, above. now, trying with none.
    salt_config["ou_path"] = None

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)

    saltworker_lx._set_grain = MagicMock(return_value=None)
    saltworker_lx.run_salt = MagicMock(
        return_value={"retcode": 0, "stdout": b"", "stderr": b""}
    )

    saltworker_lx.process_grains()

    # assertions ===================
    assert saltworker_lx._set_grain.call_count == 2

def test_linux_admin_groups_none():
    """Test that Pythonic None can be used without error rather than 'None'."""
    # setup ========================
    system_params = {}
    salt_config = {}
    system_params["prepdir"] = "a27f71e5-4af3-5ad4-9d69-05fb8b7cbe4f"
    system_params["logdir"] = "9b504864-814c-5226-9a05-b7613dd96efa"
    system_params["workingdir"] = "d468d406-1e89-5041-9900-0a9189e541b0"

    # try "normal" first, with a value. try with none below.
    salt_config["admin_groups"] = "5a8915b6-8ceb-53c8-a9c6-064365dd10bd"

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)

    saltworker_lx._set_grain = MagicMock(return_value=None)
    saltworker_lx.run_salt = MagicMock(
        return_value={"retcode": 0, "stdout": b"", "stderr": b""}
    )

    saltworker_lx.process_grains()

    # assertions ===================
    assert saltworker_lx._set_grain.call_count == 3
    saltworker_lx._set_grain.assert_called_with(
        'join-domain', {'admin_groups': [salt_config["admin_groups"]]})

    # tried "normal" first, with a value, above. now, trying with none.
    salt_config["admin_groups"] = None

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)

    saltworker_lx._set_grain = MagicMock(return_value=None)
    saltworker_lx.run_salt = MagicMock(
        return_value={"retcode": 0, "stdout": b"", "stderr": b""}
    )

    saltworker_lx.process_grains()

    # assertions ===================
    assert saltworker_lx._set_grain.call_count == 2

def test_linux_admin_users_none():
    """Test that Pythonic None can be used without error rather than 'None'."""
    # setup ========================
    system_params = {}
    salt_config = {}
    system_params["prepdir"] = "ff7b4ffb-99a0-50c2-af78-98ebfea33295"
    system_params["logdir"] = "3744bc20-0357-50f1-8633-178151d904ab"
    system_params["workingdir"] = "455feea8-481c-5014-8a7b-cdeb619a2177"

    # try "normal" first, with a value. try with none below.
    salt_config["admin_users"] = "3113d136-bfde-5bc4-bc47-855d72d58d29"

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)

    saltworker_lx._set_grain = MagicMock(return_value=None)
    saltworker_lx.run_salt = MagicMock(
        return_value={"retcode": 0, "stdout": b"", "stderr": b""}
    )

    saltworker_lx.process_grains()

    # assertions ===================
    assert saltworker_lx._set_grain.call_count == 3
    saltworker_lx._set_grain.assert_called_with(
        'join-domain', {'admin_users': [salt_config["admin_users"]]})

    # tried "normal" first, with a value, above. now, trying with none.
    salt_config["admin_users"] = None

    # execution ====================
    saltworker_lx = SaltLinux(system_params, **salt_config)

    saltworker_lx._set_grain = MagicMock(return_value=None)
    saltworker_lx.run_salt = MagicMock(
        return_value={"retcode": 0, "stdout": b"", "stderr": b""}
    )

    saltworker_lx.process_grains()

    # assertions ===================
    assert saltworker_lx._set_grain.call_count == 2

@patch.dict(os.environ, {"systemdrive": "C:",
                         "ProgramFiles": "C:\\Program Files"})
def test_win_ash_role_none():
    """Test that Pythonic None can be used without error rather than 'None'."""
    # setup ========================
    system_params = {}
    salt_config = {}
    system_params["prepdir"] = "4e91a26a-c325-5548-9e99-e0cea505eca6"
    system_params["logdir"] = "1a74aa66-1eb5-5f6e-bbdc-a247cfabdcb7"
    system_params["workingdir"] = "3cbd1221-01f3-5ed8-8df1-79918a1ebe3d"

    # try "normal" first, with a value. try with none below.
    salt_config["ash_role"] = "ff059d6b-b614-5b55-8b94-4d29570b8da8"

    saltworker_win = SaltWindows(system_params, **salt_config)

    saltworker_win.working_dir = system_params["workingdir"]
    saltworker_win._prepare_for_install = MagicMock(return_value=None)
    saltworker_win.service_status = MagicMock(return_value=None)
    saltworker_win._install_package = MagicMock(return_value=None)
    saltworker_win.service_stop = MagicMock(return_value=None)
    saltworker_win._build_salt_formula = MagicMock(return_value=None)
    saltworker_win.service_enable = MagicMock(return_value=None)
    saltworker_win.service_disable = MagicMock(return_value=None)
    saltworker_win.service_start = MagicMock(return_value=None)
    saltworker_win._set_grain = MagicMock(return_value=None)
    saltworker_win.process_grains = MagicMock(return_value=None)
    saltworker_win.run_salt = MagicMock(
        return_value={"retcode": 0, "stdout": b"", "stderr": b""}
    )
    saltworker_win.process_states = MagicMock(return_value=None)
    saltworker_win.cleanup = MagicMock(return_value=None)

    # execution ====================
    saltworker_win.install()

    # assertions ===================
    assert saltworker_win._set_grain.call_count == 1
    saltworker_win._set_grain.assert_called_with(
        'ash-windows', {'lookup': {'role': salt_config["ash_role"]}})

    # tried "normal" first, with a value, above. now, trying with none.
    salt_config["ash_role"] = None

    saltworker_win = SaltWindows(system_params, **salt_config)

    saltworker_win.working_dir = system_params["workingdir"]
    saltworker_win._prepare_for_install = MagicMock(return_value=None)
    saltworker_win.service_status = MagicMock(return_value=None)
    saltworker_win._install_package = MagicMock(return_value=None)
    saltworker_win.service_stop = MagicMock(return_value=None)
    saltworker_win._build_salt_formula = MagicMock(return_value=None)
    saltworker_win.service_enable = MagicMock(return_value=None)
    saltworker_win.service_disable = MagicMock(return_value=None)
    saltworker_win.service_start = MagicMock(return_value=None)
    saltworker_win._set_grain = MagicMock(return_value=None)
    saltworker_win.process_grains = MagicMock(return_value=None)
    saltworker_win.run_salt = MagicMock(
        return_value={"retcode": 0, "stdout": b"", "stderr": b""}
    )
    saltworker_win.process_states = MagicMock(return_value=None)
    saltworker_win.cleanup = MagicMock(return_value=None)

    # execution ====================
    saltworker_win.install()

    # assertions ===================
    assert saltworker_win._set_grain.call_count == 0


text:
package com.zimbra.cs.index.query;

import java.util.HashMap;

import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;

public final class ConvQueryTest {

    @BeforeClass
    public static void init() throws Exception {
        MailboxTestUtil.initServer();
        Provisioning prov = Provisioning.getInstance();
        prov.createAccount("test@zimbra.com", "secret", new HashMap<String, Object>());
    }

    @Before
    public void setUp() throws Exception {
        MailboxTestUtil.clearData();
    }

    @Test
    public void remoteConvId() throws Exception {
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);
        Assert.assertEquals("<DB[CONV:\"11111111-1111-1111-1111-111111111111:111\" ]>",
                ConvQuery.create(mbox, "11111111-1111-1111-1111-111111111111:111").compile(mbox, true).toString());
    }

}


text:
<?php
namespace Composer\Installers;

class EliasisInstaller extends BaseInstaller
{
    protected $locations = array(
        'component' => 'components/{$name}/',
        'module'    => 'modules/{$name}/',
        'plugin'    => 'plugins/{$name}/',
        'template'  => 'templates/{$name}/',
    );
}


text:
using System;
using System.Threading.Tasks;

namespace Artportalen
{
    using System.Net.Http;
    using System.Net.Http.Headers;

    using Artportalen.Helpers;
    using Artportalen.Request;
    using Artportalen.Response;

    public class Ap2ApiClient
    {
        private readonly HttpClient httpClient;

        private string basicAuthToken;

        private string baseAddress = "https://www.artportalen.se/";

        private IJsonConverter jsonConverter;

        public Ap2ApiClient(string accessKey, HttpClientHandler handler = null)
        {
            var messageHandler = handler ?? new HttpClientHandler();

            this.httpClient = new HttpClient(messageHandler)
                                  {
                                      BaseAddress = new Uri(this.baseAddress)
                                  };

            this.httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            this.httpClient.DefaultRequestHeaders.Add("access-key", accessKey);
        }

        public IJsonConverter JsonConverter
        {
            get
            {
                return this.jsonConverter ?? (this.jsonConverter = new DataContractJsonConverter());
            }
            set
            {
                this.jsonConverter = value;
            }
        }

        public void SetCredentials(string username, string password)
        {
            this.basicAuthToken = BasicAuthHelper.Encode(username, password);
        }

        public void SetCredentials(string basicAuth)
        {
            this.basicAuthToken = basicAuth;
        }

        public async Task<Sighting> GetSightingAsync(long sightingId)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, string.Format("/api/sightings/{0}", sightingId));
            this.AddAuthorizationHeader(request);

            var response = await this.httpClient.SendAsync(request);

            var sightingResponse = await this.ParseResponse<Sighting>(response);

            return sightingResponse;
        }

        public async Task<SightingsResponse> GetSightingsAsync(SightingsQuery query)
        {
            var qb = new QueryStringBuilder(query, new[] { "LastSightingId" });

            var request = new HttpRequestMessage(HttpMethod.Get, string.Format("/api/sightings/search?{0}", qb));
            this.AddAuthorizationHeader(request);

            var response = await this.httpClient.SendAsync(request);

            var sightingsResponse = await this.ParseResponse<SightingsResponse>(response);
            sightingsResponse.Query = query;

            foreach (var sighting in sightingsResponse.Data)
            {
                sighting.Source = this.httpClient.BaseAddress.Host;
            }

            return sightingsResponse;
        }

        public async Task<AreaDataset[]> GetAreaDatasetsAsync()
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "/api/areadatasets");

            var response = await this.httpClient.SendAsync(request);

            var areaDatasetResponse = await this.ParseResponse<BaseCollection<AreaDataset>>(response);

            return areaDatasetResponse != null ? areaDatasetResponse.Data : new AreaDataset[0];
        }

        private void AddAuthorizationHeader(HttpRequestMessage request)
        {
            if (string.IsNullOrEmpty(this.basicAuthToken))
            {
                throw new UnauthorizedAccessException("No credentals added to client, use SetCredentials method");
            }

            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", this.basicAuthToken);
        }

        private async Task<T> ParseResponse<T>(HttpResponseMessage response)
        {
            if (response.IsSuccessStatusCode)
            {
                var responseStream = await response.Content.ReadAsStreamAsync();
                return this.JsonConverter.Deserialize<T>(responseStream);
            }

            throw new HttpRequestException(string.Format("{0} {1}", response.StatusCode, response.ReasonPhrase));
        }
    }
}


text:
Users = Meteor.users;

// Search a user in the complete server database by its name or username. This
// is used for instance to add a new user to a board.
var searchInFields = ['username', 'profile.name'];
Users.initEasySearch(searchInFields, {
    use: 'mongo-db',
    returnFields: searchInFields
});

// HELPERS
Users.helpers({
    boards: function() {
        return Boards.find({ userId: this._id });
    },
    hasStarred: function(boardId) {
        return this.profile.starredBoards && _.contains(this.profile.starredBoards, boardId);
    },
    isBoardMember: function() {
        var board = Boards.findOne(Router.current().params.boardId);
        return _.contains(_.pluck(board.members, 'userId'), this._id);
    },
    isBoardAdmin: function() {
        var board = Boards.findOne(Router.current().params.boardId);
        return this.isBoardMember(board) && _.where(board.members, {userId: this._id})[0].isAdmin;
    }
});

// BEFORE HOOK
Users.before.insert(function (userId, doc) {

    // connect profile.status default
    doc.profile.status = 'offline';

    // slugify to username
    doc.username = getSlug(doc.profile.name, '');
});

// AFTER HOOK
isServer(function() {
    Users.after.insert(function(userId, doc) {
        var ExampleBoard = {
            title: 'Welcome Board',
            userId: doc._id,
            permission: 'private' // Private || Public
        };

        // Welcome Board insert and list, card :)
        Boards.insert(ExampleBoard, function(err, boardId) {

            // lists
            _.forEach(['Basics', 'Advanced'], function(title) {
                var list = {
                    title: title,
                    boardId: boardId,
                    userId: ExampleBoard.userId,

                    // XXX Not certain this is a bug, but we except these fields
                    // get inserted by the Lists.before.insert collection-hook.
                    // Since this hook is not called in this case, we have to
                    // dublicate the logic and set them here.
                    archived: false,
                    createdAt: new Date()
                };

                // insert List
                Lists.insert(list);
            });
        });
    });
});


text:
package org.bricolages.streaming.stream.op;
import org.bricolages.streaming.stream.processor.CleanseException;
import org.bricolages.streaming.object.Record;
import lombok.*;

public abstract class SingleColumnOp extends Op {
    protected SingleColumnOp(OperatorDefinition def) {
        super(def);
    }

    protected String targetColumnName() {
        return getColumnName();
    }

    @Override
    public Record apply(Record record) {
        Object result;
        try {
            result = applyValue(record.get(targetColumnName()), record);
        }
        catch (OpException | CleanseException ex) {
            result = null;
        }
        if (result == null) {
            record.remove(targetColumnName());
            return record.isEmpty() ? null : record;
        }
        else {
            record.put(targetColumnName(), result);
            return record;
        }
    }

    protected abstract Object applyValue(Object value, Record record) throws OpException, CleanseException;
}


text:
GitTutorial
===========

Learn to Use GIT


text:
package org.krysalis.barcode4j.fop;

import org.krysalis.barcode4j.tools.PageInfo;

import org.apache.fop.area.PageViewport;

/**
 * Helper class to replace certain variables in the barcode message.
 * @author Jeremias Maerki
 */
public class VariableUtil extends org.krysalis.barcode4j.tools.VariableUtil {

    /**
     * Legacy method to replace page number variables in the message.
     * @param page the FOP page
     * @param msg the message
     * @return the message after the variable processing
     */
    public static String getExpandedMessage(PageViewport page, String msg) {
        PageInfo pageInfo = null;
        if (page != null) {
            pageInfo = new PageInfo(page.getPageNumber(), page.getPageNumberString());
        }
        return getExpandedMessage(pageInfo, msg);
    }

}