text:
module Distribution.Server.Pages.Template
    ( hackagePage
    , hackagePageWith
    , hackagePageWithHead
    ) where

import Text.XHtml.Strict

--TODO: replace all this with external templates

-- | Create top-level HTML document by wrapping the Html with boilerplate.
hackagePage :: String -> [Html] -> Html
hackagePage = hackagePageWithHead []

hackagePageWithHead :: [Html] -> String -> [Html] -> Html
hackagePageWithHead headExtra docTitle docContent =
    hackagePageWith headExtra docTitle docSubtitle docContent bodyExtra
  where
    docSubtitle = anchor ! [href introductionURL] << "Hackage :: [Package]"
    bodyExtra   = []

hackagePageWith :: [Html] -> String -> Html -> [Html] -> [Html] -> Html
hackagePageWith headExtra docTitle docSubtitle docContent bodyExtra =
    toHtml [ header << (docHead ++ headExtra)
           , body   << (docBody ++ bodyExtra) ]
  where
    docHead   = [ thetitle << (docTitle ++ " | Hackage")
                , thelink ! [ rel "stylesheet"
                            , href stylesheetURL
                            , thetype "text/css"] << noHtml
                -- if Search is enabled
                , thelink ! [ rel "search", href "/packages/opensearch.xml"
                            , thetype "application/opensearchdescription+xml"
                            , title "Hackage" ] << noHtml
                ]
    docBody   = [ thediv ! [identifier "page-header"] << docHeader
                , thediv ! [identifier "content"] << docContent ]
    docHeader = [ navigationBar
                , paragraph ! [theclass "caption"] << docSubtitle ]

navigationBar :: Html
navigationBar =
    ulist ! [theclass "links", identifier "page-menu"]
      <<  map (li <<)
          [ anchor ! [href introductionURL] << "Home"
          , form   ! [action "/packages/search", theclass "search", method "get"]
                  << [ button ! [thetype "submit"] << "Search", spaceHtml
                     , input  ! [thetype "text", name "terms" ] ]
          , anchor ! [href pkgListURL] << "Browse"
          , anchor ! [href recentAdditionsURL] << "What's new"
          , anchor ! [href uploadURL]   << "Upload"
          , anchor ! [href accountsURL] << "User accounts"
          ]

stylesheetURL :: URL
stylesheetURL = "/static/hackage.css"

-- URL of the package list
pkgListURL :: URL
pkgListURL = "/packages/"

-- URL of the upload form
introductionURL :: URL
introductionURL = "/"

-- URL of the upload form
uploadURL :: URL
uploadURL = "/upload"

-- URL about user accounts, including the form to change passwords
accountsURL :: URL
accountsURL = "/accounts"

-- URL of the admin front end
adminURL :: URL
adminURL = "/admin"

-- URL of the list of recent additions to the database
recentAdditionsURL :: URL
recentAdditionsURL = "/packages/recent"


text:
Validation
==========

.. currentmodule:: graphql.validation

.. automodule:: graphql.validation
   :no-members:
   :no-inherited-members:

.. autofunction:: validate

.. autoclass:: ASTValidationContext

.. autoclass:: ASTValidationRule

.. autoclass:: SDLValidationContext

.. autoclass:: SDLValidationRule

.. autoclass:: ValidationContext

.. autoclass:: ValidationRule

Rules
-----

.. module:: graphql.validation.rules
.. currentmodule:: graphql.validation

.. data:: specified_rules

   A tuple with all validation rules defined by the GraphQL specification

**Spec Section: "Executable Definitions"**

.. autoclass:: ExecutableDefinitionsRule

**Spec Section: "Field Selections on Objects, Interfaces, and Unions Types"**

.. autoclass:: FieldsOnCorrectTypeRule

**Spec Section: "Fragments on Composite Types"**

.. autoclass:: FragmentsOnCompositeTypesRule

**Spec Section: "Argument Names"**

.. autoclass:: KnownArgumentNamesRule

**Spec Section: "Directives Are Defined"**

.. autoclass:: KnownDirectivesRule

**Spec Section: "Fragment spread target defined"**

.. autoclass:: KnownFragmentNamesRule

**Spec Section: "Fragment Spread Type Existence"**

.. autoclass:: KnownTypeNamesRule

**Spec Section: "Lone Anonymous Operation"**

.. autoclass:: LoneAnonymousOperationRule

**Spec Section: "Fragments must not form cycles"**

.. autoclass:: NoFragmentCyclesRule

**Spec Section: "All Variable Used Defined"**

.. autoclass:: NoUndefinedVariablesRule

**Spec Section: "Fragments must be used"**

.. autoclass:: NoUnusedFragmentsRule

**Spec Section: "All Variables Used"**

.. autoclass:: NoUnusedVariablesRule

**Spec Section: "Field Selection Merging"**

.. autoclass:: OverlappingFieldsCanBeMergedRule

**Spec Section: "Fragment spread is possible"**

.. autoclass:: PossibleFragmentSpreadsRule

**Spec Section: "Argument Optionality"**

.. autoclass:: ProvidedRequiredArgumentsRule

**Spec Section: "Leaf Field Selections"**

.. autoclass:: ScalarLeafsRule

**Spec Section: "Subscriptions with Single Root Field"**

.. autoclass:: SingleFieldSubscriptionsRule

**Spec Section: "Argument Uniqueness"**

.. autoclass:: UniqueArgumentNamesRule

**Spec Section: "Directives Are Unique Per Location"**

.. autoclass:: UniqueDirectivesPerLocationRule

**Spec Section: "Fragment Name Uniqueness"**

.. autoclass:: UniqueFragmentNamesRule

**Spec Section: "Input Object Field Uniqueness"**

.. autoclass:: UniqueInputFieldNamesRule

**Spec Section: "Operation Name Uniqueness"**

.. autoclass:: UniqueOperationNamesRule

**Spec Section: "Variable Uniqueness"**

.. autoclass:: UniqueVariableNamesRule

**Spec Section: "Value Type Correctness"**

.. autoclass:: ValuesOfCorrectTypeRule

**Spec Section: "Variables are Input Types"**

.. autoclass:: VariablesAreInputTypesRule

**Spec Section: "All Variable Usages Are Allowed"**

.. autoclass:: VariablesInAllowedPositionRule

**SDL-specific validation rules**

.. autoclass:: LoneSchemaDefinitionRule
.. autoclass:: UniqueOperationTypesRule
.. autoclass:: UniqueTypeNamesRule
.. autoclass:: UniqueEnumValueNamesRule
.. autoclass:: UniqueFieldDefinitionNamesRule
.. autoclass:: UniqueArgumentDefinitionNamesRule
.. autoclass:: UniqueDirectiveNamesRule
.. autoclass:: PossibleTypeExtensionsRule

redpajama_set_name: RedPajamaGithub


text:
/*
 * (C) 2007-2010 Alibaba Group Holding Limited.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 */
package com.taobao.common.tfs.exception;

import com.taobao.common.tfs.etc.TfsUtil;
import com.taobao.common.tfs.packet.StatusMessage;

public class ErrorStatusException extends ConnectionException {
    private static final long serialVersionUID = -5798332922782946065L;
    private StatusMessage packet;

    public ErrorStatusException(long server, StatusMessage packet) {
        super(server);
        this.packet = packet;
    }

    public int getStatus() {
        if (this.packet != null) {
            return packet.getStatus();
        }
        return StatusMessage.STATUS_MESSAGE_ERROR;
    }

    @Override
    public String getMessage() {
        if (this.packet != null)
            return "receive wrong status message, code:[" + packet.getStatus() + "] from "
                + TfsUtil.idToAddress(getServer()).toString() + ",errmsg:" + packet.getError();
        return "receive wrong packet null from "
            + TfsUtil.idToAddress(getServer()).toString();
    }

}


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

describe Ohai::System, "Solaris plugin platform" do
  before(:each) do
    @ohai = Ohai::System.new
    @ohai.extend(SimpleFromFile)
    @ohai.stub!(:require_plugin).and_return(true)
    @ohai[:os] = "solaris2"
    @ohai.stub!(:popen4).with("/sbin/uname -X")
  end

  describe "on SmartOS" do
    before(:each) do
      @stdin = mock("STDIN", { :close => true })
      @pid = 10
      @stderr = mock("STDERR")
      @stdout = mock("STDOUT")
      @status = 0
      @stdout.stub!(:each).
        and_yield("System = SunOS").
        and_yield("Node = node.example.com").
        and_yield("Release = 5.11").
        and_yield("KernelID = joyent_20120130T201844Z").
        and_yield("Machine = i86pc").
        and_yield("BusType = <unknown>").
        and_yield("Serial = <unknown>").
        and_yield("Users = <unknown>").
        and_yield("OEM# = 0").
        and_yield("Origin# = 1").
        and_yield("NumCPU = 16")
      File.stub!(:exists?).with("/sbin/uname").and_return(true)
      @ohai.stub(:popen4).with("/sbin/uname -X").and_yield(@pid, @stdin, @stdout, @stderr).and_return(@status)

      @release = StringIO.new("  SmartOS 20120130T201844Z x86_64\n")
      @mock_file.stub!(:close).and_return(0)
      File.stub!(:open).with("/etc/release").and_yield(@release)
    end

    it "should run uname and set platform and build" do
      @ohai._require_plugin("solaris2::platform")
      @ohai[:platform_build].should == "joyent_20120130T201844Z"
    end

    it "should set the platform" do
      @ohai._require_plugin("solaris2::platform")
      @ohai[:platform].should == "smartos"
    end

    it "should set the platform_version" do
      @ohai._require_plugin("solaris2::platform")
      @ohai[:platform_version].should == "5.11"
    end

  end

end


text:
"""
Python twisted server, implements an HTTP socket-server and command queue to
execute python commands, parse XTSM, and manage data in user-specific contexts.

Created on Thu May 16 18:24:40 2013

This software is described at
https://amo.phys.psu.edu/GemelkeLabWiki/index.php/Python_server

TODO:
    permit standard command library calls with POST payloads on websocket
    connections (for faster exchanges on standard calls) ?
    is this done and working ?
    redirect stdio to console
    execute command queue items on schedule
    queue in databomb upkeep (links and storage)

@author: Nate, Jed
"""

import uuid
import time
import sys
from datetime import datetime
from datetime import date
import pdb
import colorama
colorama.init(strip=False)

import msgpack
import msgpack_numpy

import simplejson
import XTSMobjectify
import DataBomb
import InfiniteFileStream
msgpack_numpy.patch()#This patch actually changes the behavior of "msgpack"
#specifically, it changes how, "encoding='utf-8'" functions when unpacking
import XTSM_Server_Objects
import file_locations

import numpy
from enthought.traits.api import HasTraits
from enthought.traits.api import Int as TraitedInt
from enthought.traits.api import Str as TraitedStr

import collections
DEBUG = True

NUM_RETAINED_XTSM=10

#port = 8083
#wsport = 8084
#udpbport = 8085

class Experiment_Sync_Group(HasTraits):
    """
    A class to hold experiment sychronization data - this is the core
    organizational element, holding the current shotnumber, the active_xtsm
    generator, and the last several compiled xtsm objects ()
    """
    active_xtsm = TraitedStr('<XTSM></XTSM>')
    last_successful_xtsm = TraitedStr('<XTSM></XTSM>')
    shotnumber = TraitedInt(0)
    # note: last element is compiled_xtsm, defined by class below
    def __init__(self,server, data_context_name):
        if DEBUG: print "class Experiment_Sync_Group, func __init__"
        self.server=server
        self.data_context_name = data_context_name
    def _active_xtsm_changed(self, old, new):
        pass
        #if DEBUG: print "class Experiment_Sync_Group, func _active_xtsm_changed"
        #msg = {"active_xtsm_post":str(new),"data_context":self.data_context_name}
        #json = simplejson.dumps(msg, ensure_ascii = False).encode('utf8')
        #self.server.broadcast(json)
    def _shotnumber_changed(self, old, new):
        pass
        #if DEBUG: print "class Experiment_Sync_Group, func _shotnumber_changed"
        #msg = {"shotnumber":str(new),"data_context":self.data_context_name}
        #json = simplejson.dumps(msg, ensure_ascii = False).encode('utf8')
    def __flush__(self):
        if DEBUG: print "class Experiment_Sync_Group, func __flush__"
        lsx=open(file_locations.file_locations['last_xtsm'][uuid.getnode()]+"last_xtsm.xtsm","w")
        lsx.write(self.last_successful_xtsm)
        lsx.close()
        self.compiled_xtsm.flush()
        self.compiled_xtsm.filestream.__flush__()
    def __getstate__(self):
        if DEBUG: print "class Experiment_Sync_Group, func __getstate__"

    class XTSM_stack(collections.OrderedDict):
        """
        A class to hold a stack of compiled XTSM objects and manage their
        storage and retrieval - for simplicity we subclass the orderedDict class
        in collections.  This is extended with an infinite filestream, into which
        the oldest xtsm objects are serialized for storage in this messagepack
        format as shotnumber:xtsm entries.
        """
        filestream = InfiniteFileStream.Filestream({"file_root_selector":"xtsm_feed"})
        packer = msgpack.Packer()
        def __init__(self):
            collections.OrderedDict.__init__(self)
            self.archived={}
            self.timeadded={}
        def __del__(self):
            self.flush()
        def __getstate__(self):
            print 'andhere'

        def update(self,*args,**kwds):
            """
            inserts another element - should be shotnumber:xtsm pair
            """
            collections.OrderedDict.update(self,*args,**kwds)
            for elm in args:
                self.archived.update({elm.keys()[0]:False})
            for elm in args:
                self.timeadded.update({elm.keys()[0]:time.time()})
            while len(self)>NUM_RETAINED_XTSM:
                self.heave()
            #pdb.set_trace()

        def archive(self):
            """
            checks if any elements are currently archivable, and archives them
            if any have not yet been archived, and are active
            but exceed the archive_timeout, they are forced deactive and archived.

            """
            #pdb.set_trace() #Check to see if "self has elm" in it.
            for elm in self:
                if not self[elm].isActive():
                    self._archive_elm(elm)
                    continue
                if (time.time()-self.timeadded[elm]) > self.archive_timeout:
                    self._archive_elm(elm)
                    self[elm].deactivate(params={"message":"This element was deactivated when timed out from XTSM_Stack"})
                    continue

        def _archive_elm(self,elm):
            """
            stores an element to disk in the infinite filestream - does not check
            if element is active - that is duty of caller
            """
            if type(elm)==type(0):
                elm=(elm,self[elm])
            self._write_out(elm)
            self.archived[elm[0]] = True

        def _write_out(self,elm):
            """
            stores an element to disk in the infinite filestream
            """
            sn = None
            try:
                sn = elm[1].XTSM.getItemByFieldValue("Parameter","Name","shotnumber").Value.PCDATA
            except:
                pdb.set_trace()
                pass
            self.filestream.write_file(self.packer.pack({elm[0]:elm[1].XTSM.write_xml()}),
                                       comments='',
                                       prefix=str('XTSM_SN'+str(sn))+'_',
                                         extension='.txt')

        def heave(self):
            """
            removes the oldest element from the stack (FIFO-style), archiving
            it if it has not already been - in this case, the element is removed
            even if it has active listeners; they are removed too, to avoid memory leaks.
            """
            heavethis = self.popitem(last=False)
            if heavethis[1].isActive():
                heavethis[1].deactivate(params={"message":"This element was deactivated when heaved from XTSM_Stack"})
            if not self.archived[heavethis[0]]:
                self._write_out(heavethis)

        def flush(self):
            """
            heaves all elements from stack, saving to disk if necessary
            """
            while len(self)>0:
                self.heave()

    compiled_xtsm = XTSM_stack()

class DataContext(XTSM_Server_Objects.XTSM_Server_Object):
    """
    A dataContext object stores variable definitions for a Python session
    in a sheltered scope, roughly one for each user, such that independent
    data analysis and experiment control sessions can be run without interferences

    .dict contains dictionary of variables and values
    """
    def __init__(self, name, server):
        if DEBUG: print "class DataContext, function __init__", 'name:', name
        self.dict = {"__context__":name}
        self.name = name
        self.server = server
        #Create DataBombCatcher
        d = DataBomb.DataBombCatcher(params={"server":self.server})
        self.dict.update({'_bombstack':d})
        #Create DataBombDispatcher
        d = DataBomb.DataBombDispatcher(params={"server":self.server})
        self.dict.update({'databomb_dispatcher':d})
        #Create DataListenerManager
        d = DataBomb.DataListenerManager()
        self.dict.update({'data_listener_manager':d})

    def _close(self):
        pass

    def update(self,data):
        """
        updates a variable or variables according to a dictionary of new values
        """
        self.dict.update(data)
    def get(self,variablename):
        return self.dict[variablename]
    def __getitem__(self,vname):
        return self.get(vname)
    def xstatus(self):
        stat = '<DataContext><Name>' + self.name + '</Name>'
        for var in self.dict:
            try:
                stat +='<Variable>'
                stat += '<Name>'
                stat += var
                stat += '</Name>'
                stat += '<Type>'
                stat += '<![CDATA['
                stat += str(type(self.dict[var]))
                stat += ']]></Type>'
                stat += '<Value>'
                stat += '<![CDATA['
                stat += str(self.dict[var])[0:25]
                stat += ']]>'
                stat += '</Value>'
                stat += '</Variable>'
            except:
                stat += '<Unknown></Unknown>'
        stat += '</DataContext>'
        return stat
    def __flush__(self):
        for item in self.dict:
            try:
                self.dict[item].__flush__()
                self.dict[item].flush()
            except AttributeError:
                pass
        XTSM_Server_Objects.XTSM_Server_Object.__flush__(self)


text:
/*****************************************************************************/
/**
*
* @file xspi.c
* @addtogroup spi_v4_4
* @{
*
* Contains required functions of the XSpi driver component.  See xspi.h for
* a detailed description of the device and driver.
*
*

* MODIFICATION HISTORY:
*
* Ver   Who  Date     Changes
* ----- ---- -------- -----------------------------------------------
* 1.00a rpm  10/11/01 First release
* 1.00b jhl  03/14/02 Repartitioned driver for smaller files.
* 1.00b rpm  04/25/02 Collapsed IPIF and reg base addresses into one
* 1.00b rmm  05/14/03 Fixed diab compiler warnings relating to asserts
* 1.01a jvb  12/13/05 Changed Initialize() into CfgInitialize(), and made
*                     CfgInitialize() take a pointer to a config structure
*                     instead of a device id. Moved Initialize() into
*                     xspi_sinit.c, and had Initialize() call CfgInitialize()
*                     after it retrieved the config structure using the device
*                     id. Removed include of xparameters.h along with any
*                     dependencies on xparameters.h and the _g.c config table.
* 1.11a wgr  03/22/07 Converted to new coding style.
* 1.11a rpm  01/22/08 Updated comment on Transfer regarding needing interrupts.
* 1.12a sdm  03/27/08 Updated the code to support 16/32 bit transfer width and
*                     polled mode of operation. Even for the polled mode of
*                     operation the Interrupt Logic in the core should be
*                     included. The driver can be put in polled mode of
*                     operation by disabling the Global Interrupt after the
*                     Spi Initialization is completed.
* 2.00a sdm  07/30/08 Updated the code to support 16/32 bit transfer width and
*                     polled mode of operation. Even for the polled mode of
*                     operation the Interrupt Logic in the core should be
*                     included. The driver can be put in polled mode of
*                     operation by disabling the Global Interrupt after the
*                     Spi Initialization is completed.
* 2.01b sdm  04/08/09 Fixed an issue in the XSpi_Transfer function where the
*                     Global Interrupt is being enabled in polled mode when a
*                     slave is not selected.
* 3.00a ktn  10/28/09 Updated all the register accesses as 32 bit access.
*		      Updated to use the HAL APIs/macros.
*		      Removed the macro XSpi_mReset, XSpi_Reset API should be
*		      used in its place.
*		      The macros have been renamed to remove _m from the name.
*		      Removed an unnecessary read to the core register in the
*		      XSpi_GetSlaveSelect API.
* 3.01a sdm  04/23/10 Updated the driver to handle new slave mode interrupts
*		      and the DTR Half Empty interrupt.
* 3.04a bss  03/21/12 Updated XSpi_CfgInitialize to support XIP Mode
* 3.05a adk  18/04/13 Updated the code to avoid unused variable
*	              warnings when compiling with the -Wextra -Wall flags
*		      In the file xspi.c. CR:705005.
* 3.06a adk  07/08/13 Added a dummy read in the CfgInitialize(), if startup
*		      block is used in the h/w design (CR 721229).
* 3.07a adk 11/10/13  In the xspi_transfer function moved the assert slave chip
* 		      select after the configuration of the Data Transmit
*		      register inorder to work with CPOL and CPHA High Options.
* 		      As per spec (Dual/Quad SPI Transaction instrunction 7,8,9)
* 		      CR:732962
* 4.1	bss 08/07/14  Modified XSpi_Transfer to check for Interrupt Status
*		      register Tx Empty bit instead of Status register
*		      CR#810294.
* 4.2   sk   11/10/15 Used UINTPTR instead of u32 for Baseaddress CR# 867425.
*                     Changed the prototype of XSpi_CfgInitialize API.
* 4.4	tjs  11/28/17 When receive fifo exists, we need to check for status
*                     register rx fifo empty flag. If clear we can proceed for
*                     read. Otherwise we will hit execption. CR# 989938
*

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

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

#include "xspi.h"
#include "xspi_i.h"

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

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

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

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

static void StubStatusHandler(void *CallBackRef, u32 StatusEvent,
				unsigned int ByteCount);

void XSpi_Abort(XSpi *InstancePtr);

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

/*****************************************************************************/
/**
*
* Initializes a specific XSpi instance such that the driver is ready to use.
*
* The state of the device after initialization is:
*	- Device is disabled
*	- Slave mode
*	- Active high clock polarity
*	- Clock phase 0
*
* @param	InstancePtr is a pointer to the XSpi instance to be worked on.
* @param	Config is a reference to a structure containing information
*		about a specific SPI device. This function initializes an
*		InstancePtr object for a specific device specified by the
*		contents of Config. This function can initialize multiple
*		instance objects with the use of multiple calls giving
		different Config information on each call.
* @param	EffectiveAddr is the device base address in the virtual memory
*		address space. The caller is responsible for keeping the
*		address mapping from EffectiveAddr to the device physical base
*		address unchanged once this function is invoked. Unexpected
*		errors may occur if the address mapping changes after this
*		function is called. If address translation is not used, use
*		Config->BaseAddress for this parameters, passing the physical
*		address instead.
*
* @return
*		- XST_SUCCESS if successful.
*		- XST_DEVICE_IS_STARTED if the device is started. It must be
*		  stopped to re-initialize.
*
* @note		None.
*
******************************************************************************/
int XSpi_CfgInitialize(XSpi *InstancePtr, XSpi_Config *Config,
			UINTPTR EffectiveAddr)
{
	u8  Buffer[3];
	u32 ControlReg;
	u32 StatusReg;

	Xil_AssertNonvoid(InstancePtr != NULL);

	/*
	 * If the device is started, disallow the initialize and return a status
	 * indicating it is started.  This allows the user to stop the device
	 * and reinitialize, but prevents a user from inadvertently
	 * initializing.
	 */
	if (InstancePtr->IsStarted == XIL_COMPONENT_IS_STARTED) {
		return XST_DEVICE_IS_STARTED;
	}

	/*
	 * Set some default values.
	 */
	InstancePtr->IsStarted = 0;
	InstancePtr->IsBusy = FALSE;

	InstancePtr->StatusHandler = StubStatusHandler;

	InstancePtr->SendBufferPtr = NULL;
	InstancePtr->RecvBufferPtr = NULL;
	InstancePtr->RequestedBytes = 0;
	InstancePtr->RemainingBytes = 0;
	InstancePtr->BaseAddr = EffectiveAddr;
	InstancePtr->HasFifos = Config->HasFifos;
	InstancePtr->SlaveOnly = Config->SlaveOnly;
	InstancePtr->NumSlaveBits = Config->NumSlaveBits;
	if (Config->DataWidth == 0) {
		InstancePtr->DataWidth = XSP_DATAWIDTH_BYTE;
	} else {
		InstancePtr->DataWidth = Config->DataWidth;
	}

	InstancePtr->SpiMode = Config->SpiMode;

	InstancePtr->FlashBaseAddr = Config->AxiFullBaseAddress;
	InstancePtr->XipMode = Config->XipMode;

	InstancePtr->IsReady = XIL_COMPONENT_IS_READY;

	/*
	 * Create a slave select mask based on the number of bits that can
	 * be used to deselect all slaves, initialize the value to put into
	 * the slave select register to this value.
	 */
	InstancePtr->SlaveSelectMask = (1 << InstancePtr->NumSlaveBits) - 1;
	InstancePtr->SlaveSelectReg = InstancePtr->SlaveSelectMask;

	/*
	 * Clear the statistics for this driver.
	 */
	InstancePtr->Stats.ModeFaults = 0;
	InstancePtr->Stats.XmitUnderruns = 0;
	InstancePtr->Stats.RecvOverruns = 0;
	InstancePtr->Stats.SlaveModeFaults = 0;
	InstancePtr->Stats.BytesTransferred = 0;
	InstancePtr->Stats.NumInterrupts = 0;

        if(Config->Use_Startup == 1) {
		/*
		 * Perform a dummy read this is used when startup block is
		 * enabled in the hardware to fix CR #721229.
		 */
		ControlReg = XSpi_GetControlReg(InstancePtr);
		ControlReg |= XSP_CR_TXFIFO_RESET_MASK | XSP_CR_RXFIFO_RESET_MASK |
				XSP_CR_ENABLE_MASK | XSP_CR_MASTER_MODE_MASK ;
		XSpi_SetControlReg(InstancePtr, ControlReg);

		/*
		 * Initiate Read command to get the ID. This Read command is for
		 * Numonyx flash.
		 *
		 * NOTE: If user interfaces different flash to the SPI controller
		 * this command need to be changed according to target flash Read
		 * command.
		 */
		Buffer[0] = 0x9F;
		Buffer[1] = 0x00;
		Buffer[2] = 0x00;

		/* Write dummy ReadId to the DTR register */
		XSpi_WriteReg(InstancePtr->BaseAddr, XSP_DTR_OFFSET, Buffer[0]);
		XSpi_WriteReg(InstancePtr->BaseAddr, XSP_DTR_OFFSET, Buffer[1]);
		XSpi_WriteReg(InstancePtr->BaseAddr, XSP_DTR_OFFSET, Buffer[2]);

		/* Master Inhibit enable in the CR */
		ControlReg = XSpi_GetControlReg(InstancePtr);
		ControlReg &= ~XSP_CR_TRANS_INHIBIT_MASK;
		XSpi_SetControlReg(InstancePtr, ControlReg);

		/* Master Inhibit disable in the CR */
		ControlReg = XSpi_GetControlReg(InstancePtr);
		ControlReg |= XSP_CR_TRANS_INHIBIT_MASK;
		XSpi_SetControlReg(InstancePtr, ControlReg);

		/* Read the Rx Data Register */
		StatusReg = XSpi_GetStatusReg(InstancePtr);
		if ((StatusReg & XSP_SR_RX_EMPTY_MASK) == 0) {
			XSpi_ReadReg(InstancePtr->BaseAddr, XSP_DRR_OFFSET);
		}
		StatusReg = XSpi_GetStatusReg(InstancePtr);
		if ((StatusReg & XSP_SR_RX_EMPTY_MASK) == 0) {
			XSpi_ReadReg(InstancePtr->BaseAddr, XSP_DRR_OFFSET);
		}
	}

	/*
	 * Reset the SPI device to get it into its initial state. It is expected
	 * that device configuration will take place after this initialization
	 * is done, but before the device is started.
	 */
	XSpi_Reset(InstancePtr);

	return XST_SUCCESS;
}

/*****************************************************************************/
/**
*
* This function enables interrupts for the SPI device. If the Spi driver is used
* in interrupt mode, it is up to the user to connect the SPI interrupt handler
* to the interrupt controller before this function is called. If the Spi driver
* is used in polled mode the user has to disable the Global Interrupts after
* this function is called. If the device is configured with FIFOs, the FIFOs are
* reset at this time.
*
* @param	InstancePtr is a pointer to the XSpi instance to be worked on.
*
* @return
*		- XST_SUCCESS if the device is successfully started
*		- XST_DEVICE_IS_STARTED if the device was already started.
*
* @note		None.
*
******************************************************************************/
int XSpi_Start(XSpi *InstancePtr)
{
	u32 ControlReg;

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

	/*
	 * If it is already started, return a status indicating so.
	 */
	if (InstancePtr->IsStarted == XIL_COMPONENT_IS_STARTED) {
		return XST_DEVICE_IS_STARTED;
	}

	/*
	 * Enable the interrupts.
	 */
	XSpi_IntrEnable(InstancePtr, XSP_INTR_DFT_MASK);

	/*
	 * Indicate that the device is started before we enable the transmitter
	 * or receiver or interrupts.
	 */
	InstancePtr->IsStarted = XIL_COMPONENT_IS_STARTED;

	/*
	 * Reset the transmit and receive FIFOs if present. There is a critical
	 * section here since this register is also modified during interrupt
	 * context. So we wait until after the r/m/w of the control register to
	 * enable the Global Interrupt Enable.
	 */
	ControlReg = XSpi_GetControlReg(InstancePtr);
	ControlReg |= XSP_CR_TXFIFO_RESET_MASK | XSP_CR_RXFIFO_RESET_MASK |
			XSP_CR_ENABLE_MASK;
	XSpi_SetControlReg(InstancePtr, ControlReg);

	/*
	 * Enable the Global Interrupt Enable just after we start.
	 */
	XSpi_IntrGlobalEnable(InstancePtr);

	return XST_SUCCESS;
}

/*****************************************************************************/
/**
*
* This function stops the SPI device by disabling interrupts and disabling the
* device itself. Interrupts are disabled only within the device itself. If
* desired, the caller is responsible for disabling interrupts in the interrupt
* controller and disconnecting the interrupt handler from the interrupt
* controller.
*
* In interrupt mode, if the device is in progress of transferring data on the
* SPI bus, this function returns a status indicating the device is busy. The
* user will be notified via the status handler when the transfer is complete,
* and at that time can again try to stop the device. As a master, we do not
* allow the device to be stopped while a transfer is in progress because the
* slave may be left in a bad state. As a slave, we do not allow the device to be
* stopped while a transfer is in progress because the master is not done with
* its transfer yet.
*
* @param	InstancePtr is a pointer to the XSpi instance to be worked on.
*
* @return
* 		- XST_SUCCESS if the device is successfully started.
*		- XST_DEVICE_BUSY if a transfer is in progress and cannot be
*		  stopped.
*
* @note
*
* This function makes use of internal resources that are shared between the
* XSpi_Stop() and XSpi_SetOptions() functions. So if one task might be setting
* device options while another is trying to stop the device, the user is
* is required to provide protection of this shared data (typically using a
* semaphore).
*
******************************************************************************/
int XSpi_Stop(XSpi *InstancePtr)
{
	u32 ControlReg;

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

	/*
	 * Do not allow the user to stop the device while a transfer is in
	 * progress.
	 */
	if (InstancePtr->IsBusy) {
		return XST_DEVICE_BUSY;
	}

	/*
	 * Disable the device. First disable the interrupts since there is
	 * a critical section here because this register is also modified during
	 * interrupt context. The device is likely disabled already since there
	 * is no transfer in progress, but we do it again just to be sure.
	 */
	XSpi_IntrGlobalDisable(InstancePtr);

	ControlReg = XSpi_GetControlReg(InstancePtr);
	XSpi_SetControlReg(InstancePtr, ControlReg & ~XSP_CR_ENABLE_MASK);

	InstancePtr->IsStarted = 0;

	return XST_SUCCESS;
}

/*****************************************************************************/
/**
*
* Resets the SPI device by writing to the Software Reset register. Reset must
* only be called after the driver has been initialized. The configuration of the
* device after reset is the same as its configuration after initialization.
* Refer to the XSpi_Initialize function for more details. This is a hard reset
* of the device. Any data transfer that is in progress is aborted.
*
* The upper layer software is responsible for re-configuring (if necessary)
* and restarting the SPI device after the reset.
*
* @param	InstancePtr is a pointer to the XSpi instance to be worked on.
*
* @return	None.
*
* @note		None.
*
******************************************************************************/
void XSpi_Reset(XSpi *InstancePtr)
{
	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	/*
	 * Abort any transfer that is in progress.
	 */
	XSpi_Abort(InstancePtr);

	/*
	 * Reset any values that are not reset by the hardware reset such that
	 * the software state matches the hardware device.
	 */
	InstancePtr->IsStarted = 0;
	InstancePtr->SlaveSelectReg = InstancePtr->SlaveSelectMask;

	/*
	 * Reset the device.
	 */
	XSpi_WriteReg(InstancePtr->BaseAddr, XSP_SRR_OFFSET,
			XSP_SRR_RESET_MASK);
}

/*****************************************************************************/
/**
*
* Transfers the specified data on the SPI bus. If the SPI device is configured
* to be a master, this function initiates bus communication and sends/receives
* the data to/from the selected SPI slave. If the SPI device is configured to
* be a slave, this function prepares the data to be sent/received when selected
* by a master. For every byte sent, a byte is received.
*
* This function/driver operates in interrupt mode and polled mode.
*  - In interrupt mode this function is non-blocking and the transfer is
*    initiated by this function and completed by the interrupt service routine.
*  - In polled mode this function is blocking and the control exits this
*    function only after all the requested data is transferred.
*
* The caller has the option of providing two different buffers for send and
* receive, or one buffer for both send and receive, or no buffer for receive.
* The receive buffer must be at least as big as the send buffer to prevent
* unwanted memory writes. This implies that the byte count passed in as an
* argument must be the smaller of the two buffers if they differ in size.
* Here are some sample usages:
*

*	XSpi_Transfer(InstancePtr, SendBuf, RecvBuf, ByteCount)
*	The caller wishes to send and receive, and provides two different
*	buffers for send and receive.
*
*	XSpi_Transfer(InstancePtr, SendBuf, NULL, ByteCount)
*	The caller wishes only to send and does not care about the received
*	data. The driver ignores the received data in this case.
*
*	XSpi_Transfer(InstancePtr, SendBuf, SendBuf, ByteCount)
*	The caller wishes to send and receive, but provides the same buffer
*	for doing both. The driver sends the data and overwrites the send
*	buffer with received data as it transfers the data.
*
*	XSpi_Transfer(InstancePtr, RecvBuf, RecvBuf, ByteCount)
*	The caller wishes to only receive and does not care about sending
*	data.  In this case, the caller must still provide a send buffer, but
*	it can be the same as the receive buffer if the caller does not care
*	what it sends. The device must send N bytes of data if it wishes to
*	receive N bytes of data.
*

* In interrupt mode, though this function takes a buffer as an argument, the
* driver can only transfer a limited number of bytes at time. It transfers only
* one byte at a time if there are no FIFOs, or it can transfer the number of
* bytes up to the size of the FIFO if FIFOs exist.
*  - In interrupt mode a call to this function only starts the transfer, the
*    subsequent transfer of the data is performed by the interrupt service
*    routine until the entire buffer has been transferred.The status callback
*    function is called when the entire buffer has been sent/received.
*  - In polled mode this function is blocking and the control exits this
*    function only after all the requested data is transferred.
*
* As a master, the SetSlaveSelect function must be called prior to this
* function.
*
* @param	InstancePtr is a pointer to the XSpi instance to be worked on.
* @param	SendBufPtr is a pointer to a buffer of data which is to be sent.
*		This buffer must not be NULL.
* @param	RecvBufPtr is a pointer to a buffer which will be filled with
*		received data. This argument can be NULL if the caller does not
*		wish to receive data.
* @param	ByteCount contains the number of bytes to send/receive. The
*		number of bytes received always equals the number of bytes sent.
*
* @return
*		-XST_SUCCESS if the buffers are successfully handed off to the
*		driver for transfer. Otherwise, returns:
*		- XST_DEVICE_IS_STOPPED if the device must be started before
*		transferring data.
*		- XST_DEVICE_BUSY indicates that a data transfer is already in
*		progress. This is determined by the driver.
*		- XST_SPI_NO_SLAVE indicates the device is configured as a
*		master and a slave has not yet been selected.
*
* @notes
*
* This function is not thread-safe.  The higher layer software must ensure that
* no two threads are transferring data on the SPI bus at the same time.
*
******************************************************************************/
int XSpi_Transfer(XSpi *InstancePtr, u8 *SendBufPtr,
		  u8 *RecvBufPtr, unsigned int ByteCount)
{
	u32 ControlReg;
	u32 GlobalIntrReg;
	u32 StatusReg;
	u32 Data = 0;
	u8  DataWidth;

	/*
	 * The RecvBufPtr argument can be NULL.
	 */
	Xil_AssertNonvoid(InstancePtr != NULL);
	Xil_AssertNonvoid(SendBufPtr != NULL);
	Xil_AssertNonvoid(ByteCount > 0);
	Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	if (InstancePtr->IsStarted != XIL_COMPONENT_IS_STARTED) {
		return XST_DEVICE_IS_STOPPED;
	}

	/*
	 * Make sure there is not a transfer already in progress. No need to
	 * worry about a critical section here. Even if the Isr changes the bus
	 * flag just after we read it, a busy error is returned and the caller
	 * can retry when it gets the status handler callback indicating the
	 * transfer is done.
	 */
	if (InstancePtr->IsBusy) {
		return XST_DEVICE_BUSY;
	}

	/*
	 * Save the Global Interrupt Enable Register.
	 */
	GlobalIntrReg = XSpi_IsIntrGlobalEnabled(InstancePtr);

	/*
	 * Enter a critical section from here to the end of the function since
	 * state is modified, an interrupt is enabled, and the control register
	 * is modified (r/m/w).
	 */
	XSpi_IntrGlobalDisable(InstancePtr);

	ControlReg = XSpi_GetControlReg(InstancePtr);

	/*
	 * If configured as a master, be sure there is a slave select bit set
	 * in the slave select register. If no slaves have been selected, the
	 * value of the register will equal the mask.  When the device is in
	 * loopback mode, however, no slave selects need be set.
	 */
	if (ControlReg & XSP_CR_MASTER_MODE_MASK) {
		if ((ControlReg & XSP_CR_LOOPBACK_MASK) == 0) {
			if (InstancePtr->SlaveSelectReg ==
				InstancePtr->SlaveSelectMask) {
				if (GlobalIntrReg == TRUE) {
					/* Interrupt Mode of operation */
					XSpi_IntrGlobalEnable(InstancePtr);
				}
				return XST_SPI_NO_SLAVE;
			}
		}
	}

	/*
	 * Set the busy flag, which will be cleared when the transfer
	 * is completely done.
	 */
	InstancePtr->IsBusy = TRUE;

	/*
	 * Set up buffer pointers.
	 */
	InstancePtr->SendBufferPtr = SendBufPtr;
	InstancePtr->RecvBufferPtr = RecvBufPtr;

	InstancePtr->RequestedBytes = ByteCount;
	InstancePtr->RemainingBytes = ByteCount;

	DataWidth = InstancePtr->DataWidth;

	/*
	 * Fill the DTR/FIFO with as many bytes as it will take (or as many as
	 * we have to send). We use the tx full status bit to know if the device
	 * can take more data. By doing this, the driver does not need to know
	 * the size of the FIFO or that there even is a FIFO. The downside is
	 * that the status register must be read each loop iteration.
	 */
	StatusReg = XSpi_GetStatusReg(InstancePtr);

	while (((StatusReg & XSP_SR_TX_FULL_MASK) == 0) &&
		(InstancePtr->RemainingBytes > 0)) {
		if (DataWidth == XSP_DATAWIDTH_BYTE) {
			/*
			 * Data Transfer Width is Byte (8 bit).
			 */
			Data = *InstancePtr->SendBufferPtr;
		} else if (DataWidth == XSP_DATAWIDTH_HALF_WORD) {
			/*
			 * Data Transfer Width is Half Word (16 bit).
			 */
			Data = *(u16 *)InstancePtr->SendBufferPtr;
		} else if (DataWidth == XSP_DATAWIDTH_WORD){
			/*
			 * Data Transfer Width is Word (32 bit).
			 */
			Data = *(u32 *)InstancePtr->SendBufferPtr;
		}

		XSpi_WriteReg(InstancePtr->BaseAddr, XSP_DTR_OFFSET, Data);
		InstancePtr->SendBufferPtr += (DataWidth >> 3);
		InstancePtr->RemainingBytes -= (DataWidth >> 3);
		StatusReg = XSpi_GetStatusReg(InstancePtr);
	}

	/*
	 * Set the slave select register to select the device on the SPI before
	 * starting the transfer of data.
	 */
	XSpi_SetSlaveSelectReg(InstancePtr,
				InstancePtr->SlaveSelectReg);

	/*
	 * Start the transfer by no longer inhibiting the transmitter and
	 * enabling the device. For a master, this will in fact start the
	 * transfer, but for a slave it only prepares the device for a transfer
	 * that must be initiated by a master.
	 */
	ControlReg = XSpi_GetControlReg(InstancePtr);
	ControlReg &= ~XSP_CR_TRANS_INHIBIT_MASK;
	XSpi_SetControlReg(InstancePtr, ControlReg);

	/*
	 * If the interrupts are enabled as indicated by Global Interrupt
	 * Enable Register, then enable the transmit empty interrupt to operate
	 * in Interrupt mode of operation.
	 */
	if (GlobalIntrReg == TRUE) { /* Interrupt Mode of operation */

		/*
		 * Enable the transmit empty interrupt, which we use to
		 * determine progress on the transmission.
		 */
		XSpi_IntrEnable(InstancePtr, XSP_INTR_TX_EMPTY_MASK);

		/*
		 * End critical section.
		 */
		XSpi_IntrGlobalEnable(InstancePtr);

	} else { /* Polled mode of operation */

		/*
		 * If interrupts are not enabled, poll the status register to
		 * Transmit/Receive SPI data.
		 */
		while(ByteCount > 0) {

			/*
			 * Wait for the transfer to be done by polling the
			 * Transmit empty status bit
			 */
			do {
				StatusReg = XSpi_IntrGetStatus(InstancePtr);
			} while ((StatusReg & XSP_INTR_TX_EMPTY_MASK) == 0);

			XSpi_IntrClear(InstancePtr,XSP_INTR_TX_EMPTY_MASK);

			/*
			 * A transmit has just completed. Process received data
			 * and check for more data to transmit. Always inhibit
			 * the transmitter while the transmit register/FIFO is
			 * being filled, or make sure it is stopped if we're
			 * done.
			 */
			ControlReg = XSpi_GetControlReg(InstancePtr);
			XSpi_SetControlReg(InstancePtr, ControlReg |
						XSP_CR_TRANS_INHIBIT_MASK);

			/*
			 * First get the data received as a result of the
			 * transmit that just completed. We get all the data
			 * available by reading the status register to determine
			 * when the Receive register/FIFO is empty. Always get
			 * the received data, but only fill the receive
			 * buffer if it points to something (the upper layer
			 * software may not care to receive data).
			 */
			StatusReg = XSpi_GetStatusReg(InstancePtr);

			while ((StatusReg & XSP_SR_RX_EMPTY_MASK) == 0) {

				Data = XSpi_ReadReg(InstancePtr->BaseAddr,
								XSP_DRR_OFFSET);
				if (DataWidth == XSP_DATAWIDTH_BYTE) {
					/*
					 * Data Transfer Width is Byte (8 bit).
					 */
					if(InstancePtr->RecvBufferPtr != NULL) {
						*InstancePtr->RecvBufferPtr++ =
							(u8)Data;
					}
				} else if (DataWidth ==
						XSP_DATAWIDTH_HALF_WORD) {
					/*
					 * Data Transfer Width is Half Word
					 * (16 bit).
					 */
					if (InstancePtr->RecvBufferPtr != NULL){
					    *(u16 *)InstancePtr->RecvBufferPtr =
							(u16)Data;
						InstancePtr->RecvBufferPtr += 2;
					}
				} else if (DataWidth == XSP_DATAWIDTH_WORD) {
					/*
					 * Data Transfer Width is Word (32 bit).
					 */
					if (InstancePtr->RecvBufferPtr != NULL){
					    *(u32 *)InstancePtr->RecvBufferPtr =
							Data;
						InstancePtr->RecvBufferPtr += 4;
					}
				}
				InstancePtr->Stats.BytesTransferred +=
						(DataWidth >> 3);
				ByteCount -= (DataWidth >> 3);
				StatusReg = XSpi_GetStatusReg(InstancePtr);
			}

			if (InstancePtr->RemainingBytes > 0) {

				/*
				 * Fill the DTR/FIFO with as many bytes as it
				 * will take (or as many as we have to send).
				 * We use the Tx full status bit to know if the
				 * device can take more data.
				 * By doing this, the driver does not need to
				 * know the size of the FIFO or that there even
				 * is a FIFO.
				 * The downside is that the status must be read
				 * each loop iteration.
				 */
				StatusReg = XSpi_GetStatusReg(InstancePtr);

				while(((StatusReg & XSP_SR_TX_FULL_MASK)== 0) &&
					(InstancePtr->RemainingBytes > 0)) {
					if (DataWidth == XSP_DATAWIDTH_BYTE) {
						/*
						 * Data Transfer Width is Byte
						 * (8 bit).
						 */
						Data = *InstancePtr->
								SendBufferPtr;

					} else if (DataWidth ==
						XSP_DATAWIDTH_HALF_WORD) {

						/*
						 * Data Transfer Width is Half
						 * Word (16 bit).
			 			 */
						Data = *(u16 *)InstancePtr->
								SendBufferPtr;
					} else if (DataWidth ==
							XSP_DATAWIDTH_WORD) {
						/*
						 * Data Transfer Width is Word
						 * (32 bit).
			 			 */
						Data = *(u32 *)InstancePtr->
								SendBufferPtr;
					}
					XSpi_WriteReg(InstancePtr->BaseAddr,
							XSP_DTR_OFFSET, Data);
					InstancePtr->SendBufferPtr +=
							(DataWidth >> 3);
					InstancePtr->RemainingBytes -=
							(DataWidth >> 3);
					StatusReg = XSpi_GetStatusReg(
							InstancePtr);
				}

				/*
				 * Start the transfer by not inhibiting the
				 * transmitter any longer.
				 */
				ControlReg = XSpi_GetControlReg(InstancePtr);
				ControlReg &= ~XSP_CR_TRANS_INHIBIT_MASK;
				XSpi_SetControlReg(InstancePtr, ControlReg);
			}
		}

		/*
		 * Stop the transfer (hold off automatic sending) by inhibiting
		 * the transmitter.
		 */
		ControlReg = XSpi_GetControlReg(InstancePtr);
		XSpi_SetControlReg(InstancePtr,
				    ControlReg | XSP_CR_TRANS_INHIBIT_MASK);

		/*
		 * Select the slave on the SPI bus when the transfer is
		 * complete, this is necessary for some SPI devices,
		 * such as serial EEPROMs work correctly as chip enable
		 * may be connected to slave select
		 */
		XSpi_SetSlaveSelectReg(InstancePtr,
					InstancePtr->SlaveSelectMask);
		InstancePtr->IsBusy = FALSE;
	}

	return XST_SUCCESS;
}

/*****************************************************************************/
/**
*
* Selects or deselect the slave with which the master communicates. Each slave
* that can be selected is represented in the slave select register by a bit.
* The argument passed to this function is the bit mask with a 1 in the bit
* position of the slave being selected. Only one slave can be selected.
*
* The user is not allowed to deselect the slave while a transfer is in progress.
* If no transfer is in progress, the user can select a new slave, which
* implicitly deselects the current slave. In order to explicitly deselect the
* current slave, a zero can be passed in as the argument to the function.
*
* @param	InstancePtr is a pointer to the XSpi instance to be worked on.
* @param	SlaveMask is a 32-bit mask with a 1 in the bit position of the
*		slave being selected. Only one slave can be selected. The
*		SlaveMask can be zero if the slave is being deselected.
*
* @return
* 		- XST_SUCCESS if the slave is selected or deselected
*		successfully.
*		- XST_DEVICE_BUSY if a transfer is in progress, slave cannot be
*		changed
*		- XST_SPI_TOO_MANY_SLAVES if more than one slave is being
*		selected.
*
* @note
*
* This function only sets the slave which will be selected when a transfer
* occurs. The slave is not selected when the SPI is idle. The slave select
* has no affect when the device is configured as a slave.
*
******************************************************************************/
int XSpi_SetSlaveSelect(XSpi *InstancePtr, u32 SlaveMask)
{
	int NumAsserted;
	int Index;

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

	/*
	 * Do not allow the slave select to change while a transfer is in
	 * progress.
	 * No need to worry about a critical section here since even if the Isr
	 * changes the busy flag just after we read it, the function will return
	 * busy and the caller can retry when notified that their current
	 * transfer is done.
	 */
	if (InstancePtr->IsBusy) {
		return XST_DEVICE_BUSY;
	}

	/*
	 * Verify that only one bit in the incoming slave mask is set.
	 */
	NumAsserted = 0;
	for (Index = (InstancePtr->NumSlaveBits - 1); Index >= 0; Index--) {
		if ((SlaveMask >> Index) & 0x1) {
			/* this bit is asserted */
			NumAsserted++;
		}
	}

	/*
	 * Return an error if more than one slave is selected.
	 */
	if (NumAsserted > 1) {
		return XST_SPI_TOO_MANY_SLAVES;
	}

	/*
	 * A single slave is either being selected or the incoming SlaveMask is
	 * zero, which means the slave is being deselected. Setup the value to
	 * be  written to the slave select register as the inverse of the slave
	 * mask.
	 */
	InstancePtr->SlaveSelectReg = ~SlaveMask;

	return XST_SUCCESS;
}

/*****************************************************************************/
/**
*
* Gets the current slave select bit mask for the SPI device.
*
* @param	InstancePtr is a pointer to the XSpi instance to be worked on.
*
* @return	The value returned is a 32-bit mask with a 1 in the bit position
*		of the slave currently selected. The value may be zero if no
*		slaves are selected.
*
* @note		This API is used to get the current slave select bit mask
*		that was set using the XSpi_SetSlaveSelect API.
*		This API deos not read the register from the core and returns
*		the slave select register stored in the instance pointer.
*
******************************************************************************/
u32 XSpi_GetSlaveSelect(XSpi *InstancePtr)
{
	Xil_AssertNonvoid(InstancePtr != NULL);
	Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	/*
	 * Return the inverse of the value contained in
	 * InstancePtr->SlaveSelectReg. This value is set using the API
	 * XSpi_SetSlaveSelect.
	 */
	return ~InstancePtr->SlaveSelectReg;
}

/*****************************************************************************/
/**
*
* Sets the status callback function, the status handler, which the driver calls
* when it encounters conditions that should be reported to the higher layer
* software. The handler executes in an interrupt context, so it must minimize
* the amount of processing performed such as transferring data to a thread
* context. One of the following status events is passed to the status handler.
*

*   - XST_SPI_MODE_FAULT	A mode fault error occurred, meaning another
*				master tried to select this device as a slave
*				when this device was configured to be a master.
*				Any transfer in progress is aborted.
*
*   - XST_SPI_TRANSFER_DONE	The requested data transfer is done
*
*   - XST_SPI_TRANSMIT_UNDERRUN	As a slave device, the master clocked
*				data but there were none available in the
*				transmit register/FIFO. This typically means the
*				slave application did not issue a transfer
*				request fast enough, or the processor/driver
*				could not fill the transmit register/FIFO fast
*				enough.
*
*   - XST_SPI_RECEIVE_OVERRUN	The SPI device lost data. Data was received
*				but the receive data register/FIFO was full.
*				This indicates that the device is receiving data
*				faster than the processor/driver can consume it.
*
*   - XST_SPI_SLAVE_MODE_FAULT	A slave SPI device was selected as a slave while
*				it was disabled.  This indicates the master is
*				already transferring data (which is being
*				dropped until the slave application issues a
*				transfer).
*

* @param	InstancePtr is a pointer to the XSpi instance to be worked on.
* @param	CallBackRef is the upper layer callback reference passed back
*		when the callback function is invoked.
* @param	FuncPtr is the pointer to the callback function.
*
* @return	None.
*
* @note
*
* The handler is called within interrupt context, so it should do its work
* quickly and queue potentially time-consuming work to a task-level thread.
*
******************************************************************************/
void XSpi_SetStatusHandler(XSpi *InstancePtr, void *CallBackRef,
			   XSpi_StatusHandler FuncPtr)
{
	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(FuncPtr != NULL);
	Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	InstancePtr->StatusHandler = FuncPtr;
	InstancePtr->StatusRef = CallBackRef;
}

/*****************************************************************************/
/**
*
* This is a stub for the status callback. The stub is here in case the upper
* layers forget to set the handler.
*
* @param	CallBackRef is a pointer to the upper layer callback reference
* @param	StatusEvent is the event that just occurred.
* @param	ByteCount is the number of bytes transferred up until the event
*		occurred.
*
* @return	None.
*
* @note		None.
*
******************************************************************************/
static void StubStatusHandler(void *CallBackRef, u32 StatusEvent,
				unsigned int ByteCount)
{
	(void )CallBackRef;
	(void )StatusEvent;
	(void ) ByteCount;
	Xil_AssertVoidAlways();
}

/*****************************************************************************/
/**
*
* The interrupt handler for SPI interrupts. This function must be connected
* by the user to an interrupt source. This function does not save and restore
* the processor context such that the user must provide this processing.
*
* The interrupts that are handled are:
*
* - Mode Fault Error. This interrupt is generated if this device is selected
*   as a slave when it is configured as a master. The driver aborts any data
*   transfer that is in progress by resetting FIFOs (if present) and resetting
*   its buffer pointers. The upper layer software is informed of the error.
*
* - Data Transmit Register (FIFO) Empty. This interrupt is generated when the
*   transmit register or FIFO is empty. The driver uses this interrupt during a
*   transmission to continually send/receive data until there is no more data
*   to send/receive.
*
* - Data Transmit Register (FIFO) Underrun. This interrupt is generated when
*   the SPI device, when configured as a slave, attempts to read an empty
*   DTR/FIFO.  An empty DTR/FIFO usually means that software is not giving the
*   device data in a timely manner. No action is taken by the driver other than
*   to inform the upper layer software of the error.
*
* - Data Receive Register (FIFO) Overrun. This interrupt is generated when the
*   SPI device attempts to write a received byte to an already full DRR/FIFO.
*   A full DRR/FIFO usually means software is not emptying the data in a timely
*   manner.  No action is taken by the driver other than to inform the upper
*   layer software of the error.
*
* - Slave Mode Fault Error. This interrupt is generated if a slave device is
*   selected as a slave while it is disabled. No action is taken by the driver
*   other than to inform the upper layer software of the error.
*
* - Command Error. This interrupt occurs when the first byte in the Tx FIFO,
*   after the CS is asserted, doesn't match any command in the Lookup table.
*   This interrupt is valid only for axi_qspi.
*
* @param	InstancePtr is a pointer to the XSpi instance to be worked on.
*
* @return	None.
*
* @note
*
* The slave select register is being set to deselect the slave when a transfer
* is complete.  This is being done regardless of whether it is a slave or a
* master since the hardware does not drive the slave select as a slave.
*
******************************************************************************/
void XSpi_InterruptHandler(void *InstancePtr)
{
	XSpi *SpiPtr = (XSpi *)InstancePtr;
	u32 IntrStatus;
	unsigned int BytesDone;	/* number of bytes done so far */
	u32 Data = 0;
	u32 ControlReg;
	u32 StatusReg;
	u8  DataWidth;

	Xil_AssertVoid(InstancePtr != NULL);

	/*
	 * Update the statistics for the number of interrupts.
	 */
	SpiPtr->Stats.NumInterrupts++;

	/*
	 * Get the Interrupt Status. Immediately clear the interrupts in case
	 * this Isr causes another interrupt to be generated. If we clear at the
	 * end of the Isr, we may miss this newly generated interrupt. This
	 * occurs because we transmit from within the Isr, potentially causing
	 * another TX_EMPTY interrupt.
	 */
	IntrStatus = XSpi_IntrGetStatus(SpiPtr);
	XSpi_IntrClear(SpiPtr, IntrStatus);

	/*
	 * Check for mode fault error. We want to check for this error first,
	 * before checking for progress of a transfer, since this error needs
	 * to abort any operation in progress.
	 */
	if (IntrStatus & XSP_INTR_MODE_FAULT_MASK) {
		BytesDone = SpiPtr->RequestedBytes - SpiPtr->RemainingBytes;
		SpiPtr->Stats.ModeFaults++;

		/*
		 * Abort any operation currently in progress. This includes
		 * clearing the mode fault condition by reading the status
		 * register.
		 * Note that the status register should be read after the Abort
		 * since reading the status register clears the mode fault
		 * condition and would cause the device to restart any transfer
		 * that may be in progress.
		 */
		XSpi_Abort(SpiPtr);

		(void) XSpi_GetStatusReg(SpiPtr);

		SpiPtr->StatusHandler(SpiPtr->StatusRef, XST_SPI_MODE_FAULT,
					BytesDone);

		return;		/* Do not continue servicing other interrupts */
	}

	DataWidth = SpiPtr->DataWidth;
	if ((IntrStatus & XSP_INTR_TX_EMPTY_MASK) ||
	    (IntrStatus & XSP_INTR_TX_HALF_EMPTY_MASK)) {

		/*
		 * A transmit has just completed. Process received data and
		 * check for more data to transmit. Always inhibit the
		 * transmitter while the Isr re-fills the transmit
		 * register/FIFO, or make sure it is stopped if we're done.
		 */
		ControlReg = XSpi_GetControlReg(SpiPtr);
		XSpi_SetControlReg(SpiPtr, ControlReg |
					XSP_CR_TRANS_INHIBIT_MASK);

		/*
		 * First get the data received as a result of the transmit that
		 * just completed.  We get all the data available by reading the
		 * status register to determine when the receive register/FIFO
		 * is empty. Always get the received data, but only fill the
		 * receive buffer if it points to something (the upper layer
		 * software may not care to receive data).
		 */
		StatusReg = XSpi_GetStatusReg(SpiPtr);

		while ((StatusReg & XSP_SR_RX_EMPTY_MASK) == 0) {

			Data = XSpi_ReadReg(SpiPtr->BaseAddr, XSP_DRR_OFFSET);

			/*
			 * Data Transfer Width is Byte (8 bit).
			 */
			if (DataWidth == XSP_DATAWIDTH_BYTE) {
				if (SpiPtr->RecvBufferPtr != NULL) {
					*SpiPtr->RecvBufferPtr++ = (u8) Data;
				}
			} else if (DataWidth == XSP_DATAWIDTH_HALF_WORD) {
				if (SpiPtr->RecvBufferPtr != NULL) {
					*(u16 *) SpiPtr->RecvBufferPtr =
							(u16) Data;
					SpiPtr->RecvBufferPtr +=2;
				}
			} else if (DataWidth == XSP_DATAWIDTH_WORD) {
				if (SpiPtr->RecvBufferPtr != NULL) {
					*(u32 *) SpiPtr->RecvBufferPtr =
							Data;
					SpiPtr->RecvBufferPtr +=4;
				}
			}

			SpiPtr->Stats.BytesTransferred += (DataWidth >> 3);
			StatusReg = XSpi_GetStatusReg(SpiPtr);
		}

		/*
		 * See if there is more data to send.
		 */
		if (SpiPtr->RemainingBytes > 0) {
			/*
			 * Fill the DTR/FIFO with as many bytes as it will take
			 * (or as many as we have to send). We use the full
			 * status bit to know if the device can take more data.
			 * By doing this, the driver does not need to know the
			 * size of the FIFO or that there even is a FIFO.
			 * The downside is that the status must be read each
			 * loop iteration.
			 */
			StatusReg = XSpi_GetStatusReg(SpiPtr);
			while (((StatusReg & XSP_SR_TX_FULL_MASK) == 0) &&
				(SpiPtr->RemainingBytes > 0)) {
				if (DataWidth == XSP_DATAWIDTH_BYTE) {
					/*
					 * Data Transfer Width is Byte (8 bit).
					 */
					Data = *SpiPtr->SendBufferPtr;

				} else if (DataWidth ==
						XSP_DATAWIDTH_HALF_WORD) {
					/*
					 * Data Transfer Width is Half Word
					 * (16 bit).
					 */
					Data = *(u16 *) SpiPtr->SendBufferPtr;
				} else if (DataWidth ==
						XSP_DATAWIDTH_WORD) {
					/*
					 * Data Transfer Width is Word (32 bit).
					 */
					Data = *(u32 *) SpiPtr->SendBufferPtr;
				}

				XSpi_WriteReg(SpiPtr->BaseAddr, XSP_DTR_OFFSET,
						Data);
				SpiPtr->SendBufferPtr += (DataWidth >> 3);
				SpiPtr->RemainingBytes -= (DataWidth >> 3);
				StatusReg = XSpi_GetStatusReg(SpiPtr);
			}

			/*
			 * Start the transfer by not inhibiting the transmitter
			 * any longer.
			 */
			XSpi_SetControlReg(SpiPtr, ControlReg);
		} else {

			/*
			 * Select the slave on the SPI bus when the transfer is
			 * complete, this is necessary for some SPI devices,
			 * such as serial EEPROMs work correctly as chip enable
			 * may be connected to slave select.
			 */
			XSpi_SetSlaveSelectReg(SpiPtr,
						SpiPtr->SlaveSelectMask);
			/*
			 * No more data to send.  Disable the interrupt and
			 * inform the upper layer software that the transfer is
			 * done. The interrupt will be re-enabled when another
			 * transfer is initiated.
			 */
			XSpi_IntrDisable(SpiPtr, XSP_INTR_TX_EMPTY_MASK);

			SpiPtr->IsBusy = FALSE;

			SpiPtr->StatusHandler(SpiPtr->StatusRef,
						XST_SPI_TRANSFER_DONE,
						SpiPtr->RequestedBytes);
		}
	}

	/*
	 * Check if the device has been addressed as a slave. Report the status
	 * to the application layer.
	 */
	if (IntrStatus & XSP_INTR_SLAVE_MODE_MASK) {
		SpiPtr->StatusHandler(SpiPtr->StatusRef,
					XST_SPI_SLAVE_MODE, 0);
	}

	/*
	 * Check if the device has received data from the master. Report the
	 * status to the application layer.
	 */
	if (IntrStatus & XSP_INTR_RX_NOT_EMPTY_MASK) {
		SpiPtr->StatusHandler(SpiPtr->StatusRef,
					XST_SPI_RECEIVE_NOT_EMPTY, 0);
	}

	/*
	 * Check for slave mode fault. Simply report the error and update the
	 * statistics.
	 */
	if (IntrStatus & XSP_INTR_SLAVE_MODE_FAULT_MASK) {
		BytesDone = SpiPtr->RequestedBytes - SpiPtr->RemainingBytes;
		SpiPtr->Stats.SlaveModeFaults++;
		SpiPtr->StatusHandler(SpiPtr->StatusRef,
				XST_SPI_SLAVE_MODE_FAULT, BytesDone);
	}

	/*
	 * Check for overrun error. Simply report the error and update the
	 * statistics.
	 */
	if (IntrStatus & XSP_INTR_RX_OVERRUN_MASK) {
		BytesDone = SpiPtr->RequestedBytes - SpiPtr->RemainingBytes;
		SpiPtr->Stats.RecvOverruns++;
		SpiPtr->StatusHandler(SpiPtr->StatusRef,
				XST_SPI_RECEIVE_OVERRUN, BytesDone);
	}

	/*
	 * Check for underrun error. Simply report the error and update the
	 * statistics.
	 */
	if (IntrStatus & XSP_INTR_TX_UNDERRUN_MASK) {
		BytesDone = SpiPtr->RequestedBytes - SpiPtr->RemainingBytes;
		SpiPtr->Stats.XmitUnderruns++;
		SpiPtr->StatusHandler(SpiPtr->StatusRef,
				XST_SPI_TRANSMIT_UNDERRUN, BytesDone);
	}

	/*
	 * Check for command error. Simply report the error and update the
	 * statistics.
	 */
	if (IntrStatus & XSP_INTR_CMD_ERR_MASK) {
		BytesDone = SpiPtr->RequestedBytes - SpiPtr->RemainingBytes;
		SpiPtr->Stats.XmitUnderruns++;
		SpiPtr->StatusHandler(SpiPtr->StatusRef,
				XST_SPI_COMMAND_ERROR, BytesDone);
	}
}

/*****************************************************************************/
/**
*
* Aborts a transfer in progress by setting the stop bit in the control register,
* then resetting the FIFOs if present. The byte counts are cleared and the
* busy flag is set to false.
*
* @param	InstancePtr is a pointer to the XSpi instance to be worked on.
*
* @return	None.
*
* @note
*
* This function does a read/modify/write of the control register. The user of
* this function needs to take care of critical sections.
*
******************************************************************************/
void XSpi_Abort(XSpi *InstancePtr)
{
	u16 ControlReg;

	/*
	 * Deselect the slave on the SPI bus to abort a transfer, this must be
	 * done before the device is disabled such that the signals which are
	 * driven by the device are changed without the device enabled.
	 */
	XSpi_SetSlaveSelectReg(InstancePtr,
				InstancePtr->SlaveSelectMask);
	/*
	 * Abort the operation currently in progress. Clear the mode
	 * fault condition by reading the status register (done) then
	 * writing the control register.
	 */
	ControlReg = XSpi_GetControlReg(InstancePtr);

	/*
	 * Stop any transmit in progress and reset the FIFOs if they exist,
	 * don't disable the device just inhibit any data from being sent.
	 */
	ControlReg |= XSP_CR_TRANS_INHIBIT_MASK;

	if (InstancePtr->HasFifos) {
		ControlReg |= (XSP_CR_TXFIFO_RESET_MASK |
				XSP_CR_RXFIFO_RESET_MASK);
	}

	XSpi_SetControlReg(InstancePtr, ControlReg);

	InstancePtr->RemainingBytes = 0;
	InstancePtr->RequestedBytes = 0;
	InstancePtr->IsBusy = FALSE;
}

/** @} */


text:
<?php

namespace Oro\Bundle\SecurityBundle\Tests\Unit\Util;

use Doctrine\ORM\Mapping\ClassMetadata;
use Oro\Bundle\SecurityBundle\Tests\Unit\Fixtures\Models\CMS\CmsAddress;
use Oro\Bundle\SecurityBundle\Tests\Unit\Fixtures\Models\CMS\CmsArticle;
use Oro\Bundle\SecurityBundle\Tests\Unit\Fixtures\Models\CMS\CmsUser;
use Oro\Bundle\SecurityBundle\Util\PropertyPathSecurityHelper;
use Symfony\Component\Security\Acl\Voter\FieldVote;

class PropertyPathSecurityHelperTest extends \PHPUnit_Framework_TestCase
{
    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $authorizationChecker;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $managerRegistry;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $entityConfigProvider;

    /** @var PropertyPathSecurityHelper */
    protected $helper;

    protected function setUp()
    {
        $this->authorizationChecker = $this
            ->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
        $this->managerRegistry = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')
            ->disableOriginalConstructor()
            ->getMock();
        $this->entityConfigProvider = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider')
            ->disableOriginalConstructor()
            ->getMock();
        $this->helper = new PropertyPathSecurityHelper(
            $this->authorizationChecker,
            $this->managerRegistry,
            $this->entityConfigProvider
        );
    }

    public function testIsGrantedByPropertyPath()
    {
        $address = new CmsAddress();
        $address->city = 'test';
        $user = new CmsUser();
        $user->id = 1;
        $user->setAddress($address);
        $article = new CmsArticle();
        $article->setAuthor($user);

        $addressMetadata = new ClassMetadata(get_class($address));
        $userMetadata = new ClassMetadata(get_class($user));
        $user->associationMappings = [
            'address' => ['targetEntity' => get_class($address)]
        ];
        $articleMetadata = new ClassMetadata(get_class($article));
        $articleMetadata->associationMappings = [
            'user' => ['targetEntity' => get_class($user)]
        ];

        $propertyPath = 'user.address.city';

        $em = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectManager')
            ->disableOriginalConstructor()
            ->getMock();
        $this->managerRegistry->expects($this->any())
            ->method('getManagerForClass')
            ->willReturn($em);
        $em->expects($this->any())
            ->method('getClassMetadata')
            ->willReturnMap(
                [
                    [get_class($address), $addressMetadata],
                    [get_class($user), $userMetadata],
                    [get_class($article), $articleMetadata]
                ]
            );

        $this->authorizationChecker->expects($this->any())
            ->method('isGranted')
            ->willReturnCallback(function ($permission, $object) {
                if ($object instanceof FieldVote) {
                    if ($object->getField() === 'city') {
                        return false;
                    }
                }

                return true;
            });

        $isGranted = $this->helper->isGrantedByPropertyPath($article, $propertyPath, 'EDIT');
        $this->assertFalse($isGranted);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Can't get entity manager for class stdClass
     */
    public function testIisGrantedByPropertyPathOnWrongClass()
    {
        $this->helper->isGrantedByPropertyPath(new \stdClass(), 'somePath', 'EDIT');
    }
}


text:
<?php

namespace Mautic\LeadBundle\Model;

use Mautic\CoreBundle\Model\FormModel;
use Mautic\LeadBundle\Entity\Lead;
use Mautic\LeadBundle\Entity\LeadNote;
use Mautic\LeadBundle\Event\LeadNoteEvent;
use Mautic\LeadBundle\LeadEvents;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

/**
 * Class NoteModel
 * {@inheritdoc}
 * @package Mautic\CoreBundle\Model\FormModel
 */
class NoteModel extends FormModel
{
    /**
     * @var Session
     */
    protected $session;

    /**
     * @param Session $session
     */
    public function setSession(Session $session)
    {
        $this->session = $session;
    }

    /**
     * {@inheritdoc}
     *
     * @return string
     */
    public function getRepository()
    {
        return $this->em->getRepository('MauticLeadBundle:LeadNote');
    }

    /**
     * {@inheritdoc}
     *
     * @return string
     */
    public function getPermissionBase()
    {
        return 'lead:notes';
    }

    /**
     * Get a specific entity or generate a new one if id is empty
     *
     * @param $id
     * @return null|object
     */
    public function getEntity($id = null)
    {
        if ($id === null) {
            return new LeadNote();
        }

        return parent::getEntity($id);
    }

    /**
     * {@inheritdoc}
     *
     * @param      $entity
     * @param      $formFactory
     * @param null $action
     * @param array $options
     * @return mixed
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     */
    public function createForm($entity, $formFactory, $action = null, $options = array())
    {
        if (!$entity instanceof LeadNote) {
            throw new MethodNotAllowedHttpException(array('LeadNote'));
        }
        $params = (!empty($action)) ? array('action' => $action) : array();
        return $formFactory->create('leadnote', $entity, $params);
    }

     /**
      * {@inheritdoc}
      *
      * @param $action
      * @param $event
      * @param $entity
      * @param $isNew
      * @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
      */
     protected function dispatchEvent($action, &$entity, $isNew = false, Event $event = null)
     {
         if (!$entity instanceof LeadNote) {
             throw new MethodNotAllowedHttpException(array('LeadNote'));
         }

         switch ($action) {
             case "pre_save":
                 $name = LeadEvents::NOTE_PRE_SAVE;
                 break;
             case "post_save":
                 $name = LeadEvents::NOTE_POST_SAVE;
                 break;
             case "pre_delete":
                 $name = LeadEvents::NOTE_PRE_DELETE;
                 break;
             case "post_delete":
                 $name = LeadEvents::NOTE_POST_DELETE;
                 break;
             default:
                 return null;
         }

         if ($this->dispatcher->hasListeners($name)) {
             if (empty($event)) {
                 $event = new LeadNoteEvent($entity, $isNew);
                 $event->setEntityManager($this->em);
             }

             $this->dispatcher->dispatch($name, $event);

             return $event;
         } else {
             return null;
         }
     }

    /**
     * @param Lead $lead
     * @param      $useFilters
     * @return mixed
     */
    public function getNoteCount(Lead $lead, $useFilters = false)
    {
        $filter   = ($useFilters) ? $this->session->get('mautic.lead.'.$lead->getId().'.note.filter', '') : null;
        $noteType = ($useFilters) ? $this->session->get('mautic.lead.'.$lead->getId().'.notetype.filter', array()) : null;

        return $this->getRepository()->getNoteCount($lead->getId(), $filter, $noteType);
    }
}


text:
import newProject from './newProject';

export default function (mainWindow) {
  newProject(mainWindow);
};


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

using System;
using Test.Common;

namespace LongHaulTest
{
    abstract class CommonArguments : Arguments
    {
        protected CommonArguments(string[] args, int start)
            : base(args, start)
        {
        }

        [Argument(Name = "address", Shortcut = "a", Description = "address of the remote peer or the local listener", Default = "amqp://guest:guest@127.0.0.1:5672")]
        public string Address
        {
            get;
            protected set;
        }

        [Argument(Name = "host", Shortcut = "h", Description = "host name to set on open", Default = null)]
        public string Host
        {
            get;
            protected set;
        }

        [Argument(Name = "node", Shortcut = "n", Description = "name of the AMQP node", Default = "q1")]
        public string Node
        {
            get;
            protected set;
        }

        [Argument(Name = "sync", Shortcut = "s", Description = "start a role using synchronous API", Default = true)]
        public bool Synchronous
        {
            get;
            protected set;
        }

        [Argument(Name = "async", Shortcut = "y", Description = "start a role using asynchronous API", Default = true)]
        public bool Asynchronous
        {
            get;
            protected set;
        }

        [Argument(Name = "duration", Shortcut = "d", Description = "duration in seconds (0=infinite)", Default = 5 * 60)]
        public int Duration
        {
            get;
            protected set;
        }

        [Argument(Name = "progess", Shortcut = "p", Description = "duration in seconds to report progress", Default = 10)]
        public int Progress
        {
            get;
            protected set;
        }

        [Argument(Name = "trace", Shortcut = "t", Description = "trace level: err|warn|info|verbose|frm", Default = "info")]
        public string Trace
        {
            get;
            set;
        }
    }
}


text:
package com.microrisc.simply.demos.automation.mqtt;

import com.microrisc.simply.demos.automation.AppStd;
import com.microrisc.simply.demos.automation.dpa.DPA_Request;
import com.microrisc.simply.demos.automation.dpa.DPA_Result;
import com.microrisc.simply.demos.automation.dpa.ResponseData;
import com.microrisc.simply.demos.automation.web.WebRequestParser;
import com.microrisc.simply.demos.automation.web.WebRequestParserException;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.sql.Timestamp;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Rostislav Spinar
 * @author Michal Konopa
 */
public class MqttCommunicator implements MqttCallback {

    private MqttClient client;
    private String brokerUrl;
    private boolean quietMode;
    private MqttConnectOptions conOpt;
    private boolean clean;
    private String password;
    private String userName;
    private String certFile;

    // time  between consecutive attempts to reconnection [in ms]
    private static final int DEFAULT_RECONNECTION_SLEEP_TIME = 3000;

    private Runnable reconnectionRunnable = new Runnable() {
        @Override
        public void run() {

            while ( (client != null) && !(client.isConnected()) ) {
                // Connect to the MQTT server
                log("Reconnecting to " + brokerUrl + " with client ID " + client.getClientId());

                try {
                    client.connect(conOpt);
                } catch ( MqttException ex ) {
                    log(
                        "Reconnecting to " + brokerUrl + " with client "
                        + "ID " + client.getClientId() + " failed: " + ex.getMessage()
                    );
                }

                if ( !client.isConnected() ) {
                   try {
                    Thread.sleep(DEFAULT_RECONNECTION_SLEEP_TIME);
                    } catch ( InterruptedException ex ) {
                        log.warn(ex.toString());
                    }
                }
            }
            log("Connected");
        }
    };

    private Thread reconnectionThread;

    private Runnable responseMessagesProcessorRunnable = new Runnable() {
        @Override
        public void run() {
            System.out.println("Response worker thread - message processing");

            if(!responseDataToPublish.isEmpty()) {
                Map<String, ResponseData> responseDataMap = responseDataToPublish.poll();
                processResponseData(responseDataMap);
            } else {
                System.out.println("Response worker thread - message buffer is empty");
            }
        }
    };

    private Thread responseMessagesThread;

    // response messages to publish
    private Queue<Map<String, ResponseData>> responseDataToPublish = new ConcurrentLinkedQueue<>();

    private void processResponseData(Map<String, ResponseData> responseDataMap) {

        Set<String> topics = responseDataMap.keySet();
        String topic = (String) topics.toArray()[0];

        // converting DPA result into web response form
        String webResponse = MqttFormatter.formatResponseData(responseDataMap.get(topic));

        System.out.println("Web topic: " + topic);
        System.out.println("Web response: " + webResponse);

        try {
            publish(topic, 0, webResponse.getBytes());
        } catch (MqttException ex) {
            System.err.println("Error while publishing web response message: " + ex);
        }
    }

    private static final Logger log = LoggerFactory.getLogger(MqttCommunicator.class);

    // sets connection options
    private void setConnectionOptions(
            boolean isCleanSession, String password, String userName, String certFile
    ) throws CertificateException, IOException, KeyStoreException,
            NoSuchAlgorithmException, KeyManagementException
    {
        conOpt.setCleanSession(isCleanSession);

        if ( !password.isEmpty() ) {
            conOpt.setPassword(password.toCharArray());
        }
        if ( !userName.isEmpty() ) {
            conOpt.setUserName(userName);
        }

        if ( !certFile.isEmpty() ) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");

            InputStream certFileInputStream = fullStream(certFile);
            Certificate ca = cf.generateCertificate(certFileInputStream);

            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            keyStore.setCertificateEntry("ca", ca);

            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLSv1");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            conOpt.setSocketFactory(sslContext.getSocketFactory());
        }
    }

    /**
     * Constructs an instance of the sample client wrapper
     *
     * @param MQTTConfig the configuration params of the server to connect to
     * @throws MqttException
     */
    public MqttCommunicator(MqttConfiguration mqttConfig) throws MqttException {

        String brokerUrl = mqttConfig.getProtocol() + mqttConfig.getBroker() + ":" + mqttConfig.getPort();

        this.brokerUrl = brokerUrl;
        this.quietMode = mqttConfig.isQuiteMode();
        this.clean = mqttConfig.isCleanSession();
        this.certFile = mqttConfig.getCertFilePath();
        this.userName = mqttConfig.getUsername();
        this.password = mqttConfig.getPassword();

    	//This sample stores in a temporary directory... where messages temporarily
        // stored until the message has been delivered to the server.
        //..a real application ought to store them somewhere
        // where they are not likely to get deleted or tampered with
        String tmpDir = System.getProperty("java.io.tmpdir");
        MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);

        try {
            // Construct the connection options object that contains connection parameters
            // such as cleanSession and LWT
            conOpt = new MqttConnectOptions();
            setConnectionOptions(clean, password, userName, certFile);

            // Construct an MQTT blocking mode client
            client = new MqttClient(this.brokerUrl, mqttConfig.getClientId(), dataStore);

            // Set this wrapper as the callback handler
            client.setCallback(this);

            // Connect to the MQTT server
            log("Connecting to " + brokerUrl + " with client ID " + client.getClientId());

            client.connect(conOpt);
            log("Connected");
        } catch (MqttException e) {
            e.printStackTrace();
            log("Unable to set up client: " + e.toString());
            System.exit(1);
        } catch (CertificateException e) {
            e.printStackTrace();
            log("Unable to set up client - certificate exception: " + e.toString());
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
            log("Unable to set up client - certificate exception in input stream: " + e.toString());
            System.exit(1);
        } catch (KeyStoreException e) {
            e.printStackTrace();
            log("Unable to set up client - certificate exception in key store: " + e.toString());
            System.exit(1);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            log("Unable to set up client - certificate exception in loading key store: " + e.toString());
            System.exit(1);
        } catch (KeyManagementException e) {
            e.printStackTrace();
            log("Unable to set up client - certificate exception in ssl context: " + e.toString());
            System.exit(1);
        }
    }

    /**
     * Publish / send a message to an MQTT server
     *
     * @param topicName the name of the topic to publish to
     * @param qos the quality of service to delivery the message at (0,1,2)
     * @param payload the set of bytes to send to the MQTT server
     * @throws MqttException
     */
    public synchronized void publish(String topicName, int qos, byte[] payload) throws MqttException {

        // Connect to the MQTT server
        //log("Connecting to " + brokerUrl + " with client ID " + client.getClientId());
        //client.connect(conOpt);
        //log("Connected");

        String time = new Timestamp(System.currentTimeMillis()).toString();
        log("Publishing at: " + time + " to topic \"" + topicName + "\" qos " + qos);

        // Create and configure a message
        MqttMessage message = new MqttMessage(payload);
        message.setQos(qos);

    	// Send the message to the server, control is not returned until
        // it has been delivered to the server meeting the specified
        // quality of service.
        client.publish(topicName, message);

        // Disconnect the client
        //client.disconnect();
        //log("Disconnected");
    }

    /**
     * Subscribe to a topic on an MQTT server. Once subscribed this method waits
     * for the messages to arrive from the server that match the subscription.
     * It continues listening for messages until the enter key is pressed.
     *
     * @param topicName to subscribe to (can be wild carded)
     * @param qos the maximum quality of service to receive messages at for this
     * subscription
     * @throws MqttException
     */
    public void subscribe(String topicName, int qos) throws MqttException {

        // Connect to the MQTT server
        //client.connect(conOpt);
        //log("Connected to " + brokerUrl + " with client ID " + client.getClientId());

    	// Subscribe to the requested topic
        // The QoS specified is the maximum level that messages will be sent to the client at.
        // For instance if QoS 1 is specified, any messages originally published at QoS 2 will
        // be downgraded to 1 when delivering to the client but messages published at 1 and 0
        // will be received at the same level they were published at.
        log("Subscribing to topic \"" + topicName + "\" qos " + qos);
        client.subscribe(topicName, qos);

        // Disconnect the client from the server
        //client.disconnect();
        //log("Disconnected");
    }

    /**
     * Utility method to handle logging. If 'quietMode' is set, this method does
     * nothing
     *
     * @param message the message to log
     */
    private void log(String message) {
        if (!quietMode) {
            System.out.println(message);
        }
    }

    /**
     * @see MqttCallback#connectionLost(Throwable)
     */
    public void connectionLost(Throwable cause) {
        log.debug("connectionLost - start: cause=" + cause.getMessage());

        // Called when the connection to the server has been lost.
        // An application may choose to implement reconnection
        // logic at this point. This sample simply exits.
        log("Connection to " + brokerUrl + " lost! " + cause);

        reconnectionThread = new Thread(reconnectionRunnable);
        reconnectionThread.start();

        log.debug("connectionLost - end");
    }

    /**
     * @see MqttCallback#deliveryComplete(IMqttDeliveryToken)
     */
    public void deliveryComplete(IMqttDeliveryToken token) {

        // Called when a message has been delivered to the
        // server. The token passed in here is the same one
        // that was passed to or returned from the original call to publish.
        // This allows applications to perform asynchronous
        // delivery without blocking until delivery completes.
        //
        // This sample demonstrates asynchronous deliver and
        // uses the token.waitForCompletion() call in the main thread which
        // blocks until the delivery has completed.
        // Additionally the deliveryComplete method will be called if
        // the callback is set on the client
        //
        // If the connection to the server breaks before delivery has completed
        // delivery of a message will complete after the client has re-connected.
        // The getPendingTokens method will provide tokens for any messages
        // that are still to be delivered.
    }

    /**
     * @see MqttCallback#messageArrived(String, MqttMessage)
     */
    public void messageArrived(String topic, MqttMessage message) throws MqttException {

        // Called when a message arrives from the server that matches any
        // subscription made by the client

        String time = new Timestamp(System.currentTimeMillis()).toString();
        System.out.println("Time:\t" + time
                           + "  Topic:\t" + topic
                           + "  Message:\t" + new String(message.getPayload())
                           + "  QoS:\t" + message.getQos());

        // message data
        final String messageData = new String(message.getPayload());

        DPA_Request dpaRequest = null;
        DPA_Result result = null;
        try {
            dpaRequest = WebRequestParser.parse( messageData );

            if(dpaRequest.getDpa().equalsIgnoreCase("req")) {
                result = AppStd.sendWebRequestToDpaNetwork(dpaRequest, topic);
            }
        } catch ( WebRequestParserException ex ) {
            System.err.println("Error while parsing web request: " + ex);
            return;
        }

        // no result - usually in the case of error
        if ( result == null ) {
            System.err.println("Null result from DPA.");
            return;
        }

        // holding topic and response data
        Map<String, ResponseData> responseDataMap = new LinkedHashMap<>();

        // creating data of response to publish
        ResponseData responseData = createResponseData(dpaRequest, result);

        // adding topic and response data
        responseDataMap.put(topic, responseData);

        // buffer and notify
        responseDataToPublish.add(responseDataMap);

        // process it
        responseMessagesThread = new Thread(responseMessagesProcessorRunnable);
        responseMessagesThread.start();
    }

    // creates response data for publishing
    private ResponseData createResponseData(DPA_Request request, DPA_Result result) {
        return new ResponseData(
                request.getN(),
                request.getSv(),
                String.valueOf(request.getPid()),
                result.getRequest().getNadr(),
                String.valueOf(result.getRequest().getPnum()),
                result.getRequest().getPcmd(),
                String.valueOf(result.getDpaAddInfo().getHwProfile()),
                String.valueOf(result.getDpaAddInfo().getResponseCode()),
                String.valueOf(result.getDpaAddInfo().getDPA_Value()),
                result.getRequest().getModuleId()
        );
    }

    /**
     *
Creates an InputStream from a file, and fills it with the complete
     * file. Thus, available() on the returned InputStream will return the
     * full number of bytes the file contains

     * @param fname The filename
     * @return The filled InputStream
     * @exception IOException, if the Streams couldn't be created.
     **/
    private InputStream fullStream ( String fname ) throws IOException {
        InputStream is = this.getClass().getResourceAsStream(fname);
        //FileInputStream fis = new FileInputStream(fname);

        DataInputStream dis = new DataInputStream(is);
        byte[] bytes = new byte[dis.available()];
        dis.readFully(bytes);
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        return bais;
    }
}


text:
package gigigo.com.orchextra.data.datasources.api.model.requests;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import gigigo.com.orchextra.data.datasources.api.model.responses.ApiPoint;

public class ApiGeoLocation {

  @Expose @SerializedName("country") private String country;

  @Expose @SerializedName("countryCode") private String countryCode;

  @Expose @SerializedName("locality") private String locality;

  @Expose @SerializedName("zip") private String zip;

  @Expose @SerializedName("street") private String street;

  @Expose @SerializedName("point") private ApiPoint point;

  public String getCountry() {
    return country;
  }

  public void setCountry(String country) {
    this.country = country;
  }

  public String getCountryCode() {
    return countryCode;
  }

  public void setCountryCode(String countryCode) {
    this.countryCode = countryCode;
  }

  public String getLocality() {
    return locality;
  }

  public void setLocality(String locality) {
    this.locality = locality;
  }

  public String getZip() {
    return zip;
  }

  public void setZip(String zip) {
    this.zip = zip;
  }

  public String getStreet() {
    return street;
  }

  public void setStreet(String street) {
    this.street = street;
  }

  public ApiPoint getPoint() {
    return point;
  }

  public void setPoint(ApiPoint point) {
    this.point = point;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <fixed facet="jst.ejb"/>
  <fixed facet="java"/>
  <installed facet="java" version="1.8"/>
  <installed facet="jst.ejb" version="3.1"/>
</faceted-project>