text:
#ifndef ALIFEMTOPARJPYTHIA_H
#define ALIFEMTOPARJPYTHIA_H

/* $Id$ */

//
// Generator using the TPythia interface (via AliPythia)
// to generate pp collisions.
// Using SetNuclei() also nuclear modifications to the structure functions
// can be taken into account. This makes, of course, only sense for the
// generation of the products of hard processes (heavy flavor, jets ...)
//
// andreas.morsch@cern.ch
//

#include "AliGenMC.h"
#include "AliPythia.h"

class AliPythia;
class TParticle;
class AliGenPythiaEventHeader;
class AliGenEventHeader;
class AliStack;
class AliRunLoader;
class TObjArray;

class AliFemtoPARJGenPythia : public AliGenMC
{
 public:

    typedef enum {kFlavorSelection, kParentSelection, kHeavyFlavor} StackFillOpt_t;
    typedef enum {kCountAll, kCountParents, kCountTrackables} CountMode_t;
    typedef enum {kCluster, kCell} JetRecMode_t;

    AliFemtoPARJGenPythia();
    AliFemtoPARJGenPythia(Int_t npart);
    virtual ~AliFemtoPARJGenPythia();
    virtual void    Generate();
    virtual void    Init();
    // Range of events to be printed
    virtual void    SetEventListRange(Int_t eventFirst=-1, Int_t eventLast=-1);
    // Select process type
    virtual void    SetProcess(Process_t proc = kPyCharm) {fProcess = proc;}
    virtual void    SetTune(Int_t itune) {fItune = itune;}
    virtual void    SetSeed(UInt_t seed);

    // Select structure function
    virtual void    SetStrucFunc(StrucFunc_t func =  kCTEQ5L) {fStrucFunc = func;}
    // Rewieght pt, hard spectrum with pT/p0^n, set power n
    virtual void    SetWeightPower(Float_t power = 0.) { fWeightPower = power; }
    // Select pt of hard scattering
    virtual void    SetPtHard(Float_t ptmin = 0, Float_t ptmax = 1.e10)
	{fPtHardMin = ptmin; fPtHardMax = ptmax; }
    // y of hard scattering
    virtual void    SetYHard(Float_t ymin = -1.e10, Float_t ymax = 1.e10)
	{fYHardMin = ymin; fYHardMax = ymax; }
    // Set initial and final state gluon radiation
    virtual void    SetGluonRadiation(Int_t iIn, Int_t iFin)
	{fGinit = iIn; fGfinal = iFin;}
    virtual void SetColorReconnectionOff(Int_t iflag=0){fCRoff=iflag;}
   // Intrinsic kT
    virtual void    SetPtKick(Float_t kt = 1.)
	{fPtKick = kt;}
    // Use the Pythia 6.3 new multiple interations scenario
    virtual void    UseNewMultipleInteractionsScenario() {fNewMIS = kTRUE;}
    // Switch off heavy flavors
    virtual void    SwitchHFOff() {fHFoff = kTRUE;}
    // Set centre of mass energy
    virtual void    SetEnergyCMS(Float_t energy = 5500) {fEnergyCMS = energy;}
    // Treat protons as inside nuclei with mass numbers a1 and a2
    virtual void    SetNuclei(Int_t a1, Int_t a2, Int_t pdfset = 0);
    // Set colliding nuclei ("p","n",...)
    virtual void    SetCollisionSystem(TString projectile, TString target) { fProjectile = projectile; fTarget = target; }
    virtual void    SetNuclearPDF(Int_t pdf) {fNucPdf = pdf;}
    virtual void    SetUseNuclearPDF(Bool_t val) {fUseNuclearPDF = val;}
    virtual void    SetUseLorentzBoost(Bool_t val) {fUseLorentzBoost = val;}
    //
    // Trigger options
    //
    // Energy range for jet trigger
    virtual void    SetJetEtRange(Float_t etmin = 0., Float_t etmax = 1.e4)
	{fEtMinJet = etmin; fEtMaxJet = etmax;}
    // Eta range for jet trigger
    virtual void    SetJetEtaRange(Float_t etamin = -20., Float_t etamax = 20.)
	{fEtaMinJet = etamin; fEtaMaxJet = etamax;}
    // Phi range for jet trigger
    virtual void    SetJetPhiRange(Float_t phimin = 0., Float_t phimax = 360.)
	{fPhiMinJet = TMath::Pi()*phimin/180.; fPhiMaxJet = TMath::Pi()*phimax/180.;}
    // Jet reconstruction mode; default is cone algorithm
    virtual void    SetJetReconstructionMode(Int_t mode = kCell) {fJetReconstruction = mode;}
    // Eta range for gamma trigger
    virtual void    SetGammaEtaRange(Float_t etamin = -20., Float_t etamax = 20.)
	{fEtaMinGamma = etamin; fEtaMaxGamma = etamax;}
    // Phi range for gamma trigger
    virtual void    SetGammaPhiRange(Float_t phimin = 0., Float_t phimax = 360.)
	{fPhiMinGamma = TMath::Pi()*phimin/180.; fPhiMaxGamma = TMath::Pi()*phimax/180.;}
    // Y range for heavy quark trigger
    virtual void    SetHeavyQuarkYRange(Float_t ymin=-20., Float_t ymax=20.){
      fYMinHQ = ymin;    fYMaxHQ=ymax;   fUseYCutHQ=kTRUE;
    }

    // Select events with fragmentation photon, decay photon, pi0 or eta going to PHOS or EMCAL and central barrel
    virtual Bool_t TriggerOnSelectedParticles(Int_t np);

    virtual void  SetCheckPHOS         (Bool_t b) {fCheckPHOS    = b;}
    virtual void  SetCheckEMCAL        (Bool_t b) {fCheckEMCAL   = b;}
    virtual void  SetCheckBarrel       (Bool_t b) {fCheckBarrel  = b;}

    //virtual void  SetElectronInEMCAL   (Bool_t b) {fEleInEMCAL   = b;}
    //virtual void  SetPhotonInPHOS      (Bool_t b) {fCheckPHOS    = b; fPhotonInCalo     = b;} // Not in use

    virtual void  SetFragPhotonInCalo  (Bool_t b) {                   fFragPhotonInCalo = b;}
    virtual void  SetFragPhotonInBarrel(Bool_t b) {fCheckBarrel  = b; fFragPhotonInCalo = b;}
    virtual void  SetFragPhotonInEMCAL (Bool_t b) {fCheckEMCAL   = b; fFragPhotonInCalo = b;}
    virtual void  SetFragPhotonInPHOS  (Bool_t b) {fCheckPHOS    = b; fFragPhotonInCalo = b;}

    virtual void  SetHadronInCalo      (Bool_t b) {                   fHadronInCalo     = b;}
    virtual void  SetHadronInBarrel    (Bool_t b) {fCheckBarrel  = b; fHadronInCalo     = b;}
    virtual void  SetHadronInEMCAL     (Bool_t b) {fCheckEMCAL   = b; fHadronInCalo     = b;}
    virtual void  SetHadronInPHOS      (Bool_t b) {fCheckPHOS    = b; fHadronInCalo     = b;}

    virtual void  SetElectronInCalo    (Bool_t b) {                   fEleInCalo        = b;}
    virtual void  SetElectronInBarrel  (Bool_t b) {fCheckBarrel  = b; fEleInCalo        = b;}
    virtual void  SetElectronInEMCAL   (Bool_t b) {fCheckEMCAL   = b; fEleInCalo        = b;}
    virtual void  SetElectronInPHOS    (Bool_t b) {fCheckPHOS    = b; fEleInCalo        = b;}

    virtual void  SetDecayPhotonInCalo (Bool_t d)  {fDecayPhotonInCalo = d;}
    virtual void  SetDecayPhotonInBarrel(Bool_t d) {fDecayPhotonInCalo = d; fCheckBarrel  = d;}
    virtual void  SetDecayPhotonInEMCAL(Bool_t d)  {fDecayPhotonInCalo = d; fCheckEMCAL   = d;}
    virtual void  SetDecayPhotonInPHOS (Bool_t d)  {fDecayPhotonInCalo = d; fCheckPHOS    = d;}

    virtual void  SetPi0InCalo         (Bool_t b, Bool_t f = kFALSE) {fPi0InCalo = b; fForceNeutralMeson2PhotonDecay = f;}
    virtual void  SetPi0InBarrel       (Bool_t b, Bool_t f = kFALSE) {fPi0InCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckBarrel= b; }
    virtual void  SetPi0InEMCAL        (Bool_t b, Bool_t f = kFALSE) {fPi0InCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckEMCAL = b; }
    virtual void  SetPi0InPHOS         (Bool_t b, Bool_t f = kFALSE) {fPi0InCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckPHOS  = b; }

    virtual void  SetEtaInCalo         (Bool_t b, Bool_t f = kFALSE) {fEtaInCalo = b; fForceNeutralMeson2PhotonDecay = f;}
    virtual void  SetEtaInBarrel       (Bool_t b, Bool_t f = kFALSE) {fEtaInCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckBarrel= b; }
    virtual void  SetEtaInEMCAL        (Bool_t b, Bool_t f = kFALSE) {fEtaInCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckEMCAL = b; }
    virtual void  SetEtaInPHOS         (Bool_t b, Bool_t f = kFALSE) {fEtaInCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckPHOS  = b; }

    virtual void  SetPi0PhotonDecayInBarrel(Bool_t b, Bool_t f = kFALSE) {fPi0InCalo = b; fDecayPhotonInCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckBarrel  = b; }
    virtual void  SetPi0PhotonDecayInEMCAL (Bool_t b, Bool_t f = kFALSE) {fPi0InCalo = b; fDecayPhotonInCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckEMCAL   = b; }
    virtual void  SetPi0PhotonDecayInPHOS  (Bool_t b, Bool_t f = kFALSE) {fPi0InCalo = b; fDecayPhotonInCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckPHOS    = b; }

    virtual void  SetEtaPhotonDecayInBarrel(Bool_t b, Bool_t f = kFALSE) {fEtaInCalo = b; fDecayPhotonInCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckBarrel  = b; }
    virtual void  SetEtaPhotonDecayInEMCAL (Bool_t b, Bool_t f = kFALSE) {fEtaInCalo = b; fDecayPhotonInCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckEMCAL   = b; }
    virtual void  SetEtaPhotonDecayInPHOS  (Bool_t b, Bool_t f = kFALSE) {fEtaInCalo = b; fDecayPhotonInCalo = b; fForceNeutralMeson2PhotonDecay = f; fCheckPHOS    = b; }

    // Trigger on a minimum multiplicity
    virtual void  SetTriggerChargedMultiplicity(Int_t multiplicity, Float_t etamax = 0, Float_t ptmin = -1.)
    {fTriggerMultiplicity = multiplicity; fTriggerMultiplicityEta = etamax;
      fTriggerMultiplicityPtMin = ptmin;}

    // Trigger on a minimum multiplicity for a given eta range
    virtual void  SetTriggerMultiplicityEtaRange(Int_t multiplicity, Float_t etamin = 0., Float_t etamax = 0., Float_t ptmin = -1.)
    {fTriggerMultiplicity = multiplicity; fTriggerMultiplicityEtaMin = etamin; fTriggerMultiplicityEtaMax = etamax;
      fTriggerMultiplicityPtMin = ptmin;}

    // Calorimeters acceptance
    // Set Phi in degrees, and Eta coverage, should not be negative
    virtual void  SetBarrelAcceptance(Float_t deta) {fTriggerEta = deta ;}
    virtual void  SetTriggerY(Float_t dy) {fTriggerY = dy;}
    virtual void  SetEMCALAcceptance (Float_t phimin, Float_t phimax, Float_t deta) {fEMCALMinPhi = phimin ; fEMCALMaxPhi = phimax ; fEMCALEta = deta ; }
    virtual void  SetPHOSAcceptance  (Float_t phimin, Float_t phimax, Float_t deta) {fPHOSMinPhi  = phimin ; fPHOSMaxPhi  = phimax ; fPHOSEta  = deta ; }
    virtual void  SetRotateParticleInPHOSeta(Bool_t b) {fCheckPHOSeta = b;}

    virtual void  SetTriggerParticleMinPt(Float_t pt) {fTriggerParticleMinPt = pt;}
//    virtual void  SetPhotonMinPt(Float_t pt)          {fPhotonMinPt = pt;}
//    virtual void  SetElectronMinPt(Float_t pt)        {fElectronMinPt = pt;}
    // Trigger and rotate event
    void RotatePhi(Bool_t& okdd);

    // Trigger on a single particle (not related to calorimeter trigger above)
    virtual void    SetTriggerParticle(Int_t particle = 0, Float_t etamax = 0.9, Float_t ptmin = -1, Float_t ptmax = 1000)
    {fTriggerParticle = particle; fTriggerEta = etamax; fTriggerEtaMin = etamax; fTriggerMinPt = ptmin; fTriggerMaxPt = ptmax;}
    virtual void    SetTriggerParticle(Int_t particle, Float_t etamin, Float_t etamax, Float_t ptmin, Float_t ptmax)
    {fTriggerParticle = particle; fTriggerEtaMin = etamin, fTriggerEta = etamax; fTriggerMinPt = ptmin; fTriggerMaxPt = ptmax;}

    //
    // Heavy flavor options
    //
    // Set option for feed down from higher family
    virtual void SetFeedDownHigherFamily(Bool_t opt) {
	fFeedDownOpt = opt;
    }
    // Set option for selecting particles kept in stack according to flavor
    // or to parent selection
    virtual void SetStackFillOpt(StackFillOpt_t opt) {
	fStackFillOpt = opt;
    }
    // Set fragmentation option
    virtual void SetFragmentation(Bool_t opt) {
	fFragmentation = opt;
    }
    // Set counting mode
    virtual void SetCountMode(CountMode_t mode) {
	fCountMode = mode;
    }
    //
    // Quenching
    //
    // Set quenching mode 0 = no, 1 = AM, 2 = IL,  3 = NA, 4 = ACS
    virtual void SetQuench(Int_t flag = 0) {fQuench = flag;}
    // Set transport coefficient.
    void SetQhat(Float_t qhat) {fQhat = qhat;}
    //Set initial medium length.
    void SetLength(Float_t length) {fLength = length;}
    //set parameters for pyquen afterburner
    virtual void SetPyquenPar(Float_t t0=1., Float_t tau0=0.1, Int_t nf=0,Int_t iengl=0, Int_t iangl=3)
    {fpyquenT = t0; fpyquenTau = tau0; fpyquenNf=nf;fpyquenEloss=iengl;fpyquenAngle=iangl;}
    virtual void SetHadronisation(Int_t flag = 1) {fHadronisation = flag;}
    virtual void SetPatchOmegaDalitz(Int_t flag = 1) {fPatchOmegaDalitz = flag;}
    virtual void SetDecayerExodus(Int_t flag = 1) {fDecayerExodus = flag;}
    virtual void SetReadFromFile(const Text_t *filname) {fkFileName = filname;  fReadFromFile = 1;}
    virtual void SetReadLHEF(const Text_t *filename) {fkNameLHEF = filename; fReadLHEF = 1;}

    //
    // Pile-up
    //
    // Get interaction rate for pileup studies
    virtual void    SetInteractionRate(Float_t rate,Float_t timewindow = 90.e-6);
    virtual Float_t GetInteractionRate() const {return fInteractionRate;}
    // get cross section of process
    virtual Float_t GetXsection() const {return fXsection;}
    // get triggered jets
    void GetJets(Int_t& njets, Int_t& ntrig, Float_t jets[4][10]);
    void RecJetsUA1(Int_t& njets, Float_t jets[4][50]);
    void SetPycellParameters(Float_t etamax = 2., Int_t neta = 274, Int_t nphi = 432,
			     Float_t thresh = 0., Float_t etseed = 4.,
			     Float_t minet = 10., Float_t r = 1.);

  void LoadEvent(AliStack* stack, Int_t flag = 0, Int_t reHadr = 0);
  void LoadEvent(const TObjArray* stack, Int_t flag = 0, Int_t reHadr = 0);
    // Getters
    virtual Process_t    GetProcess() const {return fProcess;}
    virtual StrucFunc_t  GetStrucFunc() const {return fStrucFunc;}
    virtual void         GetPtHard(Float_t& ptmin, Float_t& ptmax) const
	{ptmin = fPtHardMin; ptmax = fPtHardMax;}
    virtual void         GetNuclei(Int_t&  a1, Int_t& a2) const
	{a1 = fAProjectile; a2 = fATarget;}
    virtual void         GetJetEtRange(Float_t& etamin, Float_t& etamax) const
	{etamin = fEtaMinJet; etamax = fEtaMaxJet;}
    virtual void         GetJetPhiRange(Float_t& phimin, Float_t& phimax) const
	{phimin = fPhiMinJet*180./TMath::Pi(); phimax = fPhiMaxJet*180/TMath::Pi();}
    virtual void         GetGammaEtaRange(Float_t& etamin, Float_t& etamax) const
	{etamin = fEtaMinGamma; etamax = fEtaMaxGamma;}
    virtual void         GetGammaPhiRange(Float_t& phimin, Float_t& phimax) const
	{phimin = fPhiMinGamma*180./TMath::Pi(); phimax = fPhiMaxGamma*180./TMath::Pi();}
    //
    Bool_t CheckDetectorAcceptance(Float_t phi, Float_t eta, Int_t iparticle);
    Bool_t IsInEMCAL (Float_t phi, Float_t eta) const;
    Bool_t IsInPHOS  (Float_t phi, Float_t eta, Int_t iparticle) ;
    Bool_t IsInBarrel(Float_t eta) const;
    Bool_t IsFromHeavyFlavor(Int_t ipart);
    //
    virtual void FinishRun();
    Bool_t CheckTrigger(const TParticle* jet1, const TParticle* jet2);
    //Used in some processes to selected child properties
    Bool_t CheckKinematicsOnChild();
    void     GetSubEventTime();

    void SetTuneForDiff(Bool_t a=kTRUE) {fkTuneForDiff=a;}
    AliDecayer * GetDecayer(){return fDecayer;}

    //baryon production
    void SetUseFemtoPARJ(Bool_t val) {fUseFemtoPARJ = val;}
    void SetPARJ1(Float_t p) {fPARJ_1 = p;}
    void SetPARJ2(Float_t p) {fPARJ_2 = p;}
    void SetPARJ3(Float_t p) {fPARJ_3 = p;}
    void SetPARJ4(Float_t p) {fPARJ_4 = p;}
    void SetPARJ5(Float_t p) {fPARJ_5 = p;}
    void SetPARJ6(Float_t p) {fPARJ_6 = p;}
    void SetPARJ7(Float_t p) {fPARJ_7 = p;}
    void SetPARJ8(Float_t p) {fPARJ_8 = p;}
    void SetPARJ9(Float_t p) {fPARJ_9 = p;}
    void SetPARJ10(Float_t p) {fPARJ_10 = p;}

 protected:
    // adjust the weight from kinematic cuts
    void     AdjustWeights() const;
    Int_t    GenerateMB();
    void     MakeHeader();
    void     GeneratePileup();
    Process_t   fProcess;           //Process type
    Int_t       fItune;             // Pythia tune > 6.4
    StrucFunc_t fStrucFunc;         //Structure Function
    Float_t     fKineBias;          //!Bias from kinematic selection
    Int_t       fTrials;            //!Number of trials for current event
    Int_t       fTrialsRun;         //!Number of trials for run
    Float_t     fQ;                 //Mean Q
    Float_t     fX1;                //Mean x1
    Float_t     fX2;                //Mean x2
    Float_t     fEventTime;         //Time of the subevent
    Float_t     fInteractionRate;   //Interaction rate (set by user)
    Float_t     fTimeWindow;        //Time window for pileup events (set by user)
    Int_t       fCurSubEvent;       //Index of the current sub-event
    TArrayF     *fEventsTime;       //Subevents time for pileup
    Int_t       fNev;               //Number of events
    Int_t       fFlavorSelect;      //Heavy Flavor Selection
    Float_t     fXsection;          //Cross-section
    AliPythia   *fPythia;           //!Pythia
    Float_t     fWeightPower;       //power for cross section weights; 0 means no reweighting
    Float_t     fPtHardMin;         //lower pT-hard cut
    Float_t     fPtHardMax;         //higher pT-hard cut
    Float_t     fYHardMin;          //lower  y-hard cut
    Float_t     fYHardMax;          //higher y-hard cut
    Int_t       fGinit;             //initial state gluon radiation
    Int_t       fGfinal;            //final state gluon radiation
    Int_t       fCRoff;             //color reconnection off in the pythia6 annealying model
    Int_t       fHadronisation;     //hadronisation
    Bool_t      fPatchOmegaDalitz;  //flag for omega dalitz decay patch
    Bool_t      fDecayerExodus;     //flag for exodus decayer
    Int_t       fNpartons;          //Number of partons before hadronisation
    Int_t       fReadFromFile;      //read partons from file
    Int_t       fReadLHEF;          //read lhef file
    Int_t       fQuench;            //Flag for quenching
    Float_t     fQhat;              //Transport coefficient (GeV^2/fm)
    Float_t     fLength;            //Medium length (fm)
    Float_t     fpyquenT;           //Pyquen initial temperature
    Float_t     fpyquenTau;         //Pyquen initial proper time
    Int_t       fpyquenNf;          //Pyquen number of flavours into the game
    Int_t       fpyquenEloss;       //Pyquen type of energy loss
    Int_t       fpyquenAngle;       //Pyquen radiation angle for gluons
    Float_t     fImpact;            //Impact parameter for quenching simulation (q-pythia)
    Float_t     fPtKick;            //Transverse momentum kick
    Bool_t      fFullEvent;         //!Write Full event if true
    AliDecayer  *fDecayer;          //!Pointer to the decayer instance
    Int_t       fDebugEventFirst;   //!First event to debug
    Int_t       fDebugEventLast;    //!Last  event to debug
    Float_t     fEtMinJet;          //Minimum et of triggered Jet
    Float_t     fEtMaxJet;          //Maximum et of triggered Jet
    Float_t     fEtaMinJet;         //Minimum eta of triggered Jet
    Float_t     fEtaMaxJet;         //Maximum eta of triggered Jet
    Float_t     fPhiMinJet;         //Minimum phi of triggered Jet
    Float_t     fPhiMaxJet;         //Maximum phi of triggered Jet
    Int_t       fJetReconstruction; //Jet Reconstruction mode
    Float_t     fEtaMinGamma;       // Minimum eta of triggered gamma
    Float_t     fEtaMaxGamma;       // Maximum eta of triggered gamma
    Float_t     fPhiMinGamma;       // Minimum phi of triggered gamma
    Float_t     fPhiMaxGamma;       // Maximum phi of triggered gamma
    Bool_t      fUseYCutHQ;         // siwtch for using y cut for heavy quarks
    Float_t     fYMinHQ;            // Minimum y of triggered heavy quarks
    Float_t     fYMaxHQ;            // Maximum y of triggered heavy quarks
    Float_t     fPycellEtaMax;      // Max. eta for Pycell
    Int_t       fPycellNEta;        // Number of eta bins for Pycell
    Int_t       fPycellNPhi;        // Number of phi bins for Pycell
    Float_t	fPycellThreshold;   // Pycell threshold
    Float_t 	fPycellEtSeed;      // Pycell seed
    Float_t	fPycellMinEtJet;    // Pycell min. jet et
    Float_t	fPycellMaxRadius;   // Pycell cone radius
    StackFillOpt_t fStackFillOpt;   // Stack filling with all particles with
                                    // that flavour or only with selected
                                    // parents and their decays
    Bool_t fFeedDownOpt;            // Option to set feed down from higher
                                    // quark families (e.g. b->c)
    Bool_t  fFragmentation;         // Option to activate fragmentation by Pythia
    Bool_t  fSetNuclei;             // Flag indicating that SetNuclei has been called
    Bool_t  fUseNuclearPDF;         // flag if nuclear pdf should be applied
    Bool_t  fUseLorentzBoost;       // flag if lorentz boost should be applied
    Bool_t  fNewMIS;                // Flag for the new multipple interactions scenario
    Bool_t  fHFoff;                 // Flag for switching heafy flavor production off
    Int_t   fNucPdf;                // Nuclear pdf 0: EKS98 1: EPS08
    Int_t   fTriggerParticle;       // Trigger on this particle ...
    Float_t fTriggerEta;            // .. within |eta| < fTriggerEta
    Float_t fTriggerY;              // .. within |y|   < fTriggerEta
    Float_t fTriggerEtaMin;         // .. within fTriggerEtaMin < eta < fTriggerEta
    Float_t fTriggerMinPt;          // .. within pt > fTriggerMinPt
    Float_t fTriggerMaxPt;          // .. within pt < fTriggerMaxPt
    Int_t       fTriggerMultiplicity;       // Trigger on events with a minimum charged multiplicity
    Float_t     fTriggerMultiplicityEta;    // in a given eta range
    Float_t     fTriggerMultiplicityEtaMin;    // in a given eta min
    Float_t     fTriggerMultiplicityEtaMax;    // in a given eta max
    Float_t     fTriggerMultiplicityPtMin;  // above this pT
    CountMode_t fCountMode;         // Options for counting when the event will be finished.
    // fCountMode = kCountAll         --> All particles that end up in the
    //                                    stack are counted
    // fCountMode = kCountParents     --> Only selected parents are counted
    // fCountMode = kCountTrackabless --> Only particles flagged for tracking
    //                                     are counted
    //
    //

    AliGenPythiaEventHeader* fHeader;  //! Event header
    AliRunLoader*            fRL;      //! Run Loader
    const Text_t* fkFileName;          //! Name of file to read from
    const Text_t* fkNameLHEF;          //! Name of lhef file to read from
    Bool_t fFragPhotonInCalo; // Option to ask for Fragmentation Photon in calorimeters acceptance
    Bool_t fHadronInCalo;     // Option to ask for hadron (not pi0) in calorimeters acceptance
    Bool_t fPi0InCalo;        // Option to ask for Pi0 in calorimeters acceptance
    Bool_t fEtaInCalo;        // Option to ask for Eta in calorimeters acceptance
    Bool_t fPhotonInCalo;     // Option to ask for Photon in calorimeter acceptance (not in use)
    Bool_t fDecayPhotonInCalo;// Option to ask for Decay Photon in calorimeter acceptance
    Bool_t fForceNeutralMeson2PhotonDecay; // Option to ask for Pi0/Eta in calorimeters acceptance when decay into 2 photons
    Bool_t fEleInCalo;        // Option to ask for Electron in EMCAL acceptance
    Bool_t fEleInEMCAL;       // Option to ask for Electron in EMCAL acceptance (not in use)
    Bool_t fCheckBarrel;      // Option to ask for FragPhoton or Pi0 or Eta or gamma decays in central barrel acceptance
    Bool_t fCheckEMCAL;       // Option to ask for FragPhoton or Pi0 or Eta or gamma decays in calorimeters EMCAL acceptance
    Bool_t fCheckPHOS;        // Option to ask for FragPhoton or Pi0 or Eta or gamma decays in calorimeters PHOS acceptance
    Bool_t fCheckPHOSeta;     // Option to ask for rotate event particles in phi to have in PHOS acceptance a requested particle that previously had the good eta
    Int_t  fPHOSRotateCandidate; // Internal member to select the particle candidate to trigger the event phi rotation, to put it in PHOS phi acceptance
    Float_t fTriggerParticleMinPt; // Minimum momentum of Fragmentation Photon or Pi0 or other hadron
    Float_t fPhotonMinPt;          // Minimum momentum of Photon  (not in use)
    Float_t fElectronMinPt;        // Minimum momentum of Electron (not in use)
    //Calorimeters eta-phi acceptance
    Float_t fPHOSMinPhi;           // Minimum phi PHOS, degrees
    Float_t fPHOSMaxPhi;           // Maximum phi PHOS, degrees
    Float_t fPHOSEta;              // Minimum eta PHOS, coverage delta eta
    Float_t fEMCALMinPhi;          // Minimum phi EMCAL, degrees
    Float_t fEMCALMaxPhi;          // Maximum phi EMCAL, degrees
    Float_t fEMCALEta;             // Maximum eta EMCAL, coverage delta eta

    Bool_t fkTuneForDiff;    // Pythia tune
    Int_t  fProcDiff;

    // baryons
    Bool_t fUseFemtoPARJ;
    Float_t fPARJ_1; // PARJ parameter number 1 (baryons)
    Float_t fPARJ_2; // PARJ parameter number 2 (baryons)
    Float_t fPARJ_3; // PARJ parameter number 3 (baryons)
    Float_t fPARJ_4; // PARJ parameter number 4 (baryons)
    Float_t fPARJ_5; // PARJ parameter number 5 (baryons)
    Float_t fPARJ_6; // PARJ parameter number 6 (baryons)
    Float_t fPARJ_7; // PARJ parameter number 7 (baryons)
    Float_t fPARJ_8; // PARJ parameter number 8 (baryons)
    Float_t fPARJ_9; // PARJ parameter number 8 (baryons)
    Float_t fPARJ_10; // PARJ parameter number 8 (baryons)
 private:
    AliFemtoPARJGenPythia(const AliFemtoPARJGenPythia &Pythia);
    AliFemtoPARJGenPythia & operator=(const AliFemtoPARJGenPythia & rhs);

    Bool_t CheckDiffraction();
    Bool_t GetWeightsDiffraction(Double_t M, Double_t &Mmin, Double_t &Mmax,
					       Double_t &wSD, Double_t &wDD, Double_t &wND);

    ClassDef(AliFemtoPARJGenPythia, 15) // AliGenerator interface to Pythia
};
#endif


text:
> Compile object rest and spread to ES5

See our website [@babel/plugin-proposal-object-rest-spread](https://babeljs.io/docs/en/babel-plugin-proposal-object-rest-spread) for more information.

## Install

Using npm:

```sh
npm install --save-dev @babel/plugin-proposal-object-rest-spread
```

or using yarn:

```sh
yarn add @babel/plugin-proposal-object-rest-spread --dev
```

redpajama_set_name: RedPajamaGithub


text:
package com.cyphercove.doublehelix;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.InputProcessor;

public class FlippingInputMultiplexer extends InputMultiplexer {

    public FlippingInputMultiplexer() {
        super();
    }

    public FlippingInputMultiplexer(InputProcessor... processors) {
        super(processors);
    }

    private int applyX (int screenX){
        if (Settings.flipH)
            return Gdx.graphics.getWidth() - screenX;
        return screenX;
    }

    private int applyY (int screenY){
        if (Settings.flipV)
            return Gdx.graphics.getHeight() - screenY;
        return screenY;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        return super.touchDown(applyX(screenX), applyY(screenY), pointer, button);
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        return super.touchUp(applyX(screenX), applyY(screenY), pointer, button);
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return super.touchDragged(applyX(screenX), applyY(screenY), pointer);
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return super.mouseMoved(applyX(screenX), applyY(screenY));
    }
}


text:
var RegEx = function() {

  var specialChars = '\\^${}[]().*+?|<>-&'.split('');

  var escapeChar = function(char) {
    if (specialChars.indexOf(char) == -1)
      return char;
    return '\\' + char;
  };

  var buildEscapedChars = function(charsStr) {
    var chars = charsStr.split('');

    for (var i = 0; i < chars.length; i++)
      chars[i] = escapeChar(chars[i]);

    return chars;
  };

  return {
    delimiter:function(charsStr) {
      var chars = buildEscapedChars(charsStr);
      var rePattern = '[' + chars.join('|') + ']';
      return new RegExp(rePattern, 'g');
    },
    squishyMatch:function(charsStr) {
      var chars = buildEscapedChars(charsStr);
      var rePattern = chars.join('.*');
      return new RegExp(rePattern);
    }
  };

};


text:
module tetra.common {
    import SessionService = tetra.auth.SessionService;
    import AuthService = tetra.auth.AuthService;
    import LoggedInUser = tetra.auth.LoggedInUser;
    import Notifier = tetra.common.Notifier;
    import IProjectSummaryData = tetra.services.IProjectSummaryData;

    export class RootController {
        private $location: ng.ILocationService;
        private sessionService: SessionService;
        private notifier: Notifier;

        constructor($location: ng.ILocationService, sessionService: SessionService, notifier: Notifier) {
            this.$location = $location;
            this.sessionService = sessionService;
            this.notifier = notifier;
        }

        get isLoggedIn(): boolean {
            return this.sessionService.isLoggedIn;
        }

        get currentUser(): LoggedInUser {
            return this.sessionService.currentUser;
        }

        get currentProjectCode(): string {
            return this.sessionService.selectedProjectCode;
        }

        get currentProject(): IProjectSummaryData {
            return this.sessionService.selectedProject;
        }

        changeProject(projectCode: string): void {
            this.sessionService.setCurrentProject(projectCode);
        }

        logout(): void {
            this.sessionService.logoutUser()
                .then(() => {
                    this.notifier.success('Successfully logged out!');
                    this.$location.path('/login')
                })
                .catch(err => this.notifier.error(err, 'Error logging out'));
        }

        isActive(...paths: string[]): boolean {
            return Enumerable.from(paths).any(path => this.isPathActive(path));
        }

        private isPathActive(path: string): boolean {
            var activePath = this.$location.path(),
                activeParts = activePath.split('/').filter(str => !!str),
                pathParts = path.split('/').filter(str => !!str);

            if (pathParts.length !== activeParts.length) {
                return false;
            }

            for(var i = 0; i < activeParts.length; i++) {
                var currentExpected = pathParts[i].toLowerCase(),
                    currentActive = activeParts[i].toLowerCase();

                if (currentExpected === '*') {
                    continue;
                }

                if (currentExpected !== currentActive) {
                    return false;
                }
            }

            return true;
        }
    }

    angular.module('app').controller('rootCtrl', RootController);
}


text:
from .tags import TagPatterns

class Criticality(object):

    def __init__(self, critical_tags=None, non_critical_tags=None):
        self.critical_tags = TagPatterns(critical_tags)
        self.non_critical_tags = TagPatterns(non_critical_tags)

    def tag_is_critical(self, tag):
        return self.critical_tags.match(tag)

    def tag_is_non_critical(self, tag):
        return self.non_critical_tags.match(tag)

    def test_is_critical(self, test):
        if self.critical_tags and not self.critical_tags.match(test.tags):
            return False
        return not self.non_critical_tags.match(test.tags)

    def __nonzero__(self):
        return bool(self.critical_tags or self.non_critical_tags)


text:
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type weatherProvider interface {
	temperature(city string) (float64, error) // in Kelvin
}

type Coord struct {
	Lon float64
	Lat float64
}
type multiWeatherProvider []weatherProvider
type openWeatherMap struct{}
type weatherUnderground struct {
	apiKey string
}
type forecastIo struct {
	apiKey string
}

func FloatToString(input_num float64) string {
	return strconv.FormatFloat(input_num, 'f', 2, 64)
}

func FahrenheitToCelsius(input_num float64) float64 {
	result := (input_num - 32) * 5 / 9
	return result
}

func (w forecastIo) temperature(city string) (float64, error) {
	coord, err := openWeatherMap{}.coordinates(city)
	if err != nil {
		return 0, err
	}

	url := "https://api.forecast.io/forecast/" + w.apiKey + "/" + FloatToString(coord.Lat) + "," + FloatToString(coord.Lon)

	resp, err := http.Get(url)
	if err != nil {
		return 0, err
	}

	defer resp.Body.Close()

	var d struct {
		Currently struct {
			Fahrenheit float64 `json:"temperature"`
		} `json:"currently"`
	}

	if err := json.NewDecoder(resp.Body).Decode(&d); err != nil {
		return 0, err
	}

	log.Printf("forecastIo: %s: %.2f", city, FahrenheitToCelsius(d.Currently.Fahrenheit))
	return FahrenheitToCelsius(d.Currently.Fahrenheit), nil
}

func (w openWeatherMap) coordinates(city string) (Coord, error) {
	resp, err := http.Get("http://api.openweathermap.org/data/2.5/weather?q=" + city)
	if err != nil {
		return Coord{}, nil
	}

	defer resp.Body.Close()

	var d struct {
		Coord struct {
			Lon float64 `json:"lon"`
			Lat float64 `json:"lat"`
		} `json:"coord"`
	}

	if err := json.NewDecoder(resp.Body).Decode(&d); err != nil {
		return Coord{}, nil
	}

	return Coord{d.Coord.Lon, d.Coord.Lat}, nil
}

func (w openWeatherMap) temperature(city string) (float64, error) {
	resp, err := http.Get("http://api.openweathermap.org/data/2.5/weather?q=" + city)
	if err != nil {
		return 0, err
	}

	defer resp.Body.Close()

	var d struct {
		Main struct {
			Kelvin float64 `json:"temp"`
		} `json:"main"`
	}

	if err := json.NewDecoder(resp.Body).Decode(&d); err != nil {
		return 0, err
	}

	celsius := d.Main.Kelvin - 273.15
	log.Printf("openWeatherMap: %s: %.2f", city, celsius)
	return celsius, nil
}

func (w weatherUnderground) temperature(city string) (float64, error) {
	resp, err := http.Get("http://api.wunderground.com/api/" + w.apiKey + "/conditions/q/" + city + ".json")
	if err != nil {
		return 0, err
	}

	defer resp.Body.Close()

	var d struct {
		Observation struct {
			Celsius float64 `json:"temp_c"`
		} `json:"current_observation"`
	}

	if err := json.NewDecoder(resp.Body).Decode(&d); err != nil {
		return 0, err
	}

	log.Printf("weatherUnderground: %s, %.2f", city, d.Observation.Celsius)
	return d.Observation.Celsius, err
}

func (w multiWeatherProvider) temperature(city string) (float64, error) {
	temps := make(chan float64, len(w))
	errs := make(chan error, len(w))

	for _, provider := range w {
		go func(p weatherProvider) {
			k, err := p.temperature(city)
			if err != nil {
				errs <- err
				return
			}
			temps <- k
		}(provider)
	}

	sum := 0.0

	for i := 0; i < len(w); i++ {
		select {
		case temp := <-temps:
			sum += temp

		case err := <-errs:
			return 0, err
		}
	}

	return sum / float64(len(w)), nil
}

func main() {

	http.HandleFunc("/", hello)
	http.HandleFunc("/coordinates/", coordinates)
	http.HandleFunc("/weather/", weather)

	http.ListenAndServe(":8080", nil)
}

func hello(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello!"))
}

func coordinates(w http.ResponseWriter, r *http.Request) {
	city := strings.SplitN(r.URL.Path, "/", 3)[2]

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	lat, err := openWeatherMap{}.coordinates(city)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	json.NewEncoder(w).Encode(map[string]interface{}{
		"city": city,
		"temp": lat,
	})
}

func weather(w http.ResponseWriter, r *http.Request) {
	mw := multiWeatherProvider{
		openWeatherMap{},
		weatherUnderground{apiKey: "1df429f462bc7ee1"},
		forecastIo{apiKey: "12e03ff21975540f37c2b8cc79e3093b"},
	}

	begin := time.Now()
	city := strings.SplitN(r.URL.Path, "/", 3)[2]

	temp, err := mw.temperature(city)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"city": city,
		"temp": temp,
		"took": time.Since(begin).String(),
	})
}


text:
using SerializationTypes;
using System.IO;
using System.Runtime.Serialization;
using Xunit;

public static partial class DataContractSerializerTests
{
	[Fact]
    public static void DCS_MyPersonSurrogate()
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof(Family));
        dcs.SetSerializationSurrogateProvider(new MyPersonSurrogateProvider());
        MemoryStream ms = new MemoryStream();
        Family myFamily = new Family
        {
            Members = new NonSerializablePerson[]
            {
                new NonSerializablePerson("John", 34),
                new NonSerializablePerson("Jane", 32),
                new NonSerializablePerson("Bob", 5),
            }
        };
        dcs.WriteObject(ms, myFamily);
        ms.Position = 0;
        var newFamily = (Family)dcs.ReadObject(ms);
        Assert.StrictEqual(myFamily.Members.Length, newFamily.Members.Length);
        for (int i = 0; i < myFamily.Members.Length; ++i)
        {
            Assert.StrictEqual(myFamily.Members[i].Name, newFamily.Members[i].Name);
        }
    }

    [Fact]
    public static void DCS_FileStreamSurrogate()
    {
        const string TestFileName = "Test.txt";
        const string TestFileData = "Some data for data contract surrogate test";

        // Create the serializer and specify the surrogate
        var dcs = new DataContractSerializer(typeof(MyFileStream));
        dcs.SetSerializationSurrogateProvider(MyFileStreamSurrogateProvider.Singleton);

        // Create and initialize the stream
        byte[] serializedStream;

        // Serialize the stream
        using (MyFileStream stream1 = new MyFileStream(TestFileName))
        {
            stream1.WriteLine(TestFileData);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                dcs.WriteObject(memoryStream, stream1);
                serializedStream = memoryStream.ToArray();
            }
        }

        // Deserialize the stream
        using (MemoryStream stream = new MemoryStream(serializedStream))
        {
            using (MyFileStream stream2 = (MyFileStream)dcs.ReadObject(stream))
            {
                string fileData = stream2.ReadLine();
                Assert.StrictEqual(TestFileData, fileData);
            }
        }
    }
}


text:
import { __Schema } from '../introspection';

import { GraphQLSchema } from '../schema';

import {
  GraphQLInputObjectType,
  GraphQLInterfaceType,
  GraphQLList,
  GraphQLNonNull,
  GraphQLObjectType,
  GraphQLUnionType
} from '../definition';

import { GraphQLFloat } from '../scalars';

import { validateSchema } from '../validator';

import InterfacePossibleTypesMustImplementTheInterface
  from '../rules/InterfacePossibleTypesMustImplementTheInterface';
import NoInputTypesAsOutputFields from '../rules/NoInputTypesAsOutputFields';
import NoOutputTypesAsInputArgs from '../rules/NoOutputTypesAsInputArgs';
import TypesInterfacesMustShowThemAsPossible
  from '../rules/TypesInterfacesMustShowThemAsPossible';

import { describe, it } from 'mocha';
import { expect } from 'chai';

var SomeInputType = new GraphQLInputObjectType({
  name: 'SomeInputType',
  fields: {
    val: { type: GraphQLFloat, defaultValue: 42 }
  }
});

describe('Type System Validator', () => {
  it('passes on the introspection schema', () => {
    var validationErrors = validateSchema(new GraphQLSchema({
      query: __Schema
    }));
    expect(validationErrors).to.have.length(0);
  });
});

function expectToAcceptSchemaWithNormalInputArg(rule) {
  let SomeOutputType = new GraphQLObjectType({
    name: 'SomeOutputType',
    fields: {
      fieldWithArg: {
        args: { someArg: { type: SomeInputType } },
        type: GraphQLFloat
      }
    }
  });
  var schema = new GraphQLSchema({ query: SomeOutputType });
  var validationErrors = validateSchema(schema, [ rule ]);
  expect(validationErrors).to.have.length(0);
}

describe('Rule: NoInputTypesAsOutputFields', () => {
  function expectedError(operationType) {
    return `Schema ${operationType} type SomeInputType must be an object type!`;
  }

  function checkValidationResult(validationErrors, operationType) {
    expect(validationErrors).to.have.length(1);
    expect(validationErrors[0].message).to.equal(
      expectedError(operationType)
    );
  }

  it('rejects a schema whose query or mutation type is an input type', () => {
    let schema = new GraphQLSchema({ query: SomeInputType });
    let validationErrors = validateSchema(
      schema,
      [ NoInputTypesAsOutputFields ]
    );
    checkValidationResult(validationErrors, 'query');

    schema = new GraphQLSchema({ mutation: SomeInputType });
    validationErrors = validateSchema(schema, [ NoInputTypesAsOutputFields ]);
    checkValidationResult(validationErrors, 'mutation');
  });

  it('rejects a schema that uses an input type as a field', () => {
    [ GraphQLObjectType, GraphQLInterfaceType ].forEach((kind) => {
      var SomeOutputType = new kind({
        name: 'SomeOutputType',
        fields: {
          sneaky: { type: SomeInputType }
        }
      });

      var schema = new GraphQLSchema({ query: SomeOutputType });
      var validationErrors = validateSchema(
        schema,
        [ NoInputTypesAsOutputFields ]
      );
      expect(validationErrors).to.have.length(1);
      expect(validationErrors[0].message).to.equal(
        'Field SomeOutputType.sneaky is of type SomeInputType, which is an ' +
          'input type, but field types must be output types!'
      );
    });
  });

  it('accepts a schema that simply has an input type as a field arg', () => {
    expectToAcceptSchemaWithNormalInputArg(NoInputTypesAsOutputFields);
  });
});

describe('Rule: NoOutputTypesAsInputArgs', () => {

  function schemaWithFieldArgOfType(argType) {
    var SomeIncorrectInputType = new GraphQLInputObjectType({
      name: 'SomeIncorrectInputType',
      fields: {
        val: { type: argType }
      }
    });
    var QueryType = new GraphQLObjectType({
      name: 'QueryType',
      fields: {
        f2: {
          type: GraphQLFloat,
          args: { arg: { type: SomeIncorrectInputType } }
        }
      }
    });

    return new GraphQLSchema({ query: QueryType });
  }

  function expectRejectionBecauseFieldIsNotInputType(
    validationErrors,
    fieldTypeName
  ) {
    expect(validationErrors).to.have.length(1);
    expect(validationErrors[0].message).to.equal(
      `Input field SomeIncorrectInputType.val has type ${fieldTypeName}, ` +
      'which is not an input type!'
    );
  }

  function testAcceptingFieldArgOfType(fieldArgType) {
    var schema = schemaWithFieldArgOfType(fieldArgType);
    var validationErrors = validateSchema(schema, [ NoOutputTypesAsInputArgs ]);
    expect(validationErrors).to.have.length(0);
  }

  function testRejectingFieldArgOfType(fieldArgType) {
    var schema = schemaWithFieldArgOfType(fieldArgType);
    var validationErrors = validateSchema(schema, [ NoOutputTypesAsInputArgs ]);
    expectRejectionBecauseFieldIsNotInputType(
      validationErrors,
      fieldArgType
    );
  }

  it('accepts a schema that simply has an input type as a field arg', () => {
    expectToAcceptSchemaWithNormalInputArg(NoOutputTypesAsInputArgs);
  });

  it('rejects a schema with an object type as an input field arg', () => {
    var SomeOutputType = new GraphQLObjectType({
      name: 'SomeOutputType',
      fields: { f: { type: GraphQLFloat } }
    });
    testRejectingFieldArgOfType(SomeOutputType);
  });

  it('rejects a schema with a union type as an input field arg', () => {
    var UnionType = new GraphQLUnionType({
      name: 'UnionType',
      types: [
        new GraphQLObjectType({
          name: 'SomeOutputType',
          fields: { f: { type: GraphQLFloat } }
        })
      ]
    });
    testRejectingFieldArgOfType(UnionType);
  });

  it('rejects a schema with an interface type as an input field arg', () => {
    var InterfaceType = new GraphQLInterfaceType({
      name: 'InterfaceType',
      fields: []
    });
    testRejectingFieldArgOfType(InterfaceType);
  });

  it('rejects a schema with a list of objects as an input field arg', () => {
    var ListOfObjects = new GraphQLList(new GraphQLObjectType({
      name: 'SomeOutputType',
      fields: { f: { type: GraphQLFloat } }
    }));
    testRejectingFieldArgOfType(ListOfObjects);
  });

  it('rejects a schema with a nonnull object as an input field arg', () => {
    var NonNullObject = new GraphQLNonNull(new GraphQLObjectType({
      name: 'SomeOutputType',
      fields: { f: { type: GraphQLFloat } }
    }));
    testRejectingFieldArgOfType(NonNullObject);
  });

  it('accepts a schema with a list of input type as an input field arg', () => {
    testAcceptingFieldArgOfType(new GraphQLList(new GraphQLInputObjectType({
      name: 'SomeInputType'
    })));
  });

  it('accepts a schema with a nonnull input type as an input field arg', () => {
    testAcceptingFieldArgOfType(new GraphQLNonNull(new GraphQLInputObjectType({
      name: 'SomeInputType'
    })));
  });
});

function testAcceptingAnInterfaceWithANormalSubtype(rule) {
  var InterfaceType = new GraphQLInterfaceType({
    name: 'InterfaceType',
    fields: {}
  });
  var SubType = new GraphQLObjectType({
    name: 'SubType',
    fields: {},
    interfaces: [ InterfaceType ]
  });

  var schema = new GraphQLSchema({
    query: InterfaceType,
    mutation: SubType
  });
  var validationErrors = validateSchema(
    schema,
    [ rule ]
  );
  expect(validationErrors).to.have.length(0);
}

describe('Rule: InterfacePossibleTypesMustImplementTheInterface', () => {
  it('accepts an interface with a subtype declared using our infra', () => {
    testAcceptingAnInterfaceWithANormalSubtype(
      InterfacePossibleTypesMustImplementTheInterface
    );
  });

  it('rejects when a possible type does not implement the interface', () => {
    var InterfaceType = new GraphQLInterfaceType({
      name: 'InterfaceType',
      fields: {}
    });
    var SubType = new GraphQLObjectType({
      name: 'SubType',
      fields: {},
      interfaces: []
    });

    InterfaceType._implementations.push(SubType);
    // Sanity check.
    expect(InterfaceType.getPossibleTypes().length).to.equal(1);
    expect(InterfaceType.getPossibleTypes()[0]).to.equal(SubType);

    var schema = new GraphQLSchema({ query: InterfaceType });
    var validationErrors = validateSchema(
      schema,
      [ InterfacePossibleTypesMustImplementTheInterface ]
    );
    expect(validationErrors).to.have.length(1);
    expect(validationErrors[0].message).to.equal(
      'SubType is a possible type of interface InterfaceType but does not ' +
      'implement it!'
    );
  });
});

describe('Rule: TypesInterfacesMustShowThemAsPossible', () => {
  it('accepts an interface with a subtype declared using our infra', () => {
    testAcceptingAnInterfaceWithANormalSubtype(
      TypesInterfacesMustShowThemAsPossible
    );
  });

  it('rejects when an implementation is not a possible type', () => {
    var InterfaceType = new GraphQLInterfaceType({
      name: 'InterfaceType',
      fields: {}
    });
    var SubType = new GraphQLObjectType({
      name: 'SubType',
      fields: {},
      interfaces: []
    });

    SubType._typeConfig.interfaces.push(InterfaceType);
    // Sanity check the test.
    expect(SubType.getInterfaces()).to.eql([ InterfaceType ]);
    expect(InterfaceType.isPossibleType(SubType)).to.equal(false);

    var schema = new GraphQLSchema({
      query: InterfaceType,
      // Need to make sure SubType is in the schema! We rely on
      // possibleTypes to be able to see it unless it's explicitly used.
      mutation: SubType
    });
    // Another sanity check.
    expect(schema.getTypeMap().SubType).to.equal(SubType);

    var validationErrors = validateSchema(
      schema,
      [ TypesInterfacesMustShowThemAsPossible ]
    );
    expect(validationErrors).to.have.length(1);
    expect(validationErrors[0].message).to.equal(
      'SubType implements interface InterfaceType, but InterfaceType does ' +
      'not list it as possible!'
    );
  });
});


text:
using System;
using System.Data;
using System.Data.OleDb;

namespace MyMeta.PostgreSQL8
{
#if ENTERPRISE
	using System.Runtime.InteropServices;
	[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IColumn))]
#endif
	public class PostgreSQL8Column : Column
	{
		internal bool _isAutoKey = false;
		internal int _autoInc   = 0;
		internal int _autoSeed  = 0;

		public PostgreSQL8Column()
		{

		}

		override internal Column Clone()
		{
			Column c = base.Clone();

			return c;
		}

		override public System.Boolean IsNullable
		{
			get
			{
				string s = this.GetString(Columns.f_IsNullable);

				if(s == "YES")
					return true;
				else
					return false;
			}
		}

		override public System.Boolean HasDefault
		{
			get
			{
				object o = this._row[Columns.f_Default];

				if(o == DBNull.Value)
				{
					return false;
				}
				else
				{
					return true;
				}
			}
		}

		public override System.Boolean IsAutoKey
		{
			get
			{
				return this._isAutoKey;
			}
		}

		public override Int32 AutoKeyIncrement
		{
			get
			{
				return this._autoInc;
			}
		}

		public override Int32 AutoKeySeed
		{
			get
			{
				return this._autoSeed;
			}
		}

		override public System.Boolean IsComputed
		{
			get
			{
				return this.GetBool(Columns.f_IsComputed);
			}
		}

		override public string DataTypeName
		{
			get
			{
				PostgreSQL8Columns cols = Columns as PostgreSQL8Columns;
				return this.GetString(cols.f_TypeName);
			}
		}

		override public string DataTypeNameComplete
		{
			get
			{
				PostgreSQL8Columns cols = Columns as PostgreSQL8Columns;
				return this.GetString(cols.f_TypeNameComplete);
			}
		}
	}
}


text:
require "crufty/version"
require "crufty/context"
require "crufty/exceptions"
require "logger"

module Crufty
  class << self
    attr_accessor :logger, :stale_handler, :expired_handler
    attr_writer :env

    def env
      @env ||= ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
    end

    def on_stale(&block)
      self.stale_handler = block
    end

    def on_expired(&block)
      self.expired_handler = block
    end
  end

  DEFAULT_ON_STALE_HANDLER = proc do |ctx|
    stale_detail = (ctx.best_by.nil?) ? "Crufty code" : "Code went crufty at #{ctx.best_by} and"
    expires_detail = (ctx.expires.nil?) ? "should be removed" : "will stop working at #{ctx.expires}"
    Crufty.logger.warn("#{stale_detail} #{expires_detail}: #{ctx.backtrace[0]}")
  end

  DEFAULT_ON_EXPIRED_HANDLER = proc do |ctx|
    raise ::Crufty::CodeExpired.new(ctx), "Crufty code expired at #{ctx.expires}", ctx.backtrace
  end

  if defined?(Rails) && Rails.logger
    self.logger = Rails.logger
  else
    self.logger = Logger.new($stdout)
  end

  self.stale_handler = DEFAULT_ON_STALE_HANDLER
  self.expired_handler = DEFAULT_ON_EXPIRED_HANDLER

  module Methods
    def crufty(warn_after = nil, error_after = nil, best_by: nil, expires: nil)
      raise ArgumentError if (warn_after && best_by) || (error_after && expires)

      best_by = warn_after || best_by
      expires = error_after || expires

      ctx = ::Crufty::Context.new(best_by, expires, caller)

      if ctx.state == :expired
        Crufty.expired_handler.call(ctx)
      elsif ctx.state == :stale
        Crufty.stale_handler.call(ctx)
        yield
      else
        yield
      end
    end
  end
end

Object.send :include, Crufty::Methods


text:
using System;
using System.Numerics;

internal partial class VectorTest
{
    private const int Pass = 100;
    private const int Fail = -1;

    private class VectorCopyToArrayTest<T> where T : struct, IComparable<T>, IEquatable<T>
    {
        public static int VectorCopyToArray(int size, Random random)
        {
            int returnVal = Pass;

            if (size < Vector<T>.Count) size = Vector<T>.Count;
            int index = size - Vector<T>.Count;
            T[] inputArray = GetRandomArray<T>(size, random);

            Vector<T> v1 = new Vector<T>(inputArray);
            Vector<T> v2 = new Vector<T>(inputArray, index);
            bool caught;

            T[] outputArray = new T[2 * Vector<T>.Count];
            v1.CopyTo(outputArray);
            v2.CopyTo(outputArray, Vector<T>.Count);

            for (int i = 0; i < Vector<T>.Count; i++)
            {
                if (!CheckValue(v1[i], outputArray[i])) returnVal = Fail;
                if (!CheckValue(v2[i], outputArray[i + Vector<T>.Count])) returnVal = Fail;
            }

            // Test a null input array.
            caught = false;
            try
            {
                v1.CopyTo(null);
            }
            catch (NullReferenceException)
            {
                caught = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught exception: " + e.GetType());
            }
            if (!caught)
            {
                Console.WriteLine("Failed to throw NullReferenceException for a null input array.");
                returnVal = Fail;
            }

            // Test a negative index.
            caught = false;
            try
            {
                v1.CopyTo(outputArray, -1);
            }
            catch (ArgumentOutOfRangeException)
            {
                caught = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught exception: " + e.GetType());
            }
            if (!caught)
            {
                Console.WriteLine("Failed to throw ArgumentOutOfRangeException for a negative index.");
                returnVal = Fail;
            }

            // Test an out-of-range index.
            caught = false;
            try
            {
                v1.CopyTo(outputArray, outputArray.Length);
            }
            catch (ArgumentOutOfRangeException)
            {
                caught = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught exception: " + e.GetType());
            }
            if (!caught)
            {
                Console.WriteLine("Failed to throw ArgumentOutOfRangeException for an out-of-range index.");
                returnVal = Fail;
            }

            // Test insufficient range in target array.
            caught = false;
            try
            {
                v1.CopyTo(outputArray, outputArray.Length - 1);
            }
            catch (ArgumentException)
            {
                caught = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught exception: " + e.GetType());
            }
            if (!caught)
            {
                Console.WriteLine("Failed to throw ArgumentException for insufficient range in target array.");
                returnVal = Fail;
            }

            return returnVal;
        }
    }

    private static int Main()
    {
        int returnVal = Pass;
        Random random = new Random(100);

        if (VectorCopyToArrayTest<Single>.VectorCopyToArray(17, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<Single>.VectorCopyToArray(12, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<Double>.VectorCopyToArray(12, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<Double>.VectorCopyToArray(17, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<int>.VectorCopyToArray(12, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<int>.VectorCopyToArray(17, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<long>.VectorCopyToArray(12, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<long>.VectorCopyToArray(17, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<ushort>.VectorCopyToArray(12, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<ushort>.VectorCopyToArray(17, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<byte>.VectorCopyToArray(12, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<byte>.VectorCopyToArray(17, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<short>.VectorCopyToArray(12, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<short>.VectorCopyToArray(17, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<sbyte>.VectorCopyToArray(12, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<sbyte>.VectorCopyToArray(17, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<uint>.VectorCopyToArray(12, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<uint>.VectorCopyToArray(17, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<ulong>.VectorCopyToArray(12, random) == Fail) returnVal = Fail;
        if (VectorCopyToArrayTest<ulong>.VectorCopyToArray(17, random) == Fail) returnVal = Fail;

        JitLog jitLog = new JitLog();
        if (!jitLog.Check("CopyTo(ref)", "Single")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref,int)", "Single")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref)", "Double")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref,int)", "Double")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref)", "Int32")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref,int)", "Int32")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref)", "Int64")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref,int)", "Int64")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref)", "UInt16")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref,int)", "UInt16")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref)", "Byte")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref,int)", "Byte")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref)", "Int16")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref,int)", "Int16")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref)", "SByte")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref,int)", "SByte")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref)", "UInt32")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref,int)", "UInt32")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref)", "UInt64")) returnVal = Fail;
        if (!jitLog.Check("CopyTo(ref,int)", "UInt64")) returnVal = Fail;
        jitLog.Dispose();

        return returnVal;
    }
}


text:
namespace chrome_pdf {

const int kLeftBorderSize = 52;
const int kBorderSize = 12;
const int kHighlightBorderSize = 2;

const uint32 kLeftColor = 0x003F537B;
const uint32 kRightColor = 0x990D1626;

const uint32 kTopHighlightColor = 0xFF426DC9;
const uint32 kBottomHighlightColor = 0xFF6391DE;
const uint32 kThumbnailBackgroundColor = 0xFF000000;

const uint32 kSlidingTimeoutMs = 50;
const int32 kSlidingShift = 50;

const double kNonSelectedThumbnailAlpha = 0.91;

ThumbnailControl::ThumbnailControl()
    : engine_(NULL), sliding_width_(0), sliding_shift_(kSlidingShift),
      sliding_timeout_(kSlidingTimeoutMs), sliding_timer_id_(0) {
}

ThumbnailControl::~ThumbnailControl() {
  ClearCache();
}

bool ThumbnailControl::CreateThumbnailControl(
    uint32 id, const pp::Rect& rc,
    bool visible, Owner* owner, PDFEngine* engine,
    NumberImageGenerator* number_image_generator) {
  engine_ = engine;
  number_image_generator_ = number_image_generator;
  sliding_width_ = rc.width();

  return Control::Create(id, rc, visible, owner);
}

void ThumbnailControl::SetPosition(int position, int total, bool invalidate) {
  visible_rect_ = pp::Rect();
  visible_pages_.clear();

  if (rect().width() < kLeftBorderSize + kBorderSize) {
    return;  // control is too narrow to show thumbnails.
  }

  int num_pages = engine_->GetNumberOfPages();

  int max_doc_width = 0, total_doc_height = 0;
  std::vector<pp::Rect> page_sizes(num_pages);
  for (int i = 0; i < num_pages; ++i) {
    page_sizes[i] = engine_->GetPageRect(i);
    max_doc_width = std::max(max_doc_width, page_sizes[i].width());
    total_doc_height += page_sizes[i].height();
  }

  if (!max_doc_width)
    return;

  int max_thumbnail_width = rect().width() - kLeftBorderSize - kBorderSize;
  double thumbnail_ratio =
      max_thumbnail_width / static_cast<double>(max_doc_width);

  int total_thumbnail_height = 0;
  for (int i = 0; i < num_pages; ++i) {
    total_thumbnail_height += kBorderSize;
    int thumbnail_width =
        static_cast<int>(page_sizes[i].width() * thumbnail_ratio);
    int thumbnail_height =
        static_cast<int>(page_sizes[i].height() * thumbnail_ratio);
    int x = (max_thumbnail_width - thumbnail_width) / 2;
    page_sizes[i] =
        pp::Rect(x, total_thumbnail_height, thumbnail_width, thumbnail_height);
    total_thumbnail_height += thumbnail_height;
  }
  total_thumbnail_height += kBorderSize;

  int visible_y = 0;
  if (total > 0) {
    double range = total_thumbnail_height - rect().height();
    if (range < 0)
      range = 0;
    visible_y = static_cast<int>(range * position / total);
  }
  visible_rect_ = pp::Rect(0, visible_y, max_thumbnail_width, rect().height());

  for (int i = 0; i < num_pages; ++i) {
    if (page_sizes[i].Intersects(visible_rect_)) {
      PageInfo page_info;
      page_info.index = i;
      page_info.rect = page_sizes[i];
      page_info.rect.Offset(kLeftBorderSize, -visible_rect_.y());
      visible_pages_.push_back(page_info);
    }
  }

  if (invalidate)
    owner()->Invalidate(id(), rect());
}

void ThumbnailControl::Show(bool visible, bool invalidate) {
  if (!visible || invalidate)
    ClearCache();
  sliding_width_ = rect().width();
  Control::Show(visible, invalidate);
}

void ThumbnailControl::SlideIn() {
  if (visible())
    return;

  Show(true, false);
  sliding_width_ = 0;
  sliding_shift_ = kSlidingShift;

  sliding_timer_id_ = owner()->ScheduleTimer(id(), sliding_timeout_);
  owner()->Invalidate(id(), rect());
}

void ThumbnailControl::SlideOut() {
  if (!visible())
    return;
  sliding_shift_ = -kSlidingShift;
  sliding_timer_id_ = owner()->ScheduleTimer(id(), sliding_timeout_);
}

void ThumbnailControl::Paint(pp::ImageData* image_data, const pp::Rect& rc) {
  if (!visible())
    return;

  pp::Rect control_rc(rect());
  control_rc.Offset(control_rc.width() - sliding_width_, 0);
  control_rc.set_width(sliding_width_);

  pp::Rect draw_rc = rc.Intersect(control_rc);
  if (draw_rc.IsEmpty())
    return;

  pp::Rect gradient_rc(control_rc.x(), draw_rc.y(),
                       control_rc.width(), draw_rc.height());
  GradientFill(owner()->GetInstance(),
               image_data,
               draw_rc,
               gradient_rc,
               kLeftColor,
               kRightColor,
               true,
               transparency());

  int selected_page = engine_->GetMostVisiblePage();
  for (size_t i = 0; i < visible_pages_.size(); ++i) {
    pp::Rect page_rc = visible_pages_[i].rect;
    page_rc.Offset(control_rc.point());

    if (visible_pages_[i].index == selected_page) {
      pp::Rect highlight_rc = page_rc;
      highlight_rc.Inset(-kHighlightBorderSize, -kHighlightBorderSize);
      GradientFill(owner()->GetInstance(),
                   image_data,
                   draw_rc,
                   highlight_rc,
                   kTopHighlightColor,
                   kBottomHighlightColor,
                   false,
                   transparency());
    }

    pp::Rect draw_page_rc = page_rc.Intersect(draw_rc);
    if (draw_page_rc.IsEmpty())
      continue;

    // First search page image in the cache.
    pp::ImageData* thumbnail = NULL;
    std::map<int, pp::ImageData*>::iterator it =
        image_cache_.find(visible_pages_[i].index);
    if (it != image_cache_.end()) {
      if (it->second->size() == page_rc.size())
        thumbnail = image_cache_[visible_pages_[i].index];
      else
        image_cache_.erase(it);
    }

    // If page is not found in the cache, create new one.
    if (thumbnail == NULL) {
      thumbnail = new pp::ImageData(owner()->GetInstance(),
                                    PP_IMAGEDATAFORMAT_BGRA_PREMUL,
                                    page_rc.size(),
                                    false);
      engine_->PaintThumbnail(thumbnail, visible_pages_[i].index);

      pp::ImageData page_number;
      number_image_generator_->GenerateImage(
          visible_pages_[i].index + 1, &page_number);
      pp::Point origin(
          (thumbnail->size().width() - page_number.size().width()) / 2,
          (thumbnail->size().height() - page_number.size().height()) / 2);

      if (origin.x() > 0 && origin.y() > 0) {
        AlphaBlend(page_number, pp::Rect(pp::Point(), page_number.size()),
                   thumbnail, origin, kOpaqueAlpha);
      }

      image_cache_[visible_pages_[i].index] = thumbnail;
    }

    uint8 alpha = transparency();
    if (visible_pages_[i].index != selected_page)
      alpha = static_cast<uint8>(alpha * kNonSelectedThumbnailAlpha);
    FillRect(image_data, draw_page_rc, kThumbnailBackgroundColor);
    draw_page_rc.Offset(-page_rc.x(), -page_rc.y());
    AlphaBlend(*thumbnail, draw_page_rc, image_data,
        draw_page_rc.point() + page_rc.point(), alpha);
  }
}

bool ThumbnailControl::HandleEvent(const pp::InputEvent& event) {
  if (!visible())
    return false;

  pp::MouseInputEvent mouse_event(event);
  if (mouse_event.is_null())
    return false;
  pp::Point pt = mouse_event.GetPosition();
  if (!rect().Contains(pt))
    return false;

  int over_page = -1;
  for (size_t i = 0; i < visible_pages_.size(); ++i) {
    pp::Rect page_rc = visible_pages_[i].rect;
    page_rc.Offset(rect().point());
    if (page_rc.Contains(pt)) {
      over_page = i;
      break;
    }
  }

  bool handled = false;
  switch (event.GetType()) {
    case PP_INPUTEVENT_TYPE_MOUSEMOVE:
      owner()->SetCursor(id(),
          over_page == -1 ? PP_CURSORTYPE_POINTER : PP_CURSORTYPE_HAND);
      break;
    case PP_INPUTEVENT_TYPE_MOUSEDOWN:
      if (over_page != -1) {
        owner()->Invalidate(id(), rect());
        owner()->OnEvent(id(), EVENT_ID_THUMBNAIL_SELECTED,
                         &visible_pages_[over_page].index);
      }
      handled = true;
      break;
    default:
      break;
  }

  return handled;
}

void ThumbnailControl::OnTimerFired(uint32 timer_id) {
  if (timer_id == sliding_timer_id_) {
    sliding_width_ += sliding_shift_;
    if (sliding_width_ <= 0) {
      // We completely slided out. Make control invisible now.
      Show(false, false);
    } else if (sliding_width_ >= rect().width()) {
      // We completely slided in. Make sliding width to full control width.
      sliding_width_ = rect().width();
    } else {
      // We have not completed sliding yet. Keep sliding.
      sliding_timer_id_ = owner()->ScheduleTimer(id(), sliding_timeout_);
    }
    owner()->Invalidate(id(), rect());
  }
}

void ThumbnailControl::ResetEngine(PDFEngine* engine) {
  engine_ = engine;
  ClearCache();
}

void ThumbnailControl::ClearCache() {
  std::map<int, pp::ImageData*>::iterator it;
  for (it = image_cache_.begin(); it != image_cache_.end(); ++it) {
    delete it->second;
  }
  image_cache_.clear();
}

}  // namespace chrome_pdf


text:
"""
RIA Bot interactions

"""
import json
import pprint

import requests
from requests.auth import HTTPBasicAuth

"""
Global Constants
"""
HTTPS = 'false'
USER='anonymous'
PASSWORD=''

def replace_value_with_definition(current_dict, key_to_find, definition):
    """
    This method is used to substitute the default values read from .json file
    by a value that the user specified on CLI.

    :param current_dict:
    :param key_to_find:
    :param definition:
    :return:
    """
    for key in current_dict.keys():
        if key == key_to_find:
            current_dict[key] = definition

def get_http_scheme():
    """
    Gets the http/https protocol scheme prefix for url
    :return:
    """
    if HTTPS.lower() == 'true':
        return "https"
    else:
        return "http"

def pretty_print_json(response):
    """
    Pretty print the response.
    """
    print("Response Headers:%s" % (response.headers))
    print("Reason:%s" % (response.reason))
    try:
        res = json.dumps(response.json(), sort_keys=True, indent=4, separators=(',', ':'))
        print("[HTTPCode:%s]JSON:" % (response.status_code))
        print(res)
    except:
        if response is not None:
            print("[HTTPCode:%s]Text:[%s]" % (response.status_code, response.text))
        else:
            print("Noresponse.")

#################### HTTP method wrapper functions ################

def get_request(url, headers=None):
    """
    GETrequest.
    :paramurl:
    :return:
    """
    print('GET ' + str(url))
    if headers is not None:
        print('Request Headers:' + str(headers))
        r = requests.get(url, auth=HTTPBasicAuth(USER, PASSWORD), headers=headers, verify=False)
    else:
        r = requests.get(url, auth=HTTPBasicAuth(USER, PASSWORD), verify=False)
        pretty_print_json(r)
    return r

def put_request(payload, url, headers=None):
    """
    PUT request.
    :param headers:
    :param payload:
    :param url:
    :return:
    """
    print('PUT ' + str(url))
    print('RequestHeaders:' + str(headers))
    pp = pprint.PrettyPrinter(indent=2)
    pp.pprint(payload)
    r = requests.put(url, auth=HTTPBasicAuth(USER, PASSWORD), data=json.dumps(payload), headers=headers, verify=False)
    pretty_print_json(r)
    return r

def post_request(url, payload=None, headers=None, auth=HTTPBasicAuth(USER, PASSWORD)):
    """
    POST request.
    :param url:
    :param payload:
    :param headers:
    :return:
    """
    print('POST ' + str(url))
    if payload is None and headers is None:
        r = requests.post(url, auth=auth, verify=False)
    else:
        print('RequestHeaders:' + str(headers))
    pp = pprint.PrettyPrinter(indent=2)
    pp.pprint(payload)
    r = requests.post(url, auth=auth, data=json.dumps(payload), headers=headers, verify=False)
    pretty_print_json(r)
    return r

def delete_request(url, headers=None):
    """
    DELETE request.
    :param url:
    :return:
    """
    print('DELETE ' + str(url))
    r = requests.delete(url, auth=HTTPBasicAuth(USER, PASSWORD), headers=headers, verify=False)
    pretty_print_json(r)
    return r

######################################################################################################

def send_message(hostPort, speech_txt, riaId):
    """
    Sends message to Amigo chatbot service.
    Waits for the response in a loop until the response is success or failed.

    :param speech_txt: actual message spoken by user
    :param riaId: unique id of RIA device that identifies an Amigo user to the backend
    :return: generic message of success or failure of submission of the message to amigo bot
    """
    url = "%s://%s/api/v1.0/ria" % (get_http_scheme(), hostPort)
    data = {}
    data['botType'] = 'RIA'
    data['content'] = speech_txt
    data['riaId'] = riaId
    json_data = json.dumps(data)
    r = post_request(url, payload=json_data, headers={"content-type":"application/json"})

def poll_response(hostPort)


text:
extern "C" {
#endif

struct gbm_device;
struct gbm_surface;

struct waffle_gbm_display {
    struct gbm_device *gbm_device;
    EGLDisplay egl_display;
};

struct waffle_gbm_config {
    struct waffle_gbm_display display;
    EGLConfig egl_config;
};

struct waffle_gbm_context {
    struct waffle_gbm_display display;
    EGLContext egl_context;
};

struct waffle_gbm_window {
    struct waffle_gbm_display display;
    struct gbm_surface *gbm_surface;
    EGLSurface egl_surface;
};

#ifdef __cplusplus
} // end extern "C"
#endif


text:
class WrongPerson < ActiveRecord::Base
  validates :email, :name, uniqueness: { scope: [:city, :state] }
end


text:
package utils;

import java.util.Iterator;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.usertype.UserCollectionType;

@SuppressWarnings("unchecked")
public abstract class AbstractOwnedListType implements UserCollectionType {

	@Override
	public boolean contains(Object collection, Object entity) {
		return ((java.util.List) collection).contains(entity);
	}

	@Override
	public Iterator getElementsIterator(Object collection) {
		return ((java.util.List) collection).iterator();
	}

	@Override
	public Object indexOf(Object collection, Object entity) {
		return null;
	}

	@Override
	public abstract Object instantiate(int anticipatedSize);
	// return new x_entclass#x_prop#Set(anticipatedSize < 1 ? 0 : anticipatedSize );

	@Override
	public PersistentCollection instantiate(SessionImplementor session, CollectionPersister persister) throws HibernateException {
		return new utils.PersistentOwnedList(session);
	}

	@Override
	public Object replaceElements(Object original, Object target,
			CollectionPersister persister, Object owner, Map copyCache,
			SessionImplementor session) throws HibernateException {
		java.util.List result = (java.util.List) target;
		result.clear();
		result.addAll((java.util.List) original);
		return result;
	}

	@Override
	public PersistentCollection wrap(SessionImplementor session, Object collection) {
		if ( session.getEntityMode() == org.hibernate.EntityMode.DOM4J ) {
			throw new IllegalStateException("dom4j not supported");
		}
		else {
			return new utils.PersistentOwnedList( session, (java.util.List) collection );
		}
	}

	public abstract boolean isAffectedBy(String filter);

	public abstract boolean isFilterCompatible(org.hibernate.impl.FilterImpl oldFilter, org.hibernate.impl.FilterImpl newFilter);

}


text:
from datetime import date, time, datetime
import os.path

from django.test import TestCase

from panda import utils
from panda.exceptions import TypeCoercionError
from panda.tests import utils as test_utils

class TestCSV(TestCase):
    def setUp(self):
        self.path = os.path.join(test_utils.TEST_DATA_PATH, test_utils.TEST_DATA_FILENAME)
        self.dialect = {
            'delimiter': ',',
            'doublequote': False,
            'lineterminator': '\r\n',
            'quotechar': '"',
            'quoting': 0,
            'skipinitialspace': False
        }

    def test_csv_sniff_dialect(self):
        dialect = utils.csv.sniff_dialect(self.path)

        self.assertEqual(dialect, self.dialect)

    def test_csv_sniff_dialect_latin1(self):
        path = os.path.join(test_utils.TEST_DATA_PATH, test_utils.TEST_LATIN1_FILENAME)

        dialect = utils.csv.sniff_dialect(path, encoding='Latin-1')

        self.assertEqual(dialect, self.dialect)

    def test_csv_extract_column_names(self):
        columns = utils.csv.extract_column_names(self.path, self.dialect)

        self.assertEqual(columns, ['id', 'first_name', 'last_name', 'employer'])

    def test_csv_extract_column_names_latin1(self):
        path = os.path.join(test_utils.TEST_DATA_PATH, test_utils.TEST_LATIN1_FILENAME)

        columns = utils.csv.extract_column_names(path, self.dialect, encoding='Latin-1')

        self.assertEqual(columns, ['activity', 'unsupplemented mean', 'dir', 'sem', 'n', 'supplemented mean', 'dir', 'sem'])

    def test_csv_sample_data(self):
        samples = utils.csv.sample_data(self.path, self.dialect, 2)

        self.assertEqual(samples, [['1', 'Brian', 'Boyer', 'Chicago Tribune'], ['2', 'Joseph', 'Germuska', 'Chicago Tribune']])

    def test_csv_sample_data_latin1(self):
        path = os.path.join(test_utils.TEST_DATA_PATH, test_utils.TEST_LATIN1_FILENAME)

        samples = utils.csv.sample_data(path, self.dialect, 2, encoding='Latin-1')

        self.assertEqual(samples, [[u'sitting', u'1.21', u'\xb1', u'0.02', u'76', u'1.27', u'\xb1', u'0.02*'], [u'standing', u'1.23', u'\xb1', u'0.03', u'58', u'1.28', u'\xb1', u'0.03']])

    def test_csv_guess_column_types(self):
        guessed_types = utils.csv.guess_column_types(self.path, self.dialect, 5, encoding='Latin-1')

        self.assertEqual(guessed_types, ['int', 'unicode', 'unicode', 'unicode'])

class TestXLS(TestCase):
    def setUp(self):
        self.path = os.path.join(test_utils.TEST_DATA_PATH, test_utils.TEST_XLS_FILENAME)
        self.dialect = {}

    def test_xls_sniff_dialect(self):
        dialect = utils.xls.sniff_dialect(self.path)

        self.assertEqual(dialect, self.dialect)

    def test_xls_extract_column_names(self):
        columns = utils.xls.extract_column_names(self.path, self.dialect)

        self.assertEqual(columns, ['id', 'first_name', 'last_name', 'employer'])

    def test_xls_sample_data(self):
        samples = utils.xls.sample_data(self.path, self.dialect, 2)

        self.assertEqual(samples, [['1', 'Brian', 'Boyer', 'Chicago Tribune'], ['2', 'Joseph', 'Germuska', 'Chicago Tribune']])

    def test_xls_guess_column_types(self):
        self.path = os.path.join(test_utils.TEST_DATA_PATH, test_utils.TEST_XLS_TYPES_FILENAME)

        guessed_types = utils.xls.guess_column_types(self.path, self.dialect, 5, encoding='Latin-1')

        self.assertEqual(guessed_types, ['unicode', 'date', 'int', 'bool', 'float', 'time', 'datetime', None, 'unicode'])

class TestXLSX(TestCase):
    def setUp(self):
        self.path = os.path.join(test_utils.TEST_DATA_PATH, test_utils.TEST_EXCEL_XLSX_FILENAME)
        self.dialect = {}

    def test_xlsx_sniff_dialect(self):
        dialect = utils.xlsx.sniff_dialect(self.path)

        self.assertEqual(dialect, self.dialect)

    def test_xlsx_extract_column_names(self):
        columns = utils.xlsx.extract_column_names(self.path, self.dialect)

        self.assertEqual(columns, ['id', 'first_name', 'last_name', 'employer'])

    def test_xlsx_sample_data(self):
        samples = utils.xlsx.sample_data(self.path, self.dialect, 2)

        self.assertEqual(samples, [['1', 'Brian', 'Boyer', 'Chicago Tribune'], ['2', 'Joseph', 'Germuska', 'Chicago Tribune']])

    def test_xlsx_guess_column_types(self):
        self.path = os.path.join(test_utils.TEST_DATA_PATH, test_utils.TEST_XLSX_TYPES_FILENAME)

        guessed_types = utils.xlsx.guess_column_types(self.path, self.dialect, 5, encoding='Latin-1')

        self.assertEqual(guessed_types, ['unicode', 'date', 'int', 'bool', 'float', 'time', 'datetime', None, 'unicode'])

class TestTypeCoercion(TestCase):
    def setUp(self):
        self.data_typer = utils.typecoercion.DataTyper([])
        self.coerce_type = self.data_typer.coerce_type

    def test_coerce_nulls(self):
        self.assertEqual(self.coerce_type(None, bool), None)
        self.assertEqual(self.coerce_type('N/A', int), None)
        self.assertEqual(self.coerce_type('n/a', datetime), None)

    def test_coerce_int_from_str(self):
        self.assertEqual(self.coerce_type('171', int), 171)

    def test_coerce_int_from_str_fails(self):
        with self.assertRaises(TypeCoercionError):
            self.assertEqual(self.coerce_type('#171', int), 171)

    def test_coerce_int_from_unicode(self):
        self.assertEqual(self.coerce_type(u'171', int), 171)

    def test_coerce_int_from_currency_str(self):
        self.assertEqual(self.coerce_type('$171,000', int), 171000)

    def test_coerce_int_from_currency_float(self):
        self.assertEqual(self.coerce_type(u'$171,000', int), 171000)

    def test_coerce_float_from_str(self):
        self.assertEqual(self.coerce_type('171.59', float), 171.59)

    def test_coerce_float_from_unicode(self):
        self.assertEqual(self.coerce_type(u'171.59', float), 171.59)

    def test_coerce_float_from_currency_str(self):
        self.assertEqual(self.coerce_type('$171,000.59', float), 171000.59)

    def test_coerce_float_from_currency_float(self):
        self.assertEqual(self.coerce_type(u'$171,000.59', float), 171000.59)

    def test_coerce_bool_from_str(self):
        self.assertEqual(self.coerce_type('True', bool), True)
        self.assertEqual(self.coerce_type('true', bool), True)
        self.assertEqual(self.coerce_type('T', bool), True)
        self.assertEqual(self.coerce_type('yes', bool), True)

    def test_coerce_bool_from_unicode(self):
        self.assertEqual(self.coerce_type(u'True', bool), True)
        self.assertEqual(self.coerce_type(u'true', bool), True)
        self.assertEqual(self.coerce_type(u'T', bool), True)
        self.assertEqual(self.coerce_type(u'yes', bool), True)

    def test_coerce_datetime_from_str(self):
        self.assertEqual(self.coerce_type('2011-4-13 8:28 AM', datetime), datetime(2011, 4, 13, 8, 28, 0))

    def test_coerce_date_from_str(self):
        self.assertEqual(self.coerce_type('2011-4-13', date), datetime(2011, 4, 13, 0, 0, 0))

    def test_coerce_time_from_str(self):
        self.assertEqual(self.coerce_type('8:28 AM', time), datetime(9999, 12, 31, 8, 28, 0))


text:
"""
Test multiple_comparison module

Run with::
	nosetests test_multiple_comparison.py
"""

import numpy as np
from .. import multiple_comparison
from numpy.testing import assert_array_equal, assert_almost_equal

def test_multiple_comp():
	res = np.linspace(0,1,100)
	res.shape = (10,10)
	actual = multiple_comparison.multiple_comp(res)
	expected = [0, 0, 0, 0]
	assert_array_equal(actual, expected)


text:
require('inmation.string-extension')
require('inmation.table-extension')
local objsLib = require('inmation.objects')
local pathLib = require('inmation.path')
local DropzoneFileParser = require('inmation.dropzone-file-parser')

local parser = DropzoneFileParser.new()

local selfPath = inmation.getself():path()
local headerCells = {}

parser:onAction('Line', function(args)
	if string.isEmpty(args.line) then return end
	local cells = string.split(args.line, ',')
    if args.lineNumber == 0 then
		-- Header
		headerCells = cells

		table.imap(cells, function(cell, idx)
			-- Skip timestamp
            if idx > 1 then
                local propertyList = {
                    ObjectName = cell,
					ModelClass = 'MODEL_CLASS_HOLDERITEM',
                    ["ArchiveOptions.StorageStrategy"] = "STORE_RAW_HISTORY"
                }
                objsLib:ensureObject(selfPath, propertyList)
            end
		end)
	else
		-- Content
		if #headerCells ~= #cells then error('Number of cell mismatch')	end

		local timestamp = inmation.currenttime()
		table.imap(cells, function(cell, idx)
			if idx == 1 then
				timestamp = inmation.gettime(cell)
				return
			end
			local itemPath = pathLib.join(selfPath, headerCells[idx])
			inmation.setvalue(itemPath, cell, 0, timestamp)
		end)
	end
end)

return function(filename, filetime)
	parser:process(filename)
	return true
end


text:
package com.yiibai;

public class SpellChecker {
	public SpellChecker() {
		System.out.println("Inside SpellChecker constructor.");
	}

	public void checkSpelling() {
		System.out.println("Inside checkSpelling.");
	}
}


text:
require_relative '../../spec_helper'

describe Suby::Downloader::OpenSubtitles do
  file = Path("breaking.bad.s05e04.hdtv.x264-fqm.mp4")
  downloader = Suby::Downloader::OpenSubtitles.new file
  correct_query = { moviehash: "709b9ff887cf987d", moviebytesize: "308412149", sublanguageid: "eng" }
  wrong_query = correct_query.merge({ sublanguageid: "wrong_language" })

  it 'finds the right subtitles' do
    response = downloader.search_subtitles(correct_query)
    response.should_not be_false
    response.first['MovieName'].should == '"Breaking Bad" Fifty-One'
  end

  it 'finds the right download link' do
    url = downloader.download_url
    url.should match(%r{http(s)?://.*opensubtitles.org/en/download/.*})
  end

  it "doesn't find anything for bad query" do
    response = downloader.search_subtitles(wrong_query)
    response.should == []
  end

  it "gets right token" do
    downloader.token.should match(/\A[a-zA-Z0-9]+\z/)
  end

  it 'fails gently when there is no subtitles available' do
    d = Suby::Downloader::OpenSubtitles.new(Path("Not Existing Show 1x1.mkv"), :eawdad)
    -> { d.download_url }.should raise_error(Suby::NotFoundError, "no subtitles available")
  end
end


text:
<?php

namespace Lampager\Contracts\Exceptions;

/**
 * Interface LampagerException
 */
interface LampagerException
{
}


text:
#ifndef MBED_SPI_DEVICE_H
#define MBED_SPI_DEVICE_H

#include "stm32l5xx_ll_spi.h"

// Defines the word legnth capability of the device where Nth bit allows for N window size
#define STM32_SPI_CAPABILITY_WORD_LENGTH (0x0000FFF8)

#endif


text:
print("Importing serial_handlers __init__.py")
print("__name__:", __name__)
print("__file__:", __file__)

from serial import serialutil

class NoOpSerial(serialutil.SerialBase):
    """No-op implementation of PySerial's SerialBase.

    Provides no-op implementation of various methods that SerialBase expects
    to have implemented by the sub-class. Can be used as is for a /dev/null
    type of behavior.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    @property
    def in_waiting(self):
        """The number of input bytes available to read immediately."""
        return 0

    def open(self):
        """Open port.

        Raises:
            SerialException if the port cannot be opened.
        """
        self.is_open = True

    def close(self):
        """Close port immediately."""
        self.is_open = False

    def read(self, size=1):
        """Read size bytes.

        If a timeout is set it may return fewer characters than requested.
        With no timeout it will block until the requested number of bytes
        is read.

        Args:
            size: Number of bytes to read.

        Returns:
            Bytes read from the port, of type 'bytes'.

        Raises:
            SerialTimeoutException: In case a write timeout is configured for
                the port and the time is exceeded.
        """
        if not self.is_open:
            raise serialutil.portNotOpenError
        return bytes()

    def write(self, data):
        """
        Args:
            data: The data to write.

        Returns:
            Number of bytes written.

        Raises:
            SerialTimeoutException: In case a write timeout is configured for
                the port and the time is exceeded.
        """
        if not self.is_open:
            raise serialutil.portNotOpenError
        return 0

    def reset_input_buffer(self):
        """Remove any accumulated bytes from the device."""
        pass

    def reset_output_buffer(self):
        """Remove any accumulated bytes not yet sent to the device."""
        pass

    # --------------------------------------------------------------------------
    # There are a number of methods called by SerialBase that need to be
    # implemented by sub-classes, assuming their calls haven't been blocked
    # by replacing the calling methods/properties. These are no-op
    # implementations.

    def _reconfigure_port(self):
        """Reconfigure the open port after a property has been changed.

        If you need to know which property has been changed, override the
        setter for the appropriate properties.
        """
        pass

    def _update_rts_state(self):
        """Handle rts being set to some value.

        "self.rts = value" has been executed, for some value. This may not
        have changed the value.
        """
        pass

    def _update_dtr_state(self):
        """Handle dtr being set to some value.

        "self.dtr = value" has been executed, for some value. This may not
        have changed the value.
        """
        pass

    def _update_break_state(self):
        """Handle break_condition being set to some value.

        "self.break_condition = value" has been executed, for some value.
        This may not have changed the value.
        Note that break_condition is set and then cleared by send_break().
        """
        pass


text:
<?php

declare(strict_types=1);

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

namespace ParkManager\Module\CoreModule\Tests\Infrastructure\UserInterface\Web\Form\Type\Security;

use ParkManager\Module\CoreModule\Infrastructure\Security\ClientUser;
use ParkManager\Module\CoreModule\Infrastructure\UserInterface\Web\Form\Type\Security\SecurityUserHashedPasswordType;
use RuntimeException;
use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;

/**
 * @internal
 */
final class SecurityUserHashedPasswordTypeTest extends TypeTestCase
{
    use ValidatorExtensionTrait;

    /** @var EncoderFactoryInterface */
    private $encoderFactory;

    protected function setUp(): void
    {
        $encoder = new class() implements PasswordEncoderInterface {
            public function encodePassword($raw, $salt): string
            {
                return 'encoded(' . $raw . ')';
            }

            public function isPasswordValid($encoded, $raw, $salt): bool
            {
                return false;
            }
        };

        $this->encoderFactory = new class($encoder) implements EncoderFactoryInterface {
            private $encoder;

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

            public function getEncoder($user): PasswordEncoderInterface
            {
                if ($user !== ClientUser::class) {
                    throw new RuntimeException('Nope, that is not the right user.');
                }

                return $this->encoder;
            }
        };

        parent::setUp();
    }

    protected function getTypes(): array
    {
        return [
            new SecurityUserHashedPasswordType($this->encoderFactory),
        ];
    }

    /** @test */
    public function it_hashes_password(): void
    {
        $form = $this->factory->createBuilder()
            ->add('password', SecurityUserHashedPasswordType::class, ['user_class' => ClientUser::class])
            ->getForm();

        $form->submit([
            'password' => ['password' => 'Hello there'],
        ]);

        self::assertTrue($form->isValid());
        self::assertEquals(['password' => 'encoded(Hello there)'], $form->getData());
    }
}