text:
/*****************************************************************************/
/**
*
* @file xcanps_intr.c
*
* This file contains functions related to CAN interrupt handling.
*
*

* MODIFICATION HISTORY:
*
* Ver   Who    Date	Changes
* ----- -----  -------- -----------------------------------------------
* 1.00a xd/sv  01/12/10 First release
* 3.00  kvn    02/13/15 Modified code for MISRA-C:2012 compliance.
*

*
******************************************************************************/

/***************************** Include Files *********************************/

#include "xcanps.h"

/************************** Constant Definitions *****************************/

/**************************** Type Definitions *******************************/

/***************** Macros (Inline Functions) Definitions *********************/

/************************** Variable Definitions *****************************/

/************************** Function Prototypes ******************************/

/****************************************************************************/
/**
*
* This routine enables interrupt(s). Use the XCANPS_IXR_* constants defined in
* xcanps_hw.h to create the bit-mask to enable interrupts.
*
* @param	InstancePtr is a pointer to the XCanPs instance.
* @param	Mask is the mask to enable. Bit positions of 1 will be enabled.
*		Bit positions of 0 will keep the previous setting. This mask is
*		formed by OR'ing XCANPS_IXR_* bits defined in xcanps_hw.h.
*
* @return	None.
*
* @note		None.
*
*****************************************************************************/
void XCanPs_IntrEnable(XCanPs *InstancePtr, u32 Mask)
{
	u32 IntrValue;

	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	/*
	 * Write to the IER to enable the specified interrupts.
	 */
	IntrValue = XCanPs_IntrGetEnabled(InstancePtr);
	IntrValue |= Mask & XCANPS_IXR_ALL;
	XCanPs_WriteReg(InstancePtr->CanConfig.BaseAddr,
			XCANPS_IER_OFFSET, IntrValue);
}

/****************************************************************************/
/**
*
* This routine disables interrupt(s). Use the XCANPS_IXR_* constants defined in
* xcanps_hw.h to create the bit-mask to disable interrupt(s).
*
* @param	InstancePtr is a pointer to the XCanPs instance.
* @param	Mask is the mask to disable. Bit positions of 1 will be
*		disabled. Bit positions of 0 will keep the previous setting.
*		This mask is formed by OR'ing XCANPS_IXR_* bits defined in
*		xcanps_hw.h.
*
* @return	None.
*
* @note		None.
*
*****************************************************************************/
void XCanPs_IntrDisable(XCanPs *InstancePtr, u32 Mask)
{
	u32 IntrValue;

	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	/*
	 * Write to the IER to disable the specified interrupts.
	 */
	IntrValue = XCanPs_IntrGetEnabled(InstancePtr);
	IntrValue &= ~Mask;
	XCanPs_WriteReg(InstancePtr->CanConfig.BaseAddr,
			XCANPS_IER_OFFSET, IntrValue);
}

/****************************************************************************/
/**
*
* This routine returns enabled interrupt(s). Use the XCANPS_IXR_* constants
* defined in xcanps_hw.h to interpret the returned value.
*
* @param	InstancePtr is a pointer to the XCanPs instance.
*
* @return	Enabled interrupt(s) in a 32-bit format.
*
* @note		None.
*
*****************************************************************************/
u32 XCanPs_IntrGetEnabled(XCanPs *InstancePtr)
{

	Xil_AssertNonvoid(InstancePtr != NULL);
	Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	return XCanPs_ReadReg(InstancePtr->CanConfig.BaseAddr,
				XCANPS_IER_OFFSET);
}

/****************************************************************************/
/**
*
* This routine returns interrupt status read from Interrupt Status Register.
* Use the XCANPS_IXR_* constants defined in xcanps_hw.h to interpret the
* returned value.
*
* @param	InstancePtr is a pointer to the XCanPs instance.
*
* @return	The value stored in Interrupt Status Register.
*
* @note		None.
*
*****************************************************************************/
u32 XCanPs_IntrGetStatus(XCanPs *InstancePtr)
{
	Xil_AssertNonvoid(InstancePtr != NULL);
	Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	return XCanPs_ReadReg(InstancePtr->CanConfig.BaseAddr,
				XCANPS_ISR_OFFSET);
}

/****************************************************************************/
/**
*
* This function clears interrupt(s). Every bit set in Interrupt Status
* Register indicates that a specific type of interrupt is occurring, and this
* function clears one or more interrupts by writing a bit mask to Interrupt
* Clear Register.
*
* @param	InstancePtr is a pointer to the XCanPs instance.
* @param	Mask is the mask to clear. Bit positions of 1 will be cleared.
*		Bit positions of 0 will not change the previous interrupt
*		status. This mask is formed by OR'ing XCANPS_IXR_* bits defined
* 		in xcanps_hw.h.
*
* @note		None.
*
*****************************************************************************/
void XCanPs_IntrClear(XCanPs *InstancePtr, u32 Mask)
{
	u32 IntrValue;

	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	/*
	 * Clear the currently pending interrupts.
	 */
	IntrValue = XCanPs_IntrGetStatus(InstancePtr);
	IntrValue &= Mask;
	XCanPs_WriteReg(InstancePtr->CanConfig.BaseAddr, XCANPS_ICR_OFFSET,
				IntrValue);
}

/*****************************************************************************/
/**
*
* This routine is the interrupt handler for the CAN driver.
*
* This handler reads the interrupt status from the ISR, determines the source of
* the interrupts, calls according callbacks, and finally clears the interrupts.
*
* Application beyond this driver is responsible for providing callbacks to
* handle interrupts and installing the callbacks using XCanPs_SetHandler()
* during initialization phase. An example delivered with this driver
* demonstrates how this could be done.
*
* @param	InstancePtr is a pointer to the XCanPs instance that just
*		interrupted.
*
* @return	None.
*
* @note		None.
*
******************************************************************************/
void XCanPs_IntrHandler(void *InstancePtr)
{
	u32 PendingIntr;
	u32 EventIntr;
	XCanPs *CanPtr = (XCanPs *) ((void *)InstancePtr);

	Xil_AssertVoid(CanPtr != NULL);
	Xil_AssertVoid(CanPtr->IsReady == XIL_COMPONENT_IS_READY);

	PendingIntr = XCanPs_IntrGetStatus(CanPtr);
	PendingIntr &= XCanPs_IntrGetEnabled(CanPtr);

	/*
	 * Clear all pending interrupts.
	 * Rising Edge interrupt
	 */
	XCanPs_IntrClear(CanPtr, PendingIntr);

	/*
	 * An error interrupt is occurring.
	 */
	if (((PendingIntr & XCANPS_IXR_ERROR_MASK) != (u32)0) &&
		(CanPtr->ErrorHandler != NULL)) {
			CanPtr->ErrorHandler(CanPtr->ErrorRef,
					XCanPs_GetBusErrorStatus(CanPtr));
		/*
		 * Clear Error Status Register.
		 */
		XCanPs_ClearBusErrorStatus(CanPtr,
					XCanPs_GetBusErrorStatus(CanPtr));
	}

	/*
	 * Check if any following event interrupt is pending:
	 *	  - RX FIFO Overflow
	 *	  - RX FIFO Underflow
	 *	  - TX High Priority Buffer full
	 *	  - TX FIFO Full
	 *	  - Wake up from sleep mode
	 *	  - Enter sleep mode
	 *	  - Enter Bus off status
	 *	  - Arbitration is lost
	 *
	 * If so, call event callback provided by upper level.
	 */
	EventIntr = PendingIntr & ((u32)XCANPS_IXR_RXOFLW_MASK |
				(u32)XCANPS_IXR_RXUFLW_MASK |
				(u32)XCANPS_IXR_TXBFLL_MASK |
				(u32)XCANPS_IXR_TXFLL_MASK |
				(u32)XCANPS_IXR_WKUP_MASK |
				(u32)XCANPS_IXR_SLP_MASK |
				(u32)XCANPS_IXR_BSOFF_MASK |
				(u32)XCANPS_IXR_ARBLST_MASK);
	if ((EventIntr != (u32)0) && (CanPtr->EventHandler != NULL)) {
		CanPtr->EventHandler(CanPtr->EventRef, EventIntr);

		if ((EventIntr & XCANPS_IXR_BSOFF_MASK) != (u32)0) {
			/*
			 * Event callback should reset whole device if "Enter
			 * Bus Off Status" interrupt occurred. All pending
			 * interrupts are cleared and no further checking and
			 * handling of other interrupts is needed any more.
			 */
			return;
		} else {
			/*This else was made for misra-c compliance*/
			;
		}
	}

	if (((PendingIntr & (XCANPS_IXR_RXFWMFLL_MASK |
			XCANPS_IXR_RXNEMP_MASK)) != (u32)0) &&
		(CanPtr->RecvHandler != NULL)) {

		/*
		 * This case happens when
		 * A number of frames depending on the Rx FIFO Watermark
		 * threshold are received.
		 * And  also when frame was received and is sitting in RX FIFO.
		 *
		 * XCANPS_IXR_RXOK_MASK is not used because the bit is set
		 * just once even if there are multiple frames sitting
		 * in the RX FIFO.
		 *
		 * XCANPS_IXR_RXNEMP_MASK is used because the bit can be
		 * set again and again automatically as long as there is
		 * at least one frame in RX FIFO.
		 */
		CanPtr->RecvHandler(CanPtr->RecvRef);
	}

	/*
	 * A frame was transmitted successfully.
	 */
	if (((PendingIntr & XCANPS_IXR_TXOK_MASK) != (u32)0) &&
		(CanPtr->SendHandler != NULL)) {
		CanPtr->SendHandler(CanPtr->SendRef);
	}
}

/*****************************************************************************/
/**
*
* This routine installs an asynchronous callback function for the given
* HandlerType:
*
*

* HandlerType			Callback Function Type
* -----------------------	------------------------
* XCANPS_HANDLER_SEND		XCanPs_SendRecvHandler
* XCANPS_HANDLER_RECV		XCanPs_SendRecvHandler
* XCANPS_HANDLER_ERROR		XCanPs_ErrorHandler
* XCANPS_HANDLER_EVENT		XCanPs_EventHandler
*
* HandlerType			Invoked by this driver when:
* -------------------------------------------------------------------------
* XCANPS_HANDLER_SEND		A frame transmitted by a call to
*				XCanPs_Send() has been sent successfully.
*
* XCANPS_HANDLER_RECV		A frame(s) has been received and is sitting in
*				the RX FIFO.
*
* XCANPS_HANDLER_ERROR		An error interrupt is occurring.
*
* XCANPS_HANDLER_EVENT		Any other kind of interrupt is occurring.
*

*
* @param	InstancePtr is a pointer to the XCanPs instance.
* @param	HandlerType specifies which handler is to be attached.
* @param	CallBackFunc is the address of the callback function.
* @param	CallBackRef is a user data item that will be passed to the
*		callback function when it is invoked.
*
* @return
*		- XST_SUCCESS when handler is installed.
*		- XST_INVALID_PARAM when HandlerType is invalid.
*
* @note
* Invoking this function for a handler that already has been installed replaces
* it with the new handler.
*
******************************************************************************/
s32 XCanPs_SetHandler(XCanPs *InstancePtr, u32 HandlerType,
			void *CallBackFunc, void *CallBackRef)
{
	s32 Status;
	Xil_AssertNonvoid(InstancePtr != NULL);
	Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	switch (HandlerType) {
		case XCANPS_HANDLER_SEND:
			InstancePtr->SendHandler =
				(XCanPs_SendRecvHandler) CallBackFunc;
			InstancePtr->SendRef = CallBackRef;
			Status = XST_SUCCESS;
			break;

		case XCANPS_HANDLER_RECV:
			InstancePtr->RecvHandler =
				(XCanPs_SendRecvHandler) CallBackFunc;
			InstancePtr->RecvRef = CallBackRef;
			Status = XST_SUCCESS;
			break;

		case XCANPS_HANDLER_ERROR:
			InstancePtr->ErrorHandler =
				(XCanPs_ErrorHandler) CallBackFunc;
			InstancePtr->ErrorRef = CallBackRef;
			Status = XST_SUCCESS;
			break;

		case XCANPS_HANDLER_EVENT:
			InstancePtr->EventHandler =
				(XCanPs_EventHandler) CallBackFunc;
			InstancePtr->EventRef = CallBackRef;
			Status = XST_SUCCESS;
			break;

		default:
			Status = XST_INVALID_PARAM;
			break;
	}
	return Status;
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Septoria pistaciarum Caracc., 1934

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package mesh

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"

	goversion "github.com/hashicorp/go-version"
	"gopkg.in/yaml.v2"

	"istio.io/operator/pkg/version"
	binversion "istio.io/operator/version"
)

func TestGetVersionCompatibleMap(t *testing.T) {
	type args struct {
		versionsURI string
		binVersion  *goversion.Version
		l           *Logger
	}

	testDataDir = filepath.Join(repoRootDir, "cmd/mesh/testdata/manifest-versions")
	testdataVersionsFilePath := filepath.Join(testDataDir, "input", "versions.yaml")
	operatorVersionsFilePath := "../../data/versions.yaml"
	nonexistentFilePath := "__nonexistent-versions.yaml"

	goVerNonexistent, _ := goversion.NewVersion("0.0.999")
	goVer133, _ := goversion.NewVersion("1.3.3")
	goVer137, _ := goversion.NewVersion("1.3.7")
	goVer1331, _ := goversion.NewVersion("1.3.3.1")
	goVer1399, _ := goversion.NewVersion("1.3.9.9")

	l := NewLogger(true, os.Stdout, os.Stderr)

	b, err := ioutil.ReadFile(operatorVersionsFilePath)
	if err != nil {
		t.Fatal(err)
	}
	var vs []version.CompatibilityMapping
	if err := yaml.Unmarshal(b, &vs); err != nil {
		t.Fatal(err)
	}
	var curCm, ver133Cm, ver137Cm *version.CompatibilityMapping
	for i := range vs {
		if binversion.OperatorBinaryGoVersion.Equal(vs[i].OperatorVersion) {
			curCm = &vs[i]
		}
		if goVer133.Equal(vs[i].OperatorVersion) {
			ver133Cm = &vs[i]
		}
		if goVer137.Equal(vs[i].OperatorVersion) {
			ver137Cm = &vs[i]
		}
	}

	if curCm == nil {
		t.Fatalf("OperatorBinaryGoVersion %v cannot be found in %s, "+
			"if OperatorBinaryGoVersion is updated to a new version, please also add it "+
			"into versions.yaml and generate the built-in vfs data.",
			binversion.OperatorBinaryGoVersion, operatorVersionsFilePath)
	}

	tests := []struct {
		name    string
		args    args
		want    *version.CompatibilityMapping
		wantErr error
	}{
		{
			name: "read the current binary version from data versions",
			args: args{
				versionsURI: operatorVersionsFilePath,
				binVersion:  binversion.OperatorBinaryGoVersion,
				l:           l,
			},
			want:    curCm,
			wantErr: nil,
		},
		{
			name: "read the current binary version from built-in version map",
			args: args{
				versionsURI: nonexistentFilePath,
				binVersion:  binversion.OperatorBinaryGoVersion,
				l:           l,
			},
			want:    curCm,
			wantErr: nil,
		},
		{
			name: "read version 133 from testdata",
			args: args{
				versionsURI: testdataVersionsFilePath,
				binVersion:  goVer133,
				l:           l,
			},
			want:    ver133Cm,
			wantErr: nil,
		},
		{
			name: "read nonexistent version from testdata",
			args: args{
				versionsURI: testdataVersionsFilePath,
				binVersion:  goVerNonexistent,
				l:           l,
			},
			want: nil,
			wantErr: fmt.Errorf("this operator version %s was not found in the version map",
				goVerNonexistent.String()),
		},
		{
			name: "read nonexistent version in built-in version map",
			args: args{
				versionsURI: nonexistentFilePath,
				binVersion:  goVerNonexistent,
				l:           l,
			},
			want: nil,
			wantErr: fmt.Errorf("this operator version %s was not found in the version map",
				goVerNonexistent.String()),
		},
		{
			name: "read previous version if not found from testdata",
			args: args{
				versionsURI: testdataVersionsFilePath,
				binVersion:  goVer1331,
				l:           l,
			},
			want:    ver133Cm,
			wantErr: nil,
		},
		{
			name: "read previous version if not found in built-in version map",
			args: args{
				versionsURI: nonexistentFilePath,
				binVersion:  goVer1331,
				l:           l,
			},
			want:    ver133Cm,
			wantErr: nil,
		},
		{
			name: "read version matching range only from testdata",
			args: args{
				versionsURI: testdataVersionsFilePath,
				binVersion:  goVer1399,
				l:           l,
			},
			want:    ver137Cm,
			wantErr: nil,
		},
		{
			name: "read version matching range only in built-in version map",
			args: args{
				versionsURI: nonexistentFilePath,
				binVersion:  goVer1399,
				l:           l,
			},
			want:    ver137Cm,
			wantErr: nil,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, gotErr := getVersionCompatibleMap(tt.args.versionsURI, tt.args.binVersion, tt.args.l)
			if fmt.Sprintf("%v", got) != fmt.Sprintf("%v", tt.want) {
				t.Errorf("got: %v, want: %v", got, tt.want)
			}
			if errToString(gotErr) != errToString(tt.wantErr) {
				t.Errorf("gotErr: %v, wantErr: %v", gotErr, tt.wantErr)
			}
		})
	}
}

// errToString returns the string representation of err and the empty string if
// err is nil.
func errToString(err error) string {
	if err == nil {
		return ""
	}
	return err.Error()
}


text:
package com.intellij.formatting;

import com.intellij.openapi.util.InvalidDataException;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;

public enum ForceBraces {
  Never(CommonCodeStyleSettings.DO_NOT_FORCE),
  IfMultiline(CommonCodeStyleSettings.FORCE_BRACES_IF_MULTILINE),
  Always(CommonCodeStyleSettings.FORCE_BRACES_ALWAYS);

  private final int myIntValue;

  ForceBraces(int value) {
    myIntValue = value;
  }

  public int intValue() {
    return myIntValue;
  }

  public static ForceBraces fromInt(int value) {
    for (ForceBraces mode : values()) {
      if (mode.intValue() == value) {
        return mode;
      }
    }
    throw new InvalidDataException("Unknown brace style integer value " + value);
  }
}


text:
package com.springDemo.proj.model;

/**
 * The Class Employee.
 */
public class Employee {

	/** The emp name. */
	private String empName;

	/** The emp id. */
	private int empId;

	/**
	 * Gets the emp name.
	 *
	 * @return the emp name
	 */
	public String getEmpName() {
		return empName;
	}

	/**
	 * Sets the emp name.
	 *
	 * @param empName the new emp name
	 */
	public void setEmpName(String empName) {
		this.empName = empName;
	}

	/**
	 * Gets the emp id.
	 *
	 * @return the emp id
	 */
	public int getEmpId() {
		return empId;
	}

	/**
	 * Sets the emp id.
	 *
	 * @param empId the new emp id
	 */
	public void setEmpId(int empId) {
		this.empId = empId;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Employee [empName=" + empName + ", empId=" + empId + "]";
	}

}


text:
from datetime import date

from django.db import models
from accounts.models import Account

class CleaningRoster(models.Model):
    """
    Model representing a randomly-selected roster for the room's cleaning
    """

    # Date where the people were selected
    date = models.DateField(auto_now_add=True)

    cleaners = models.ManyToManyField(Account)

    def save(self, *args, **kwargs):
        CleaningRoster.objects.filter(date=date.today()).delete()
        return super(CleaningRoster, self).save(*args, **kwargs)

    def __str__(self):
        return "Ménage du %s" % self.date


text:
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';

-- -----------------------------------------------------
-- Table `snapshot_window`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `snapshot_window` (
  `snapshot_window_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `scope_id` INT UNSIGNED NOT NULL ,
  `name` VARCHAR(100) NOT NULL ,
  `visible` TINYINT(1) NULL ,
  `request_user` VARCHAR(100) NULL ,
  `request_date` DATETIME NULL ,
  `execute_date` DATETIME NULL ,
  `change_date` DATETIME NULL ,
  `change_user` VARCHAR(100) NULL ,
  PRIMARY KEY (`snapshot_window_id`) )
ENGINE = InnoDB;

CREATE UNIQUE INDEX `snapshotwindow_name_scopeid_uc` ON `snapshot_window` (`name` ASC, `scope_id` ASC) ;

-- -----------------------------------------------------
-- Table `snapshot_summary`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `snapshot_summary` (
  `snapshot_summary_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `snapshot_window_id` INT UNSIGNED NOT NULL ,
  `org_id` INT UNSIGNED NOT NULL ,
  `create_date` DATETIME NULL ,
  `change_date` DATETIME NULL ,
  `change_user` VARCHAR(100) NULL ,
  PRIMARY KEY (`snapshot_summary_id`) ,
  CONSTRAINT `snapshotsummary_snapshotwindow_fk`
    FOREIGN KEY (`snapshot_window_id` )
    REFERENCES `snapshot_window` (`snapshot_window_id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `snapshotsummary_snapshotwindow_fki` ON `snapshot_summary` (`snapshot_window_id` ASC) ;

CREATE UNIQUE INDEX `snapshotsummary_snapshotwindowid_orgid_uc` ON `snapshot_summary` (`snapshot_window_id` ASC, `org_id` ASC) ;

-- -----------------------------------------------------
-- Table `snapshot_summary_value`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `snapshot_summary_value` (
  `snapshot_summary_value_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `snapshot_summary_id` INT UNSIGNED NOT NULL ,
  `type` VARCHAR(100) NOT NULL ,
  `value` VARCHAR(100) NOT NULL ,
  `change_date` DATETIME NULL ,
  `change_user` VARCHAR(100) NULL ,
  PRIMARY KEY (`snapshot_summary_value_id`) ,
  CONSTRAINT `snapshotsummaryvalue_snapshotsummary_fk`
    FOREIGN KEY (`snapshot_summary_id` )
    REFERENCES `snapshot_summary` (`snapshot_summary_id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `snapshotsummaryvalue_snapshotsummary_fki` ON `snapshot_summary_value` (`snapshot_summary_id` ASC) ;

CREATE UNIQUE INDEX `snapshotsummaryvalue_snapshotsummaryid_type_uc` ON `snapshot_summary_value` (`snapshot_summary_id` ASC, `type` ASC) ;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;


text:
package gov.va.med.imaging.storage.cache.impl.timer;

import gov.va.med.imaging.storage.cache.exceptions.InitializationException;
import gov.va.med.imaging.storage.cache.exceptions.InvalidSweepSpecification;
import gov.va.med.imaging.storage.cache.memento.EvictionTimerImplMemento;
import gov.va.med.imaging.storage.cache.timer.EvictionTimerImpl;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import junit.framework.TestCase;

public class TestEvictionTimerImpl extends TestCase
{

	protected void setUp() throws Exception
	{
		super.setUp();
	}

	public void testMemento()
	throws InitializationException, InvalidSweepSpecification
	{
		Map<Long, String> sweepIntervalMap = new HashMap<Long, String>();

		sweepIntervalMap.put(new Long(60000L), "0000:00:00:00:00:10");
		sweepIntervalMap.put(new Long(3600000L), "0000:00:00:00:01:00");
		sweepIntervalMap.put(new Long(86400000L), "0000:00:00:01:00:00");
		sweepIntervalMap.put(EvictionTimerImpl.defaultAgeSpecification, "0000:00:01:00:00:00@0000:00:00:03:00:00");

		EvictionTimerImpl timer = EvictionTimerImpl.create(sweepIntervalMap);
		EvictionTimerImplMemento memento = timer.createMemento();

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		XMLEncoder encoder = new XMLEncoder(outStream);
		encoder.writeObject(memento);
		encoder.close();

		System.out.println(outStream.toString());

		XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(outStream.toByteArray()));
		EvictionTimerImplMemento restoredMemento = (EvictionTimerImplMemento)decoder.readObject();

		EvictionTimerImpl restoredTimer = EvictionTimerImpl.create(restoredMemento);

		assertTrue( timer.equals(restoredTimer) );
	}
}


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Enable this package
    |--------------------------------------------------------------------------
    |
    | Define if this package should be enabled.
    | You can set this setting to false when for example building up the form
    | and testing the logic for your campaign, so that the crm is not spammed
    |
    */

    'enabled' => true,

    /*
    |--------------------------------------------------------------------------
    | Application Environment
    |--------------------------------------------------------------------------
    |
    | This value determines the "environment" your application is currently
    | running in. This may determine how you prefer to configure various
    | services your application utilizes. Set this in your ".env" file.
    |
    */

    'env' => env('APP_ENV', 'production'),

    /*
    |--------------------------------------------------------------------------
    | API Key
    |--------------------------------------------------------------------------
    |
    | The api key used to connect to the crm.
    |
    |
    |
    */

    'key' => env('MBR_API_KEY', null),

    /*
    |--------------------------------------------------------------------------
    | Campaign
    |--------------------------------------------------------------------------
    |
    | The id of the created campaign within the MBR CRM.
    |
    |
    |
    */

    'campaign' => 'your-campaign-id-here',

    /*
    |--------------------------------------------------------------------------
    | CRM endpoints
    |--------------------------------------------------------------------------
    |
    | An array containing a base url for each application environment.
    |
    |
    |
    */

    'endpoints' => [
        'dev' => 'http://endpoint.be/',
        'production' => 'https://endpointproduction.be/'
    ],

    /*
    |--------------------------------------------------------------------------
    | CRM fields
    |--------------------------------------------------------------------------
    |
    | An array that holds all the fields
    | that are available in the crm.
    |
    |
    */

    'fields' => [
        'salutation', 'first_name', 'last_name', 'primary_address_country', 'primary_address_postalcode',
        'primary_address_street', 'primary_address_city', 'primary_address_state', 'email1', 'phone_work',
        'dateofbirth_c', 'language_preferences_c', 'boss_motoring_interests_c', 'gender_c', 'lead_source',
        'twitter_username_c', 'facebook_username_c', 'bridgestone_pref_channel_c', 'first_opt_in',
        'third_party_pref_channel_c', 'third_party_opt_in_c', 'campaign_id',
    ],
];


text:
DATE=`date`
BUILD_HASH=`git log -n 1 | grep commit | cut -d " " -f 2`
VERSION="0.0" # `git describe --abbrev=0`

git --no-pager diff --exit-code "$VERSION" master > /dev/null 2>&1
PRE_RELEASE=$?

# TODO: Hash should not be added when building from a tagged version
#       but it looks like it currently does.  This can be fixed later.
if [ $PRE_RELEASE ]; then
  VERSION="$VERSION.$BUILD_HASH"
fi

CODE="// gen is a generated package, DO NOT EDIT!\n
\n
package gen\n
\n
var Version string = \"$VERSION\"\n
var BuildDate string = \"$DATE\"\n
var BuildHash string = \"$BUILD_HASH\"\n
"

TMP=`go-bindata -version`
if [ $? -ne 0 ]
then
  # go-bindata is required to embed assets into binary
  echo "Downloading go-bindata"
  go get -u github.com/jteeuwen/go-bindata/...
fi

# generate all the files we need
mkdir -p gen
go-bindata -pkg gen -ignore="/*.pyxel" -o gen/assets.go assets/
echo -e $CODE | gofmt > gen/build_info.go


text:
<?php

namespace Edge\Serializer;

use Zend\Paginator\Paginator;
use JMS\Serializer\Serializer as JMSSerializer;
use JMS\Serializer\SerializationContext;

class Serializer
{
    const FORMAT_ARRAY = 'array';
    const FORMAT_JSON  = 'json';

    protected $serializer;

    protected $serializeNull = true;

    public function __construct(JMSSerializer $serializer)
    {
        $this->serializer = $serializer;
    }

    /**
     * Serialize data to desired format
     *
     * @param object|array|scalar|Paginator $data
     * @param array|null $groups serialization groups
     * @param string $format serialization format
     * @param string $key root key for items, leave null to return items in root
     * @return mixed
     */
    public function serialize($data, array $groups = null, $format = self::FORMAT_ARRAY, $key = null)
    {
        if ($data instanceof Paginator) {
            $data = $this->paginatorToArray($data, $key);
        } elseif ($key !== null) {
            $data = array($key => $data);
        }

        if ($format == self::FORMAT_ARRAY) {
            return $this->getSerializer()->toArray($data, $this->createNewContext($groups));
        }

        return $this->getSerializer()->serialize($data, $format, $this->createNewContext($groups));
    }

    /**
     * Convert a paginator to array
     *
     * @param Paginator $paginator
     * @param string $key root key for items, leave null to return items in root
     * @return array
     */
    protected function paginatorToArray(Paginator $paginator, $key = null)
    {
        $items = iterator_to_array($paginator->getCurrentItems());

        if (null === $key) {
            return $items;
        }

        return array(
            'pages'   => $paginator->count(),
            'current' => $paginator->getCurrentPageNumber(),
            'count'   => $paginator->getTotalItemCount(),
            $key      => $items
        );
    }

    /**
     * Create a new serialization context
     *
     * @param array $groups [optional]
     * @return SerializationContext
     */
    protected function createNewContext(array $groups = null)
    {
        $context = new SerializationContext();
        $context->setSerializeNull($this->serializeNull);

        if (null !== $groups) {
            $context->setGroups($groups);
        }

        return $context;
    }

    public function setSerializeNull($bool)
    {
        $this->serializeNull = (boolean) $bool;
        return $this;
    }

    protected function getSerializer()
    {
        return $this->serializer;
    }
}


text:
fab target.regression -R main,service,checker,admin sysconf.install_server sysconf.configure_server
fab target.regression -R main,service,checker,admin app.service.install_elasticsearch
fab target.regression -R main,service,checker,admin app.service.start_elasticsearch
fab target.regression -R main,service,checker,admin app.service.deploy_sesame


text:
<title></title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/default.css" type="text/css"></link>

Class diagram

TODO / Markers

Errors

OpenCloud/DNS/Service.php

Classes |

Properties

author

copyright

package

version

Description
The Rackspace Cloud DNS service

Classes

Service

Properties

Extends

Implements

Abstract
No

Final
No

Description

This class defines a "service"—a relationship between a specific OpenStack
and a provided service, represented by a URL in the service catalog.
Because Service is an abstract class, it cannot be called directly. Provider
services such as Rackspace Cloud Servers or OpenStack Swift are each
subclassed from Service.

Methods

AsyncRequest,
      Domain,
      DomainList,
      Import,
      LimitTypes,
      Limits,
      PtrRecord,
      PtrRecordList,
      Request,
      SimpleRequest,
      __construct,

AsyncRequest(
          string

            $url,
          string

            $method
            = 'GET',
          array

            $headers
            = array(),
          string

            $body
            = null,

          )

        :
        \OpenCloud\DNS\DNS\AsyncResponse

Description

retrieves an asynchronous response
This method calls the provided `$url` and expects an asynchronous
response. It checks for various HTTP error codes and returns
an `AsyncResponse` object. This object can then be used to poll
for the status or to retrieve the final data as needed.

Arguments

Name
Type
Description
Default

$url
string

the URL of the request

$method
string

the HTTP method to use

'GET'

$headers
array

key/value pairs for headers to include

array()

$body
string

the body of the request (for PUT and POST)

null

Return value

Type
Description

\OpenCloud\DNS\DNS\AsyncResponse

Domain(
          mixed

            $info
            = null,

          )

        :
        \OpenCloud\DNS\DNS\Domain

Description

returns a DNS::Domain object

Arguments

Name
Type
Description
Default

$info
mixed

either the ID, an object, or array of parameters

null

Return value

Type
Description

\OpenCloud\DNS\DNS\Domain

Tags

Name
Description

api

DomainList(
          array

            $filter
            = array(),

          )

        :
        \OpenCloud\Collection

Description

returns a Collection of DNS::Domain objects

Arguments

Name
Type
Description
Default

$filter
array

key/value pairs to use as query strings

array()

Return value

Type
Description

\OpenCloud\Collection

Tags

Name
Description

api

Import(
          string

            $data,

          )

        :
        \OpenCloud\DNS\DNS\AsyncResponse

Description

imports domain records
Note that this function is called from the service (DNS) level, and
not (as you might suspect) from the Domain object. Because the function
return an AsyncResponse, the domain object will not actually exist
until some point after the import has occurred.

Arguments

Name
Type
Description
Default

$data
string

the BIND_9 formatted data to import

Return value

Type
Description

\OpenCloud\DNS\DNS\AsyncResponse

Tags

Name
Description

api

LimitTypes(

          )

        :
        array

Description

returns an array of limit types

Return value

Type
Description

array

Limits(

            $type
            = null,

          )

        :
        n/a

Description

returns a list of limits

Arguments

Name
Type
Description
Default

$type
n/a

null

Return value

Type
Description

n/a
n/a

PtrRecord(
          mixed

            $info
            = null,

          )

        :
        \OpenCloud\DNS\Record

Description

returns a PtrRecord object for a server

Arguments

Name
Type
Description
Default

$info
mixed

ID, array, or object containing record data

null

Return value

Type
Description

\OpenCloud\DNS\Record

PtrRecordList(
          \OpenCloud\Compute\Server

            $server,

          )

        :
        \OpenCloud\DNS\Collection

Description

returns a Collection of PTR records for a given Server

Arguments

Name
Type
Description
Default

$server
\OpenCloud\Compute\Server

the server for which to
     retrieve the PTR records

Return value

Type
Description

\OpenCloud\DNS\Collection

Request(
          string

            $url,
          string

            $method
            = 'GET',
          array

            $headers
            = array(),
          string

            $body
            = null,

          )

        :
        \OpenCloud\HttpResponse

Description

performs a HTTP request
This method overrides the request with JSON content type

Arguments

Name
Type
Description
Default

$url
string

the URL to target

$method
string

the HTTP method to use

'GET'

$headers
array

key/value pairs for headers to include

array()

$body
string

the body of the request (for PUT and POST)

null

Return value

Type
Description

\OpenCloud\HttpResponse

SimpleRequest(
          string

            $url,

          )

        :
        n/a

Description

performs a simple request and returns the JSON as an object

Arguments

Name
Type
Description
Default

$url
string

the URL to GET

Return value

Type
Description

n/a
n/a

__construct(

            $connection,
          string

            $serviceName,
          string

            $serviceRegion,
          string

            $urltype,

          )

        :
        n/a

Description

creates a new DNS object

Arguments

Name
Type
Description
Default

$connection
n/a

$serviceName
string

the name of the service

$serviceRegion
string

(not currently used; DNS is regionless)

$urltype
string

the type of URL

Return value

Type
Description

n/a
n/a

Documentation was generated by phpDocumentor 2.0.0b6
.

<input id="search_box"></input>

Namespaces

OpenCloud

OpenStack
The OpenStack class represents a relationship (or "connection")
between a user and a service.

Rackspace
Rackspace extends the OpenStack class with support for Rackspace's
API key and tenant requirements.

Autoscale

Service
The Autoscale class represents the OpenStack Heat service.

CloudMonitoring

Service
The Rackspace Cloud Monitoring service.

Exception

AgentException

AlarmException

CheckException

CloudMonitoringException

EntityException

MetricException

NotificationHistoryException

NotificationPlanException

ServiceException

TestException

ZoneException

Resource

AbstractResource
Abstract AbstractResource class.

Account
Account class.

Agent
Agent class.

AgentConnection
AgentConnection class.

AgentHost
Agent class.

AgentHostInfo
Agent class.

AgentTarget
Agent class.

AgentToken
Agent class.

Alarm
Alarm class.

Changelog
Changelog class.

Check
Check class.

CheckType
CheckType class.

Entity
Entity class.

Metric
Metric class.

Notification
Notification class.

NotificationHistory
NotificationHistory class.

NotificationPlan
Abstract AbstractResource class.

NotificationType
NotificationType class.

ReadonlyResource
ReadonlyResource class.

ResourceInterface
ResourceInterface interface.

View
View class.

Zone
Zone class.

Common

Base
The Base class is the root class for all other objects used or defined by
this SDK.

Collection
Provides an abstraction for working with ordered sets of objects

Debug

Lang

Metadata
The Metadata class represents either Server or Image metadata

Nova
Nova is an abstraction layer for the OpenStack compute service.

ObjectStore
Intermediate (abstract) class to implement shared
features of all object-storage classes

PersistentObject
represents an object that has the ability to be
retrieved, created, updated, and deleted.

Service
This class defines a "service"—a relationship between a specific OpenStack
and a provided service, represented by a URL in the service catalog.

ServiceCatalogItem
Holds information on a single service from the Service Catalog

Exceptions

AsyncError

AsyncHttpError

AsyncTimeoutError

AttributeError

AuthenticationError

BaseException

CdnError

CdnHttpError

CdnNotAvailableError

CdnTtlError

CollectionError

ContainerCreateError

ContainerDeleteError

ContainerError

ContainerNameError

ContainerNotEmptyError

ContainerNotFoundError

CreateError

CreateUpdateError

CredentialError

DatabaseCreateError

DatabaseDeleteError

DatabaseListError

DatabaseNameError

DatabaseUpdateError

DeleteError

DocumentError

DomainError

EmptyResponseError

EndpointError

FlavorError

HttpError

HttpForbiddenError

HttpOverLimitError

HttpRetryError

HttpTimeoutError

HttpUnauthorizedError

HttpUrlError

IOError

IdRequiredError

ImageError

InstanceCreateError

InstanceDeleteError

InstanceError

InstanceFlavorError

InstanceNotFound

InstanceUpdateError

InvalidArgumentError

InvalidIdTypeError

InvalidIpTypeError

InvalidParameterError

InvalidRequestError

JsonError

MetadataCreateError

MetadataDeleteError

MetadataError

MetadataJsonError

MetadataKeyError

MetadataPrefixError

MetadataUpdateError

MisMatchedChecksumError

MissingValueError

NameError

NetworkCreateError

NetworkDeleteError

NetworkError

NetworkUpdateError

NetworkUrlError

NoContentTypeError

NoNameError

ObjFetchError

ObjectCopyError

ObjectError

RebuildError

RecordTypeError

ServerActionError

ServerCreateError

ServerDeleteError

ServerIpsError

ServerJsonError

ServerUpdateError

ServerUrlError

ServiceValueError

SnapshotError

TempUrlMethodError

UnknownError

UnknownParameterError

UnrecognizedServiceError

UnsupportedExtensionError

UnsupportedFeatureExtension

UnsupportedVersionError

UpdateError

UrlError

UserCreateError

UserDeleteError

UserListError

UserNameError

UserUpdateError

VolumeError

VolumeTypeError

Request

Curl
The CurlRequest class is a simple wrapper to CURL functions. Not only does
this permit stubbing of the interface as described under the HttpRequest
interface, it could potentially allow us to replace the interface methods
with other function calls in the future.

HttpRequestInterface
The HttpRequest interface defines methods for wrapping CURL; this allows
those methods to be stubbed out for unit testing, thus allowing us to
test without actually making live calls.

Response

Blank
The HttpResponse returns an object with status information, separated
headers, and any response body necessary.

Http
The HttpResponse returns an object with status information, separated
headers, and any response body necessary.

Compute

Flavor
The Flavor class represents a flavor defined by the Compute service

Image
The Image class represents a stored machine image returned by the
Compute service.

Network
The Network class represents a single virtual network

Server
The Server class represents a single server node.

ServerMetadata
This class handles server metadata

Service
The Compute class represents the OpenStack Nova service.

VolumeAttachment
The VolumeAttachment class represents a volume that is attached
to a server.

DNS

AsyncResponse
The AsyncResponse class encapsulates the data returned by a Cloud DNS
asynchronous response.

Domain
The Domain class represents a single domain

Object
The DnsObject class is an extension of the PersistentObject class that
permits the asynchronous responses used by Cloud DNS

PtrRecord
PTR records are used for reverse DNS

Record
The Record class represents a single domain record

Service
This class defines a "service"—a relationship between a specific OpenStack
and a provided service, represented by a URL in the service catalog.

Subdomain
The Subdomain is basically another domain, albeit one that is a child of
a parent domain. In terms of the code involved, the JSON is slightly
different than a top-level domain, and the parent is a domain instead of
the DNS service itself.

Database

Database
This class represents a Database in the Rackspace "Red Dwarf"
database-as-a-service product.

Instance
Instance represents an instance of DbService, similar to a Server in a
Compute service

Service
The Rackspace Database As A Service (aka "Red Dwarf")

User
This class represents a User in the Rackspace "Red Dwarf"
database-as-a-service product.

LoadBalancer

Algorithm
sub-resource to manage algorithms (read-only)

AllowedDomain
sub-resource to manage allowed domains

BillableLoadBalancer
used to get a list of billable load balancers for a specific date range

LoadBalancer
The LoadBalancer class represents a single load balancer

Protocol
sub-resource to manage protocols (read-only)

Service
The Rackspace Cloud Load Balancers

Resources

Access
sub-resource to manage access lists

ConnectionLogging
sub-resource to manage connection logging

ConnectionThrottle
sub-resource to manage connection throttling

ContentCaching
sub-resource to manage content caching

ErrorPage
The /loadbalancer/{id}/errorpage manages the error page for the load
balancer.

HealthMonitor
sub-resource to manage health monitor info

Metadata
sub-resource to manage Metadata

Node
information on a single node in the load balancer

NodeEvent
a single node event, usually called as part of a Collection

Readonly
This defines a read-only SubResource - one that cannot be created, updated,
or deleted. Many subresources are like this, and this simplifies their
class definitions.

SSLTermination
sub-resource to manage SSL termination

SessionPersistence
sub-resource to manage session persistence setting

Stats
Stats returns statistics about the load balancer

SubResource
SubResource is an abstract class that handles subresources of a
LoadBalancer object; for example, the
`/loadbalancers/{id}/errorpage`. Since most of the subresources are
handled in a similar manner, this consolidates the functions.

Usage
used to get usage data for a load balancer

VirtualIp
VirtualIp represents a single virtual IP (usually returned in a Collection)

ObjectStore

CDNContainer
A simple container for the CDN Service

Container
A regular container with a (potentially) CDN container

DataObject
A DataObject is an object in the ObjectStore

ObjectStoreBase
A base class for common code shared between the ObjectStore and
ObjectStoreCDN
objects

ObjectStoreCDN
This is the CDN related to the ObjectStore

Service
ObjectStore - this defines the object-store (Cloud Files) service.

Orchestration

Resource

Service
The Orchestration class represents the OpenStack Heat service.

Stack
The Stack class requires a CloudFormation template and may contain additional
parameters for that template.

Volume

Service
Nova is an abstraction layer for the OpenStack compute service.

Snapshot
The Snapshot class represents a single block storage snapshot

Volume
The Volume class represents a single block storage volume

VolumeType
The VolumeType class represents a single block storage volume type

global

Packages

Default

AbstractResource
Abstract AbstractResource class.

Access
sub-resource to manage access lists

Account
Account class.

Agent
Agent class.

AgentConnection
AgentConnection class.

AgentException

AgentHost
Agent class.

AgentHostInfo
Agent class.

AgentTarget
Agent class.

AgentToken
Agent class.

Alarm
Alarm class.

AlarmException

Algorithm
sub-resource to manage algorithms (read-only)

AllowedDomain
sub-resource to manage allowed domains

AsyncError

AsyncHttpError

AsyncResponse
The AsyncResponse class encapsulates the data returned by a Cloud DNS
asynchronous response.

AsyncTimeoutError

AttributeError

AuthenticationError

Base
The Base class is the root class for all other objects used or defined by
this SDK.

BaseException

BillableLoadBalancer
used to get a list of billable load balancers for a specific date range

Blank
The HttpResponse returns an object with status information, separated
headers, and any response body necessary.

CDNContainer
A simple container for the CDN Service

CdnError

CdnHttpError

CdnNotAvailableError

CdnTtlError

Changelog
Changelog class.

Check
Check class.

CheckException

CheckType
CheckType class.

ClassLoader

CloudMonitoringException

Collection
Provides an abstraction for working with ordered sets of objects

CollectionError

ConnectionLogging
sub-resource to manage connection logging

ConnectionThrottle
sub-resource to manage connection throttling

Container
A regular container with a (potentially) CDN container

ContainerCreateError

ContainerDeleteError

ContainerError

ContainerNameError

ContainerNotEmptyError

ContainerNotFoundError

ContentCaching
sub-resource to manage content caching

CreateError

CreateUpdateError

CredentialError

Curl
The CurlRequest class is a simple wrapper to CURL functions. Not only does
this permit stubbing of the interface as described under the HttpRequest
interface, it could potentially allow us to replace the interface methods
with other function calls in the future.

DataObject
A DataObject is an object in the ObjectStore

Database
This class represents a Database in the Rackspace "Red Dwarf"
database-as-a-service product.

DatabaseCreateError

DatabaseDeleteError

DatabaseListError

DatabaseNameError

DatabaseUpdateError

Debug

DeleteError

DocumentError

Domain
The Domain class represents a single domain

DomainError

EmptyResponseError

EndpointError

Entity
Entity class.

EntityException

ErrorPage
The /loadbalancer/{id}/errorpage manages the error page for the load
balancer.

Flavor
The Flavor class represents a flavor defined by the Compute service

FlavorError

HealthMonitor
sub-resource to manage health monitor info

Http
The HttpResponse returns an object with status information, separated
headers, and any response body necessary.

HttpError

HttpForbiddenError

HttpOverLimitError

HttpRequestInterface
The HttpRequest interface defines methods for wrapping CURL; this allows
those methods to be stubbed out for unit testing, thus allowing us to
test without actually making live calls.

HttpRetryError

HttpTimeoutError

HttpUnauthorizedError

HttpUrlError

IOError

IdRequiredError

Image
The Image class represents a stored machine image returned by the
Compute service.

ImageError

Instance
Instance represents an instance of DbService, similar to a Server in a
Compute service

InstanceCreateError

InstanceDeleteError

InstanceError

InstanceFlavorError

InstanceNotFound

InstanceUpdateError

InvalidArgumentError

InvalidIdTypeError

InvalidIpTypeError

InvalidParameterError

InvalidRequestError

JsonError

Lang

LoadBalancer
The LoadBalancer class represents a single load balancer

Metadata
The Metadata class represents either Server or Image metadata

Metadata
sub-resource to manage Metadata

MetadataCreateError

MetadataDeleteError

MetadataError

MetadataJsonError

MetadataKeyError

MetadataPrefixError

MetadataUpdateError

Metric
Metric class.

MetricException

MisMatchedChecksumError

MissingValueError

NameError

Network
The Network class represents a single virtual network

NetworkCreateError

NetworkDeleteError

NetworkError

NetworkUpdateError

NetworkUrlError

NoContentTypeError

NoNameError

Node
information on a single node in the load balancer

NodeEvent
a single node event, usually called as part of a Collection

Notification
Notification class.

NotificationHistory
NotificationHistory class.

NotificationHistoryException

NotificationPlan
Abstract AbstractResource class.

NotificationPlanException

NotificationType
NotificationType class.

Nova
Nova is an abstraction layer for the OpenStack compute service.

ObjFetchError

Object
The DnsObject class is an extension of the PersistentObject class that
permits the asynchronous responses used by Cloud DNS

ObjectCopyError

ObjectError

ObjectStore
Intermediate (abstract) class to implement shared
features of all object-storage classes

ObjectStoreBase
A base class for common code shared between the ObjectStore and
ObjectStoreCDN
objects

ObjectStoreCDN
This is the CDN related to the ObjectStore

OpenStack
The OpenStack class represents a relationship (or "connection")
between a user and a service.

PersistentObject
represents an object that has the ability to be
retrieved, created, updated, and deleted.

Protocol
sub-resource to manage protocols (read-only)

PtrRecord
PTR records are used for reverse DNS

Rackspace
Rackspace extends the OpenStack class with support for Rackspace's
API key and tenant requirements.

Readonly
This defines a read-only SubResource - one that cannot be created, updated,
or deleted. Many subresources are like this, and this simplifies their
class definitions.

ReadonlyResource
ReadonlyResource class.

RebuildError

Record
The Record class represents a single domain record

RecordTypeError

Resource

ResourceInterface
ResourceInterface interface.

SSLTermination
sub-resource to manage SSL termination

Server
The Server class represents a single server node.

ServerActionError

ServerCreateError

ServerDeleteError

ServerIpsError

ServerJsonError

ServerMetadata
This class handles server metadata

ServerUpdateError

ServerUrlError

Service
The Autoscale class represents the OpenStack Heat service.

Service
The Rackspace Cloud Monitoring service.

Service
This class defines a "service"—a relationship between a specific OpenStack
and a provided service, represented by a URL in the service catalog.

Service
The Compute class represents the OpenStack Nova service.

Service
The Rackspace Database As A Service (aka "Red Dwarf")

Service
This class defines a "service"—a relationship between a specific OpenStack
and a provided service, represented by a URL in the service catalog.

Service
The Rackspace Cloud Load Balancers

Service
ObjectStore - this defines the object-store (Cloud Files) service.

Service
The Orchestration class represents the OpenStack Heat service.

Service
Nova is an abstraction layer for the OpenStack compute service.

ServiceCatalogItem
Holds information on a single service from the Service Catalog

ServiceException

ServiceValueError

SessionPersistence
sub-resource to manage session persistence setting

Snapshot
The Snapshot class represents a single block storage snapshot

SnapshotError

Stack
The Stack class requires a CloudFormation template and may contain additional
parameters for that template.

Stats
Stats returns statistics about the load balancer

SubResource
SubResource is an abstract class that handles subresources of a
LoadBalancer object; for example, the
`/loadbalancers/{id}/errorpage`. Since most of the subresources are
handled in a similar manner, this consolidates the functions.

Subdomain
The Subdomain is basically another domain, albeit one that is a child of
a parent domain. In terms of the code involved, the JSON is slightly
different than a top-level domain, and the parent is a domain instead of
the DNS service itself.

TempUrlMethodError

TestException

UnknownError

UnknownParameterError

UnrecognizedServiceError

UnsupportedExtensionError

UnsupportedFeatureExtension

UnsupportedVersionError

UpdateError

UrlError

Usage
used to get usage data for a load balancer

User
This class represents a User in the Rackspace "Red Dwarf"
database-as-a-service product.

UserCreateError

UserDeleteError

UserListError

UserNameError

UserUpdateError

View
View class.

VirtualIp
VirtualIp represents a single virtual IP (usually returned in a Collection)

Volume
The Volume class represents a single block storage volume

VolumeAttachment
The VolumeAttachment class represents a volume that is attached
to a server.

VolumeError

VolumeType
The VolumeType class represents a single block storage volume type

VolumeTypeError

Zone
Zone class.

ZoneException

global

phpOpenCloud

AbstractResource
Abstract AbstractResource class.

Service
The Rackspace Cloud Monitoring service.


text:
package com.amazonaws.services.route53.model;

import javax.annotation.Generated;

/**
 * <p>
 * This error code is not in use.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class HealthCheckInUseException extends com.amazonaws.services.route53.model.AmazonRoute53Exception {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new HealthCheckInUseException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public HealthCheckInUseException(String message) {
        super(message);
    }

}


text:
using System;
using System.Text;

public class Worker : Human
{
    private double weekSalary;
    private double hoursPerDay;
    private string lastName;

    public Worker(string firstName, string lastName, double weekSalary, double hoursPerDay)
        : base(firstName, lastName)
    {
        this.WeekSalary = weekSalary;
        this.HoursPerDay = hoursPerDay;
        this.LastName = lastName;
    }

    public double HoursPerDay
    {
        get { return hoursPerDay; }

        set
        {
            if (value < 1 || value > 12)
            {
                throw new ArgumentException($"Expected value mismatch! Argument: workHoursPerDay");
            }
            hoursPerDay = value;
        }
    }

    public double WeekSalary
    {
        get { return weekSalary; }

        set
        {
            if (value <= 10)
            {
                throw new ArgumentException($"Expected value mismatch! Argument: weekSalary");
            }
            weekSalary = value;
        }
    }

    public override string LastName
    {
        get { return lastName; }

        set
        {
            if (value.Length <= 3) // may be if the above is true and this one is true should show 2 Exceptions???
            {
                throw new ArgumentException($"Expected length at least 3 symbols! Argument: lastName");
            }
            lastName = value;
        }
    }

    public override string ToString()
    {
        var sb = new StringBuilder();
        sb.AppendLine($"First Name: {FirstName}");
        sb.AppendLine($"Last Name: {lastName}");
        sb.AppendLine($"Week Salary: {weekSalary:0.00}");
        sb.AppendLine($"Hours per day: {hoursPerDay:0.00}");
        sb.AppendLine($"Salary per hour: {(weekSalary / 5) / hoursPerDay:0.00}");

        return sb.ToString();
    }
}


text:
package com.github.dannil.scbjavaclient.utility;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;

/**
 *
Class which is responsible for constructing the query which should be sent to the
 * API.

 *
 * @since 0.0.1
 */
public final class QueryBuilder {

    private static final int APPROXIMATE_OFFSET_CHARS = 44;

    private static final int APPROXIMATE_ENTRY_CHARS = 80;

    /**
     *
Private constructor to prevent instantiation.

     */
    private QueryBuilder() {

    }

    /**
     *
Filter out the specified value from the input map, including both keys and their
     * respective values. The filtering is done in-place on the input map.

     *
     * @param inputMap
     *            the Map to filter
     * @param value
     *            the value to remove from the Map
     */
    private static void filterMap(Map<String, Collection<?>> inputMap, Object value) {
        Iterator<Entry<String, Collection<?>>> it = inputMap.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, Collection<?>> entry = it.next();
            if (entry.getKey() == null || entry.getValue() == null || entry.getValue().isEmpty()) {
                it.remove();
            } else {
                filterValue(entry.getValue(), value);
                if (entry.getValue().isEmpty()) {
                    it.remove();
                }
            }
        }
    }

    /**
     *
Filter out the specified value from the input collection. The filtering is done
     * in-place on the input collection.

     *
     * @param collection
     *            the Collection to filter
     * @param value
     *            the value to remove from the Collection
     */
    private static void filterValue(Collection<?> collection, Object value) {
        Iterator<?> it = collection.iterator();
        while (it.hasNext()) {
            if (Objects.equals(value, it.next())) {
                it.remove();
            }
        }
    }

    /**
     *
Constructs a query which matches the format the API expects. This method
     * performs two distinct steps:

     *
     *
1. Filter out the null keys and values

     *
     *
If a key (such as region or year) is defined and it's value is either defined as
     * null or as an empty list, it means that all data for this key should be fetched
     * (such as fetching the data for all available years). By not sending this key at all
     * to the API it recognizes that it should respond with all data corresponding to this
     * key.

     *
     *
2. Construct the query

     *
     *
For every key in the input map, it creates an entry for this key. It then writes
     * all of the values corresponding with this key (defined somewhere by using the
     * put-method on the input map) into this entry. For example, if the input for the key
     * Tid (Swedish for year) contains the years (values) 2011 and 2012, the resulting
     * entry looks like this:

     *
     *
{ "code": "Tid", "selection": { "filter": "item", "values": [ "2011", "2012" ] }
     * }

     *
     *
The method works on the principle of pasting all these blocks together in an
     * orderly fashion to conform to the API specification.

     *
     * @param inputMap
     *            the input map which contains the keys and the values for every key
     * @return a string which can be sent as the payload to the API
     */
    public static String build(Map<String, Collection<?>> inputMap) {
        // 1: Filter out null values
        filterMap(inputMap, null);

        // Approximate a good initial capacity for the string builder
        int size = APPROXIMATE_OFFSET_CHARS + (APPROXIMATE_ENTRY_CHARS * inputMap.size());
        StringBuilder builder = new StringBuilder(size);

        // 2: Construct the query
        builder.append("{\"query\": [");
        for (Iterator<Entry<String, Collection<?>>> entries = inputMap.entrySet().iterator(); entries.hasNext();) {
            Entry<String, Collection<?>> entry = entries.next();
            builder.append("{\"code\": \"");
            builder.append(entry.getKey());
            builder.append("\", \"selection\": {\"filter\": \"item\", \"values\": [");
            for (Iterator<?> values = entry.getValue().iterator(); values.hasNext();) {
                builder.append("\"" + values.next() + "\"");
                if (values.hasNext()) {
                    builder.append(',');
                }
            }
            builder.append("]}}");
            if (entries.hasNext()) {
                builder.append(',');
            }
        }
        builder.append("],\"response\": {\"format\": \"json\"}}");

        return builder.toString();
    }

}


text:
sidebar_position: 1
---

# Quick Start

:::info Requirements
- PHP **7.1**
- [MongoDB Driver](http://php.net/manual/en/set.mongodb.php)
:::

## Installation

You can install library through Composer:

```shell title="command"
composer require leroy-merlin-br/mongolid
```

## Setup

If you are not using Laravel, you should initialize the Mongolid connection and container manually.
The minimalistic way of doing it is to use `Mongolid\Connection\Manager`:

```php title="config"
require 'vendor/autoload.php';

use Mongolid\Connection\Manager;
use Mongolid\Connection\Connection;

$manager = new Manager();
$manager->setConnection(new Connection('mongodb://localhost:27017'));
```

Now you are ready to create your own models :smile:

## Basic usage

```php title="Post.php"
class Post extends \Mongolid\Model\AbstractModel
{
}
```

Note that we did not tell Mongolid which collection to use for our `Post` model. So, in this case, Mongolid **will not save the model into the database**.
This can be used for models that represents objects that will be embedded within another object and will not have their own collection.

You may specify a collection by defining a `collection` property on your model:

```php title="Post.php"
class Post extends \Mongolid\Model\AbstractModel {

    protected $collection = 'posts';

}
```

Mongolid will also assume each collection has a primary key attribute named `_id`, since MongoDB requires an `_id` for every single document.
The `_id` attribute can be of any type. The default type for this attribute is `ObjectId`.
[Learn more about the MongoId](https://docs.mongodb.org/manual/reference/method/ObjectId/).

:::info
Mongolid will automatically convert strings in ObjectId format (For example: "4af9f23d8ead0e1d32000000")
to `ObjectId` when querying or saving an object.
:::

Once a model is defined, you are ready to start retrieving and creating documents in your collection.

```php title="Retrieving all models"
    $posts = Post::all();
```

```php title="Retrieving a document by primary key"
    $post = Post::first('4af9f23d8ead0e1d32000000');

    // or

    $post = Post::first(new MongoDB\BSON\ObjectID('4af9f23d8ead0e1d32000000'));
```

```php title="Retrieving a document by attribute"
    $post = Post::first(['title' => 'How Mongolid saved the day']);
```

```php title="Retrieving many documents by attribute"
    $posts = Post::where(['category' => 'coding']); // where() method returns a MongolidCursor
```

```php title="Querying using mongolid models"
    $posts = Post::where(['votes' => ['$gt' => 100]])->limit(10); // Mongolid\Cursor\Cursor

    foreach ($posts as $post) {
        var_dump($post->title);
    }
```

```php title="Mongolid count"
    $count = Post::where(['votes' => ['$gt' => 100]])->count(); // int
```

---

***Pretty easy right?***