text:
Plugin coding guidelines
========================

In addition to the Elgg Coding Standards, these are guidelines for creating plugins. Core plugins are being updated to this format and all plugin authors should follow these guidelines in their own plugins.

.. seealso::

   Be sure to follow the :doc:`plugins/plugin-skeleton` for your plugin's layout.

.. warning::

  :doc:`dont-modify-core`

.. contents:: Contents
   :local:
   :depth: 1

Use standardized routing with page handlers
-------------------------------------------

- Example: Bookmarks plugin
- Page handlers should accept the following standard URLs:
   +---------------+-----------------------------------+
   | Purpose       | URL                               |
   +===============+===================================+
   | All           | page_handler/all                  |
   +---------------+-----------------------------------+
   | User          | page_handler/owner/<username>     |
   +---------------+-----------------------------------+
   | User friends' | page_handler/friends/<username>   |
   +---------------+-----------------------------------+
   | Single entity | page_handler/view/<guid>/<title>  |
   +---------------+-----------------------------------+
   | Add           | page_handler/add/<container_guid> |
   +---------------+-----------------------------------+
   | Edit          | page_handler/edit/<guid>          |
   +---------------+-----------------------------------+
   | Group list    | page_handler/group/<guid>/owner   |
   +---------------+-----------------------------------+
- Include page handler scripts from the page handler. Almost every page handler should have a page handler script. (Example: ``bookmarks/all`` => ``mod/bookmarks/pages/bookmarks/all.php``)
- Call ``set_input()`` for entity guids in the page handler and use ``get_input()`` in the page handler scripts.
- Call ``elgg_gatekeeper()`` and ``elgg_admin_gatekeeper()`` in the page handler function if required.
- The group URL should use the ``pages/<handler>/owner.php`` script.
- Page handlers should not contain HTML.
- If upgrading a 1.7 plugin, update the URLs throughout the plugin. (Don't forget to remove ``/pg/``!)

Use standardized page handlers and scripts
------------------------------------------

- Example: Bookmarks plugin
- Store page handler scripts in ``mod/<plugin>/pages/<page_handler>/<page_name>``
- Use the content page layout in page handler scripts: ``$content = elgg_view_layout('content', $options);``
- Page handler scripts should not contain HTML
- Call ``elgg_push_breadcrumb()`` in the page handler scripts.
- No need to worry about setting the page owner if the URLs are in the standardized format
- For group content, check the ``container_guid`` by using ``elgg_get_page_owner_entity()``

The object/<subtype> view
-------------------------

- Example: Bookmarks plugin
- Make sure there are views for ``$vars['full'] == true`` and ``$vars['full'] == false``
- Check for the object in ``$vars['entity']`` . Use ``elgg_instance_of()`` to make sure it's the type entity you want. Return ``true`` to short circuit the view if the entity is missing or wrong.
- Use the new list body and list metadata views to help format. You should use almost no markup in these views.
- Update action structure - Example: Bookmarks plugin.
- Namespace action files and action names (example: ``mod/blog/actions/blog/save.php`` => ``action/blog/save``)
- Use the following action URLs:
   +---------+----------------------+
   | Purpose | URL                  |
   +=========+======================+
   | Add     | action/plugin/save   |
   +---------+----------------------+
   | Edit    | action/plugin/save   |
   +---------+----------------------+
   | Delete  | action/plugin/delete |
   +---------+----------------------+
- Make the delete action accept ``action/<handler>/delete?guid=<guid>`` so the metadata entity menu has the correct URL by default
- If updating a 1.7 plugin, replace calls to functions deprecated in 1.7 because these will produce visible errors on every load in 1.8

Actions
-------

Actions are transient states to perform an action such as updating the database or sending a notification to a user. Used correctly, actions are secure and prevent against CSRF and XSS attacks.

.. note::

   As of Elgg 1.7 all actions require action tokens.

Action best practices
^^^^^^^^^^^^^^^^^^^^^

Never call an action directly by saying:

.. code:: html

   ...href="/mod/mymod/actions/myaction.php"

This circumvents the security systems in Elgg.

There is no need to include the ``engine/start.php`` file in your actions. Actions should never be called directly, so the engine will be started automatically when called correctly.

Because actions are time-sensitive they are not suitable for links in emails or other delayed notifications. An example of this would be invitations to join a group. The clean way to create an invitation link is to create a page handler for invitations and email that link to the user. It is then the page handler's responsibility to create the action links for a user to join or ignore the invitation request.

Directly calling a file
-----------------------

This is an easy one: **Don't do it**. With the exception of 3rd party application integration, there is not a reason to directly call a file in mods directory.

Recommended
-----------

These points are good ideas, but are not yet in the official guidelines. Following these suggestions will help to keep your plugin consistent with Elgg core.

- Update the widget views (see the blog or file widgets)
- Update the group profile "widget" using blog or file plugins as example
- Update the forms
   - Move form bodies to ``/forms/<handler>/<action>`` to use Evan's new ``elgg_view_form()``
   - Use input views in form bodies rather than html
   - Add a function that prepares the form (see ``mod/file/lib/file.php`` for example)
   - Integrate sticky forms (see the file plugin's upload action and form prepare function)
- Clean up CSS/HTML
   - Should be able to remove almost all CSS (look for patterns that can be moved into core if you need CSS)
- Use hyphens rather than underscores in classes/ids
- Update the ``manifest.xml`` file to the 1.8 format. Use http://el.gg/manifest17to18 to automate this
- Do not use the ``bundled`` category with your plugins. That is for plugins distributed with Elgg
- Update functions deprecated in 1.8.
   - Many registration functions simply added an ``elgg_`` prefix for consistency
   - See ``/engine/lib/deprecated-1.8.php`` for the full list. You can also set the debug level to warning to get visual reminders of deprecated functions


text:
package au.org.aurin.scatsanalysis;

import java.io.IOException;

import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.DataUtilities;
import org.geotools.feature.SchemaException;
import org.locationtech.geomesa.core.data.AccumuloDataStore;
import org.locationtech.geomesa.core.data.AccumuloFeatureStore;
import org.opengis.feature.simple.SimpleFeatureType;

/**
 * @author Siqi Wu
 *
 * Class implementing GeoMesa feature store to hold Scats records
 */
public class ScatsFeatureStore {

  protected static String schemaDef = "timestamp:Date, siteNo:String, "
      + "location:Point:srid=4326, vehicleCount:int";

  public ScatsFeatureStore() {
    // TODO Auto-generated constructor stub
  }

  /**
   * Returns a SimpleFeatureType to hold Scats with simpleFeatureTypeName
   *
   * @param simpleFeatureTypeName
   *          Accumulo table name for the schema
   * @throws SchemaException
   */
  public static SimpleFeatureType createSchema(String simpleFeatureTypeName)
      throws SchemaException {

    SimpleFeatureType simpleFeatureType = DataUtilities.createType(
        simpleFeatureTypeName, ScatsFeatureStore.schemaDef);

    return simpleFeatureType;
  }

  /**
   * Returns the FeatureSource of name ftName (returns null if not existing)
   *
   * @param options
   *          Datastore parameters
   *
   * @return
   * @throws IOException
   * @throws SchemaException
   */
  public static AccumuloFeatureStore getFeatureType(ScatsAnalysisOptions options)
      throws IOException, SchemaException {

    // Verifies that we can see this GeoMesa feature type
    DataStore dataStore = DataStoreFinder.getDataStore(options
        .getAccumuloOptions());
    if (dataStore == null) {
      return null;
    }

    // Creates the FeatureType if not existing
    if (dataStore.getSchema(options.tableName) == null) {
      return null;
    }

    return (AccumuloFeatureStore) dataStore.getFeatureSource(options.tableName);
  }

  /**
   * Creates if not existing a FeatureType in Accumulo, adn drops and re-creates
   * it if the overwrite options is set
   *
   * @param options
   *          Datastore parameters
   *
   * @return
   * @throws IOException
   * @throws SchemaException
   */
  public static void createFeatureType(ScatsAnalysisOptions options)
      throws IOException, SchemaException {

    // Verifies that we can see this Accumulo feature type
    AccumuloDataStore dataStore = (AccumuloDataStore) (DataStoreFinder
        .getDataStore(options.getAccumuloOptions()));
    assert dataStore != null;

    // Drops the Feature Type if the overwrite options is set
    if (options.overwrite && dataStore.getSchema(options.tableName) != null) {
      dataStore.removeSchema(options.tableName);
    }

    // Creates the FeatureType if not existing
    if (dataStore.getSchema(options.tableName) == null) {
      dataStore.createSchema(ScatsFeatureStore.createSchema(options.tableName));
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sling.query.selector;

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

import org.apache.sling.query.api.SearchStrategy;
import org.apache.sling.query.api.internal.IteratorToIteratorFunction;
import org.apache.sling.query.api.internal.Option;
import org.apache.sling.query.api.internal.TreeProvider;
import org.apache.sling.query.function.CompositeFunction;
import org.apache.sling.query.function.FilterFunction;
import org.apache.sling.query.iterator.AlternativeIterator;
import org.apache.sling.query.iterator.EmptyElementFilter;
import org.apache.sling.query.iterator.SuppIterator;
import org.apache.sling.query.selector.parser.Modifier;
import org.apache.sling.query.selector.parser.Selector;
import org.apache.sling.query.selector.parser.SelectorParser;
import org.apache.sling.query.selector.parser.SelectorSegment;
import org.apache.sling.query.util.IteratorUtils;
import org.apache.sling.query.util.LazyList;

public class SelectorFunction<T> implements IteratorToIteratorFunction<T>, Predicate<T> {

	private final List<IteratorToIteratorFunction<T>> selectorFunctions;

	private final TreeProvider<T> provider;

	private final SearchStrategy strategy;

	public SelectorFunction(String selector, TreeProvider<T> provider, SearchStrategy strategy) {
		this.provider = provider;
		this.strategy = strategy;
		List<Selector> selectors = SelectorParser.parse(selector);
		selectorFunctions = new ArrayList<>();
		for (Selector s : selectors) {
			selectorFunctions.add(createSelectorFunction(s.getSegments()));
		}
	}

	@Override
	public Iterator<Option<T>> apply(Iterator<Option<T>> input) {
		LazyList<Option<T>> list = new LazyList<Option<T>>(input);
		List<Iterator<Option<T>>> iterators = new ArrayList<>();
		for (IteratorToIteratorFunction<T> function : selectorFunctions) {
			iterators.add(new SuppIterator<T>(list, function));
		}
		return new AlternativeIterator<T>(iterators);
	}

	@Override
	public boolean test(T resource) {
		Iterator<Option<T>> result = apply(IteratorUtils.singleElementIterator(Option.of(resource, 0)));
		return new EmptyElementFilter<T>(result).hasNext();
	}

	private IteratorToIteratorFunction<T> createSelectorFunction(List<SelectorSegment> segments) {
		List<Function<?, ?>> segmentFunctions = new ArrayList<>();
		for (SelectorSegment segment : segments) {
			segmentFunctions.addAll(createSegmentFunction(segment));
		}
		return new CompositeFunction<T>(segmentFunctions);
	}

	private List<Function<?, ?>> createSegmentFunction(SelectorSegment segment) {
		List<Function<?, ?>> functions = new ArrayList<>();
		HierarchyOperator operator = HierarchyOperator.findByCharacter(segment.getHierarchyOperator());
		functions.add(operator.getFunction(segment, strategy, provider));
		Predicate<T> predicate = provider.getPredicate(segment.getType(), segment.getName(),
				segment.getAttributes());
		functions.add(new FilterFunction<T>(predicate));
		for (Modifier modifiers : segment.getModifiers()) {
			FunctionType type = FunctionType.valueOf(modifiers.getName().toUpperCase());
			Function<?, ?> f = type.getFunction(modifiers.getArgument(), strategy, provider);
			functions.add(f);
		}
		return functions;
	}

}


text:
<?php

namespace LaraPayNG\Traits;

use LaraPayNG\Events\TransactionSuccessful;
use LaraPayNG\Events\TransactionUnsuccessful;

//

trait DetermineViewToPresent
{
    /**
     * @param $result
     *
     * @return \Illuminate\View\View
     */
    private function determineViewToPresent($result)
    {
        if ($this->determineTransactionStatus($result) == 'successful') {
            return view(config('lara-pay-ng.gateways.routes.success_view_name'), compact('result'));
        }

        return view(config('lara-pay-ng.gateways.routes.failure_view_name'), compact('result'));
    }

    private function dispatchAppropriateEvents($result)
    {
        switch ($this->determineTransactionStatus($result)) {
            case 'successful':
                event(new TransactionSuccessful($result));
                break;

            case 'failed':
                event(new TransactionUnsuccessful($result));
                break;

            default:
                event(new TransactionUnsuccessful($result));

                break;
        }
    }

    /**
     * @param $result
     *
     * @return \Illuminate\View\View
     */
    private function determineTransactionStatus($result)
    {
        switch ($result['status']) {
            case 'Approved':
            case 'Approved by Financial Institution':
            case 'CashEnvoy transaction successful.':
                return 'successful';
            break;

            default:
                return 'failed';
                break;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/E:/GITPROJECT/Android-PullToRefresh/PullToRefreshViewPager/build/intermediates/exploded-aar/Android-PullToRefresh/library/unspecified/res/values-zh/values-zh.xml -->
    <eat-comment/>
    <string name="pull_to_refresh_pull_label">下拉刷新…</string>
    <string name="pull_to_refresh_refreshing_label">正在载入…</string>
    <string name="pull_to_refresh_release_label">放开以刷新…</string>
</resources>


text:
package org.ovirt.engine.core.bll;

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

import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.profiles.DiskProfileHelper;
import org.ovirt.engine.core.bll.quota.QuotaConsumptionParameter;
import org.ovirt.engine.core.bll.quota.QuotaStorageConsumptionParameter;
import org.ovirt.engine.core.bll.quota.QuotaStorageDependent;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.bll.validator.DiskValidator;
import org.ovirt.engine.core.bll.validator.StorageDomainValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.LockProperties;
import org.ovirt.engine.core.common.action.LockProperties.Scope;
import org.ovirt.engine.core.common.action.MoveOrCopyImageGroupParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.businessentities.CopyVolumeType;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.ImageOperation;
import org.ovirt.engine.core.common.businessentities.ImageStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.errors.VdcBllMessages;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.VmDeviceDAO;

@DisableInPrepareMode
@NonTransactiveCommandAttribute
public class MoveOrCopyDiskCommand<T extends MoveOrCopyImageGroupParameters> extends CopyImageGroupCommand<T>
        implements QuotaStorageDependent {

    private List<PermissionSubject> cachedPermsList;
    private List<Pair<VM, VmDevice>> cachedVmsDeviceInfo;
    private String cachedDiskIsBeingMigratedMessage;

    public MoveOrCopyDiskCommand(T parameters) {
        this(parameters, null);
    }

    public MoveOrCopyDiskCommand(T parameters, CommandContext commandContext) {
        super(parameters, commandContext);
        defineVmTemplate();
    }

    @Override
    protected LockProperties applyLockProperties(LockProperties lockProperties) {
        return lockProperties.withScope(Scope.Command);
    }

    protected void defineVmTemplate() {
        if (getParameters().getOperation() == ImageOperation.Copy) {
            setVmTemplate(getTemplateForImage());
        }
    }

    protected VmTemplate getTemplateForImage() {
        if (getImage() == null) {
            return null;
        }
        Collection<VmTemplate> templates = getVmTemplateDAO().getAllForImage(getImage().getImageId()).values();
        return !templates.isEmpty() ? templates.iterator().next() : null;
    }

    @Override
    protected void setActionMessageParameters() {
        addCanDoActionMessage(getParameters().getOperation() == ImageOperation.Copy ?
                        VdcBllMessages.VAR__ACTION__COPY
                        : VdcBllMessages.VAR__ACTION__MOVE);
        addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_DISK);
    }

    @Override
    protected boolean canDoAction() {
        return isImageExist()
                && checkOperationIsCorrect()
                && canFindVmOrTemplate()
                && isDiskUsedAsOvfStore()
                && isImageNotLocked()
                && isSourceAndDestTheSame()
                && validateSourceStorageDomain()
                && validateDestStorage()
                && checkTemplateInDestStorageDomain()
                && validateSpaceRequirements()
                && checkCanBeMoveInVm()
                && checkIfNeedToBeOverride()
                && setAndValidateDiskProfiles();
    }

    protected boolean isSourceAndDestTheSame() {
        if (getParameters().getOperation() == ImageOperation.Move
                && getParameters().getSourceDomainId().equals(getParameters().getStorageDomainId())) {
            return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_SOURCE_AND_TARGET_SAME);
        }
        return true;
    }

    protected boolean isImageExist() {
        if (getImage() == null) {
            return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST);
        }
        return true;
    }

    protected boolean isImageNotLocked() {
        DiskImage diskImage = getImage();
        if (diskImage.getImageStatus() == ImageStatus.LOCKED) {
            if (getParameters().getOperation() == ImageOperation.Move) {
                return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISKS_LOCKED,
                        String.format("$%1$s %2$s", "diskAliases", diskImage.getDiskAlias()));
            } else {
                return failCanDoAction(VdcBllMessages.VM_TEMPLATE_IMAGE_IS_LOCKED);
            }
        }
        return true;
    }

    protected boolean isDiskUsedAsOvfStore() {
        return validate(new DiskValidator(getImage()).isDiskUsedAsOvfStore());
    }

    /**
     * The following method will perform a check for correctness of operation
     * It is allow to copy only if it is image that belongs to template and
     * it is allow to move only if it is image of disk
     * @return
     */
    protected boolean checkOperationIsCorrect() {
        if (getParameters().getOperation() == ImageOperation.Copy
                && (getImage().getVmEntityType() == null || !getImage().getVmEntityType().isTemplateType())) {
            return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_NOT_TEMPLATE_DISK);
        }

        if (getParameters().getOperation() == ImageOperation.Move
                && getImage().getVmEntityType() != null && getImage().getVmEntityType().isTemplateType()) {
            return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_NOT_VM_DISK);
        }
        return true;
    }

    protected boolean validateDestStorage() {
        StorageDomainValidator validator = new StorageDomainValidator(getStorageDomain());
        return validate(validator.isDomainExistAndActive())
                && validate(validator.domainIsValidDestination());
    }

    /**
     * Check if destination storage has enough space
     * @return
     */
    protected boolean validateSpaceRequirements() {
        StorageDomainValidator storageDomainValidator = createStorageDomainValidator();
        if (validate(storageDomainValidator.isDomainWithinThresholds())) {
            getImage().getSnapshots().addAll(getAllImageSnapshots());
            return validate(storageDomainValidator.hasSpaceForClonedDisk(getImage()));
        }
        return false;
    }

    protected List<DiskImage> getAllImageSnapshots() {
        return ImagesHandler.getAllImageSnapshots(getImage().getImageId());
    }

    protected boolean checkIfNeedToBeOverride() {
        if (getParameters().getOperation() == ImageOperation.Copy && !getParameters().getForceOverride()
                && getImage().getStorageIds().contains(getStorageDomain().getId())) {
            return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_ALREADY_EXISTS);
        }
        return true;
    }

    /**
     * Validate a source storage domain of image, when a source storage domain is not provided
     * any of the domains image will be used
     */
    protected boolean validateSourceStorageDomain() {
        Guid sourceDomainId = getParameters().getSourceDomainId();
        if (sourceDomainId == null || Guid.Empty.equals(sourceDomainId)) {
            sourceDomainId = getImage().getStorageIds().get(0);
            getParameters().setSourceDomainId(sourceDomainId);
        }
        StorageDomainValidator validator =
                new StorageDomainValidator(getStorageDomainDAO().getForStoragePool(sourceDomainId,
                        getImage().getStoragePoolId()));
        return validate(validator.isDomainExistAndActive());
    }

    /**
     * If a disk is attached to VM it can be moved when it is unplugged or at case that disk is plugged
     * vm should be down
     * @return
     */
    protected boolean checkCanBeMoveInVm() {
        return validate(createDiskValidator().isDiskPluggedToVmsThatAreNotDown(false, getVmsWithVmDeviceInfoForDiskId()));
    }

    /**
     * Cache method to retrieve all the VMs with the device info related to the image
     */
    protected List<Pair<VM, VmDevice>> getVmsWithVmDeviceInfoForDiskId() {
        if (cachedVmsDeviceInfo == null) {
            cachedVmsDeviceInfo = getVmDAO().getVmsWithPlugInfo(getImage().getId());
        }
        return cachedVmsDeviceInfo;
    }

    /**
     * The following method will check, if we can move disk to destination storage domain, when
     * it is based on template
     * @return
     */
    protected boolean checkTemplateInDestStorageDomain() {
        if (getParameters().getOperation() == ImageOperation.Move
                && !Guid.Empty.equals(getImage().getImageTemplateId())) {
            DiskImage templateImage = getDiskImageDao().get(getImage().getImageTemplateId());
            if (!templateImage.getStorageIds().contains(getParameters().getStorageDomainId())) {
                return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN);
            }
        }
        return true;
    }

    protected VmDeviceDAO getVmDeviceDAO() {
        return getDbFacade().getVmDeviceDao();
    }

    protected VdcActionType getImagesActionType() {
        if (getParameters().getOperation() == ImageOperation.Move) {
            return VdcActionType.MoveImageGroup;
        }
        return VdcActionType.CopyImageGroup;
    }

    @Override
    protected void executeCommand() {
        overrideParameters();
        VdcReturnValueBase vdcRetValue = runInternalActionWithTasksContext(
                getImagesActionType(),
                getParameters());
        if (!vdcRetValue.getSucceeded()) {
            setSucceeded(false);
            getReturnValue().setFault(vdcRetValue.getFault());
        } else {
            setSucceeded(true);
            getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList());
        }
    }

    private void endCommandActions() {
        getBackend().endAction(getImagesActionType(),
                getParameters(),
                getContext().clone().withoutCompensationContext().withoutLock());
        setSucceeded(true);
    }

    @Override
    protected void endSuccessfully() {
        endCommandActions();
        incrementDbGenerationForRelatedEntities();
    }

    private void incrementDbGenerationForRelatedEntities() {
        if (getParameters().getOperation() == ImageOperation.Copy) {
            getVmStaticDAO().incrementDbGeneration(getVmTemplateId());
        } else {
            List<Pair<VM, VmDevice>> vmsForDisk = getVmsWithVmDeviceInfoForDiskId();
            for (Pair<VM, VmDevice> pair : vmsForDisk) {
                getVmStaticDAO().incrementDbGeneration(pair.getFirst().getId());
            }
        }
    }

    @Override
    protected void endWithFailure() {
        endCommandActions();
    }

    @Override
    public AuditLogType getAuditLogTypeValue() {
        switch (getActionState()) {
        case EXECUTE:
            return getSucceeded() ? (getParameters().getOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_VM_DISK
                    : AuditLogType.USER_COPIED_TEMPLATE_DISK
                    : (getParameters().getOperation() == ImageOperation.Move) ? AuditLogType.USER_FAILED_MOVED_VM_DISK
                            : AuditLogType.USER_FAILED_COPY_TEMPLATE_DISK;

        case END_SUCCESS:
            return getSucceeded() ? (getParameters().getOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_VM_DISK_FINISHED_SUCCESS
                    : AuditLogType.USER_COPIED_TEMPLATE_DISK_FINISHED_SUCCESS
                    : (getParameters().getOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_VM_DISK_FINISHED_FAILURE
                            : AuditLogType.USER_COPIED_TEMPLATE_DISK_FINISHED_FAILURE;

        default:
            return (getParameters().getOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_VM_DISK_FINISHED_FAILURE
                    : AuditLogType.USER_COPIED_TEMPLATE_DISK_FINISHED_FAILURE;
        }
    }

    @Override
    public List<PermissionSubject> getPermissionCheckSubjects() {
        if (cachedPermsList == null) {
            cachedPermsList = new ArrayList<PermissionSubject>();

            DiskImage image = getImage();
            Guid diskId = image == null ? Guid.Empty : image.getId();
            cachedPermsList.add(new PermissionSubject(diskId, VdcObjectType.Disk, ActionGroup.CONFIGURE_DISK_STORAGE));
            cachedPermsList.add(new PermissionSubject(getParameters().getStorageDomainId(),
                    VdcObjectType.Storage, ActionGroup.CREATE_DISK));
        }
        return cachedPermsList;
    }

    /**
     * The following method will override a parameters which are not relevant for the MoveOrCopyDiskCommand to the
     * correct values for these scenario in order to be used at parent class
     */
    private void overrideParameters() {
        if (getParameters().getOperation() == ImageOperation.Copy) {
            getParameters().setUseCopyCollapse(true);
            getParameters().setAddImageDomainMapping(true);
        } else {
            getParameters().setUseCopyCollapse(false);
        }
        getParameters().setDestinationImageId(getImageId());
        getParameters().setImageGroupID(getImageGroupId());
        getParameters().setDestImageGroupId(getImageGroupId());
        getParameters().setVolumeFormat(getDiskImage().getVolumeFormat());
        getParameters().setVolumeType(getDiskImage().getVolumeType());
        getParameters().setCopyVolumeType(CopyVolumeType.SharedVol);
        getParameters().setParentCommand(getActionType());
        getParameters().setParentParameters(getParameters());
        getParameters().setDiskProfileId(getImage().getDiskProfileId());
    }

    /**
     * The following method will determine if a provided vm/template exists
     * @return
     */
    private boolean canFindVmOrTemplate() {
        if (getParameters().getOperation() == ImageOperation.Copy) {
            if (getVmTemplate() == null) {
                return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST);
            }
        }
        return true;
    }

    @Override
    protected Map<String, Pair<String, String>> getSharedLocks() {
        if (getParameters().getOperation() == ImageOperation.Copy) {
            if (!Guid.Empty.equals(getVmTemplateId())) {
                return Collections.singletonMap(getVmTemplateId().toString(),
                        LockMessagesMatchUtil.makeLockingPair(LockingGroup.TEMPLATE, getDiskIsBeingMigratedMessage()));
            }
        } else {
            List<Pair<VM, VmDevice>> vmsForDisk = getVmsWithVmDeviceInfoForDiskId();
            if (!vmsForDisk.isEmpty()) {
                Map<String, Pair<String, String>> lockMap = new HashMap<>();
                for (Pair<VM, VmDevice> pair : vmsForDisk) {
                    lockMap.put(pair.getFirst().getId().toString(),
                            LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, getDiskIsBeingMigratedMessage()));
                }
                return lockMap;
            }
        }
        return null;
    }

    @Override
    protected Map<String, Pair<String, String>> getExclusiveLocks() {
        return Collections.singletonMap(
                (getImage() != null ? getImage().getId() : Guid.Empty).toString(),
                LockMessagesMatchUtil.makeLockingPair(LockingGroup.DISK, getDiskIsBeingMigratedMessage()));
    }

    private String getDiskIsBeingMigratedMessage() {
        if (cachedDiskIsBeingMigratedMessage == null) {
            StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_BEING_MIGRATED.name());
            if (getImage() != null) {
                builder.append(String.format("$DiskName %1$s", getDiskAlias()));
            }
            cachedDiskIsBeingMigratedMessage = builder.toString();
        }
        return cachedDiskIsBeingMigratedMessage;
    }

    public String getDiskAlias() {
        return getImage().getDiskAlias();
    }

    protected boolean setAndValidateDiskProfiles() {
        getImage().setDiskProfileId(getParameters().getDiskProfileId());
        return validate(DiskProfileHelper.setAndValidateDiskProfiles(Collections.singletonMap(getImage(),
                getParameters().getStorageDomainId()), getStoragePool().getcompatibility_version(), getCurrentUser()));
    }

    @Override
    public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() {
        List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>();

        list.add(new QuotaStorageConsumptionParameter(
                getDestinationQuotaId(),
                null,
                QuotaConsumptionParameter.QuotaAction.CONSUME,
                getParameters().getStorageDomainId(),
                (double)getImage().getSizeInGigabytes()));

        if (ImageOperation.Move == getParameters().getOperation()) {
            if (getImage().getQuotaId() != null && !Guid.Empty.equals(getImage().getQuotaId())) {
                list.add(new QuotaStorageConsumptionParameter(
                        getImage().getQuotaId(),
                        null,
                        QuotaConsumptionParameter.QuotaAction.RELEASE,
                        getParameters().getSourceDomainId(),
                        (double)getImage().getSizeInGigabytes()));
            }
        }
        return list;
    }

    private Guid getDestinationQuotaId() {
        return getParameters().getQuotaId();
    }

    @Override
    public Map<String, String> getJobMessageProperties() {
        List<StorageDomain> storageDomains = getStorageDomainDAO().getAllForStorageDomain(getParameters().getSourceDomainId());
        String sourceSDName = StringUtils.EMPTY;

        if (storageDomains.size() > 0) {
            sourceSDName = storageDomains.get(0).getStorageName();
        }
        if (jobProperties == null) {
            jobProperties = super.getJobMessageProperties();
            jobProperties.put("sourcesd", sourceSDName);
            jobProperties.put("targetsd", getStorageDomainName());
            jobProperties.put("diskalias", getDiskAlias());
            if (ImageOperation.Move == getParameters().getOperation()) {
                jobProperties.put("action", "Moving");
            } else {
                jobProperties.put("action", "Copying");
            }
        }
        return jobProperties;
    }

    protected StorageDomainValidator createStorageDomainValidator() {
        return new StorageDomainValidator(getStorageDomain());
    }

    protected DiskValidator createDiskValidator() {
        return new DiskValidator(getImage());
    }
}


text:
namespace google {
namespace cloud {
namespace bigtable {
namespace testing {
using MockSampleRowKeysReader =
    MockResponseReader<google::bigtable::v2::SampleRowKeysResponse,
                       google::bigtable::v2::SampleRowKeysRequest>;

}  // namespace testing
}  // namespace bigtable
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BIGTABLE_TESTING_MOCK_SAMPLE_ROW_KEYS_READER_H


text:
class Item < ActiveRecord::Base
  belongs_to :restaurant
  #has_many_questions

  validates :name,
    presence: true,
    format: { with: /\A[a-zA-Z\s]+\z/,
      message: "The item name can only have letters or spaces"}

  validates :price,
    presence: true

  validates_numericality_of :price, greater_than: 0,
    message: "The price must be a number greater than 0"

  validates :ingredients,
    presence: true,
    format: { with: /\A[a-zA-Z\s\,]+\z/,
      message: "Please enter only letters or spaces, ingredients seperated by commas"}

end


text:
/**
 * @fileoverview Generates Responsive Search Ads (RSA) details to Google Sheets
 * from the Expanded Text Ads ETA) of the specified Google Ads accounts.
 */
'use strict';
/**
 * Configuration:
 *
 * SPREADSHEET_ID - ID of the spreadsheet containing account numbers under
 * your MCC.
 */
var SPREADSHEET_ID = 'XXXXXX';

// Constants
var RSA_SHEET_NAME = 'RSAs';
var ACCOUNTS_SHEET_NAME = 'Accounts';
var GENERATED_RSA_HEADER = [
  'Account',
  'Campaign',
  'Ad group Id',
  'Ad group',
  'Ad type',
  'Ad status',
  'Final URL',
  'Path 1',
  'Path 2',
  'Headline 1',
  'Headline 2',
  'Headline 3',
  'Headline 4',
  'Headline 5',
  'Headline 6',
  'Headline 7',
  'Headline 8',
  'Headline 9',
  'Headline 10',
  'Headline 11',
  'Headline 12',
  'Headline 13',
  'Headline 14',
  'Headline 15',
  'Description 1',
  'Description 2',
  'Description 3',
  'Description 4',
  'Headline 1 position',
  'Headline 2 position',
  'Headline 3 position',
  'Headline 4 position',
  'Headline 5 position',
  'Headline 6 position',
  'Headline 7 position',
  'Headline 8 position',
  'Headline 9 position',
  'Headline 10 position',
  'Headline 11 position',
  'Headline 12 position',
  'Headline 13 position',
  'Headline 14 position',
  'Headline 15 position',
  'Description 1 position',
  'Description 2 position',
  'Description 3 position',
  'Description 4 position',
  'Update',
  'Result',
];
// Status of the processed account.
var STATUS_YES = 'Y';
var STATUS_NO = 'N';
var RSA_NUM_OF_HEADLINES = 15;
var RSA_NUM_OF_DESCRIPTIONS = 4;

/**
 * A group of Expanded Text Ads.
 * @typedef {{
 *   accountId: string,
 *   adgroupId: number,
 *   adgroupName: string,
 *   campaignName: string,
 *   headlines: !Array<string>,
 *   descriptions: !Array<string>,
 *   finalUrl: string,
 *   path1: string,
 *   path2: string,
 * }}
 */
var GroupedTextAd;

/**
 * Account column index.
 * @enum {number}
 */
var AccountColumnIndex = {
  ACCOUNT: 0,
  STATUS: 1,
};

/**
 * Generates Responsive Search Ads by
 *
 * stage 1: Loads the Google Ads account from sheets.
 * stage 2: Finds all the enabled Expanded Text Ads for all enabled ad groups.
 * stage 3: Groups the Expanded Text Ads by Ad Group Id and Final URl.
 * stage 4: Derives the Responsive Text Ad details from the grouped
 *          Expanded Text Ads and export to sheets.
 */
function main() {
  const spreadsheet = SpreadsheetApp.openById(SPREADSHEET_ID);
  const accountsSheet = spreadsheet.getSheetByName(ACCOUNTS_SHEET_NAME);
  var rsaSheet = spreadsheet.getSheetByName(RSA_SHEET_NAME);
  if (!rsaSheet) {
    rsaSheet = spreadsheet.insertSheet(RSA_SHEET_NAME);
    rsaSheet.appendRow(GENERATED_RSA_HEADER);
  }
  const range = accountsSheet.getDataRange();
  const accountRows = range.getValues();

  // Start with 2nd row and skip the header.
  for (var rowIndex = 1; rowIndex < accountRows.length; rowIndex++) {
    if (!accountRows[rowIndex][AccountColumnIndex.STATUS] &&
        accountRows[rowIndex][AccountColumnIndex.ACCOUNT]) {
      var accountId = accountRows[rowIndex][AccountColumnIndex.ACCOUNT];
      var accountIterator =
          AdsManagerApp.accounts().withIds([accountId]).get();

      while (accountIterator.hasNext()) {
        var account = accountIterator.next();
        AdsManagerApp.select(account);
        var rsaCount = generateResponsiveSearchAdsForAccount(
            account.getCustomerId(), rsaSheet);
      }
      var status = STATUS_YES;
      if (rsaCount === 0) {
        status = STATUS_NO;
      }

      accountsSheet.getRange(rowIndex + 1, 2).setValue(status);
      SpreadsheetApp.flush();
    }
  }
}

/**
 * Generates Responsive Text Ads for Google Ads Account.
 *
 * @param {!string} accountId A Google Ads Account Id.
 * @param {!SpreadsheetApp.Sheet} rsaSheet A sheet object to write the
 *     Responsive Text Ads details.
 */
function generateResponsiveSearchAdsForAccount(accountId, rsaSheet) {
  const groupedTextAds = {};
  const adsIterator = AdsApp.ads()
      .withCondition('Type=EXPANDED_TEXT_AD')
      .withCondition('Status=ENABLED')
      .withCondition('AdGroupStatus=ENABLED')
      .withCondition('CampaignStatus=ENABLED')
      .get();
  while (adsIterator.hasNext()) {
    var ad = adsIterator.next().asType().expandedTextAd();
    extractInfoFromExpandedTextAd(accountId, ad, groupedTextAds);
  }
  return writeToSheet(groupedTextAds, rsaSheet);
}

/**
 * Extracts details from an Expanded Text Ad and grouped it by AdGroup Id
 * and FinalUrl.
 *
 * @param {!string} accountId A Google Ads Account Id.
 * @param {!AdsApp.ExpandedTextAd} expandedTextAd An Expanded Text Ad object.
 * @param {!Object<string, !GroupedTextAd>} groupedTextAds An object of
 *     grouped Expanded Text Ads.
 */
function extractInfoFromExpandedTextAd(
    accountId, expandedTextAd, groupedTextAds) {
  const groupKey =
      expandedTextAd.getAdGroup().getId() + expandedTextAd.urls().getFinalUrl();

  if (!groupedTextAds[groupKey]) {
    groupedTextAds[groupKey] = {
      accountId: accountId,
      adgroupId: expandedTextAd.getAdGroup().getId(),
      adgroupName: expandedTextAd.getAdGroup().getName(),
      campaignName: expandedTextAd.getCampaign().getName(),
      headlines: [],
      descriptions: [],
      finalUrl: expandedTextAd.urls().getFinalUrl(),
      path1: expandedTextAd.getPath1(),
      path2: expandedTextAd.getPath2(),
    };
  }

  const adHeadlines = groupedTextAds[groupKey].headlines;
  const adDescriptions = groupedTextAds[groupKey].descriptions;

  addValidTextAd(expandedTextAd.getHeadlinePart1(), adHeadlines);
  addValidTextAd(expandedTextAd.getHeadlinePart2(), adHeadlines);
  addValidTextAd(expandedTextAd.getHeadlinePart3(), adHeadlines);
  addValidTextAd(expandedTextAd.getDescription(), adDescriptions);
  addValidTextAd(expandedTextAd.getDescription2(), adDescriptions);
}

/**
 * Adds to array if adText is not yet on the array and if its a valid ad text.
 * @param {!string} adText An Ad headline or description.
 * @param {!Array<string>} adTextArr An array of descriptions or headlines.
 */
function addValidTextAd(adText, adTextArr) {
  if (adText && !containsAdCustomizers(adText)
      && adTextArr.indexOf(adText) === -1) {
    adTextArr.push(adText);
  }
}

/**
 * Returns if adText contains an ad customizer.
 * @param {!string} adText An Ad headline or description.
 */
function containsAdCustomizers(adText) {
  if (adText.indexOf("{=") !== -1) {
    return true;
  }
  return false;
}

/**
 * Writes to sheet the grouped Expanded Text Ads as a Responsive Search Ad
 * details.
 *
 * @param {!Object<string, !GroupedTextAd>} groupedTextAds An object of
 *     grouped Expanded Text Ads.
 * @param {!SpreadsheetApp.Sheet} rsaSheet A sheet object to write the generated
 *     Responsive Search Ad details.
 */
function writeToSheet(groupedTextAds, rsaSheet) {
  const rows = [];
  for (var groupKey in groupedTextAds) {
    var groupedTextAd = groupedTextAds[groupKey];

    if (groupedTextAd.headlines.length > 4 &&
        groupedTextAd.descriptions.length > 1) {
      var row = [
        groupedTextAd.accountId,
        groupedTextAd.campaignName,
        groupedTextAd.adgroupId,
        groupedTextAd.adgroupName,
        'responsive search ad',
        'enabled',
        groupedTextAd.finalUrl,
        groupedTextAd.path1,
        groupedTextAd.path2,
      ];
      for (var i = 0; i < RSA_NUM_OF_HEADLINES; i++) {
        var headline = (groupedTextAd.headlines.length > i) ?
            groupedTextAd.headlines[i] : '';
        row.push(headline);
      }
      for (var i = 0; i < RSA_NUM_OF_DESCRIPTIONS; i++) {
        var description = (groupedTextAd.descriptions.length > i) ?
            groupedTextAd.descriptions[i] : '';
        row.push(description);
      }
      rows.push(row);
    }
  }

  if (rows.length > 0) {
    rsaSheet.getRange(rsaSheet.getLastRow() + 1, 1, rows.length, rows[0].length)
        .setValues(rows);
    return rows.length;
  }
  return 0;
}


text:
{-|
    Module      : Solutions.Solutions0XX
    Description : Solutions for problems 1-99

    This module contains all implemented solutions for problems with IDs between 1 and 99.
-}
module Solutions.Solutions0XX
    ( solveProblem0XX
    ) where

import Utils (ProblemID, Solution, js)

-- | Solutions for problems with IDs between 1 and 99.
solveProblem0XX :: ProblemID -> Maybe Solution
solveProblem0XX 1 = js 123456789 -- Edit this line
solveProblem0XX 2 = Just "Edit me!" -- Edit this line
-- Add further solutions here
solveProblem0XX _ = Nothing


text:
package javax.servlet.http;

import java.util.Enumeration;

import javax.servlet.ServletRequest;

/**
 * Extends the {@link javax.servlet.ServletRequest} interface to provide request
 * information for HTTP servlets.
 *
 *

 * The servlet container creates an HttpServletRequest object and
 * passes it as an argument to the servlet's service methods
 * (doGet, doPost, etc).
 */
public interface HttpServletRequest extends ServletRequest {

	/**
	 * String identifier for Basic authentication. Value "BASIC"
	 */
	public static final String BASIC_AUTH = "BASIC";
	/**
	 * String identifier for Form authentication. Value "FORM"
	 */
	public static final String FORM_AUTH = "FORM";
	/**
	 * String identifier for Client Certificate authentication. Value
	 * "CLIENT_CERT"
	 */
	public static final String CLIENT_CERT_AUTH = "CLIENT_CERT";
	/**
	 * String identifier for Digest authentication. Value "DIGEST"
	 */
	public static final String DIGEST_AUTH = "DIGEST";

	/**
	 * Returns the name of the authentication scheme used to protect the
	 * servlet. All servlet containers support basic, form and client
	 * certificate authentication, and may additionally support digest
	 * authentication. If the servlet is not authenticated null is
	 * returned.
	 *
	 *

	 * Same as the value of the CGI variable AUTH_TYPE.
	 *
	 *
	 * @return one of the static members BASIC_AUTH, FORM_AUTH,
	 *         CLIENT_CERT_AUTH, DIGEST_AUTH (suitable for == comparison) or the
	 *         container-specific string indicating the authentication scheme,
	 *         or null if the request was not authenticated.
	 *
	 */
	public String getAuthType();

	/**
	 * Returns an array containing all of the Cookie objects the
	 * client sent with this request. This method returns null if
	 * no cookies were sent.
	 *
	 * @return an array of all the Cookies included with this
	 *         request, or null if the request has no cookies
	 */
	public Cookie[] getCookies();

	/**
	 * Returns the value of the specified request header as a long
	 * value that represents a Date object. Use this method with
	 * headers that contain dates, such as If-Modified-Since.
	 *
	 *

	 * The date is returned as the number of milliseconds since January 1, 1970
	 * GMT. The header name is case insensitive.
	 *
	 *

	 * If the request did not have a header of the specified name, this method
	 * returns -1. If the header can't be converted to a date, the method throws
	 * an IllegalArgumentException.
	 *
	 * @param name
	 *            a String specifying the name of the header
	 *
	 * @return a long value representing the date specified in the
	 *         header expressed as the number of milliseconds since January 1,
	 *         1970 GMT, or -1 if the named header was not included with the
	 *         request
	 *
	 * @exception IllegalArgumentException
	 *                If the header value can't be converted to a date
	 */
	public long getDateHeader(String name);

	/**
	 * Returns the value of the specified request header as a
	 * String. If the request did not include a header of the
	 * specified name, this method returns null. If there are
	 * multiple headers with the same name, this method returns the first head
	 * in the request. The header name is case insensitive. You can use this
	 * method with any request header.
	 *
	 * @param name
	 *            a String specifying the header name
	 *
	 * @return a String containing the value of the requested
	 *         header, or null if the request does not have a
	 *         header of that name
	 */
	public String getHeader(String name);

	/**
	 * Returns all the values of the specified request header as an
	 * Enumeration of String objects.
	 *
	 *

	 * Some headers, such as Accept-Language can be sent by clients
	 * as several headers each with a different value rather than sending the
	 * header as a comma separated list.
	 *
	 *

	 * If the request did not include any headers of the specified name, this
	 * method returns an empty Enumeration. The header name is case
	 * insensitive. You can use this method with any request header.
	 *
	 * @param name
	 *            a String specifying the header name
	 *
	 * @return an Enumeration containing the values of the
	 *         requested header. If the request does not have any headers of
	 *         that name return an empty enumeration. If the container does not
	 *         allow access to header information, return null
	 */
	public Enumeration getHeaders(String name);

	/**
	 * Returns an enumeration of all the header names this request contains. If
	 * the request has no headers, this method returns an empty enumeration.
	 *
	 *

	 * Some servlet containers do not allow servlets to access headers using
	 * this method, in which case this method returns null
	 *
	 * @return an enumeration of all the header names sent with this request; if
	 *         the request has no headers, an empty enumeration; if the servlet
	 *         container does not allow servlets to use this method,
	 *         null
	 */
	public Enumeration getHeaderNames();

	/**
	 * Returns the value of the specified request header as an int.
	 * If the request does not have a header of the specified name, this method
	 * returns -1. If the header cannot be converted to an integer, this method
	 * throws a NumberFormatException.
	 *
	 *

	 * The header name is case insensitive.
	 *
	 * @param name
	 *            a String specifying the name of a request header
	 *
	 * @return an integer expressing the value of the request header or -1 if
	 *         the request doesn't have a header of this name
	 *
	 * @exception NumberFormatException
	 *                If the header value can't be converted to an
	 *                int
	 */
	public int getIntHeader(String name);

	/**
	 * Returns the name of the HTTP method with which this request was made, for
	 * example, GET, POST, or PUT. Same as the value of the CGI variable
	 * REQUEST_METHOD.
	 *
	 * @return a String specifying the name of the method with
	 *         which this request was made
	 */
	public String getMethod();

	/**
	 * Returns any extra path information associated with the URL the client
	 * sent when it made this request. The extra path information follows the
	 * servlet path but precedes the query string and will start with a "/"
	 * character.
	 *
	 *

	 * This method returns null if there was no extra path
	 * information.
	 *
	 *

	 * Same as the value of the CGI variable PATH_INFO.
	 *
	 *
	 * @return a String, decoded by the web container, specifying
	 *         extra path information that comes after the servlet path but
	 *         before the query string in the request URL; or null
	 *         if the URL does not have any extra path information
	 */
	public String getPathInfo();

	/**
	 * Returns any extra path information after the servlet name but before the
	 * query string, and translates it to a real path. Same as the value of the
	 * CGI variable PATH_TRANSLATED.
	 *
	 *

	 * If the URL does not have any extra path information, this method returns
	 * null or the servlet container cannot translate the virtual
	 * path to a real path for any reason (such as when the web application is
	 * executed from an archive).
	 *
	 * The web container does not decode this string.
	 *
	 * @return a String specifying the real path, or
	 *         null if the URL does not have any extra path
	 *         information
	 */
	public String getPathTranslated();

	/**
	 * Returns the portion of the request URI that indicates the context of the
	 * request. The context path always comes first in a request URI. The path
	 * starts with a "/" character but does not end with a "/" character. For
	 * servlets in the default (root) context, this method returns "". The
	 * container does not decode this string.
	 *
	 *
	 * @return a String specifying the portion of the request URI
	 *         that indicates the context of the request
	 */
	public String getContextPath();

	/**
	 * Returns the query string that is contained in the request URL after the
	 * path. This method returns null if the URL does not have a
	 * query string. Same as the value of the CGI variable QUERY_STRING.
	 *
	 * @return a String containing the query string or
	 *         null if the URL contains no query string. The value
	 *         is not decoded by the container.
	 */
	public String getQueryString();

	/**
	 * Returns the login of the user making this request, if the user has been
	 * authenticated, or null if the user has not been
	 * authenticated. Whether the user name is sent with each subsequent request
	 * depends on the browser and type of authentication. Same as the value of
	 * the CGI variable REMOTE_USER.
	 *
	 * @return a String specifying the login of the user making
	 *         this request, or null if the user login is not known
	 */
	public String getRemoteUser();

	/**
	 * Returns a boolean indicating whether the authenticated user is included
	 * in the specified logical "role". Roles and role membership can be defined
	 * using deployment descriptors. If the user has not been authenticated, the
	 * method returns false.
	 *
	 * @param role
	 *            a String specifying the name of the role
	 *
	 * @return a boolean indicating whether the user making this
	 *         request belongs to a given role; false if the user
	 *         has not been authenticated
	 */
	public boolean isUserInRole(String role);

	/**
	 * Returns a java.security.Principal object containing the name
	 * of the current authenticated user. If the user has not been
	 * authenticated, the method returns null.
	 *
	 * @return a java.security.Principal containing the name of the
	 *         user making this request; null if the user has not
	 *         been authenticated
	 */
	public java.security.Principal getUserPrincipal();

	/**
	 * Returns the session ID specified by the client. This may not be the same
	 * as the ID of the current valid session for this request. If the client
	 * did not specify a session ID, this method returns null.
	 *
	 * @return a String specifying the session ID, or
	 *         null if the request did not specify a session ID
	 *
	 * @see #isRequestedSessionIdValid
	 */
	public String getRequestedSessionId();

	/**
	 * Returns the part of this request's URL from the protocol name up to the
	 * query string in the first line of the HTTP request. The web container
	 * does not decode this String. For example:
	 *
	 *

	 *

	 * First line of HTTP request
	 * Returned Value
	 *

	 * POST /some/path.html HTTP/1.1
	 *
	 * /some/path.html
	 *

	 * GET http://foo.bar/a.html HTTP/1.0
	 *
	 * /a.html
	 *

	 * HEAD /xyz?a=b HTTP/1.1
	 *
	 * /xyz
	 *

	 *
	 *

	 * To reconstruct an URL with a scheme and host, use {@link #getRequestURL}.
	 *
	 * @return a String containing the part of the URL from the
	 *         protocol name up to the query string
	 */
	public String getRequestURI();

	/**
	 * Reconstructs the URL the client used to make the request. The returned
	 * URL contains a protocol, server name, port number, and server path, but
	 * it does not include query string parameters.
	 *
	 *

	 * Because this method returns a StringBuffer, not a string,
	 * you can modify the URL easily, for example, to append query parameters.
	 *
	 *

	 * This method is useful for creating redirect messages and for reporting
	 * errors.
	 *
	 * @return a StringBuffer object containing the reconstructed
	 *         URL
	 */
	public StringBuffer getRequestURL();

	/**
	 * Returns the part of this request's URL that calls the servlet. This path
	 * starts with a "/" character and includes either the servlet name or a
	 * path to the servlet, but does not include any extra path information or a
	 * query string. Same as the value of the CGI variable SCRIPT_NAME.
	 *
	 *

	 * This method will return an empty string ("") if the servlet used to
	 * process this request was matched using the "/*" pattern.
	 *
	 * @return a String containing the name or path of the servlet
	 *         being called, as specified in the request URL, decoded, or an
	 *         empty string if the servlet used to process the request is
	 *         matched using the "/*" pattern.
	 */
	public String getServletPath();

	/**
	 * Returns the current HttpSession associated with this request
	 * or, if there is no current session and create is true,
	 * returns a new session.
	 *
	 *

	 * If create is false and the request has no valid
	 * HttpSession, this method returns null.
	 *
	 *

	 * To make sure the session is properly maintained, you must call this
	 * method before the response is committed. If the container is using
	 * cookies to maintain session integrity and is asked to create a new
	 * session when the response is committed, an IllegalStateException is
	 * thrown.
	 *
	 * @param create
	 *            true to create a new session for this request if
	 *            necessary; false to return null if
	 *            there's no current session
	 *
	 *
	 * @return the HttpSession associated with this request or
	 *         null if create is false
	 *         and the request has no valid session
	 *
	 * @see #getSession()
	 */
	public HttpSession getSession(boolean create);

	/**
	 * Returns the current session associated with this request, or if the
	 * request does not have a session, creates one.
	 *
	 * @return the HttpSession associated with this request
	 *
	 * @see #getSession(boolean)
	 */
	public HttpSession getSession();

	/**
	 * Checks whether the requested session ID is still valid.
	 *
	 * @return true if this request has an id for a valid session
	 *         in the current session context; false otherwise
	 *
	 * @see #getRequestedSessionId
	 * @see #getSession
	 * @see HttpSessionContext
	 */
	public boolean isRequestedSessionIdValid();

	/**
	 * Checks whether the requested session ID came in as a cookie.
	 *
	 * @return true if the session ID came in as a cookie;
	 *         otherwise, false
	 *
	 *
	 * @see #getSession
	 */
	public boolean isRequestedSessionIdFromCookie();

	/**
	 * Checks whether the requested session ID came in as part of the request
	 * URL.
	 *
	 * @return true if the session ID came in as part of a URL;
	 *         otherwise, false
	 *
	 * @see #getSession
	 */
	public boolean isRequestedSessionIdFromURL();

	/**
	 * @deprecated As of Version 2.1 of the Java Servlet API, use
	 *             {@link #isRequestedSessionIdFromURL} instead.
	 */
	public boolean isRequestedSessionIdFromUrl();
}


text:
std::shared_ptr<VPackBuffer<uint8_t>> planCollections = R"=(
{
  "someDb": {
    "11111111": {
      "name": "leadingCollection",
      "replicationFactor": 3,
      "shards": {
        "s11": [
          "PRMR-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA",
          "PRMR-BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB",
          "PRMR-CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC"
        ]
      }
    },
    "22222222": {
      "name": "followingCollection",
      "replicationFactor": 2,
      "repairingDistributeShardsLike": "11111111",
      "shards": {
        "s22": [
          "PRMR-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA",
          "PRMR-BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB"
        ]
      }
    }
  }
}
)="_vpack;

// Agency output of .[0].arango.Supervision.Health
std::shared_ptr<VPackBuffer<uint8_t>> supervisionHealth4Healthy0Bad = R"=(
{
  "PRMR-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA": {
    "Status": "GOOD"
  },
  "PRMR-BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB": {
    "Status": "GOOD"
  },
  "PRMR-CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC": {
    "Status": "GOOD"
  },
  "PRMR-DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD": {
    "Status": "GOOD"
  }
}
)="_vpack;

std::map<CollectionID, ResultT<std::vector<RepairOperation>>>
    expectedResultsWithRepairingDistributeShardsLike{
        {"22222222",
         Result(TRI_ERROR_CLUSTER_REPAIRS_REPLICATION_FACTOR_VIOLATED,
                "replicationFactor is violated: Collection "
                "someDb/followingCollection and its distributeShardsLike "
                "prototype someDb/leadingCollection have 0 and 1 different "
                "(mismatching) DBServers, respectively.")}};


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.10-b140310.1920
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.09.15 at 01:49:55 PM CEST
//

package pl.coderion.aml.generated;

import java.math.BigInteger;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;

/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * generated in the pl.coderion.aml.generated package.
 *
An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

    private final static QName _TKw_QNAME = new QName("", "tKw");
    private final static QName _TJZ_QNAME = new QName("", "tJZ");
    private final static QName _NrRachZ_QNAME = new QName("", "nrRachZ");
    private final static QName _RejDat_QNAME = new QName("", "rejDat");
    private final static QName _KRodzTr_QNAME = new QName("", "kRodzTr");
    private final static QName _NrRejDat_QNAME = new QName("", "nrRejDat");
    private final static QName _AdrM_QNAME = new QName("", "adrM");
    private final static QName _TJ_QNAME = new QName("", "tJ");
    private final static QName _KPwz_QNAME = new QName("", "kPwz");
    private final static QName _TM_QNAME = new QName("", "tM");
    private final static QName _Beneficjent_QNAME = new QName("", "Beneficjent");
    private final static QName _NrReS_QNAME = new QName("", "nrReS");
    private final static QName _NrDokTo_QNAME = new QName("", "nrDokTo");
    private final static QName _AdrUl_QNAME = new QName("", "adrUl");
    private final static QName _TypPdm_QNAME = new QName("", "typPdm");
    private final static QName _Wlasciciel_QNAME = new QName("", "Wlasciciel");
    private final static QName _NrDokT_QNAME = new QName("", "nrDokT");
    private final static QName _Uwagi_QNAME = new QName("", "Uwagi");
    private final static QName _SpDysp_QNAME = new QName("", "spDysp");
    private final static QName _JedIO_QNAME = new QName("", "jedIO");
    private final static QName _Dysponent_QNAME = new QName("", "Dysponent");
    private final static QName _Nz_QNAME = new QName("", "Nz");
    private final static QName _AdrKod_QNAME = new QName("", "adrKod");
    private final static QName _TKwZ_QNAME = new QName("", "tKwZ");
    private final static QName _NrSwt_QNAME = new QName("", "nrSwt");
    private final static QName _AdrKr_QNAME = new QName("", "adrKr");
    private final static QName _NrRachNa_QNAME = new QName("", "nrRachNa");
    private final static QName _NrReg_QNAME = new QName("", "nrReg");
    private final static QName _Obyw_QNAME = new QName("", "Obyw");
    private final static QName _Nip_QNAME = new QName("", "Nip");
    private final static QName _TDat_QNAME = new QName("", "tDat");
    private final static QName _NrPes_QNAME = new QName("", "nrPes");
    private final static QName _NrEwT_QNAME = new QName("", "nrEwT");
    private final static QName _KPdjrz_QNAME = new QName("", "kPdjrz");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: pl.coderion.aml.generated
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link Rachunki }
     *
     */
    public Rachunki createRachunki() {
        return new Rachunki();
    }

    /**
     * Create an instance of {@link KartaTr }
     *
     */
    public KartaTr createKartaTr() {
        return new KartaTr();
    }

    /**
     * Create an instance of {@link IdentTr }
     *
     */
    public IdentTr createIdentTr() {
        return new IdentTr();
    }

    /**
     * Create an instance of {@link DaneTr }
     *
     */
    public DaneTr createDaneTr() {
        return new DaneTr();
    }

    /**
     * Create an instance of {@link Podmiot }
     *
     */
    public Podmiot createPodmiot() {
        return new Podmiot();
    }

    /**
     * Create an instance of {@link RodzDokTo }
     *
     */
    public RodzDokTo createRodzDokTo() {
        return new RodzDokTo();
    }

    /**
     * Create an instance of {@link WykazTr }
     *
     */
    public WykazTr createWykazTr() {
        return new WykazTr();
    }

    /**
     * Create an instance of {@link Adres }
     *
     */
    public Adres createAdres() {
        return new Adres();
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "tKw")
    public JAXBElement<String> createTKw(String value) {
        return new JAXBElement<String>(_TKw_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "tJZ")
    public JAXBElement<String> createTJZ(String value) {
        return new JAXBElement<String>(_TJZ_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "nrRachZ")
    public JAXBElement<String> createNrRachZ(String value) {
        return new JAXBElement<String>(_NrRachZ_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link BigInteger }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "rejDat")
    public JAXBElement<BigInteger> createRejDat(BigInteger value) {
        return new JAXBElement<BigInteger>(_RejDat_QNAME, BigInteger.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "kRodzTr")
    public JAXBElement<String> createKRodzTr(String value) {
        return new JAXBElement<String>(_KRodzTr_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link BigInteger }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "nrRejDat")
    public JAXBElement<BigInteger> createNrRejDat(BigInteger value) {
        return new JAXBElement<BigInteger>(_NrRejDat_QNAME, BigInteger.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "adrM")
    public JAXBElement<String> createAdrM(String value) {
        return new JAXBElement<String>(_AdrM_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "tJ")
    public JAXBElement<String> createTJ(String value) {
        return new JAXBElement<String>(_TJ_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link BigInteger }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "kPwz")
    public JAXBElement<BigInteger> createKPwz(BigInteger value) {
        return new JAXBElement<BigInteger>(_KPwz_QNAME, BigInteger.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "tM")
    public JAXBElement<String> createTM(String value) {
        return new JAXBElement<String>(_TM_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Podmiot }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "Beneficjent")
    public JAXBElement<Podmiot> createBeneficjent(Podmiot value) {
        return new JAXBElement<Podmiot>(_Beneficjent_QNAME, Podmiot.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "nrReS")
    public JAXBElement<String> createNrReS(String value) {
        return new JAXBElement<String>(_NrReS_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "nrDokTo")
    public JAXBElement<String> createNrDokTo(String value) {
        return new JAXBElement<String>(_NrDokTo_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "adrUl")
    public JAXBElement<String> createAdrUl(String value) {
        return new JAXBElement<String>(_AdrUl_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "typPdm")
    public JAXBElement<String> createTypPdm(String value) {
        return new JAXBElement<String>(_TypPdm_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Podmiot }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "Wlasciciel")
    public JAXBElement<Podmiot> createWlasciciel(Podmiot value) {
        return new JAXBElement<Podmiot>(_Wlasciciel_QNAME, Podmiot.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "nrDokT")
    public JAXBElement<String> createNrDokT(String value) {
        return new JAXBElement<String>(_NrDokT_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "Uwagi")
    public JAXBElement<String> createUwagi(String value) {
        return new JAXBElement<String>(_Uwagi_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link BigInteger }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "spDysp")
    public JAXBElement<BigInteger> createSpDysp(BigInteger value) {
        return new JAXBElement<BigInteger>(_SpDysp_QNAME, BigInteger.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link BigInteger }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "jedIO")
    public JAXBElement<BigInteger> createJedIO(BigInteger value) {
        return new JAXBElement<BigInteger>(_JedIO_QNAME, BigInteger.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Podmiot }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "Dysponent")
    public JAXBElement<Podmiot> createDysponent(Podmiot value) {
        return new JAXBElement<Podmiot>(_Dysponent_QNAME, Podmiot.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "Nz")
    public JAXBElement<String> createNz(String value) {
        return new JAXBElement<String>(_Nz_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "adrKod")
    public JAXBElement<String> createAdrKod(String value) {
        return new JAXBElement<String>(_AdrKod_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "tKwZ")
    public JAXBElement<String> createTKwZ(String value) {
        return new JAXBElement<String>(_TKwZ_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "nrSwt")
    public JAXBElement<String> createNrSwt(String value) {
        return new JAXBElement<String>(_NrSwt_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "adrKr")
    public JAXBElement<String> createAdrKr(String value) {
        return new JAXBElement<String>(_AdrKr_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "nrRachNa")
    public JAXBElement<String> createNrRachNa(String value) {
        return new JAXBElement<String>(_NrRachNa_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "nrReg")
    public JAXBElement<String> createNrReg(String value) {
        return new JAXBElement<String>(_NrReg_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "Obyw")
    public JAXBElement<String> createObyw(String value) {
        return new JAXBElement<String>(_Obyw_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link BigInteger }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "Nip")
    public JAXBElement<BigInteger> createNip(BigInteger value) {
        return new JAXBElement<BigInteger>(_Nip_QNAME, BigInteger.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link BigInteger }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "tDat")
    public JAXBElement<BigInteger> createTDat(BigInteger value) {
        return new JAXBElement<BigInteger>(_TDat_QNAME, BigInteger.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "nrPes")
    public JAXBElement<String> createNrPes(String value) {
        return new JAXBElement<String>(_NrPes_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "nrEwT")
    public JAXBElement<String> createNrEwT(String value) {
        return new JAXBElement<String>(_NrEwT_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "", name = "kPdjrz")
    public JAXBElement<String> createKPdjrz(String value) {
        return new JAXBElement<String>(_KPdjrz_QNAME, String.class, null, value);
    }

}


text:
@interface SDCAlertPresentationController ()

@property (nonatomic, strong) UIView *dimmingView;

@end

@implementation SDCAlertPresentationController

- (instancetype)initWithPresentedViewController:(UIViewController *)presentedViewController presentingViewController:(UIViewController *)presentingViewController {
    self = [super initWithPresentedViewController:presentedViewController presentingViewController:presentedViewController];
    if (!self)
        return nil;

    _dimmingView = [[UIView alloc] init];
    _dimmingView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];

    return self;
}

- (void)presentationTransitionWillBegin {
    [super presentationTransitionWillBegin];

    self.presentingViewController.view.tintAdjustmentMode = UIViewTintAdjustmentModeDimmed;

    self.dimmingView.alpha = 0;
    [[self containerView] addSubview:self.dimmingView];

    [self.presentedViewController.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        self.dimmingView.alpha = 1;
    } completion:nil];
}

- (void)dismissalTransitionWillBegin {
    [super dismissalTransitionWillBegin];

    self.presentingViewController.view.tintAdjustmentMode = UIViewTintAdjustmentModeAutomatic;

    [self.presentedViewController.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        self.dimmingView.alpha = 0;
    } completion:nil];
}

- (void)containerViewWillLayoutSubviews {
    [super containerViewWillLayoutSubviews];
    if (!self.containerView)
        return;

    self.dimmingView.frame = self.containerView.frame;
}

@end


text:
SC.RecordArray.prototype.whenReady = function(callback) {
  if(!callback) {
    return this;
  } else if(this.get('status') & SC.Record.READY) {
    callback(this);
  } else {
    // this.addObserver('status', function() {
    //   if(this.get('status') & SC.Record.READY) { callback(this); }
    // })
  }
  return this;
};

Travis.Record = SC.Record.extend({
  childRecordNamespace: Travis,
  primaryKey: 'id',
  id: SC.Record.attr(Number),

  isReady: function() {
    return (this.get('status') & SC.Record.READY) != 0;
  }.property(),

  update: function(attrs) {
    this.whenReady(function(record) {
      $.each(attrs, function(key, value) {
        if(key != 'id') record.set(key, value);
      });
    });
    return this;
  },

  whenReady: function(callback) {
    if(!callback) {
      return this;
    } else if(this.get('isReady')) {
      callback(this);
    } else {
      // this.addObserver('status', function() {
      //   if(this.get('status') & SC.Record.READY) { callback(this); }
      // })
    }
    return this;
  }
});

Travis.Record.reopenClass({
  exists: function(id) {
    if(id === undefined) throw('id is undefined');
    return Travis.store.storeKeyExists(this, id);
  },

  createOrUpdate: function(attrs) {
    if(this.exists(attrs.id)) {
      return this.update(attrs);
    } else {
      return Travis.store.createRecord(this, attrs);
    }
  },

  update: function(attrs) {
    if(attrs.id === undefined) throw('id is undefined');
    var record = this.find(attrs.id);
    return record.update(attrs);
  },

  find: function(id, callback) {
    if(id === undefined) throw('id is undefined');
    var record = Travis.store.find(this, id);
    return record ? record.whenReady(callback) : record;
  },

  all: function(options, mode) {
    return Travis.store.find(Travis.Query.cached(this, options || {}, mode));
  }
});


text:
package uk.ac.manchester.cs.jfact.elf;

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

import org.semanticweb.owlapi.model.OWLAxiom;

import uk.ac.manchester.cs.jfact.helpers.UnreachableSituationException;
import uk.ac.manchester.cs.jfact.kernel.ExpressionManager;
import uk.ac.manchester.cs.jfact.kernel.Ontology;
import uk.ac.manchester.cs.jfact.kernel.dl.*;
import uk.ac.manchester.cs.jfact.kernel.dl.axioms.*;
import uk.ac.manchester.cs.jfact.kernel.dl.interfaces.Axiom;
import uk.ac.manchester.cs.jfact.kernel.dl.interfaces.ConceptExpression;
import uk.ac.manchester.cs.jfact.kernel.dl.interfaces.Expression;
import uk.ac.manchester.cs.jfact.kernel.dl.interfaces.ObjectRoleExpression;
import uk.ac.manchester.cs.jfact.visitors.DLAxiomVisitorAdapter;
import conformance.PortedFrom;

@PortedFrom(file = "ELFNormalizer.h", name = "ELFNormalizer")
public class ELFNormalizer extends DLAxiomVisitorAdapter {
    /** expression manager to build aux expressions */
    @PortedFrom(file = "ELFNormalizer.h", name = "pEM")
    ExpressionManager pEM;
    /** set of new/procesed axioms */
    @PortedFrom(file = "ELFNormalizer.h", name = "Axioms")
    List<Axiom> Axioms = new ArrayList<Axiom>();
    /** index of a freah variable */
    @PortedFrom(file = "ELFNormalizer.h", name = "index")
    int index;
    /** true iff the axiom was changed after visiting */
    @PortedFrom(file = "ELFNormalizer.h", name = "changed")
    boolean changed;
    /** true iff RHS is in a form \ER.C */
    @PortedFrom(file = "ELFNormalizer.h", name = "eRHS")
    boolean eRHS;

    /** process the axiom and mark it unused if necessary */
    @PortedFrom(file = "ELFNormalizer.h", name = "v")
    void v(Axiom ax) {
        ax.accept(this);
        if (changed) {
            ax.setUsed(false);
        }
    }

    /** add axiom to a list */
    @PortedFrom(file = "ELFNormalizer.h", name = "addAxiom")
    void addAxiom(Axiom ax) {
        Axioms.add(ax);
    }

    /** create a new name */
    @PortedFrom(file = "ELFNormalizer.h", name = "buildFreshName")
    ConceptExpression buildFreshName() {
        // TODO check: should the string start with a space?
        return pEM.concept(" ELF_aux_" + index);
    }

    /** split C [= D1 \and \and Dn into C [= D1, C [= Dn */
    @PortedFrom(file = "ELFNormalizer.h", name = "splitAndRHS")
    boolean splitAndRHS(OWLAxiom ax, ConceptExpression C, ConceptAnd D) {
        if (D == null) {
            return false;
        }
        // make new axioms
        for (ConceptExpression p : D.getArguments()) {
            addAxiom(new AxiomConceptInclusion(ax, C, p));
        }
        return true;
    }

    /** transform RHS into normalized one. @return a normalized RHS. Set the eRHS
     * flag if it is an existential */
    @PortedFrom(file = "ELFNormalizer.h", name = "transformExists")
    ConceptExpression transformExists(OWLAxiom ax, ConceptExpression D) {
        eRHS = false;
        // RHS now contains only Bot, A, \E R.C
        if (!(D instanceof ConceptObjectExists)) {
            assert D instanceof ConceptName || D instanceof ConceptBottom
                    || D instanceof ConceptTop;
            // for LHS
            return D;
        }
        ConceptObjectExists exists = (ConceptObjectExists) D;
        // check the filler
        ConceptExpression C = exists.getConcept();
        // if the filler is Bot, then the whole expression is bottom
        if (C instanceof ConceptBottom) {
            return C;
        }
        // if the filler is Top or CN then keep the expression
        eRHS = true;
        if (C instanceof ConceptName || C instanceof ConceptTop) {
            return D;
        }
        // complex filler: replace C with new B and the axiom B = C
        ConceptExpression B = buildFreshName();
        List<Expression> args = new ArrayList<Expression>();
        args.add(B);
        args.add(C);
        addAxiom(new AxiomEquivalentConcepts(ax, args));
        return pEM.exists(exists.getOR(), B);
    }

    /** transform conjunction into the binary one with named concepts in it;
     * simplify */
    @PortedFrom(file = "ELFNormalizer.h", name = "normalizeLHSAnd")
    ConceptExpression normalizeLHSAnd(OWLAxiom ax, ConceptAnd C) {
        if (C == null) {
            return null;
        }
        List<ConceptExpression> args = new ArrayList<ConceptExpression>();
        // check for bottom argument
        for (ConceptExpression p : C.getArguments()) {
            if (p instanceof ConceptBottom) {
                return p;
                // all And is equivalent to bottom
            }
        }
        // preprocess conjunctions
        boolean change = false;
        for (ConceptExpression p : C.getArguments()) {
            if (p instanceof ConceptTop) {
                change = true;
                continue;
                // skip Tops there
            }
            if (p instanceof ConceptName) {
                args.add(p);
                // keep concept name
            } else {
                // complex expression -- replace with new name
                ConceptExpression A = buildFreshName();
                // it's enough to use implication here
                addAxiom(new AxiomConceptInclusion(ax, p, A));
                args.add(A);
                change = true;
            }
        }
        // check already-binary thing
        if (!change && args.size() == 2 && !eRHS) {
            return C;
        }
        // make conjunction binary
        ConceptExpression B = args.get(0);
        // check the corner case: singleton conjunction
        if (args.size() == 1) {
            return B;
        }
        int size = args.size();
        if (!eRHS) {
            size--;
        }
        // now we have B1 and ... and Bn [= X
        int i;
        for (i = 1; i < size; i++) {
            // transform into B1 and B2 [= A, A and... Bn [= X
            ConceptExpression A = buildFreshName();
            addAxiom(new AxiomConceptInclusion(ax, pEM.and(B, args.get(i)), A));
            B = A;
        }
        // now B and q=q_last are the only conjuncts
        return eRHS ? B : pEM.and(B, args.get(i));
    }

    /** transform LHS into normalized one. @return a normalized LHS */
    @PortedFrom(file = "ELFNormalizer.h", name = "transformLHS")
    ConceptExpression transformLHS(OWLAxiom ax, ConceptExpression C) {
        // here C is Top, A, AND and Exists
        // first normalize LHS And to contain only 2 names (or less)
        ConceptExpression And = normalizeLHSAnd(ax, (ConceptAnd) C);
        if (And != null) {
            C = And;
        }
        if (C instanceof ConceptAnd) {
            return C;
        }
        // LHS is Top,Bot,A and exists
        boolean flag = eRHS;
        C = transformExists(ax, C); // normalize exists
        if (!(C instanceof ConceptObjectExists)) {
            return C;
        }
        if (flag) // need intermediate var: can't have ER.X [= ES.D
        {
            // make C=ER.X [= B for fresh B
            ConceptExpression B = buildFreshName();
            addAxiom(new AxiomConceptInclusion(ax, C, B));
            return B;
        }
        // here ER.X [= A
        return C;
    }

    // need only do something with a very few axioms as others doesn't present
    // here
    /** replace it with C0 [= Ci, Ci [= C0 */
    @Override
    public void visit(AxiomEquivalentConcepts axiom) {
        List<ConceptExpression> list = axiom.getArguments();
        ConceptExpression C = list.get(0);
        for (int i = 1; i < list.size(); i++) {
            addAxiom(new AxiomConceptInclusion(axiom.getOWLAxiom(), C, list.get(i)));
            addAxiom(new AxiomConceptInclusion(axiom.getOWLAxiom(), list.get(i), C));
        }
        changed = true;
    }

    /** replace with Ci \and Cj [= \bot for 0 <= i < j < n */
    @Override
    public void visit(AxiomDisjointConcepts axiom) {
        ConceptExpression bot = pEM.bottom();
        List<ConceptExpression> arguments = axiom.getArguments();
        for (int i = 0; i < arguments.size(); i++) {
            // FIXME!! replace with new var strait away if necessary
            ConceptExpression C = arguments.get(i);
            for (int j = i + 1; j < arguments.size(); j++) {
                addAxiom(new AxiomConceptInclusion(axiom.getOWLAxiom(), pEM.and(C,
                        arguments.get(j)), bot));
            }
        }
        changed = true;
    }

    /** the only legal one contains a single element, so is C = D */
    @Override
    public void visit(AxiomDisjointUnion axiom) {
        changed = true;
        // replace it anyway
        switch (axiom.size()) {
            case 0:
                // strange, but...
                return;
            case 1:
                // single element, use C=D processing
                addAxiom(new AxiomConceptInclusion(axiom.getOWLAxiom(), axiom.getC(),
                        axiom.getArguments().get(0)));
                addAxiom(new AxiomConceptInclusion(axiom.getOWLAxiom(), axiom
                        .getArguments().get(0), axiom.getC()));
                break;
            default:
                // impossible here
                throw new UnreachableSituationException();
        }
    }

    /** normalize equivalence as a number of subsumptions R0 [= Ri, Ri [= R0 */
    @Override
    public void visit(AxiomEquivalentORoles axiom) {
        List<ObjectRoleExpression> arguments = axiom.getArguments();
        ObjectRoleExpression R = arguments.get(0);
        for (int i = 1; i < arguments.size(); i++) {
            addAxiom(new AxiomORoleSubsumption(axiom.getOWLAxiom(), R, arguments.get(i)));
            addAxiom(new AxiomORoleSubsumption(axiom.getOWLAxiom(), arguments.get(i), R));
        }
        changed = true;
    }

    /** already canonical */
    @Override
    public void visit(AxiomORoleSubsumption axiom) {
        changed = false;
    }

    /** normalize transitivity as role inclusion */
    @Override
    public void visit(AxiomRoleTransitive axiom) {
        ObjectRoleExpression R = axiom.getRole();
        addAxiom(new AxiomORoleSubsumption(axiom.getOWLAxiom(), pEM.compose(R, R), R));
        changed = true;
    }

    /** all the job is done here */
    @Override
    public void visit(AxiomConceptInclusion axiom) {
        ConceptExpression C = axiom.getSubConcept(), D = axiom.getSupConcept();
        // skip tautologies
        changed = true;
        // \bot [= D is skipped
        if (C instanceof ConceptBottom) {
            return;
        }
        // C [= \top is skipped
        if (D instanceof ConceptTop) {
            return;
        }
        // split the RHS if necessary
        if (splitAndRHS(axiom.getOWLAxiom(), C, (ConceptAnd) D)) {
            return;
        }
        // do the transformation itself
        // RHS now contains only Bot, A, \E R.C
        ConceptExpression newD = transformExists(axiom.getOWLAxiom(), D);
        ConceptExpression newC = transformLHS(axiom.getOWLAxiom(), C);
        if (newC == C && newD == D) {
            changed = false; // nothing changed
        } else // not add axiom
        if (!(newC instanceof ConceptBottom)) {
            addAxiom(new AxiomConceptInclusion(axiom.getOWLAxiom(), newC, newD));
        }
    }

    @Override
    @PortedFrom(file = "ELFNormalizer.h", name = "visitOntology")
    public void visitOntology(Ontology ontology) {
        for (Axiom p : ontology.getAxioms()) {
            if (p.isUsed()) {
                v(p);
            }
        }
        // will add to Axioms during the process, so can't use iterators
        for (int i = 0; i < Axioms.size(); ++i) {
            v(Axioms.get(i));
        }
        for (int i = 0; i < Axioms.size();) {
            if (Axioms.get(i).isUsed()) {
                ontology.add(Axioms.get(i));
                i++;
            } else {
                Axioms.remove(i);
            }
        }
    }

    public ELFNormalizer(ExpressionManager p) {
        pEM = p;
        index = 0;
    }
}


text:
using System;
using System.Reactive.Subjects;

namespace StompSharp.Transport
{
    public class LateSubscriber<T> : IDisposable
    {
        private readonly IDisposable _subscription;
        private readonly ReplaySubject<T> _subject;

        public LateSubscriber(IObservable<T> observable)
        {
            _subject = new ReplaySubject<T>(int.MaxValue);
            _subscription = observable.Subscribe(_subject);
        }

        public IObservable<T> RecordedItems
        {
            get { return _subject; }
        }

        public void Dispose()
        {
            _subscription.Dispose();
            _subject.Dispose();
        }
    }
}