text:
/**
 */
package CIM15.IEC61970.Informative.InfOperations;

import CIM15.IEC61970.Core.IdentifiedObject;
import CIM15.IEC61970.Core.PowerSystemResource;

import CIM15.IEC61970.Domain.DateTimeInterval;

import java.util.Collection;

import org.eclipse.emf.common.notify.NotificationChain;

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

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.util.BasicInternalEList;
import org.eclipse.emf.ecore.util.InternalEList;

/**
 *
 * A representation of the model object 'Switching Step'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getSafetyDocument Safety Document}

 *
{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getStatusKind Status Kind}

 *
{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getText Text}

 *
{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getRequiredControlActionInterval Required Control Action Interval}

 *
{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getRequiredControlAction Required Control Action}

 *
{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getSwitchingSchedule Switching Schedule}

 *
{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getPowerSystemResources Power System Resources}

 *
{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getErpPersonRole Erp Person Role}

 *
{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getDesiredEndState Desired End State}

 *

 *

 *
 * @generated
 */
public class SwitchingStep extends IdentifiedObject {
	/**
	 * The cached value of the '{@link #getSafetyDocument() Safety Document}' reference.
	 *
	 *
	 * @see #getSafetyDocument()
	 * @generated
	 * @ordered
	 */
	protected SafetyDocument safetyDocument;

	/**
	 * The default value of the '{@link #getStatusKind() Status Kind}' attribute.
	 *
	 *
	 * @see #getStatusKind()
	 * @generated
	 * @ordered
	 */
	protected static final SwitchingStepStatusKind STATUS_KIND_EDEFAULT = SwitchingStepStatusKind.INSTRUCTED;

	/**
	 * The cached value of the '{@link #getStatusKind() Status Kind}' attribute.
	 *
	 *
	 * @see #getStatusKind()
	 * @generated
	 * @ordered
	 */
	protected SwitchingStepStatusKind statusKind = STATUS_KIND_EDEFAULT;

	/**
	 * This is true if the Status Kind attribute has been set.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	protected boolean statusKindESet;

	/**
	 * The default value of the '{@link #getText() Text}' attribute.
	 *
	 *
	 * @see #getText()
	 * @generated
	 * @ordered
	 */
	protected static final String TEXT_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getText() Text}' attribute.
	 *
	 *
	 * @see #getText()
	 * @generated
	 * @ordered
	 */
	protected String text = TEXT_EDEFAULT;

	/**
	 * This is true if the Text attribute has been set.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	protected boolean textESet;

	/**
	 * The cached value of the '{@link #getRequiredControlActionInterval() Required Control Action Interval}' containment reference.
	 *
	 *
	 * @see #getRequiredControlActionInterval()
	 * @generated
	 * @ordered
	 */
	protected DateTimeInterval requiredControlActionInterval;

	/**
	 * The default value of the '{@link #getRequiredControlAction() Required Control Action}' attribute.
	 *
	 *
	 * @see #getRequiredControlAction()
	 * @generated
	 * @ordered
	 */
	protected static final String REQUIRED_CONTROL_ACTION_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getRequiredControlAction() Required Control Action}' attribute.
	 *
	 *
	 * @see #getRequiredControlAction()
	 * @generated
	 * @ordered
	 */
	protected String requiredControlAction = REQUIRED_CONTROL_ACTION_EDEFAULT;

	/**
	 * This is true if the Required Control Action attribute has been set.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	protected boolean requiredControlActionESet;

	/**
	 * The cached value of the '{@link #getSwitchingSchedule() Switching Schedule}' reference.
	 *
	 *
	 * @see #getSwitchingSchedule()
	 * @generated
	 * @ordered
	 */
	protected SwitchingSchedule switchingSchedule;

	/**
	 * The cached value of the '{@link #getPowerSystemResources() Power System Resources}' reference list.
	 *
	 *
	 * @see #getPowerSystemResources()
	 * @generated
	 * @ordered
	 */
	protected EList<PowerSystemResource> powerSystemResources;

	/**
	 * The cached value of the '{@link #getErpPersonRole() Erp Person Role}' reference.
	 *
	 *
	 * @see #getErpPersonRole()
	 * @generated
	 * @ordered
	 */
	protected ErpPersonScheduleStepRole erpPersonRole;

	/**
	 * The default value of the '{@link #getDesiredEndState() Desired End State}' attribute.
	 *
	 *
	 * @see #getDesiredEndState()
	 * @generated
	 * @ordered
	 */
	protected static final String DESIRED_END_STATE_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getDesiredEndState() Desired End State}' attribute.
	 *
	 *
	 * @see #getDesiredEndState()
	 * @generated
	 * @ordered
	 */
	protected String desiredEndState = DESIRED_END_STATE_EDEFAULT;

	/**
	 * This is true if the Desired End State attribute has been set.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	protected boolean desiredEndStateESet;

	/**
	 *
	 *
	 * @generated
	 */
	protected SwitchingStep() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return InfOperationsPackage.Literals.SWITCHING_STEP;
	}

	/**
	 * Returns the value of the 'Safety Document' reference.
	 * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Informative.InfOperations.SafetyDocument#getScheduleSteps Schedule Steps}'.
	 *
	 *

	 * If the meaning of the 'Safety Document' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Safety Document' reference.
	 * @see #setSafetyDocument(SafetyDocument)
	 * @see CIM15.IEC61970.Informative.InfOperations.SafetyDocument#getScheduleSteps
	 * @generated
	 */
	public SafetyDocument getSafetyDocument() {
		if (safetyDocument != null && safetyDocument.eIsProxy()) {
			InternalEObject oldSafetyDocument = (InternalEObject)safetyDocument;
			safetyDocument = (SafetyDocument)eResolveProxy(oldSafetyDocument);
			if (safetyDocument != oldSafetyDocument) {
			}
		}
		return safetyDocument;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public SafetyDocument basicGetSafetyDocument() {
		return safetyDocument;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetSafetyDocument(SafetyDocument newSafetyDocument, NotificationChain msgs) {
		SafetyDocument oldSafetyDocument = safetyDocument;
		safetyDocument = newSafetyDocument;
		return msgs;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getSafetyDocument Safety Document}' reference.
	 *
	 *
	 * @param value the new value of the 'Safety Document' reference.
	 * @see #getSafetyDocument()
	 * @generated
	 */
	public void setSafetyDocument(SafetyDocument newSafetyDocument) {
		if (newSafetyDocument != safetyDocument) {
			NotificationChain msgs = null;
			if (safetyDocument != null)
				msgs = ((InternalEObject)safetyDocument).eInverseRemove(this, InfOperationsPackage.SAFETY_DOCUMENT__SCHEDULE_STEPS, SafetyDocument.class, msgs);
			if (newSafetyDocument != null)
				msgs = ((InternalEObject)newSafetyDocument).eInverseAdd(this, InfOperationsPackage.SAFETY_DOCUMENT__SCHEDULE_STEPS, SafetyDocument.class, msgs);
			msgs = basicSetSafetyDocument(newSafetyDocument, msgs);
			if (msgs != null) msgs.dispatch();
		}
	}

	/**
	 * Returns the value of the 'Status Kind' attribute.
	 * The literals are from the enumeration {@link CIM15.IEC61970.Informative.InfOperations.SwitchingStepStatusKind}.
	 *
	 *

	 * If the meaning of the 'Status Kind' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Status Kind' attribute.
	 * @see CIM15.IEC61970.Informative.InfOperations.SwitchingStepStatusKind
	 * @see #isSetStatusKind()
	 * @see #unsetStatusKind()
	 * @see #setStatusKind(SwitchingStepStatusKind)
	 * @generated
	 */
	public SwitchingStepStatusKind getStatusKind() {
		return statusKind;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getStatusKind Status Kind}' attribute.
	 *
	 *
	 * @param value the new value of the 'Status Kind' attribute.
	 * @see CIM15.IEC61970.Informative.InfOperations.SwitchingStepStatusKind
	 * @see #isSetStatusKind()
	 * @see #unsetStatusKind()
	 * @see #getStatusKind()
	 * @generated
	 */
	public void setStatusKind(SwitchingStepStatusKind newStatusKind) {
		statusKind = newStatusKind == null ? STATUS_KIND_EDEFAULT : newStatusKind;
		statusKindESet = true;
	}

	/**
	 * Unsets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getStatusKind Status Kind}' attribute.
	 *
	 *
	 * @see #isSetStatusKind()
	 * @see #getStatusKind()
	 * @see #setStatusKind(SwitchingStepStatusKind)
	 * @generated
	 */
	public void unsetStatusKind() {
		statusKind = STATUS_KIND_EDEFAULT;
		statusKindESet = false;
	}

	/**
	 * Returns whether the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getStatusKind Status Kind}' attribute is set.
	 *
	 *
	 * @return whether the value of the 'Status Kind' attribute is set.
	 * @see #unsetStatusKind()
	 * @see #getStatusKind()
	 * @see #setStatusKind(SwitchingStepStatusKind)
	 * @generated
	 */
	public boolean isSetStatusKind() {
		return statusKindESet;
	}

	/**
	 * Returns the value of the 'Text' attribute.
	 *
	 *

	 * If the meaning of the 'Text' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Text' attribute.
	 * @see #isSetText()
	 * @see #unsetText()
	 * @see #setText(String)
	 * @generated
	 */
	public String getText() {
		return text;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getText Text}' attribute.
	 *
	 *
	 * @param value the new value of the 'Text' attribute.
	 * @see #isSetText()
	 * @see #unsetText()
	 * @see #getText()
	 * @generated
	 */
	public void setText(String newText) {
		text = newText;
		textESet = true;
	}

	/**
	 * Unsets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getText Text}' attribute.
	 *
	 *
	 * @see #isSetText()
	 * @see #getText()
	 * @see #setText(String)
	 * @generated
	 */
	public void unsetText() {
		text = TEXT_EDEFAULT;
		textESet = false;
	}

	/**
	 * Returns whether the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getText Text}' attribute is set.
	 *
	 *
	 * @return whether the value of the 'Text' attribute is set.
	 * @see #unsetText()
	 * @see #getText()
	 * @see #setText(String)
	 * @generated
	 */
	public boolean isSetText() {
		return textESet;
	}

	/**
	 * Returns the value of the 'Required Control Action Interval' containment reference.
	 *
	 *

	 * If the meaning of the 'Required Control Action Interval' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Required Control Action Interval' containment reference.
	 * @see #setRequiredControlActionInterval(DateTimeInterval)
	 * @generated
	 */
	public DateTimeInterval getRequiredControlActionInterval() {
		return requiredControlActionInterval;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetRequiredControlActionInterval(DateTimeInterval newRequiredControlActionInterval, NotificationChain msgs) {
		DateTimeInterval oldRequiredControlActionInterval = requiredControlActionInterval;
		requiredControlActionInterval = newRequiredControlActionInterval;
		return msgs;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getRequiredControlActionInterval Required Control Action Interval}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Required Control Action Interval' containment reference.
	 * @see #getRequiredControlActionInterval()
	 * @generated
	 */
	public void setRequiredControlActionInterval(DateTimeInterval newRequiredControlActionInterval) {
		if (newRequiredControlActionInterval != requiredControlActionInterval) {
			NotificationChain msgs = null;
			if (requiredControlActionInterval != null)
				msgs = ((InternalEObject)requiredControlActionInterval).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - InfOperationsPackage.SWITCHING_STEP__REQUIRED_CONTROL_ACTION_INTERVAL, null, msgs);
			if (newRequiredControlActionInterval != null)
				msgs = ((InternalEObject)newRequiredControlActionInterval).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - InfOperationsPackage.SWITCHING_STEP__REQUIRED_CONTROL_ACTION_INTERVAL, null, msgs);
			msgs = basicSetRequiredControlActionInterval(newRequiredControlActionInterval, msgs);
			if (msgs != null) msgs.dispatch();
		}
	}

	/**
	 * Returns the value of the 'Required Control Action' attribute.
	 *
	 *

	 * If the meaning of the 'Required Control Action' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Required Control Action' attribute.
	 * @see #isSetRequiredControlAction()
	 * @see #unsetRequiredControlAction()
	 * @see #setRequiredControlAction(String)
	 * @generated
	 */
	public String getRequiredControlAction() {
		return requiredControlAction;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getRequiredControlAction Required Control Action}' attribute.
	 *
	 *
	 * @param value the new value of the 'Required Control Action' attribute.
	 * @see #isSetRequiredControlAction()
	 * @see #unsetRequiredControlAction()
	 * @see #getRequiredControlAction()
	 * @generated
	 */
	public void setRequiredControlAction(String newRequiredControlAction) {
		requiredControlAction = newRequiredControlAction;
		requiredControlActionESet = true;
	}

	/**
	 * Unsets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getRequiredControlAction Required Control Action}' attribute.
	 *
	 *
	 * @see #isSetRequiredControlAction()
	 * @see #getRequiredControlAction()
	 * @see #setRequiredControlAction(String)
	 * @generated
	 */
	public void unsetRequiredControlAction() {
		requiredControlAction = REQUIRED_CONTROL_ACTION_EDEFAULT;
		requiredControlActionESet = false;
	}

	/**
	 * Returns whether the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getRequiredControlAction Required Control Action}' attribute is set.
	 *
	 *
	 * @return whether the value of the 'Required Control Action' attribute is set.
	 * @see #unsetRequiredControlAction()
	 * @see #getRequiredControlAction()
	 * @see #setRequiredControlAction(String)
	 * @generated
	 */
	public boolean isSetRequiredControlAction() {
		return requiredControlActionESet;
	}

	/**
	 * Returns the value of the 'Switching Schedule' reference.
	 * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingSchedule#getScheduleSteps Schedule Steps}'.
	 *
	 *

	 * If the meaning of the 'Switching Schedule' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Switching Schedule' reference.
	 * @see #setSwitchingSchedule(SwitchingSchedule)
	 * @see CIM15.IEC61970.Informative.InfOperations.SwitchingSchedule#getScheduleSteps
	 * @generated
	 */
	public SwitchingSchedule getSwitchingSchedule() {
		if (switchingSchedule != null && switchingSchedule.eIsProxy()) {
			InternalEObject oldSwitchingSchedule = (InternalEObject)switchingSchedule;
			switchingSchedule = (SwitchingSchedule)eResolveProxy(oldSwitchingSchedule);
			if (switchingSchedule != oldSwitchingSchedule) {
			}
		}
		return switchingSchedule;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public SwitchingSchedule basicGetSwitchingSchedule() {
		return switchingSchedule;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetSwitchingSchedule(SwitchingSchedule newSwitchingSchedule, NotificationChain msgs) {
		SwitchingSchedule oldSwitchingSchedule = switchingSchedule;
		switchingSchedule = newSwitchingSchedule;
		return msgs;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getSwitchingSchedule Switching Schedule}' reference.
	 *
	 *
	 * @param value the new value of the 'Switching Schedule' reference.
	 * @see #getSwitchingSchedule()
	 * @generated
	 */
	public void setSwitchingSchedule(SwitchingSchedule newSwitchingSchedule) {
		if (newSwitchingSchedule != switchingSchedule) {
			NotificationChain msgs = null;
			if (switchingSchedule != null)
				msgs = ((InternalEObject)switchingSchedule).eInverseRemove(this, InfOperationsPackage.SWITCHING_SCHEDULE__SCHEDULE_STEPS, SwitchingSchedule.class, msgs);
			if (newSwitchingSchedule != null)
				msgs = ((InternalEObject)newSwitchingSchedule).eInverseAdd(this, InfOperationsPackage.SWITCHING_SCHEDULE__SCHEDULE_STEPS, SwitchingSchedule.class, msgs);
			msgs = basicSetSwitchingSchedule(newSwitchingSchedule, msgs);
			if (msgs != null) msgs.dispatch();
		}
	}

	/**
	 * Returns the value of the 'Power System Resources' reference list.
	 * The list contents are of type {@link CIM15.IEC61970.Core.PowerSystemResource}.
	 * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Core.PowerSystemResource#getScheduleSteps Schedule Steps}'.
	 *
	 *

	 * If the meaning of the 'Power System Resources' reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Power System Resources' reference list.
	 * @see CIM15.IEC61970.Core.PowerSystemResource#getScheduleSteps
	 * @generated
	 */
	public EList<PowerSystemResource> getPowerSystemResources() {
		if (powerSystemResources == null) {
			powerSystemResources = new BasicInternalEList<PowerSystemResource>(PowerSystemResource.class);
		}
		return powerSystemResources;
	}

	/**
	 * Returns the value of the 'Erp Person Role' reference.
	 * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Informative.InfOperations.ErpPersonScheduleStepRole#getSwitchingStep Switching Step}'.
	 *
	 *

	 * If the meaning of the 'Erp Person Role' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Erp Person Role' reference.
	 * @see #setErpPersonRole(ErpPersonScheduleStepRole)
	 * @see CIM15.IEC61970.Informative.InfOperations.ErpPersonScheduleStepRole#getSwitchingStep
	 * @generated
	 */
	public ErpPersonScheduleStepRole getErpPersonRole() {
		if (erpPersonRole != null && erpPersonRole.eIsProxy()) {
			InternalEObject oldErpPersonRole = (InternalEObject)erpPersonRole;
			erpPersonRole = (ErpPersonScheduleStepRole)eResolveProxy(oldErpPersonRole);
			if (erpPersonRole != oldErpPersonRole) {
			}
		}
		return erpPersonRole;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public ErpPersonScheduleStepRole basicGetErpPersonRole() {
		return erpPersonRole;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetErpPersonRole(ErpPersonScheduleStepRole newErpPersonRole, NotificationChain msgs) {
		ErpPersonScheduleStepRole oldErpPersonRole = erpPersonRole;
		erpPersonRole = newErpPersonRole;
		return msgs;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getErpPersonRole Erp Person Role}' reference.
	 *
	 *
	 * @param value the new value of the 'Erp Person Role' reference.
	 * @see #getErpPersonRole()
	 * @generated
	 */
	public void setErpPersonRole(ErpPersonScheduleStepRole newErpPersonRole) {
		if (newErpPersonRole != erpPersonRole) {
			NotificationChain msgs = null;
			if (erpPersonRole != null)
				msgs = ((InternalEObject)erpPersonRole).eInverseRemove(this, InfOperationsPackage.ERP_PERSON_SCHEDULE_STEP_ROLE__SWITCHING_STEP, ErpPersonScheduleStepRole.class, msgs);
			if (newErpPersonRole != null)
				msgs = ((InternalEObject)newErpPersonRole).eInverseAdd(this, InfOperationsPackage.ERP_PERSON_SCHEDULE_STEP_ROLE__SWITCHING_STEP, ErpPersonScheduleStepRole.class, msgs);
			msgs = basicSetErpPersonRole(newErpPersonRole, msgs);
			if (msgs != null) msgs.dispatch();
		}
	}

	/**
	 * Returns the value of the 'Desired End State' attribute.
	 *
	 *

	 * If the meaning of the 'Desired End State' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Desired End State' attribute.
	 * @see #isSetDesiredEndState()
	 * @see #unsetDesiredEndState()
	 * @see #setDesiredEndState(String)
	 * @generated
	 */
	public String getDesiredEndState() {
		return desiredEndState;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getDesiredEndState Desired End State}' attribute.
	 *
	 *
	 * @param value the new value of the 'Desired End State' attribute.
	 * @see #isSetDesiredEndState()
	 * @see #unsetDesiredEndState()
	 * @see #getDesiredEndState()
	 * @generated
	 */
	public void setDesiredEndState(String newDesiredEndState) {
		desiredEndState = newDesiredEndState;
		desiredEndStateESet = true;
	}

	/**
	 * Unsets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getDesiredEndState Desired End State}' attribute.
	 *
	 *
	 * @see #isSetDesiredEndState()
	 * @see #getDesiredEndState()
	 * @see #setDesiredEndState(String)
	 * @generated
	 */
	public void unsetDesiredEndState() {
		desiredEndState = DESIRED_END_STATE_EDEFAULT;
		desiredEndStateESet = false;
	}

	/**
	 * Returns whether the value of the '{@link CIM15.IEC61970.Informative.InfOperations.SwitchingStep#getDesiredEndState Desired End State}' attribute is set.
	 *
	 *
	 * @return whether the value of the 'Desired End State' attribute is set.
	 * @see #unsetDesiredEndState()
	 * @see #getDesiredEndState()
	 * @see #setDesiredEndState(String)
	 * @generated
	 */
	public boolean isSetDesiredEndState() {
		return desiredEndStateESet;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case InfOperationsPackage.SWITCHING_STEP__SAFETY_DOCUMENT:
				if (safetyDocument != null)
					msgs = ((InternalEObject)safetyDocument).eInverseRemove(this, InfOperationsPackage.SAFETY_DOCUMENT__SCHEDULE_STEPS, SafetyDocument.class, msgs);
				return basicSetSafetyDocument((SafetyDocument)otherEnd, msgs);
			case InfOperationsPackage.SWITCHING_STEP__SWITCHING_SCHEDULE:
				if (switchingSchedule != null)
					msgs = ((InternalEObject)switchingSchedule).eInverseRemove(this, InfOperationsPackage.SWITCHING_SCHEDULE__SCHEDULE_STEPS, SwitchingSchedule.class, msgs);
				return basicSetSwitchingSchedule((SwitchingSchedule)otherEnd, msgs);
			case InfOperationsPackage.SWITCHING_STEP__POWER_SYSTEM_RESOURCES:
				return ((InternalEList<InternalEObject>)(InternalEList<?>)getPowerSystemResources()).basicAdd(otherEnd, msgs);
			case InfOperationsPackage.SWITCHING_STEP__ERP_PERSON_ROLE:
				if (erpPersonRole != null)
					msgs = ((InternalEObject)erpPersonRole).eInverseRemove(this, InfOperationsPackage.ERP_PERSON_SCHEDULE_STEP_ROLE__SWITCHING_STEP, ErpPersonScheduleStepRole.class, msgs);
				return basicSetErpPersonRole((ErpPersonScheduleStepRole)otherEnd, msgs);
		}
		return super.eInverseAdd(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case InfOperationsPackage.SWITCHING_STEP__SAFETY_DOCUMENT:
				return basicSetSafetyDocument(null, msgs);
			case InfOperationsPackage.SWITCHING_STEP__REQUIRED_CONTROL_ACTION_INTERVAL:
				return basicSetRequiredControlActionInterval(null, msgs);
			case InfOperationsPackage.SWITCHING_STEP__SWITCHING_SCHEDULE:
				return basicSetSwitchingSchedule(null, msgs);
			case InfOperationsPackage.SWITCHING_STEP__POWER_SYSTEM_RESOURCES:
				return ((InternalEList<?>)getPowerSystemResources()).basicRemove(otherEnd, msgs);
			case InfOperationsPackage.SWITCHING_STEP__ERP_PERSON_ROLE:
				return basicSetErpPersonRole(null, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case InfOperationsPackage.SWITCHING_STEP__SAFETY_DOCUMENT:
				if (resolve) return getSafetyDocument();
				return basicGetSafetyDocument();
			case InfOperationsPackage.SWITCHING_STEP__STATUS_KIND:
				return getStatusKind();
			case InfOperationsPackage.SWITCHING_STEP__TEXT:
				return getText();
			case InfOperationsPackage.SWITCHING_STEP__REQUIRED_CONTROL_ACTION_INTERVAL:
				return getRequiredControlActionInterval();
			case InfOperationsPackage.SWITCHING_STEP__REQUIRED_CONTROL_ACTION:
				return getRequiredControlAction();
			case InfOperationsPackage.SWITCHING_STEP__SWITCHING_SCHEDULE:
				if (resolve) return getSwitchingSchedule();
				return basicGetSwitchingSchedule();
			case InfOperationsPackage.SWITCHING_STEP__POWER_SYSTEM_RESOURCES:
				return getPowerSystemResources();
			case InfOperationsPackage.SWITCHING_STEP__ERP_PERSON_ROLE:
				if (resolve) return getErpPersonRole();
				return basicGetErpPersonRole();
			case InfOperationsPackage.SWITCHING_STEP__DESIRED_END_STATE:
				return getDesiredEndState();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case InfOperationsPackage.SWITCHING_STEP__SAFETY_DOCUMENT:
				setSafetyDocument((SafetyDocument)newValue);
				return;
			case InfOperationsPackage.SWITCHING_STEP__STATUS_KIND:
				setStatusKind((SwitchingStepStatusKind)newValue);
				return;
			case InfOperationsPackage.SWITCHING_STEP__TEXT:
				setText((String)newValue);
				return;
			case InfOperationsPackage.SWITCHING_STEP__REQUIRED_CONTROL_ACTION_INTERVAL:
				setRequiredControlActionInterval((DateTimeInterval)newValue);
				return;
			case InfOperationsPackage.SWITCHING_STEP__REQUIRED_CONTROL_ACTION:
				setRequiredControlAction((String)newValue);
				return;
			case InfOperationsPackage.SWITCHING_STEP__SWITCHING_SCHEDULE:
				setSwitchingSchedule((SwitchingSchedule)newValue);
				return;
			case InfOperationsPackage.SWITCHING_STEP__POWER_SYSTEM_RESOURCES:
				getPowerSystemResources().clear();
				getPowerSystemResources().addAll((Collection<? extends PowerSystemResource>)newValue);
				return;
			case InfOperationsPackage.SWITCHING_STEP__ERP_PERSON_ROLE:
				setErpPersonRole((ErpPersonScheduleStepRole)newValue);
				return;
			case InfOperationsPackage.SWITCHING_STEP__DESIRED_END_STATE:
				setDesiredEndState((String)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case InfOperationsPackage.SWITCHING_STEP__SAFETY_DOCUMENT:
				setSafetyDocument((SafetyDocument)null);
				return;
			case InfOperationsPackage.SWITCHING_STEP__STATUS_KIND:
				unsetStatusKind();
				return;
			case InfOperationsPackage.SWITCHING_STEP__TEXT:
				unsetText();
				return;
			case InfOperationsPackage.SWITCHING_STEP__REQUIRED_CONTROL_ACTION_INTERVAL:
				setRequiredControlActionInterval((DateTimeInterval)null);
				return;
			case InfOperationsPackage.SWITCHING_STEP__REQUIRED_CONTROL_ACTION:
				unsetRequiredControlAction();
				return;
			case InfOperationsPackage.SWITCHING_STEP__SWITCHING_SCHEDULE:
				setSwitchingSchedule((SwitchingSchedule)null);
				return;
			case InfOperationsPackage.SWITCHING_STEP__POWER_SYSTEM_RESOURCES:
				getPowerSystemResources().clear();
				return;
			case InfOperationsPackage.SWITCHING_STEP__ERP_PERSON_ROLE:
				setErpPersonRole((ErpPersonScheduleStepRole)null);
				return;
			case InfOperationsPackage.SWITCHING_STEP__DESIRED_END_STATE:
				unsetDesiredEndState();
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case InfOperationsPackage.SWITCHING_STEP__SAFETY_DOCUMENT:
				return safetyDocument != null;
			case InfOperationsPackage.SWITCHING_STEP__STATUS_KIND:
				return isSetStatusKind();
			case InfOperationsPackage.SWITCHING_STEP__TEXT:
				return isSetText();
			case InfOperationsPackage.SWITCHING_STEP__REQUIRED_CONTROL_ACTION_INTERVAL:
				return requiredControlActionInterval != null;
			case InfOperationsPackage.SWITCHING_STEP__REQUIRED_CONTROL_ACTION:
				return isSetRequiredControlAction();
			case InfOperationsPackage.SWITCHING_STEP__SWITCHING_SCHEDULE:
				return switchingSchedule != null;
			case InfOperationsPackage.SWITCHING_STEP__POWER_SYSTEM_RESOURCES:
				return powerSystemResources != null && !powerSystemResources.isEmpty();
			case InfOperationsPackage.SWITCHING_STEP__ERP_PERSON_ROLE:
				return erpPersonRole != null;
			case InfOperationsPackage.SWITCHING_STEP__DESIRED_END_STATE:
				return isSetDesiredEndState();
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (statusKind: ");
		if (statusKindESet) result.append(statusKind); else result.append("<unset>");
		result.append(", text: ");
		if (textESet) result.append(text); else result.append("<unset>");
		result.append(", requiredControlAction: ");
		if (requiredControlActionESet) result.append(requiredControlAction); else result.append("<unset>");
		result.append(", desiredEndState: ");
		if (desiredEndStateESet) result.append(desiredEndState); else result.append("<unset>");
		result.append(')');
		return result.toString();
	}

} // SwitchingStep


text:
void test01()
{
  bool test __attribute__((unused)) = true;
  using std::tr1::is_same;
  using namespace __gnu_test;

  // Positive tests.
  VERIFY( (test_relationship<is_same, int, int>(true)) );
  VERIFY( (test_relationship<is_same, const int, const int>(true)) );
  VERIFY( (test_relationship<is_same, int&, int&>(true)) );
  VERIFY( (test_relationship<is_same, ClassType, ClassType>(true)) );

  // Negative tests.
  VERIFY( (test_relationship<is_same, void, int>(false)) );
  VERIFY( (test_relationship<is_same, int, const int>(false)) );
  VERIFY( (test_relationship<is_same, int, int&>(false)) );
  VERIFY( (test_relationship<is_same, int, ClassType>(false)) );
}

int main()
{
  test01();
  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
namespace IronFoundry.Bosh.Agent.Handlers
{
    using Newtonsoft.Json;

    public class StateResult
    {
        private const string NtpFileMissing = "file missing";
        private readonly string agentID;
        private readonly object vm;
        private readonly string serviceGroupState;
        private readonly string boshProtocol;

        public StateResult(string agentID, object vm, string serviceGroupState, string boshProtocol)
        {
            this.agentID = agentID;
            this.vm = vm;
            this.serviceGroupState = serviceGroupState; // agent/lib/agent/monit.rb running, starting, failing or unknown
            this.boshProtocol = boshProtocol;
        }

        [JsonProperty(PropertyName = "agent_id")]
        public string AgentID { get { return agentID; } }

        [JsonProperty(PropertyName = "vm")]
        public object VM { get { return vm; } }

        [JsonProperty(PropertyName = "job_state")]
        public string ServiceGroupState { get { return serviceGroupState; } }

        [JsonProperty(PropertyName = "bosh_protocol")]
        public string BoshProtocol { get { return boshProtocol; } }

        [JsonProperty(PropertyName = "ntp")]
        public string Ntp { get { return NtpFileMissing; } }
    }
}


text:
var namespaceorg_1_1onosproject_1_1vtnrsc_1_1tenantnetwork =
[
    [ "impl", "namespaceorg_1_1onosproject_1_1vtnrsc_1_1tenantnetwork_1_1impl.html", "namespaceorg_1_1onosproject_1_1vtnrsc_1_1tenantnetwork_1_1impl" ],
    [ "TenantNetworkService", "interfaceorg_1_1onosproject_1_1vtnrsc_1_1tenantnetwork_1_1TenantNetworkService.html", "interfaceorg_1_1onosproject_1_1vtnrsc_1_1tenantnetwork_1_1TenantNetworkService" ]
];


text:
package io.github.carlomicieli.scalakoans

import org.scalatest._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class AboutCaseClasses extends FunSpec with ShouldMatchers {

  // case class has to be defined outside of the test for this one
  case class Person(first: String, last: String, age: Int = 0, ssn: String = "")

  // case classes are very convenient, they give you a lot for free. The following Koans will
  // help you understand some of the conveniences. Case classes are also an integral part of
  // pattern matching which will be the subject of a later

  describe("Case classes") {
    it("have an automatic equals method that works.") {
      case class Person(first: String, last: String)

      val p1 = new Person("Fred", "Jones")
      val p2 = new Person("Shaggy", "Rogers")
      val p3 = new Person("Fred", "Jones")

      (p1 == p2) should be(false)
      (p1 == p3) should be(true)

      (p1 eq p2) should be(false)
      (p1 eq p3) should be(false) // not identical, merely equal
    }

    it("have an automatic hashcode method that works.") {
      case class Person(first: String, last: String)

      val p1 = new Person("Fred", "Jones")
      val p2 = new Person("Shaggy", "Rogers")
      val p3 = new Person("Fred", "Jones")

      (p1.hashCode == p2.hashCode) should be(false)
      (p1.hashCode == p3.hashCode) should be(true)
    }

    it("have a convenient way they can be created") {
      case class Dog(name: String, breed: String)

      val d1 = Dog("Scooby", "Doberman")
      val d2 = Dog("Rex", "Custom")
      val d3 = new Dog("Scooby", "Doberman") // the old way of creating using new

      (d1 == d3) should be(true)
      (d1 == d2) should be(false)
      (d2 == d3) should be(false)
    }

    it("have a convenient toString method defined.") {
      case class Dog(name: String, breed: String)
      val d1 = Dog("Scooby", "Doberman")
      d1.toString should be("Dog(Scooby,Doberman)")
    }

    it("Case classes have automatic properties.") {
      case class Dog(name: String, breed: String)

      val d1 = Dog("Scooby", "Doberman")
      d1.name should be("Scooby")
      d1.breed should be("Doberman")

      // what happens if you uncomment the line below? Why?
      //! "reassignment to val"
      //! d1.name = "Scooby Doo"
    }

    it("can have mutable properties.") {
      case class Dog(var name: String, breed: String) // you can rename a dog, but change its breed? nah!
      val d1 = Dog("Scooby", "Doberman")

      d1.name should be("Scooby")
      d1.breed should be("Doberman")

      d1.name = "Scooby Doo" // but is it a good idea?

      d1.name should be("Scooby Doo")
      d1.breed should be("Doberman")
    }

    it("provide safer alternatives for altering case classes.") {
      case class Dog(name: String, breed: String) // Doberman

      val d1 = Dog("Scooby", "Doberman")

      val d2 = d1.copy(name = "Scooby Doo") // copy the case class but change the name in the copy

      d1.name should be("Scooby") // original left alone
      d1.breed should be("Doberman")

      d2.name should be("Scooby Doo")
      d2.breed should be("Doberman") // copied from the original
    }

    it("Case classes have default and named parameters") {

      val p1 = Person("Fred", "Jones", 23, "111-22-3333")
      val p2 = Person("Samantha", "Jones") // note missing age and ssn
      val p3 = Person(last = "Jones", first = "Fred", ssn = "111-22-3333") // note the order can change, and missing age
      val p4 = p3.copy(age = 23)

      p1.first should be("Fred")
      p1.last should be("Jones")
      p1.age should be(23)
      p1.ssn should be("111-22-3333")

      p2.first should be("Samantha")
      p2.last should be("Jones")
      p2.age should be(0)
      p2.ssn should be("")

      p3.first should be("Fred")
      p3.last should be("Jones")
      p3.age should be(0)
      p3.ssn should be("111-22-3333")

      (p1 == p4) should be(true)
    }

    it("can be disassembled to their constituent parts as a tuple.") {
      val p1 = Person("Fred", "Jones", 23, "111-22-3333")

      // this seems weird, but it's critical to other features of Scala
      val parts = Person.unapply(p1).get

      parts._1 should be("Fred")
      parts._2 should be("Jones")
      parts._3 should be(23)
      parts._4 should be("111-22-3333")
    }
  }

}


text:
class PhotosController < ApplicationController
  before_action :set_album
  before_action :set_photo, only: [:show, :edit, :update, :destroy]
  respond_to :html

  # GET /photos
  # GET /photos.json
  def index
    @photos = @album.photos
  end

  # GET /photos/1
  # GET /photos/1.json
  def show
  end

  # GET /photos/new
  def new
    @photo = @album.photos.build
  end

  # GET /photos/1/edit
  def edit
  end

  # POST /photos
  # POST /photos.json
  def create
    @photo = @album.photos.create(photo_params)
    respond_with(@photo, location: @album)
  end

  # PATCH/PUT /photos/1
  # PATCH/PUT /photos/1.json
  def update
    @photo.update(photo_params)
    respond_with(@photo, location: @album)
  end

  # DELETE /photos/1
  # DELETE /photos/1.json
  def destroy
    @photo.destroy
    respond_with(@photo, location: @album)
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_photo
      @photo = Photo.find(params[:id])
    end

    def set_album
      @album = Album.find(params[:album_id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def photo_params
      params.require(:photo).permit(:title, :file, :album_id)
    end
end


text:
"use strict";

/**
 * Rhizome API -
 *
 * @file campaign.js
 * @description
 * @author Chris Bates-Keegan
 *
 */

const restler = require('restler');
const Rhizome = require('./rhizome');

const PATH_PREFIX = 'contact-list';

const _getAll = () => {
  return new Promise((resolve, reject) => {
    let url = `${Rhizome.url}/${PATH_PREFIX}`;
    restler.get(url, {query: {token: Rhizome.authToken}})
      .on('success', data => resolve(data))
      .on('fail', err => reject(new Error(err.message)))
      .on('error', err => reject(err));
  });
};

const _loadContactList = rhizomeContactListId => {
  return new Promise((resolve, reject) => {
    let url = `${Rhizome.url}/${PATH_PREFIX}/${rhizomeContactListId}`;
    restler
      .get(url, {query: {token: Rhizome.authToken}})
      .on('success', data => resolve(data))
      .on('fail', err => reject(new Error(err.message)))
      .on('error', err => reject(err));
  });
};

const _createContactList = details => {
  return new Promise((resolve, reject) => {
    let url = `${Rhizome.url}/contact-list`;
    restler
      .post(url, {
        query: {
          token: Rhizome.authToken
        },
        data: details
      })
      .on('success', data => resolve(data))
      .on('fail', err => reject(new Error(err.message)))
      .on('error', err => reject(err));
  });
};

const _removeAll = () => {
  return new Promise((resolve, reject) => {
    let url = `${Rhizome.url}/${PATH_PREFIX}`;
    restler
      .del(url, {
        query: {
          token: Rhizome.authToken
        }
      })
      .on('success', data => resolve(data))
      .on('fail', err => reject(new Error(err.message)))
      .on('error', err => reject(err));
  });
};

module.exports = {
  getAll: _getAll,
  load: _loadContactList,
  create: _createContactList,
  removeAll: _removeAll
};


text:
<?php

namespace SensioLabs\CeremonyTrackerBundle\Listener;

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class BehatListener {
/***
 * @var Symfony\Component\HttpKernel\Kernel $kernel
 */
private $kernel;

/***
 * @var Bool $isAppTest
 *
 */
private $isAppTest;

/***
 * @var Exception $exception
 */
private $exception;

public function __construct(Kernel $kernel) {
    $this->kernel = $kernel;
}
    public function onKernelException(GetResponseForExceptionEvent $event)
{

    $this->isAppTest = ($this->kernel->getEnvironment() == "test") ? true : false;

    if ($this->isAppTest ){

        $this->exception = $event->getException();

            throw $this->exception;

    }

}

}


text:
package com.eden.orchid.api.options.extractors;

import com.caseyjbrooks.clog.Clog;
import com.eden.orchid.api.OrchidContext;
import com.eden.orchid.api.converters.FlexibleMapConverter;
import com.eden.orchid.api.options.OptionExtractor;
import com.eden.orchid.api.options.annotations.ImpliedKey;
import com.eden.orchid.api.options.annotations.StringDefault;
import com.eden.orchid.api.theme.components.ModularType;
import javax.inject.Provider;

import javax.inject.Inject;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * ### Destination Types
 *
 * | Field Type   | Annotation     | Default Value              |
 * |--------------|----------------|----------------------------|
 * | ModularType  | @StringDefault | Annotation value() or null |
 */
public final class ModularTypeOptionExtractor extends OptionExtractor<ModularType> {

    private final Provider<OrchidContext> contextProvider;
    private final FlexibleMapConverter mapConverter;

    @Inject
    public ModularTypeOptionExtractor(Provider<OrchidContext> contextProvider, FlexibleMapConverter mapConverter) {
        super(50);
        this.contextProvider = contextProvider;
        this.mapConverter = mapConverter;
    }

    @Override
    public boolean acceptsClass(Class clazz) {
        return ModularType.class.isAssignableFrom(clazz);
    }

    @Override
    public ModularType getOption(Field field, Object sourceObject, String key) {
        final String typeKey;
        final String valueKey;
        if(field.isAnnotationPresent(ImpliedKey.class)) {
            ImpliedKey impliedKey = field.getAnnotation(ImpliedKey.class);
            typeKey = impliedKey.typeKey();
            valueKey = impliedKey.valueKey();
        }
        else {
            typeKey = null;
            valueKey = null;
        }

        Map<String, Object> data = mapConverter.convert(field.getType(), sourceObject, typeKey).second;

        ModularType t = null;

        Object actualType = data.get(typeKey);
        if(actualType != null) {
            t = createModularType(field, actualType.toString(), data);
            if(t == null) {
                Clog.e(
                        "Could not find modular type [{}] for {} {} in class {}, falling back to default [{}]",
                        actualType,
                        field.getType().getSimpleName(),
                        field.getName(),
                        field.getDeclaringClass().getSimpleName(),
                        getDefaultType(field)
                );
            }
        }

        actualType = data.get(null);
        if(actualType != null) {
            t = createModularType(field, actualType.toString(), data);
            if(t == null) {
                Clog.e(
                        "Could not find modular type [{}] for {} {} in class {}, falling back to default [{}]",
                        actualType,
                        field.getType().getSimpleName(),
                        field.getName(),
                        field.getDeclaringClass().getSimpleName(),
                        getDefaultType(field)
                );
            }
        }

        return t;
    }

    @Override
    public ModularType getDefaultValue(Field field) {
        ModularType t = createModularType(field, getDefaultType(field), new HashMap<>());

        if(t == null) {
            throw new IllegalArgumentException(
                    Clog.format(
                            "No sensible default found for ModularType {} {} in class {}",
                            field.getType().getSimpleName(), field.getName(), field.getDeclaringClass().getSimpleName()
                    )
            );
        }
        else {
            return t;
        }
    }

    @Override
    public String describeDefaultValue(Field field) {
        final String typeKey;
        final String valueKey;
        if(field.isAnnotationPresent(ImpliedKey.class)) {
            ImpliedKey impliedKey = field.getAnnotation(ImpliedKey.class);
            typeKey = impliedKey.typeKey();
            valueKey = impliedKey.valueKey();
        }
        else {
            typeKey = null;
            valueKey = null;
        }

        return "Default " + field.getType().getSimpleName() + " of type '" + typeKey + "'";
    }

    private String getDefaultType(Field field) {
        if(field.isAnnotationPresent(StringDefault.class)) {
            String[] defaultValue = field.getAnnotation(StringDefault.class).value();
            if(defaultValue.length > 0) {
                return defaultValue[0];
            }
        }

        return "";
    }

    private ModularType createModularType(Field field, String selectedTypeKey, Map<String, Object> data) {
        Set<? extends ModularType> itemTypes = (Set<? extends ModularType>) contextProvider.get().resolveSet(field.getType());
        for (ModularType itemType : itemTypes) {
            if(itemType.getType().equals(selectedTypeKey)) {
                ModularType type = contextProvider.get().resolve(itemType.getClass());
                type.extractOptions(contextProvider.get(), data);

                return type;
            }
        }
        return null;
    }

}


text:
//
//  MQCatalogCell.h
//  UITableViewDemo
//
//  Created by 闵前前 on 2016/12/7.
//  Copyright © 2016年 lyqflnh. All rights reserved.
//

#import <UIKit/UIKit.h>

@class MQCatalogCellItem;
@class MQCatalogCell;

@protocol MQCatalogCellDelegate <NSObject>

- (void)moreButtonClicked:(MQCatalogCell *)cell;
- (void)badgeValuePluseOne;

@optional

@end

@interface MQCatalogCell : UITableViewCell

/** 目录模块cell模型 */
@property (nonatomic, strong) MQCatalogCellItem *catalogCellItem;

/** 代理属性 */
@property (nonatomic, weak) id<MQCatalogCellDelegate> delegate;

/** 按钮 */
@property (weak, nonatomic) IBOutlet UIButton *addMoreButton;

@end


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using System;

public class RoadTurner : MonoBehaviour {

    public float DegreesPerTurn = 40f;
    public float SecondsPerTurn = 0.2f;

    private Vector3 currentEulerRotation;

	// Use this for initialization
	void Start () {
        currentEulerRotation = transform.rotation.eulerAngles;
	}

    // Update is called once per frame
    void Update()
    {

    }

    public void TurnLeft()
    {
        DOTween.Kill(transform);
        currentEulerRotation += new Vector3(0, 0, 40);
        transform.DORotate(currentEulerRotation, SecondsPerTurn, RotateMode.Fast).onComplete = new TweenCallback(ResetRotation);
    }

    private void ResetRotation()
    {
        currentEulerRotation = transform.rotation.eulerAngles;
    }

    public void TurnRight()
    {
        DOTween.Kill(transform);
        currentEulerRotation += new Vector3(0, 0, -40);
        transform.DORotate(currentEulerRotation, SecondsPerTurn, RotateMode.Fast).onComplete = new TweenCallback(ResetRotation); ;
    }

}


text:
<?php

class acf_field_repeater extends acf_field
{

	var $settings;

	/*
	*  __construct
	*
	*  Set name / label needed for actions / filters
	*
	*  @since	3.6
	*  @date	23/01/13
	*/

	function __construct()
	{
		// vars
		$this->name = 'repeater';
		$this->label = __("Repeater",'acf');
		$this->category = __("Layout",'acf');
		$this->defaults = array(
			'sub_fields'	=>	array(),
			'row_min'		=>	0,
			'row_limit'		=>	0,
			'layout' 		=> 'table',
			'button_label'	=>	__("Add Row",'acf'),
		);
		$this->l10n = array(
			'min'	=>	__("Minimum rows reached ( {min} rows )",'acf'),
			'max'	=>	__("Maximum rows reached ( {max} rows )",'acf'),
		);

		// do not delete!
    	parent::__construct();

    	// settings
		$this->settings = array(
			'path' => apply_filters('acf/helpers/get_path', __FILE__),
			'dir' => apply_filters('acf/helpers/get_dir', __FILE__),
			'version' => '1.1.1'
		);

	}

	/*
	*  input_admin_enqueue_scripts()
	*
	*  This action is called in the admin_enqueue_scripts action on the edit screen where your field is created.
	*  Use this action to add css + javascript to assist your create_field() action.
	*
	*  $info	http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts
	*  @type	action
	*  @since	3.6
	*  @date	23/01/13
	*/

	function input_admin_enqueue_scripts()
	{
		// register acf scripts
		wp_register_script( 'acf-input-repeater', $this->settings['dir'] . 'js/input.js', array('acf-input'), $this->settings['version'] );
		wp_register_style( 'acf-input-repeater', $this->settings['dir'] . 'css/input.css', array('acf-input'), $this->settings['version'] );

		// scripts
		wp_enqueue_script(array(
			'acf-input-repeater',
		));

		// styles
		wp_enqueue_style(array(
			'acf-input-repeater',
		));

	}

	/*
	*  field_group_admin_enqueue_scripts()
	*
	*  This action is called in the admin_enqueue_scripts action on the edit screen where your field is edited.
	*  Use this action to add css + javascript to assist your create_field_options() action.
	*
	*  $info	http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts
	*  @type	action
	*  @since	3.6
	*  @date	23/01/13
	*/

	function field_group_admin_enqueue_scripts()
	{
		wp_register_script( 'acf-field-group-repeater', $this->settings['dir'] . 'js/field-group.js', array('acf-field-group'), $this->settings['version']);

		// scripts
		wp_enqueue_script(array(
			'acf-field-group-repeater',
		));
	}

	/*
	*  load_field()
	*
	*  This filter is appied to the $field after it is loaded from the database
	*
	*  @type	filter
	*  @since	3.6
	*  @date	23/01/13
	*
	*  @param	$field - the field array holding all the field options
	*
	*  @return	$field - the field array holding all the field options
	*/

	function load_field( $field )
	{
		// apply_load field to all sub fields
		if( isset($field['sub_fields']) && is_array($field['sub_fields']) )
		{
			foreach( $field['sub_fields'] as $k => $sub_field )
			{
				// apply filters
				$sub_field = apply_filters('acf/load_field_defaults', $sub_field);

				// apply filters
				foreach( array('type', 'name', 'key') as $key )
				{
					// run filters
					$sub_field = apply_filters('acf/load_field/' . $key . '=' . $sub_field[ $key ], $sub_field); // new filter
				}

				// update sub field
				$field['sub_fields'][ $k ] = $sub_field;
			}
		}

		// return
		return $field;
	}

	/*
	*  create_field()
	*
	*  Create the HTML interface for your field
	*
	*  @param	$field - an array holding all the field's data
	*
	*  @type	action
	*  @since	3.6
	*  @date	23/01/13
	*/

	function create_field( $field )
	{
		include( $this->settings['path'] . 'views/field.php' );
	}

	/*
	*  create_options()
	*
	*  Create extra options for your field. This is rendered when editing a field.
	*  The value of $field['name'] can be used (like bellow) to save extra data to the $field
	*
	*  @type	action
	*  @since	3.6
	*  @date	23/01/13
	*
	*  @param	$field	- an array holding all the field's data
	*/

	function create_options( $field )
	{
		include( $this->settings['path'] . 'views/options.php' );
	}

	/*
	*  update_value()
	*
	*  This filter is appied to the $value before it is updated in the db
	*
	*  @type	filter
	*  @since	3.6
	*  @date	23/01/13
	*
	*  @param	$value - the value which will be saved in the database
	*  @param	$field - the field array holding all the field options
	*  @param	$post_id - the $post_id of which the value will be saved
	*
	*  @return	$value - the modified value
	*/

	function update_value( $value, $post_id, $field )
	{
		$total = 0;

		if( $value )
		{
			// remove dummy field
			unset( $value['acfcloneindex'] );

			$i = -1;

			// loop through rows
			foreach( $value as $row )
			{
				$i++;

				// increase total
				$total++;

				// loop through sub fields
				foreach( $field['sub_fields'] as $sub_field )
				{
					// get sub field data
					$v = isset( $row[$sub_field['key']] ) ? $row[$sub_field['key']] : false;

					// update full name
					$sub_field['name'] = $field['name'] . '_' . $i . '_' . $sub_field['name'];

					// save sub field value
					do_action('acf/update_value', $v, $post_id, $sub_field );

				}
			}
		}

		/*
		*  Remove Old Data
		*
		*  @credit: http://support.advancedcustomfields.com/discussion/1994/deleting-single-repeater-fields-does-not-remove-entry-from-database
		*/

		$old_total = (int) apply_filters('acf/load_value', 0, $post_id, $field);

		if( $old_total > $total )
		{
			for ( $j = $total; $j < $old_total; $j++ )
			{
				foreach( $field['sub_fields'] as $sub_field )
				{
					do_action('acf/delete_value', $post_id, $field['name'] . '_' . $j . '_' . $sub_field['name'] );
				}
			}
		}

		// update $value and return to allow for the normal save function to run
		$value = $total;

		return $value;
	}

	/*
	*  update_field()
	*
	*  This filter is appied to the $field before it is saved to the database
	*
	*  @type	filter
	*  @since	3.6
	*  @date	23/01/13
	*
	*  @param	$field - the field array holding all the field options
	*  @param	$post_id - the field group ID (post_type = acf)
	*
	*  @return	$field - the modified field
	*/

	function update_field( $field, $post_id )
	{
		// format sub_fields
		if( $field['sub_fields'] )
		{
			// remove dummy field
			unset( $field['sub_fields']['field_clone'] );

			// loop through and save fields
			$i = -1;
			$sub_fields = array();

			foreach( $field['sub_fields'] as $key => $f )
			{
				$i++;

				// order
				$f['order_no'] = $i;
				$f['key'] = $key;

				// save
				$f = apply_filters('acf/update_field/type=' . $f['type'], $f, $post_id ); // new filter

				// add
				$sub_fields[] = $f;
			}

			// update sub fields
			$field['sub_fields'] = $sub_fields;

		}

		// return updated repeater field
		return $field;
	}

	/*
	*  format_value()
	*
	*  This filter is appied to the $value after it is loaded from the db and before it is passed to the create_field action
	*
	*  @type	filter
	*  @since	3.6
	*  @date	23/01/13
	*
	*  @param	$value	- the value which was loaded from the database
	*  @param	$post_id - the $post_id from which the value was loaded
	*  @param	$field	- the field array holding all the field options
	*
	*  @return	$value	- the modified value
	*/

	function format_value( $value, $post_id, $field )
	{
		// vars
		$values = array();

		if( $value > 0 )
		{
			// loop through rows
			for($i = 0; $i < $value; $i++)
			{
				// loop through sub fields
				foreach( $field['sub_fields'] as $sub_field )
				{
					// update full name
					$key = $sub_field['key'];
					$sub_field['name'] = $field['name'] . '_' . $i . '_' . $sub_field['name'];

					$v = apply_filters('acf/load_value', false, $post_id, $sub_field);
					$v = apply_filters('acf/format_value', $v, $post_id, $sub_field);

					$values[ $i ][ $key ] = $v;

				}
			}
		}

		// return
		return $values;
	}

	/*
	*  format_value_for_api()
	*
	*  This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
	*
	*  @type	filter
	*  @since	3.6
	*  @date	23/01/13
	*
	*  @param	$value	- the value which was loaded from the database
	*  @param	$post_id - the $post_id from which the value was loaded
	*  @param	$field	- the field array holding all the field options
	*
	*  @return	$value	- the modified value
	*/

	function format_value_for_api( $value, $post_id, $field )
	{
		// vars
		$values = array();

		if( $value > 0 )
		{
			// loop through rows
			for($i = 0; $i < $value; $i++)
			{
				// loop through sub fields
				foreach( $field['sub_fields'] as $sub_field )
				{
					// update full name
					$key = $sub_field['name'];
					$sub_field['name'] = $field['name'] . '_' . $i . '_' . $sub_field['name'];

					$v = apply_filters('acf/load_value', false, $post_id, $sub_field);
					$v = apply_filters('acf/format_value_for_api', $v, $post_id, $sub_field);

					$values[ $i ][ $key ] = $v;

				}
			}
		}

		// return
		return $values;
	}

}

new acf_field_repeater();

?>


text:
@interface ADOauthViewController ()

@property (strong, nonatomic, readonly) ADOauthViewModel *viewModel;

@end

@implementation ADOauthViewController

@dynamic viewModel;

+ (ADViewController *)viewController {
    ADOauthViewController *vc = [[ADOauthViewController alloc]initWithNibName:@"ADOauthViewController" bundle:nil];

    return vc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - WKNavigationDelegate

-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSString *absoluteString = webView.URL.absoluteString;
    if ([absoluteString hasPrefix:github_callback_url]) {
        NSDictionary *param = webView.URL.oct_queryArguments;
        if ([param[@"state"] isEqualToString:self.viewModel.UUID] && self.viewModel.callback) {
            self.viewModel.callback(param[@"code"]);
        }
    }
}

#pragma mark - UIViewControllerRotation

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

@end


text:
package edu.gemini.spModel.gemini.trecs

import TReCSParams._

import edu.gemini.spModel.config.injector.ObsWavelengthTestBase
import edu.gemini.spModel.data.config.DefaultParameter
import org.junit.Test

import edu.gemini.spModel.test.{InstrumentSequenceTestBase => Base}

/**
 * ObsWavelength sequence tests for TReCS.
 */
class ObsWavelengthSeqTest extends ObsWavelengthTestBase[InstTReCS, SeqConfigTReCS] {
  private def disperserParam(d: Disperser*): DefaultParameter = param(InstTReCS.DISPERSER_PROP, d: _*)
  private def filterParam(f: Filter*): DefaultParameter       = param(InstTReCS.FILTER_PROP, f: _*)
  private def lamdaParam(l: Double*): DefaultParameter        = param(InstTReCS.DISPERSER_LAMBDA_PROP, l: _*)
  private def maskParam(m: Mask*): DefaultParameter           = param(InstTReCS.MASK_PROP, m: _*)

  private def verifyFilters(filters: Filter*) {
    verifyWavelength(filters.map(_.getWavelength): _*)
  }

  def getObsCompSpType = InstTReCS.SP_TYPE
  def getSeqCompSpType = SeqConfigTReCS.SP_TYPE

  @Test def testStatic() {
    getInstDataObj.setDisperser(Disperser.MIRROR)
    getInstDataObj.setFilter(Filter.N_PRIME)
    storeStaticUpdates

    val sc = Base.createSysConfig
    sc.putParameter(maskParam(Mask.MASK_1, Mask.MASK_2))
    setSysConfig(sc)

    verifyFilters(Filter.N_PRIME, Filter.N_PRIME)
  }

  @Test def testInheritMirror() {
    getInstDataObj.setDisperser(Disperser.MIRROR)
    storeStaticUpdates

    val sc = Base.createSysConfig
    sc.putParameter(filterParam(Filter.Q, Filter.K))
    setSysConfig(sc)

    verifyFilters(Filter.Q, Filter.K)
  }

  @Test def testInheritDisperser() {
    getInstDataObj.setDisperser(Disperser.LOW_RES_10)
    getInstDataObj.setDisperserLambda(42.0)
    storeStaticUpdates

    val sc = Base.createSysConfig
    sc.putParameter(filterParam(Filter.Q, Filter.K))
    setSysConfig(sc)

    verifyWavelength("42.0", "42.0")
  }

  @Test def testInheritFilter() {
    getInstDataObj.setFilter(Filter.Q)
    getInstDataObj.setDisperserLambda(17.0)
    storeStaticUpdates

    val d10 = Disperser.LOW_RES_10
    val dMr = Disperser.MIRROR
    val sc = Base.createSysConfig
    sc.putParameter(disperserParam(d10, dMr))
    sc.putParameter(lamdaParam(6.0, 7.0))
    setSysConfig(sc)

    verifyWavelength("6.0", Filter.Q.getWavelength)
  }

  @Test def testIterateFilterAndDisperser() {
    val sc = Base.createSysConfig

    val d10 = Disperser.LOW_RES_10
    val dMr = Disperser.MIRROR
    sc.putParameter(disperserParam(d10, dMr))
    sc.putParameter(filterParam(Filter.Q, Filter.N_PRIME))
    sc.putParameter(lamdaParam(6.0, 7.0))
    setSysConfig(sc)

    verifyWavelength("6.0", Filter.N_PRIME.getWavelength)
  }

}


text:
using Newtonsoft.Json;
using RestSharp;
using System.Collections.Generic;

namespace CustomizedPushNotifications.API.Twitch
{
    class Twitch
    {
        private static RestClient restClient = new RestClient("https://api.twitch.tv/kraken");

        public static bool StreamerOnline(string streamerName, Configuration configuration)
        {
            var request = new RestRequest("streams/{streamerName}", Method.GET);
            request.AddUrlSegment("streamerName", streamerName);

            request.AddHeader("Accept", "application/vnd.twitchtv.v3+json");
            request.AddHeader("Client-ID", configuration.TwitchClientId);

            IRestResponse response = restClient.Execute(request);
            dynamic responseJson = JsonConvert.DeserializeObject<dynamic>(response.Content);

            return responseJson.stream != null;
        }

        public static Dictionary<string, bool> StreamersOnline(string[] streamerNames, Configuration configuration)
        {
            var result = new Dictionary<string, bool>();

            foreach (var streamerName in streamerNames)
            {
                result.Add(streamerName, false);
            }

            var request = new RestRequest("streams?channel={streamerNames}", Method.GET);
            request.AddUrlSegment("streamerNames", string.Join(",", streamerNames));

            request.AddHeader("Accept", "application/vnd.twitchtv.v3+json");
            request.AddHeader("Client-ID", configuration.TwitchClientId);

            IRestResponse response = restClient.Execute(request);
            dynamic responseJson = JsonConvert.DeserializeObject<dynamic>(response.Content);

            foreach (dynamic stream in responseJson.streams)
            {
                result[stream.channel.name.Value] = true;
            }

            return result;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;

namespace SuperSecretary.Utilities
{
    public enum ExifProperties
    {
        CameraMaker = 0x010F,
        CameraModel = 0x0110,
        DateTaken = 0x9003
    }

    public class ExifUtilities
    {
        public static string GetProperty(string fileName, ExifProperties property)
        {
            string value = "";
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                using (Image image = Image.FromStream(fs, false, false))
                {
                    var propertyItem = image.GetPropertyItem((int)property);
                    value = Encoding.UTF8.GetString(propertyItem.Value, 0, propertyItem.Len - 1);
                }
            }
            return value;
        }
    }
}


text:
    //     This code was generated from a template.
    //
    //     Manual changes to this file may cause unexpected behavior in your application.
    //     Manual changes to this file will be overwritten if the code is regenerated.
    //
//  </auto-generated>
//------------------------------------------------------------------------------
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net;

namespace Tests.RouteTests
{
    [TestClass]
    public class StockItemsCoreTests : WebApiTestBaseClass
    {
        [TestMethod]
        public async Task StockItemsGetShouldReturnHTTPOk()
        {
            using (var response = await HttpClient.GetAsync("http://testserver/api/StockItems?%24top=10"))
            {
                var result = await response.Content.ReadAsStringAsync();
                Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, "Return Get 10 or less for StockItems");
            }

            using (var response = await HttpClient.GetAsync("http://testserver/api/StockItems?%24expand=Supplier&%24top=10"))
            {
                var result = await response.Content.ReadAsStringAsync();
                Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, "Return Get 10 or less StockItems with Expand of Supplier");
            }

            using (var response = await HttpClient.GetAsync("http://testserver/api/StockItems?%24expand=Color&%24top=10"))
            {
                var result = await response.Content.ReadAsStringAsync();
                Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, "Return Get 10 or less StockItems with Expand of Color");
            }

            using (var response = await HttpClient.GetAsync("http://testserver/api/StockItems?%24expand=Person&%24top=10"))
            {
                var result = await response.Content.ReadAsStringAsync();
                Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, "Return Get 10 or less StockItems with Expand of Person");
            }

            using (var response = await HttpClient.GetAsync("http://testserver/api/StockItems?%24expand=OuterPackageID&%24top=10"))
            {
                var result = await response.Content.ReadAsStringAsync();
                Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, "Return Get 10 or less StockItems with Expand of OuterPackageID");
            }

            using (var response = await HttpClient.GetAsync("http://testserver/api/StockItems?%24expand=UnitPackageID&%24top=10"))
            {
                var result = await response.Content.ReadAsStringAsync();
                Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, "Return Get 10 or less StockItems with Expand of UnitPackageID");
            }

        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.arunkrishnamurthy.twowayslider">

    <uses-permission android:name="android.permission.VIBRATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".TestActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
require 'deep_merge'
# Monkey patch Ruby on Rails
require 'rails/social_stream'
# Rails Engine Decorators
require 'rails_engine_decorators'
# Database foreign keys
require 'foreigner'
# jQuery
require 'jquery-rails'
# jQuery UI
require 'jquery-ui-rails'
# Select2 javascript library
require 'select2-rails'
# Permalinks:
require 'stringex'
# Hierarchical relationships in Activity and Relation:
require 'ancestry'
# Messages
require 'mailboxer'
require 'mailboxer/social_stream'
# User authentication
require 'devise'
# Authorization
require 'cancan'
# REST controllers
require 'inherited_resources'
require 'inherited_resources/social_stream'
# Scopes in controllers
require 'has_scope'
# Logo attachments
require 'paperclip'
require 'paperclip/social_stream'
require 'avatars_for_rails'
# Pagination
require 'kaminari'
# Oauth
require 'omniauth'
require 'omniauth-socialstream'
require 'omniauth-facebook'
require 'omniauth-linkedin'
#Tags
require 'acts-as-taggable-on'
require 'acts_as_taggable_on/social_stream'
#Background tasks
require 'resque/server'
# Modernizr.js library
require 'modernizr-rails'
# Sphinx search engine
require 'thinking-sphinx'
require 'thinking-sphinx/social_stream'
# Syntactically Awesome Stylesheets
require 'sass-rails'
# Bootstrap for Sass
require 'bootstrap-sass'
# Customize ERB views
require 'deface'
# Autolink text blocks
require 'rails_autolink'
# I18n-js
require 'i18n-js'
require 'i18n-js/social_stream-base'
# Strong parameters
require 'strong_parameters'
# Flash messages
require 'flashy'


text:
package net.pubnative.api.core.view;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;

public class PNAPIWebView extends WebView {

    public PNAPIWebView(Context context) {
        super(context);
        init();
    }

    public PNAPIWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PNAPIWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        getSettings().setJavaScriptEnabled(true);
    }

    public void loadBeacon(final String jsBeacon) {
        loadUrl("javascript:" + jsBeacon);
    }
}


text:
require 'fast_stemmer'

module TeRex
  module Classifier
    class BayesData
      class << self

        # Remove all kinds of explicit punctuation.
        def remove_punct(s)
          s.gsub(/(\,)|(\?)|(\.)|(\!)|(\;)|(\:)|(\")|(\@)|(\#)|(\$)|(\^)|(\&)|(\*)|(\()|(\))|(\_)|(\=)|(\+)|(\[)|(\])|(\\)|(\|)|(\<)|(\>)|(\/)|(\`)|(\{)|(\})/, ' ')
        end

        # Remove all kinds of newlines or big spaces: tab, newline, carraige return
        def remove_big_space(s)
          s.gsub(/\n|\t|\r/,' ')
        end

        # Remove sequences of whitespace
        def remove_space_seq(s)
          s.gsub(/\s{2,}/,' ')
        end

        # Remove cardinal terms (1st, 23rd, 42nd)
        def remove_cardinal(s)
          s.gsub(/[0-9]{2}[a-z,A-Z]{2}/, '')
        end

        # Replace date times with TERM (09MAR04, 02-23-14, 2014/03/05)
        def date_time(s)
          s.gsub(/(^\d+)|(\s\d+(AM|PM))|(\d{2}\w{3}\d{2})|(\d{2}\:\d{2})|(\d{2,4}\-\d{2,4}-\d{2,4})|(\d{1,4}\/\d{2,4}\/\d{2,4})|(\d+\:\d+)/, 'datetime')
        end

        # Replace money types with TERM ($60, 120.00, $423.89)
        def money_term(s)
          s.gsub(/(\$\d+\.\d+)|(\$\d+)|(\d+\.\d+)/, 'moneyterm')
        end

        # Return a Hashed Index of words => instance_count.
        # Each word in the string is interned and shows count in the document.
        def index_frequency(text)
          cfi = clean_stemmed_filtered_index(text)
          cni = clean_filtered_index(text)
          cfi.merge(cni)
        end

        # Return text with datetime and moneyterms replaced, remove cardinal terms (1st, 23rd, 42nd), remove punctuation.
        # At one point we were replacing any non-word chars exlcuding spaces (/[^\w\s]/) like so `gsub(/[^\w\s]/, "")` but I took it out as it removed some punctuation needed to distinguish some classes.
        def clean(text)
          dt = date_time(text)
          mt = money_term(dt)
          rp = remove_punct(mt)
          sp = remove_big_space(rp)
          ss = remove_space_seq(sp)
          remove_cardinal(ss)
        end

        # Return a filtered word freq index with stemmed morphemes and without extra punctuation or short words
        def clean_stemmed_filtered_index(text)
          stemmed_filtered_index clean(text).split
        end

        # Return a filtered word freq index without extra punctuation or short words
        def clean_filtered_index(text)
          filtered_index clean(text).split
        end

        # Return a word freq index without downcasing, stemming, or filtering with stop list
        def clean_naive_index(text)
          naive_index clean(text).split
        end

        private
        # Downcase, filter against stop list, ignore sequences less that 1 chars, and stem words
        def stemmed_filtered_index(word_array)
          idx = Hash.new(0)
          word_array.each do |word|
            word.downcase!
            if !TeRex::StopWord::LIST.include?(word) && word.length > 1
              idx[word.stem.intern] += 1
            end
          end

          idx
        end

        # Downcase, filter against stop list, and ignore sequences less that 2 chars.
        def filtered_index(word_array)
          idx = Hash.new(0)
          word_array.each do |word|
            word.downcase!
            if !TeRex::StopWord::LIST.include?(word) && word.length > 3
              idx[word.intern] += 1
            end
          end

          idx
        end

        # Count everything in the word array.
        def naive_index(word_array)
          idx = Hash.new(0)
          word_array.each do |word|
            idx[word.intern] += 1
          end

          idx
        end

      end
    end
  end
end


text:
from __future__ import print_function
from collections import OrderedDict
from orlo.queries import apply_filters, filter_release_rollback, filter_release_status
from orlo.app import app
from orlo.orm import db, Release, Package
from orlo.exceptions import InvalidUsage

__author__ = 'alforbes'

"""
Functions related to building statistics
"""

def releases_by_time(unit, summarize_by_unit=False, **kwargs):
    """
    Return stats by time from the given arguments

    :param summarize_by_unit: Passed to add_release_by_time_to_dict()
    :param unit: Passed to add_release_by_time_to_dict()
    """

    query = db.session.query(Release.id, Release.stime)\
        .join(Package)\
        .group_by(Release)
    query = apply_filters(query, kwargs)

    return get_dict_of_objects_by_time(query, unit, summarize_by_unit)

def packages_by_time(unit, summarize_by_unit=False, **kwargs):
    """
    Count packages by time from the filters given

    :param summarize_by_unit: Passed to add_release_by_time_to_dict()
    :param unit: Passed to add_release_by_time_to_dict()
    """

    query = db.session.query(Package.id, Package.name, Package.stime)\
        .join(Release)
    query = apply_filters(query, kwargs)

    return get_dict_of_objects_by_time(query, unit, summarize_by_unit)

# TODO add stats_user_time and stats_team_time
# or generalise a stats_time function

def get_dict_of_objects_by_time(query, unit, summarize_by_unit=False):
    """
    Build a dictionary which summarises the objects in the query given

    :param query:
    :param unit:
    :param summarize_by_unit:
    :return:
    """

    # Build queries for the individual stats
    q_normal_successful = filter_release_status(
        filter_release_rollback(query, rollback=False), 'SUCCESSFUL'
    )
    q_normal_failed = filter_release_status(
        filter_release_rollback(query, rollback=False), 'FAILED'
    )
    q_rollback_successful = filter_release_status(
        filter_release_rollback(query, rollback=True), 'SUCCESSFUL'
    )
    q_rollback_failed = filter_release_status(
        filter_release_rollback(query, rollback=True), 'FAILED'
    )

    output_dict = OrderedDict()

    add_objects_by_time_to_dict(
        q_normal_successful, output_dict, ('normal', 'successful'), unit,
        summarize_by_unit)
    add_objects_by_time_to_dict(
        q_normal_failed, output_dict, ('normal', 'failed'), unit,
        summarize_by_unit)
    add_objects_by_time_to_dict(
        q_rollback_successful, output_dict, ('rollback', 'successful'), unit,
        summarize_by_unit)
    add_objects_by_time_to_dict(
        q_rollback_failed, output_dict, ('rollback', 'failed'), unit,
        summarize_by_unit)

    return output_dict

def add_objects_by_time_to_dict(query, releases_dict, t_category, unit='month',
                                summarize_by_unit=False):
    """
    Take a query and add its objects to a dictionary, broken down by time

    If the query given has a 'name' column, that will be included in the
    dictionary path above the categories (t_category).

    :param dict releases_dict: Dict to add to
    :param tuple t_category: tuple of headings, i.e. (<normal|rollback>,
        <successful|failed>)
    :param query query: Query object to retrieve releases from
    :param string unit: Can be 'iso', 'hour', 'day', 'week', 'month', 'year',
    :param boolean summarize_by_unit: Only break down releases by the given
        unit, i.e. only one layer deep. For example, if "year" is the unit, we
        group all releases under the year and do not add month etc underneath.
    :return:

    **Note**: this can also be use for packages
    """
    app.logger.debug("Entered add_objects_by_time_to_dict")
    for object_ in query:
        if summarize_by_unit:
            tree_args = [str(getattr(object_.stime, unit))]
        else:
            if unit == 'year':
                tree_args = [str(object_.stime.year)]
            elif unit == 'month':
                tree_args = [str(object_.stime.year), str(object_.stime.month)]
            elif unit == 'week':
                # First two args of isocalendar(), year and week
                tree_args = [str(i) for i in object_.stime.isocalendar()][0:2]
            elif unit == 'iso':
                tree_args = [str(i) for i in object_.stime.isocalendar()]
            elif unit == 'day':
                tree_args = [str(object_.stime.year), str(object_.stime.month),
                             str(object_.stime.day)]
            elif unit == 'hour':
                tree_args = [str(object_.stime.year), str(object_.stime.month),
                             str(object_.stime.day), str(object_.stime.hour)]
            else:
                raise InvalidUsage(
                    'Invalid unit "{}" specified for release breakdown'.format(
                        unit))
        if hasattr(object_, 'name'):
            tree_args.append(object_.name)
        # Append categories
        tree_args += t_category
        append_tree_recursive(releases_dict, tree_args[0], tree_args)

def append_tree_recursive(tree, parent, nodes, node_index=0):
    """
    Recursively place the nodes under each other

    :param dict tree: The dictionary we are operating on
    :param parent: The parent for this node
    :param nodes: The list of nodes
    :param node_index: The position in the list list we are up to
    :return:
    """
    app.logger.debug('Called recursive function with args:\n{}, {}, {}'.format(
        str(tree), str(parent), str(nodes)))

    child_index = node_index + 1
    try:
        # Get the child, one after the parent
        child = nodes[child_index]
    except IndexError:
        # Must be at end
        if parent in tree:
            tree[parent] += 1
        else:
            tree[parent] = 1
        return tree

    # Otherwise recurse again
    if parent not in tree:
        tree[parent] = {}
    # Child becomes the parent
    append_tree_recursive(tree[parent], child, nodes, node_index=child_index)


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

Class toko extends CI_model{

    function GetTokoID($userid){
        $this->db->select('Toko_ID');
        $this->db->where('UserID', $userid);
        $query = $this->db->get('toko');
        return $query->row_array();
     }

     function GetTokoData($tokoid){
         $this->db->where('Toko_ID', $Tokoid);
         $query = $this->db->get('toko');
         return $query->row_array();
     }

     function GetNamaToko($tokoid){
         $this->db->select('Nama_toko');
         $this->db->where('Toko_ID', $tokoid);
         $query = $this->db->get('toko');
         return $query->row_array();
     }

     function setToko($datatoko){
         $this->db->insert('toko', $datatoko);
         return true;
        }

     function ChangeToko($tokoid, $changedatatoko){
         $this->db->where('Toko_ID', $tokid);
         $this->db->update('toko', $changedatatoko);
         return true;
     }

     function ChangeFoto($Tokoid, $urlfoto){
         $this->db->set('foto_toko', $urlfoto);
         $this->db->where('Toko_ID', $tokoid);
         $this->db->update('Fototoko');
     }

     function GetUrlFotoToko($Tokoid, $urlfoto){
         $this->db->select('foto_toko');
         $this->db->where('Toko_ID', $tokoid);
         $query = $this->db->get('toko');
         $urlfoto = $query->row_array();
     }

     function GetFotoBackground($Tokoid, $urlbackground){
         $this->db->select('foto_back');
         $this->db->where('Toko_ID', $tokoid);
         $query = $this->db->get('toko');
         $urlbackground = $query->row_array();
     }

     function DeletebFoto($Tokoid, $urlfoto){
         $this->db->where('foto_toko', $urlfoto);
         $this->db->delete('toko');
         return true;
     }

     function DeletedBackgroundFoto($Tokoid, $urlbackground){
         $this->db->where('foto_back', $urlbackground);
         $this->db->delete('toko');
         return true;
     }

}
?>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

    <input type="button" onclick="previous()" value="previous" />
    <input type="button" onclick="next()" value="next" />


text:
struct rotthrd {
    struct worker worker;
    struct fifo *input;
    int flags;
};

static void *rot_thread(void *arg)
{
    struct rotthrd *rt = container_of(arg, struct rotthrd, worker);
    struct image *img;

    int save_flags = 0;
    if (rt->flags & ROTTHREAD_NO_RDMA)
        save_flags |= IMAGE_FLAG_NO_RDMA;

    while ((img = fifo_pop(rt->input)) != NULL) {
        if (image_rot180(img)) {
            error_perror(img->filename);
        } else {
            image_save(img, save_flags);
        }

        image_free(img);
    }

    worker_finish_thread(&rt->worker);

    return NULL;
}

struct rotthrd *rotthrd_start(struct fifo *input, int num_threads, int flags)
{
    struct rotthrd *rt = malloc(sizeof(*rt));
    if (rt == NULL)
        return NULL;

    rt->input = input;
    rt->flags = flags;

    if (!worker_start(&rt->worker, num_threads, rot_thread))
        return rt;

    free(rt);
    return NULL;
}

void rotthrd_join(struct rotthrd *rt, int print_cputime)
{
    if (print_cputime)
        fprintf(stderr, "Rotation Thread CPU Time:\n");

    worker_join(&rt->worker, print_cputime);
    free(rt);
}


text:
package digitalocean

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/digitalocean/godo"

	"github.com/spf13/afero"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"

	"github.com/quilt/quilt/cluster/acl"
	"github.com/quilt/quilt/cluster/machine"
	"github.com/quilt/quilt/db"
	"github.com/quilt/quilt/util"
)

const testNamespace = "namespace"
const errMsg = "error"

var errMock = errors.New(errMsg)

var network = &godo.Networks{
	V4: []godo.NetworkV4{
		{
			IPAddress: "privateIP",
			Netmask:   "255.255.255.255",
			Gateway:   "2.2.2.2",
			Type:      "private",
		},
		{
			IPAddress: "publicIP",
			Netmask:   "255.255.255.255",
			Gateway:   "2.2.2.2",
			Type:      "public",
		},
	},
}

var sfo = &godo.Region{
	Slug: DefaultRegion,
}

func init() {
	util.AppFs = afero.NewMemMapFs()
	keyFile := filepath.Join(os.Getenv("HOME"), apiKeyPath)
	util.WriteFile(keyFile, []byte("foo"), 0666)
}

func TestList(t *testing.T) {
	mc := new(mockClient)
	// Create a list of Droplets, that are paginated.
	dropFirst := []godo.Droplet{
		{
			ID:        123,
			Name:      testNamespace,
			Networks:  network,
			SizeSlug:  "size",
			VolumeIDs: []string{"foo"},
			Region:    sfo,
		},

		// This droplet should not be listed because it has a name different from
		// testNamespace.
		{
			ID:        124,
			Name:      "foo",
			Networks:  network,
			SizeSlug:  "size",
			VolumeIDs: []string{"foo"},
			Region:    sfo,
		},
	}

	dropLast := []godo.Droplet{
		{
			ID:        125,
			Name:      testNamespace,
			Networks:  network,
			SizeSlug:  "size",
			VolumeIDs: []string{"foo"},
			Region:    sfo,
		},
	}

	respFirst := &godo.Response{
		Links: &godo.Links{
			Pages: &godo.Pages{
				Last: "2",
			},
		},
	}

	respLast := &godo.Response{
		Links: &godo.Links{},
	}

	reqFirst := &godo.ListOptions{}
	mc.On("ListDroplets", reqFirst).Return(dropFirst, respFirst, nil).Once()

	reqLast := &godo.ListOptions{
		Page: reqFirst.Page + 1,
	}
	mc.On("ListDroplets", reqLast).Return(dropLast, respLast, nil).Once()

	floatingIPsFirst := []godo.FloatingIP{
		{IP: "ignored"},
		{Droplet: &godo.Droplet{ID: -1}, IP: "ignored"},
	}
	mc.On("ListFloatingIPs", reqFirst).Return(floatingIPsFirst, respFirst, nil).Once()

	floatingIPsLast := []godo.FloatingIP{
		{Droplet: &godo.Droplet{ID: 125}, IP: "floatingIP"},
	}
	mc.On("ListFloatingIPs", reqLast).Return(floatingIPsLast, respLast, nil).Once()

	mc.On("GetVolume", mock.Anything).Return(
		&godo.Volume{
			SizeGigaBytes: 32,
		}, nil, nil,
	).Twice()

	doClust, err := newDigitalOcean(testNamespace, DefaultRegion)
	assert.Nil(t, err)
	doClust.client = mc

	machines, err := doClust.List()
	assert.Nil(t, err)
	assert.Equal(t, machines, []machine.Machine{
		{
			ID:          "123",
			Provider:    db.DigitalOcean,
			PublicIP:    "publicIP",
			PrivateIP:   "privateIP",
			Size:        "size",
			Region:      "sfo1",
			Preemptible: false,
		},
		{
			ID:          "125",
			Provider:    db.DigitalOcean,
			PublicIP:    "publicIP",
			PrivateIP:   "privateIP",
			FloatingIP:  "floatingIP",
			Size:        "size",
			Region:      "sfo1",
			Preemptible: false,
		},
	})

	// Error ListDroplets.
	mc.On("ListFloatingIPs", mock.Anything).Return(nil, &godo.Response{}, nil).Once()
	mc.On("ListDroplets", mock.Anything).Return(nil, nil, errMock).Once()
	machines, err = doClust.List()
	assert.Nil(t, machines)
	assert.EqualError(t, err, errMsg)

	// Error ListFloatingIPs.
	mc.On("ListFloatingIPs", mock.Anything).Return(nil, nil, errMock).Once()
	_, err = doClust.List()
	assert.EqualError(t, err, errMsg)

	// Error PublicIPv4. We can't error PrivateIPv4 because of the two functions'
	// similarities and the order that they are called in `List`.
	droplets := []godo.Droplet{
		{
			ID:        123,
			Name:      testNamespace,
			Networks:  nil,
			SizeSlug:  "size",
			VolumeIDs: []string{"foo"},
			Region:    sfo,
		},
	}
	mc.On("ListDroplets", mock.Anything).Return(droplets, respLast, nil).Once()
	mc.On("ListFloatingIPs", mock.Anything).Return(nil, &godo.Response{}, nil).Once()
	machines, err = doClust.List()
	assert.Nil(t, machines)
	assert.EqualError(t, err, "no networks have been defined")

	respBad := &godo.Response{
		Links: &godo.Links{
			Pages: &godo.Pages{
				Prev: "badurl",
				Last: "2",
			},
		},
	}
	mc.On("ListFloatingIPs", mock.Anything).Return(nil, &godo.Response{}, nil).Once()
	mc.On("ListDroplets", mock.Anything).Return([]godo.Droplet{}, respBad, nil).Once()
	machines, err = doClust.List()
	assert.Nil(t, machines)
	assert.EqualError(t, err, "parse badurl: invalid URI for request")
}

func TestBoot(t *testing.T) {
	mc := new(mockClient)
	doClust, err := newDigitalOcean(testNamespace, DefaultRegion)
	assert.Nil(t, err)
	doClust.client = mc

	util.Sleep = func(t time.Duration) {}

	bootSet := []machine.Machine{}
	err = doClust.Boot(bootSet)
	assert.Nil(t, err)

	// Create a list of machines to boot.
	bootSet = []machine.Machine{
		{
			ID:        "123",
			Provider:  db.DigitalOcean,
			PublicIP:  "publicIP",
			PrivateIP: "privateIP",
			Size:      "size",
			DiskSize:  0,
			Region:    "sfo1",
		},
	}

	mc.On("GetDroplet", 123).Return(&godo.Droplet{
		Status:    "active",
		VolumeIDs: []string{"abc"},
	}, nil, nil).Twice()

	mc.On("CreateDroplet", mock.Anything).Return(&godo.Droplet{
		ID: 123,
	}, nil, nil).Once()

	mc.On("CreateVolume", mock.Anything).Return(&godo.Volume{
		ID: "abc",
	}, nil, nil).Once()

	mc.On("AttachVolume", mock.Anything, mock.Anything).Return(nil, nil, nil).Once()

	err = doClust.Boot(bootSet)
	// Make sure machines are booted.
	mc.AssertNumberOfCalls(t, "CreateDroplet", 1)
	assert.Nil(t, err)

	// Error CreateDroplet.
	doubleBootSet := append(bootSet, machine.Machine{
		ID:        "123",
		Provider:  db.DigitalOcean,
		PublicIP:  "publicIP",
		PrivateIP: "privateIP",
		Size:      "size",
		DiskSize:  0,
		Region:    "sfo1",
	})
	mc.On("CreateDroplet", mock.Anything).Return(nil, nil, errMock).Twice()
	err = doClust.Boot(doubleBootSet)
	assert.EqualError(t, err, errMsg)
}

func TestStop(t *testing.T) {
	mc := new(mockClient)
	doClust, err := newDigitalOcean(testNamespace, DefaultRegion)
	assert.Nil(t, err)
	doClust.client = mc

	util.Sleep = func(t time.Duration) {}

	// Test empty stop set
	stopSet := []machine.Machine{}
	err = doClust.Stop(stopSet)
	assert.Nil(t, err)

	// Test non-empty stop set
	stopSet = []machine.Machine{
		{
			ID:        "123",
			Provider:  db.DigitalOcean,
			PublicIP:  "publicIP",
			PrivateIP: "privateIP",
			Size:      "size",
			DiskSize:  0,
			Region:    "sfo1",
		},
	}

	mc.On("GetDroplet", 123).Return(&godo.Droplet{
		Status:    "active",
		VolumeIDs: []string{"abc"},
	}, nil, nil).Once()

	mc.On("GetDroplet", 123).Return(nil, nil, nil).Once()

	mc.On("DeleteDroplet", 123).Return(nil, nil).Once()

	mc.On("DeleteVolume", "abc").Return(nil, nil).Once()

	err = doClust.Stop(stopSet)

	// Make sure machines are stopped.
	mc.AssertNumberOfCalls(t, "GetDroplet", 2)
	assert.Nil(t, err)

	// Error strconv.
	badDoubleStopSet := []machine.Machine{
		{
			ID:        "123a",
			Provider:  db.DigitalOcean,
			PublicIP:  "publicIP",
			PrivateIP: "privateIP",
			Size:      "size",
			DiskSize:  0,
			Region:    "sfo1",
		},
		{
			ID:        "123a",
			Provider:  db.DigitalOcean,
			PublicIP:  "publicIP",
			PrivateIP: "privateIP",
			Size:      "size",
			DiskSize:  0,
			Region:    "sfo1",
		},
	}
	err = doClust.Stop(badDoubleStopSet)
	assert.Error(t, err)

	// Error DeleteDroplet.
	mc.On("GetDroplet", 123).Return(&godo.Droplet{
		Status:    "active",
		VolumeIDs: []string{"abc"},
	}, nil, nil).Once()

	mc.On("DeleteDroplet", 123).Return(nil, errMock).Once()
	err = doClust.Stop(stopSet)
	assert.EqualError(t, err, errMsg)
}

func TestSetACLs(t *testing.T) {
	doClust, err := newDigitalOcean(testNamespace, DefaultRegion)
	assert.Nil(t, err)
	err = doClust.SetACLs([]acl.ACL{
		{
			CidrIP:  "digital",
			MinPort: 1,
			MaxPort: 65535,
		},
		{
			CidrIP:  "ocean",
			MinPort: 22,
			MaxPort: 22,
		},
	})
	assert.NoError(t, err)
}

func TestUpdateFloatingIPs(t *testing.T) {
	mc := new(mockClient)
	clst := &Cluster{client: mc}

	mc.On("ListFloatingIPs", mock.Anything).Return(nil, nil, errMock).Once()
	err := clst.UpdateFloatingIPs(nil)
	assert.EqualError(t, err, fmt.Sprintf("list machines: %s", errMsg))
	mc.AssertExpectations(t)

	// Test assigning a floating IP.
	mc.On("AssignFloatingIP", "ip", 1).Return(nil, nil, nil).Once()
	err = clst.syncFloatingIPs(
		[]machine.Machine{
			{ID: "1"},
			{ID: "2"},
		},
		[]machine.Machine{
			{ID: "1", FloatingIP: "ip"},
		},
	)
	assert.NoError(t, err)
	mc.AssertExpectations(t)

	// Test error when assigning a floating IP.
	mc.On("AssignFloatingIP", "ip", 1).Return(nil, nil, errMock).Once()
	err = clst.syncFloatingIPs(
		[]machine.Machine{
			{ID: "1"},
		},
		[]machine.Machine{
			{ID: "1", FloatingIP: "ip"},
		},
	)
	assert.EqualError(t, err, fmt.Sprintf("assign IP (ip to 1): %s", errMsg))
	mc.AssertExpectations(t)

	// Test assigning one floating IP, and unassigning another.
	mc.On("AssignFloatingIP", "ip", 1).Return(nil, nil, nil).Once()
	mc.On("UnassignFloatingIP", "remove").Return(nil, nil, nil).Once()
	err = clst.syncFloatingIPs(
		[]machine.Machine{
			{ID: "1"},
			{ID: "2", FloatingIP: "remove"},
		},
		[]machine.Machine{
			{ID: "1", FloatingIP: "ip"},
			{ID: "2"},
		},
	)
	assert.NoError(t, err)
	mc.AssertExpectations(t)

	// Test error when unassigning a floating IP.
	mc.On("UnassignFloatingIP", "remove").Return(nil, nil, errMock).Once()
	err = clst.syncFloatingIPs(
		[]machine.Machine{
			{ID: "2", FloatingIP: "remove"},
		},
		[]machine.Machine{
			{ID: "2"},
		},
	)
	assert.EqualError(t, err, fmt.Sprintf("unassign IP (remove): %s", errMsg))
	mc.AssertExpectations(t)

	// Test changing a floating IP, which requires removing the old one, and
	// assigning the new.
	mc.On("UnassignFloatingIP", "changeme").Return(nil, nil, nil).Once()
	mc.On("AssignFloatingIP", "ip", 1).Return(nil, nil, nil).Once()
	err = clst.syncFloatingIPs(
		[]machine.Machine{
			{ID: "1", FloatingIP: "changeme"},
		},
		[]machine.Machine{
			{ID: "1", FloatingIP: "ip"},
		},
	)
	assert.NoError(t, err)
	mc.AssertExpectations(t)

	// Test machines that need no changes.
	err = clst.syncFloatingIPs(
		[]machine.Machine{
			{ID: "1", FloatingIP: "ip"},
		},
		[]machine.Machine{
			{ID: "1", FloatingIP: "ip"},
		},
	)
	assert.NoError(t, err)
	mc.AssertExpectations(t)

	err = clst.syncFloatingIPs(
		[]machine.Machine{},
		[]machine.Machine{
			{ID: "1", FloatingIP: "ip"},
		},
	)
	assert.EqualError(t, err, "no machines match desired: "+
		"[{ID:1 PublicIP: PrivateIP: FloatingIP:ip Preemptible:false "+
		"Size: DiskSize:0 SSHKeys:[] Provider: Region: Role:}]")

	err = clst.syncFloatingIPs(
		[]machine.Machine{{ID: "NAN"}},
		[]machine.Machine{
			{ID: "NAN", FloatingIP: "ip"},
		},
	)
	assert.EqualError(t, err,
		"malformed id (NAN): strconv.Atoi: parsing \"NAN\": invalid syntax")
}

func TestNew(t *testing.T) {
	mc := new(mockClient)
	clust := &Cluster{
		namespace: testNamespace,
		client:    mc,
	}

	// Log a bad namespace.
	newDigitalOcean("___ILLEGAL---", DefaultRegion)

	// newDigitalOcean throws an error.
	newDigitalOcean = func(namespace, region string) (*Cluster, error) {
		return nil, errMock
	}
	outClust, err := New(testNamespace, DefaultRegion)
	assert.Nil(t, outClust)
	assert.EqualError(t, err, "error")

	// Normal operation.
	newDigitalOcean = func(namespace, region string) (*Cluster, error) {
		return clust, nil
	}
	mc.On("ListDroplets", mock.Anything).Return(nil, nil, nil).Once()
	outClust, err = New(testNamespace, DefaultRegion)
	assert.Nil(t, err)
	assert.Equal(t, clust, outClust)

	// ListDroplets throws an error.
	mc.On("ListDroplets", mock.Anything).Return(nil, nil, errMock)
	outClust, err = New(testNamespace, DefaultRegion)
	assert.Equal(t, clust, outClust)
	assert.EqualError(t, err, errMsg)
}


text:
package com.topo.miditest;

/**
 * Created by yaf107 on 7/15/16.
 */
public class Note {
    private boolean together;
    private boolean sustain = false;
    private int velocity = 60;
    private String[] note;
    private int[] midi;

    public Note(String note) {
        this.note = new String[1];
        this.midi = new int[1];
        this.note[0] = note;
        this.together = false;
    }

    public Note(String[] note, boolean together) {
        this.note = note;
        this.midi = new int[note.length];
        this.together = together;
    }

    public String[] getNote() {
        return note;
    }

    public int[] getMidi() {
        return midi;
    }

    public void setMidi(int index, int midi) {
        this.midi[index] = midi;
    }

    public boolean isTogether() {
        return together;
    }

    public void setTogether(boolean together) {
        this.together = together;
    }

    public boolean isSustain() {
        return sustain;
    }

    public void setSustain(boolean sustain) {
        this.sustain = sustain;
    }

    public int getVelocity() {
        return velocity;
    }

    public void setVelocity(int velocity) {
        this.velocity = velocity;
    }
}


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe Entry do

  context 'on validations' do

    it { should validate_presence_of(:title) }
    it { should validate_presence_of(:description) }
    it { should validate_presence_of(:user_id) }

    it { should belong_to(:user) }
    it { should_not allow_mass_assignment_of(:user_id) }

  end

end


text:
import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';

@withRouter
export default class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props;

    return (

You are now at {location.pathname}

The match is: {JSON.stringify(match)}

The history contains: {JSON.stringify(history)}

    )
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans bean-discovery-mode="all"
       xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd">
    <interceptors>
        <class>javaeetutorial.billpayment.interceptor.LoggedInterceptor</class>
    </interceptors>
</beans>


text:
module GraphQL::Batch
  class SetupMultiplex
    def initialize(schema, executor_class:)
      @schema = schema
      @executor_class = executor_class
    end

    def before_multiplex(multiplex)
      GraphQL::Batch::Executor.start_batch(@executor_class)
    end

    def after_multiplex(multiplex)
      GraphQL::Batch::Executor.end_batch
    end
  end
end


text:
local uv = require "lluv"

local function printf(...) io.write(string.format(...)) end

-- Run the benchmark for this many ms
local TIME = 15000

local TEST_PORT = 5555

local PING = "PING\n";

local start_time

local function pinger_new()

local pinger

local function pinger_close_cb(handle)
  printf("ping_pongs: %d roundtrips/s\n", (1000 * pinger.pongs) / TIME)
  pinger.complite = true
end

local function pinger_write_cb(handle, err)
  assert(not err, tostring(err))
end

local function pinger_write_ping(pinger)
  assert(pinger.tcp:write(PING, pinger_write_cb))
end

local function pinger_shutdown_cb(handle, err)
  assert(not err, tostring(err))
  assert(not pinger.complite)
  pinger.shutdown = true
end

local function pinger_read_cb(tcp, err, buf)
  if err then
    assert(err:name() == "EOF")

    -- assert(pinger_shutdown_cb_called == 1)
    tcp:close(pinger_close_cb)

    return
  end

  local len    = pinger.tail + #buf
  local count  = math.floor(len / #PING)

  pinger.pongs = pinger.pongs + count
  pinger.tail  = len % #PING

  if (uv.now() - start_time) > TIME then
    tcp:shutdown(pinger_shutdown_cb)
  else
    for i = 1, count do
      pinger_write_ping(pinger)
    end
  end
end

local function pinger_connect_cb(handle, err)
  assert(not err, tostring(err))

  start_time = uv.now()

  pinger_write_ping(pinger);

  assert(handle:start_read(pinger_read_cb))
end

pinger = {
  tcp   = assert(uv.tcp());
  pongs = 0;
  tail  = 0;
}

assert(pinger.tcp
  :bind("0.0.0.0", 0)
  :connect("127.0.0.1", TEST_PORT, pinger_connect_cb)
)

return pinger

end

local function start()

  local process = uv.spawn({
    file = uv.exepath();
    args = {"tcp_echo.lua"};
    cwd  = uv.cwd();
    stdio = {{}, 1, 2}
  }, function()
    print("server closed")
  end):unref()

  local p1 = pinger_new()
  -- local p2 = pinger_new()

  uv.run(debug.traceback)

  assert(p1.complite)
  -- assert(p2.complite)

  process:ref():kill()

  uv.run()
end

start()


text:
using Easylink;

namespace EasylinkWalkThrough
{
    public class EmployeeMapping : Mapping
    {
        public override IMappingConfig Setup()
        {
            var config = Class<Employee>().ToTable("EMPLOYEE").NextId(NextIdOption.AutoIncrement);

            config.Property(e => e.Id).ToIdColumn("Id");
            config.Property(e => e.FirstName).ToColumn("FIRST_NAME");
            config.Property(e => e.LastName).ToColumn("LAST_NAME");
            config.Property(e => e.Active).ToColumn("ACTIVE");
            config.Property(e => e.LoginId).ToColumn("LOGIN_ID");
            config.Property(e => e.Role.Id).ToColumn("ROLE_ID");

            config.Link<Employee,Lookup>(e=>e.Role.Id, l => l.Id);

            return config;
        }
    }
}