text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
/*================================================================================= Kunal Garg - last modified 13 May 2018 ([email protected]) *** Configuration script for K*+-->K0Short-Pi analysis *** =======================================================================================*/ // A configuration script for RSN package needs to define the followings: // // (1) decay tree of each resonance to be studied, which is needed to select // true pairs and to assign the right mass to all candidate daughters // (2) cuts at all levels: single daughters, tracks, events // (3) output objects: histograms or trees // Bool_t ConfigKStarPlusMinusRun2sp_bin ( AliRsnMiniAnalysisTask *task, //============= Int_t binning_sphero, Double_t min_sphero, Double_t max_sphero, Int_t mult_binning, Double_t mult_min, Double_t mult_max, //============== Bool_t HIST, //ST Bool_t isPP, Bool_t isMC, Bool_t isGT, Float_t piPIDCut, Int_t customQualityCutsID=AliRsnCutSetDaughterParticle::kDisableCustom, AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidphipp2015, Float_t pi_k0s_PIDCut, Int_t aodFilterBit, Bool_t enableMonitor=kTRUE , TString monitorOpt="", Float_t massTol, Float_t massTolVeto, Int_t tol_switch, Double_t tol_sigma, Float_t pLife, Float_t radiuslow, Bool_t Switch, Float_t k0sDCA, Float_t k0sCosPoinAn, Float_t k0sDaughDCA, Int_t NTPCcluster, const char *suffix, AliRsnCutSet *PairCutsSame, AliRsnCutSet *PairCutsMix, Float_t DCAxy, Bool_t enableSys, Float_t crossedRows, Float_t rowsbycluster, Float_t v0rapidity, Int_t Sys ) //kTPCpidphipp2015 { // manage suffix if (strlen(suffix) > 0) suffix = Form("_%s", suffix); ///////////////////////////////////////////////////// // selections for the pion from the decay of KStarPlusMinus* ///////////////////////////////////////////////////// // AliRsnCutSetDaughterParticle* cutSetQ; AliRsnCutSetDaughterParticle* cutSetPi; AliRsnCutTrackQuality* trkQualityCut= new AliRsnCutTrackQuality("myQualityCut"); if(SetCustomQualityCut(trkQualityCut,customQualityCutsID,aodFilterBit)){ //Set custom quality cuts for systematic checks cutSetQ=new AliRsnCutSetDaughterParticle(Form("cutQ_bit%i",aodFilterBit),trkQualityCut,AliRsnCutSetDaughterParticle::kQualityStd2011,AliPID::kPion,-1.); cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigma",cutPiCandidate, piPIDCut),trkQualityCut,cutPiCandidate,AliPID::kPion,piPIDCut); }else{ //use default quality cuts std 2010 with crossed rows TPC Bool_t useCrossedRows = 1; cutSetQ=new AliRsnCutSetDaughterParticle(Form("cutQ_bit%i",aodFilterBit),AliRsnCutSetDaughterParticle::kQualityStd2011,AliPID::kPion,-1.,aodFilterBit,kTRUE); cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigma",cutPiCandidate,piPIDCut),cutPiCandidate,AliPID::kPion,piPIDCut,aodFilterBit, kTRUE); } Int_t iCutQ=task->AddTrackCuts(cutSetQ); Int_t iCutPi=task->AddTrackCuts(cutSetPi); // AliRsnCutSetDaughterParticle * cutQ = new AliRsnCutSetDaughterParticle(Form("cutQ_bit%i",aodFilterBit), AliRsnCutSetDaughterParticle::kQualityStd2011, AliPID::kPion, -1.0, aodFilterBit, kTRUE); //cutQ->SetUse2011StdQualityCuts(kTRUE); //AliRsnCutSetDaughterParticle * cutPi = new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigma",cutPiCandidate, piPIDCut), cutPiCandidate, AliPID::kPion, piPIDCut, aodFilterBit,kTRUE); //cutPi->SetUse2011StdQualityCuts(kTRUE); //AliRsnCutSet *cutSetPi = new AliRsnCutSet("setPionForKStarPlusMinus", AliRsnTarget::kDaughter); //cutSetPi->AddCut(cutPi); //cutSetPi->SetCutScheme(cutPi->GetName()); //Int_t iCutPi = task->AddTrackCuts(cutPi); //Int_t iCutQ = task->AddTrackCuts(cutQ); // ///////////////////////////////////////////////////////////// // selections for K0s and for the daughters of K0s ///////////////////////////////////////////////////////////// // // selections for pion daugthers of K0s AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("qualityDaughterK0s"); esdTrackCuts->SetEtaRange(-0.8,0.8); esdTrackCuts->SetRequireTPCRefit(); esdTrackCuts->SetAcceptKinkDaughters(0); // esdTrackCuts->SetMinNCrossedRowsTPC(crossedRows); esdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(rowsbycluster); esdTrackCuts->SetMaxChi2PerClusterTPC(100); esdTrackCuts->SetMinDCAToVertexXY(DCAxy); //Use one of the two - pt dependent or fixed value cut. // ///////////////////////////////////////////////// // selections for K0s AliRsnCutV0 *cutK0s = new AliRsnCutV0("cutK0s", kK0Short, AliPID::kPion, AliPID::kPion); cutK0s->SetPIDCutPion(pi_k0s_PIDCut); // PID for the pion daughter of K0s cutK0s->SetESDtrackCuts(esdTrackCuts); cutK0s->SetMaxDaughtersDCA(k0sDaughDCA); cutK0s->SetMaxDCAVertex(k0sDCA); cutK0s->SetMinCosPointingAngle(k0sCosPoinAn); cutK0s->SetTolerance(massTol); cutK0s->SetToleranceVeto(massTolVeto); //Rejection range for Competing V0 Rejection cutK0s->SetSwitch(Switch); cutK0s->SetfLife(pLife); cutK0s->SetfLowRadius(radiuslow); cutK0s->SetfHighRadius(200); cutK0s->SetMaxRapidity(v0rapidity); cutK0s->SetpT_Tolerance(tol_switch); cutK0s->SetMassTolSigma(tol_sigma); if(enableSys) { if(Sys==1){cutK0s->SetPIDCutPion(pi_k0s_PIDCut-0.5);} else if(Sys==2){cutK0s->SetPIDCutPion(pi_k0s_PIDCut-1.0);} else if(Sys==3){cutK0s->SetMaxDaughtersDCA(k0sDaughDCA-0.25);} else if(Sys==4){cutK0s->SetMaxDaughtersDCA(k0sDaughDCA+0.25);} else if(Sys==5){cutK0s->SetMinCosPointingAngle(k0sCosPoinAn-0.02);} else if(Sys==6){cutK0s->SetMinCosPointingAngle(k0sCosPoinAn+0.02);} else if(Sys==7){cutK0s->SetTolerance(massTol+1);} else if(Sys==8){cutK0s->SetTolerance(massTol+2);} else if(Sys==9){cutK0s->SetTolerance(massTol-1);} else if(Sys==10){cutK0s->SetfLife(pLife-8);} else if(Sys==11){cutK0s->SetfLowRadius(radiuslow-0.2);} else if(Sys==12){cutK0s->SetfLowRadius(radiuslow+0.2);} else if(Sys==13){cutK0s->SetMaxRapidity(v0rapidity-0.1);} else if(Sys==14){cutK0s->SetMaxRapidity(v0rapidity+0.1);} else if(Sys==15){cutK0s->SetToleranceVeto(massTolVeto-0.0011);} else if(Sys==16){cutK0s->SetToleranceVeto(massTolVeto+0.0011);} else if(Sys==17){esdTrackCuts->SetMinDCAToVertexXY(DCAxy-0.01);} else if(Sys==18){esdTrackCuts->SetMinDCAToVertexXY(DCAxy+0.01);} else if(Sys==19){esdTrackCuts->SetMinNCrossedRowsTPC(crossedRows+10);} else if(Sys==20){esdTrackCuts->SetMinNCrossedRowsTPC(crossedRows+30);} else if(Sys==21){esdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(rowsbycluster+0.1);} } // AliRsnCutSet *cutSetK0s = new AliRsnCutSet("setK0s", AliRsnTarget::kDaughter); cutSetK0s->AddCut(cutK0s); cutSetK0s->SetCutScheme(cutK0s->GetName()); Int_t iCutK0s = task->AddTrackCuts(cutSetK0s); // // if(enableMonitor){ Printf("======== Cut monitoring enabled"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/AddMonitorOutput.C"); //AddMonitorOutput(isMC, cutPi->GetMonitorOutput(), monitorOpt.Data()); //AddMonitorOutput(isMC, cutQ->GetMonitorOutput(), monitorOpt.Data()); AddMonitorOutput(isMC, cutSetQ->GetMonitorOutput(), monitorOpt.Data()); AddMonitorOutput(isMC, cutSetPi->GetMonitorOutput(), monitorOpt.Data()); } // // -- Values ------------------------------------------------------------------------------------ // /// -- Values ------------------------------------------------------------------------------------ /* invariant mass */ Int_t imID = task->CreateValue(AliRsnMiniValue::kInvMass, kFALSE); /* transv. momentum */ Int_t ptID = task->CreateValue(AliRsnMiniValue::kPt, kFALSE); /* centrality */ Int_t centID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE); /* spherocity */ Int_t SpherocityID = task->CreateValue(AliRsnMiniValue::kSpherocity,kFALSE); /* pseudorapidity */ Int_t etaID = task->CreateValue(AliRsnMiniValue::kEta, kFALSE); /* rapidity */ Int_t yID = task->CreateValue(AliRsnMiniValue::kY, kFALSE); /* 1st daughter pt */ Int_t fdpt = task->CreateValue(AliRsnMiniValue::kFirstDaughterPt,kFALSE); /* 2nd daughter pt */ Int_t sdpt = task->CreateValue(AliRsnMiniValue::kSecondDaughterPt,kFALSE); /* 1st daughter p */ Int_t fdp = task->CreateValue(AliRsnMiniValue::kFirstDaughterP,kFALSE); /* 2nd daughter p */ Int_t sdp = task->CreateValue(AliRsnMiniValue::kSecondDaughterP,kFALSE); /* cos(theta) J */ Int_t ctjID = task->CreateValue(AliRsnMiniValue::kCosThetaJackson,kFALSE); /* cos(theta) J (MC)*/ Int_t ctjmID = task->CreateValue(AliRsnMiniValue::kCosThetaJackson,kTRUE); /* cos(theta) T */ Int_t cttID = task->CreateValue(AliRsnMiniValue::kCosThetaTransversity,kFALSE); /* cos(theta) T (MC)*/ Int_t cttmID = task->CreateValue(AliRsnMiniValue::kCosThetaTransversity,kTRUE); // // -- Create all needed outputs ----------------------------------------------------------------- // // use an array for more compact writing, which are different on mixing and charges // [0] = unlike // [1] = mixing // [2] = like ++ // [3] = like -- Bool_t use [6] = {1 ,1 ,1 ,1 ,1 ,1 }; Bool_t useIM [6] = {1 ,1 ,1 ,1 ,1 ,1 }; TString name [6] = {"KStarPlusMinus","AKStarPlusMinus","KStarPlusMinusmix","AKStarPlusMinusmix","KStarPlusMinust","AKStarPlusMinust"}; TString comp [6] = {"PAIR" ,"PAIR" ,"MIX" ,"MIX" ,"TRUE" ,"TRUE" }; TString output [6] = {"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" }; Char_t charge1 [6] = {'0' ,'0' ,'0' ,'0' ,'0' ,'0' }; Char_t charge2 [6] = {'+' ,'-' ,'+' ,'-' ,'+' ,'-' }; Int_t cutID1 [6] = { iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s }; Int_t cutID2 [6] = { iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi }; TString outputh [11]={"HIST","HIST","HIST","HIST","HIST","HIST","HIST","HIST","HIST","HIST" ,"HIST"}; //ST Int_t ipdg [6] = {323 ,-323 ,323 ,-323 ,323 ,-323 }; Double_t mass [6] = { 0.89166 ,0.89166 ,0.89166 ,0.89166 ,0.89166 ,0.89166 }; AliRsnCutSet* paircuts[6] = {PairCutsSame, PairCutsSame, PairCutsMix, PairCutsMix, PairCutsSame, PairCutsSame }; for (Int_t i = 0; i < 6; i++) { if (!use[i]) continue; //if (collSyst) output[i] = "SPARSE"; // create output AliRsnMiniOutput *out = task->CreateOutput(Form("ChargeKstar_%s%s", name[i].Data(), suffix), output[i].Data(), comp[i].Data()); // selection settings out->SetCutID(0, cutID1[i]); out->SetCutID(1, cutID2[i]); out->SetDaughter(0, AliRsnDaughter::kKaon0); out->SetDaughter(1, AliRsnDaughter::kPion); out->SetCharge(0, charge1[i]); out->SetCharge(1, charge2[i]); out->SetMotherPDG(ipdg[i]); out->SetMotherMass(mass[i]); // pair cuts out->SetPairCuts(paircuts[i]); // axis X: invmass if (useIM[i]) out->AddAxis(imID, 90, 0.6, 1.5); // out->AddAxis(imID, 700, 1.2, 4.0); // axis Y: transverse momentum out->AddAxis(ptID, 300, 0.0, 30.0); // out->AddAxis(k0sDCA, 10, 0.0, 1.0); //if (collSyst) out->AddAxis(centID, 10, 0.0, 100.0); if(isPP) out->AddAxis(centID, 400, 0.5, 400.5); else out->AddAxis(centID, mult_binning, mult_min, mult_max);//out->AddAxis(centID, 100, 0.0, 100.); out->AddAxis(SpherocityID, binning_sphero,min_sphero, max_sphero);//out->AddAxis(SpherocityID,1000,0.,1.); //ST if(isGT) out->AddAxis(sdpt,100,0.,10.); } // AddMonitorOutput_K0sP(cutSetK0s->GetMonitorOutput()); AddMonitorOutput_K0sPt(cutSetK0s->GetMonitorOutput()); AddMonitorOutput_K0sNegDaughPt(cutSetK0s->GetMonitorOutput()); AddMonitorOutput_K0sPosDaughPt(cutSetK0s->GetMonitorOutput()); AddMonitorOutput_K0sMass(cutSetK0s->GetMonitorOutput()); // AddMonitorOutput_K0sDCA(cutSetK0s->GetMonitorOutput()); AddMonitorOutput_K0sRadius(cutSetK0s->GetMonitorOutput()); AddMonitorOutput_K0sDaughterDCA(cutSetK0s->GetMonitorOutput()); AddMonitorOutput_K0sCosPointAngle(cutSetK0s->GetMonitorOutput()); // AddMonitorOutput_K0sProtonPID(cutSetK0s->GetMonitorOutput()); AddMonitorOutput_K0sPionPID(cutSetK0s->GetMonitorOutput()); AddMonitorOutput_K0sfpLife(cutSetK0s->GetMonitorOutput()); AddMonitorOutput_K0sMass_Pt(cutSetK0s->GetMonitorOutput()); //Monitor Output for Tracks AddMonitorOutput_MinDCAToVertexXYPtDep(cutSetK0s->GetMonitorOutput()); //AddMonitorOutput_MinDCAToVertexXY(cutSetK0s->GetMonitorOutput()); //Uncomment if fixed value Cut used if (isMC) { TString mode = "SPARSE"; //TString mode = "HIST"; //if (collSyst) mode = "SPARSE"; // create output AliRsnMiniOutput *out = task->CreateOutput(Form("KStarPlusMinus_MotherMC%s", suffix), mode.Data(), "MOTHER"); // selection settings out->SetDaughter(0, AliRsnDaughter::kKaon0); out->SetDaughter(1, AliRsnDaughter::kPion); out->SetMotherPDG(323); out->SetMotherMass(0.89166); // pair cuts out->SetPairCuts(PairCutsSame); // binnings out->AddAxis(imID, 90, 0.6, 1.5); out->AddAxis(ptID, 300, 0.0, 30.0); //out->AddAxis(k0sDCA, 10, 0.0, 1.0); if(isPP) out->AddAxis(centID, 400, 0.5, 400.5); else out->AddAxis(centID, mult_binning, mult_min, mult_max);//out->AddAxis(centID, 100, 0.0, 100.); out->AddAxis(SpherocityID, binning_sphero,min_sphero, max_sphero);//out->AddAxis(SpherocityID,1000,0.,1.); //ST //if (collSyst) out->AddAxis(centID, 10, 0.0, 100.0); if(isGT) out->AddAxis(sdpt,100,0.,10.); // create output AliRsnMiniOutput *out = task->CreateOutput(Form("AKStarPlusMinus_MotherMC%s", suffix), mode.Data(), "MOTHER"); // selection settings out->SetDaughter(0, AliRsnDaughter::kKaon0); out->SetDaughter(1, AliRsnDaughter::kPion); out->SetMotherPDG(-323); out->SetMotherMass(0.89166); // pair cuts out->SetPairCuts(PairCutsSame); // binnings out->AddAxis(imID, 90, 0.6, 1.5); out->AddAxis(ptID, 300, 0.0, 30.0); //out->AddAxis(k0sDCA, 10, 0.0, 1.0); //if (collSyst) out->AddAxis(centID, 10, 0.0, 100.0); if(isPP) out->AddAxis(centID, 400, 0.5, 400.5); else out->AddAxis(centID, mult_binning, mult_min, mult_max);//out->AddAxis(centID, 100, 0.0, 100.); out->AddAxis(SpherocityID, binning_sphero,min_sphero, max_sphero);//out->AddAxis(SpherocityID,1000,0.,1.); //ST if(isGT) out->AddAxis(sdpt,100,0.,10.); AliRsnMiniOutput* outps=task->CreateOutput(Form("K*_phaseSpace%s", suffix),"HIST","TRUE"); outps->SetDaughter(0,AliRsnDaughter::kKaon0); outps->SetDaughter(1,AliRsnDaughter::kPion); outps->SetCutID(0,iCutK0s); outps->SetCutID(1,iCutPi); outps->SetMotherPDG(323); outps->SetMotherMass(0.89166); outps->SetPairCuts(PairCutsSame); outps->AddAxis(fdpt,100,0.,10.); outps->AddAxis(sdpt,100,0.,10.); outps->AddAxis(ptID,200,0.,20.); //else outps->AddAxis(centID, mult_binning, mult_min, mult_max);//outps->AddAxis(centID,400,0.5,400.5);//ST //outps->AddAxis(SpherocityID, binning_sphero,min_sphero, max_sphero);//outps->AddAxis(SpherocityID,1000,0.,1.); //ST AliRsnMiniOutput* outpsf=task->CreateOutput(Form("K*_phaseSpaceFine%s", suffix),"HIST","TRUE"); outpsf->SetDaughter(0,AliRsnDaughter::kKaon0); outpsf->SetDaughter(1,AliRsnDaughter::kPion); outpsf->SetCutID(0,iCutK0s); outpsf->SetCutID(1,iCutPi); outpsf->SetMotherPDG(323); outpsf->SetMotherMass(0.89166); outpsf->SetPairCuts(PairCutsSame); outpsf->AddAxis(fdpt,30,0.,3.); outpsf->AddAxis(sdpt,30,0.,3.); outpsf->AddAxis(ptID,300,0.,3.); //else outpsf->AddAxis(centID, mult_binning, mult_min, mult_max);//outpsf->AddAxis(centID,400,0.5,400.5);//ST //outpsf->AddAxis(SpherocityID, binning_sphero,min_sphero, max_sphero);//outpsf->AddAxis(SpherocityID,1000,0.,1.); //ST } return kTRUE; } void AddMonitorOutput_PionPt(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *ppt=0) { // PionPt AliRsnValueDaughter *axisPionPt = new AliRsnValueDaughter("pion_pt", AliRsnValueDaughter::kPt); axisPionPt->SetBins(0.,10.0,0.001); // output: 2D histogram AliRsnListOutput *outMonitorPionPt = new AliRsnListOutput("Pion_Pt", AliRsnListOutput::kHistoDefault); outMonitorPionPt->AddValue(axisPionPt); // add outputs to loop if (mon) mon->Add(outMonitorPionPt); if (ppt) ppt->AddOutput(outMonitorPionPt); } void AddMonitorOutput_PionEta(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *peta=0) { // PionDCA AliRsnValueDaughter *axisPionEta = new AliRsnValueDaughter("pion_eta", AliRsnValueDaughter::kEta); axisPionEta->SetBins(-2.,2.,0.001); // output: 2D histogram AliRsnListOutput *outMonitorPionEta = new AliRsnListOutput("Pion_Eta", AliRsnListOutput::kHistoDefault); outMonitorPionEta->AddValue(axisPionEta); // add outputs to loop if (mon) mon->Add(outMonitorPionEta); if (peta) peta->AddOutput(outMonitorPionEta); } void AddMonitorOutput_PionDCAxy(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *pdcaxy=0) { // PionDCA AliRsnValueDaughter *axisPionDCAxy = new AliRsnValueDaughter("pion_dcaxy", AliRsnValueDaughter::kDCAXY); axisPionDCAxy->SetBins(-0.5,0.5,0.001); // output: 2D histogram AliRsnListOutput *outMonitorPionDCAxy = new AliRsnListOutput("Pion_DCAxy", AliRsnListOutput::kHistoDefault); outMonitorPionDCAxy->AddValue(axisPionDCAxy); // add outputs to loop if (mon) mon->Add(outMonitorPionDCAxy); if (pdcaxy) pdcaxy->AddOutput(outMonitorPionDCAxy); } void AddMonitorOutput_PionDCAz(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *pdcaz=0) { // PionDCA AliRsnValueDaughter *axisPionDCAz = new AliRsnValueDaughter("pion_dcaz", AliRsnValueDaughter::kDCAZ); axisPionDCAz->SetBins(-2.5,2.5,0.005); // output: 2D histogram AliRsnListOutput *outMonitorPionDCAz = new AliRsnListOutput("Pion_DCAz", AliRsnListOutput::kHistoDefault); outMonitorPionDCAz->AddValue(axisPionDCAz); // add outputs to loop if (mon) mon->Add(outMonitorPionDCAz); if (pdcaz) pdcaz->AddOutput(outMonitorPionDCAz); } void AddMonitorOutput_PionPIDCut(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *piPID=0) { // Pion PID Cut AliRsnValueDaughter *axisPionPIDCut = new AliRsnValueDaughter("pionPID", AliRsnValueDaughter::kTPCnsigmaPi); axisPionPIDCut->SetBins(0.0,5,0.01); // output: 2D histogram AliRsnListOutput *outMonitorPionPIDCut = new AliRsnListOutput("Pion_PID_Cut", AliRsnListOutput::kHistoDefault); outMonitorPionPIDCut->AddValue(axisPionPIDCut); // add outputs to loop if (mon) mon->Add(outMonitorPionPIDCut); if (piPID) piPID->AddOutput(outMonitorPionPIDCut); } void AddMonitorOutput_PionNTPC(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *piNTPC=0) { // Pion PID Cut AliRsnValueDaughter *axisPionNTPC = new AliRsnValueDaughter("pionNTPC", AliRsnValueDaughter::kNTPCclusters); axisPionNTPC->SetBins(0.0,200,1); // output: 2D histogram AliRsnListOutput *outMonitorPionNTPC = new AliRsnListOutput("Pion_NTPC", AliRsnListOutput::kHistoDefault); outMonitorPionNTPC->AddValue(axisPionNTPC); // add outputs to loop if (mon) mon->Add(outMonitorPionNTPC); if (piNTPC) pNTPC->AddOutput(outMonitorPionNTPC); } void AddMonitorOutput_PionTPCchi2(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *piTPCchi2=0) { // Pion PID Cut AliRsnValueDaughter *axisPionTPCchi2 = new AliRsnValueDaughter("pionTPCchi2", AliRsnValueDaughter::kTPCchi2); axisPionTPCchi2->SetBins(0.0,6,.1); // output: 2D histogram AliRsnListOutput *outMonitorPionTPCchi2 = new AliRsnListOutput("Pion_TPCchi2", AliRsnListOutput::kHistoDefault); outMonitorPionTPCchi2->AddValue(axisPionTPCchi2); // add outputs to loop if (mon) mon->Add(outMonitorPionTPCchi2); if (piTPCchi2) pTPCchi2->AddOutput(outMonitorPionTPCchi2); } void AddMonitorOutput_K0sP(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lp=0) { AliRsnValueDaughter *axisK0sP = new AliRsnValueDaughter("k0s_momentum", AliRsnValueDaughter::kP); axisK0sP->SetBins(0.,15.,0.001); // output: 2D histogram AliRsnListOutput *outMonitorMom = new AliRsnListOutput("K0s_Momentum", AliRsnListOutput::kHistoDefault); outMonitorMom->AddValue(axisK0sP); // add outputs to loop if (mon) mon->Add(outMonitorMom); if (lp) lp->AddOutput(outMonitorMom); } void AddMonitorOutput_K0sPt(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lpt=0) { // Pt AliRsnValueDaughter *axisK0sPt = new AliRsnValueDaughter("k0s_transversemomentum", AliRsnValueDaughter::kV0Pt); axisK0sPt->SetBins(0.,15.,0.001); // output: 2D histogram AliRsnListOutput *outMonitorTrMom = new AliRsnListOutput("K0s_TransverseMomentum", AliRsnListOutput::kHistoDefault); outMonitorTrMom->AddValue(axisK0sPt); // add outputs to loop if (mon) mon->Add(outMonitorTrMom); if (lpt) lpt->AddOutput(outMonitorTrMom); } void AddMonitorOutput_K0sNegDaughPt(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lnpt=0) { // Pt AliRsnValueDaughter *axisK0sNegDaughPt = new AliRsnValueDaughter("k0s_negdaugh_transversemomentum", AliRsnValueDaughter::kV0NPt); axisK0sNegDaughPt->SetBins(0.,15.,0.001); // output: 2D histogram AliRsnListOutput *outMonitorK0sNegDaughTrMom = new AliRsnListOutput("K0s_NegDaugh_TransverseMomentum", AliRsnListOutput::kHistoDefault); outMonitorK0sNegDaughTrMom->AddValue(axisK0sNegDaughPt); // add outputs to loop if (mon) mon->Add(outMonitorK0sNegDaughTrMom); if (lnpt) lnpt->AddOutput(outMonitorK0sNegDaughTrMom); } void AddMonitorOutput_K0sPosDaughPt(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lppt=0) { // Mass AliRsnValueDaughter *axisK0sPosDaughPt = new AliRsnValueDaughter("k0s_posdaugh_transversemomentum", AliRsnValueDaughter::kV0PPt); axisK0sPosDaughPt->SetBins(0.,15.,0.001); // output: 2D histogram AliRsnListOutput *outMonitorK0sPosDaughTrMom = new AliRsnListOutput("K0s_PosDaugh_TransverseMomentum", AliRsnListOutput::kHistoDefault); outMonitorK0sPosDaughTrMom->AddValue(axisK0sPosDaughPt); // add outputs to loop if (mon) mon->Add(outMonitorK0sPosDaughTrMom); if (lppt) lppt->AddOutput(outMonitorK0sPosDaughTrMom); } void AddMonitorOutput_K0sMass(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lm=0) { // Mass AliRsnValueDaughter *axisMass = new AliRsnValueDaughter("k0s_mass", AliRsnValueDaughter::kV0Mass); axisMass->SetBins(0.4,0.6,0.001); // output: 2D histogram AliRsnListOutput *outMonitorM = new AliRsnListOutput("K0s_Mass", AliRsnListOutput::kHistoDefault); outMonitorM->AddValue(axisMass); // add outputs to loop if (mon) mon->Add(outMonitorM); if (lm) lm->AddOutput(outMonitorM); } /*void AddMonitorOutput_K0sDCA(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *ldca=0) { // K0s DCA AliRsnValueDaughter *axisK0sDCA = new AliRsnValueDaughter("k0s_dca", AliRsnValueDaughter::kV0DCA); axisK0sDCA->SetBins(0.0,0.4,0.001); // output: 2D histogram AliRsnListOutput *outMonitorK0sDCA = new AliRsnListOutput("K0s_DCA", AliRsnListOutput::kHistoDefault); outMonitorK0sDCA->AddValue(axisK0sDCA); // add outputs to loop if (mon) mon->Add(outMonitorK0sDCA); if (ldca) ldca->AddOutput(outMonitorK0sDCA); } */ void AddMonitorOutput_K0sRadius(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *ldca=0) { // K0s Radius AliRsnValueDaughter *axisK0sRadius = new AliRsnValueDaughter("k0s_radius", AliRsnValueDaughter::kV0Radius); axisK0sRadius->SetBins(0.0,200,0.2); // output: 2D histogram AliRsnListOutput *outMonitorK0sRadius = new AliRsnListOutput("K0s_Radius", AliRsnListOutput::kHistoDefault); outMonitorK0sRadius->AddValue(axisK0sRadius); // add outputs to loop if (mon) mon->Add(outMonitorK0sRadius); if (ldca) ldca->AddOutput(outMonitorK0sRadius); } void AddMonitorOutput_K0sDaughterDCA(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *ldaugdca=0) { // K0s Daughter DCA AliRsnValueDaughter *axisK0sDDCA = new AliRsnValueDaughter("k0s_daughterDCA", AliRsnValueDaughter::kDaughterDCA); axisK0sDDCA->SetBins(0.0,2,0.001); // output: 2D histogram AliRsnListOutput *outMonitorK0sDDCA = new AliRsnListOutput("K0s_DaughterDCA", AliRsnListOutput::kHistoDefault); outMonitorK0sDDCA->AddValue(axisK0sDDCA); // add outputs to loop if (mon) mon->Add(outMonitorK0sDDCA); if (ldaugdca) ldaugdca->AddOutput(outMonitorK0sDDCA); } void AddMonitorOutput_K0sCosPointAngle(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lcpa=0) { // K0s Cosine of the Pointing Angle AliRsnValueDaughter *axisK0sCPA = new AliRsnValueDaughter("k0s_cospointang", AliRsnValueDaughter::kCosPointAng); axisK0sCPA->SetBins(0.97,1.,0.0001); // output: 2D histogram AliRsnListOutput *outMonitorK0sCPA = new AliRsnListOutput("K0s_CosineOfPointingAngle", AliRsnListOutput::kHistoDefault); outMonitorK0sCPA->AddValue(axisK0sCPA); // add outputs to loop if (mon) mon->Add(outMonitorK0sCPA); if (lcpa) lcpa->AddOutput(outMonitorK0sCPA); } void AddMonitorOutput_K0sPionPID(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lpiPID=0) { AliRsnValueDaughter *axisK0sPionPID = new AliRsnValueDaughter("k0s_pionPID", AliRsnValueDaughter::kLambdaPionPIDCut); axisK0sPionPID->SetBins(0.0,5,0.01); // output: 2D histogram AliRsnListOutput *outMonitorK0sPionPID = new AliRsnListOutput("K0s_PionPID", AliRsnListOutput::kHistoDefault); outMonitorK0sPionPID->AddValue(axisK0sPionPID); // add outputs to loop if (mon) mon->Add(outMonitorK0sPionPID); if (lpiPID) lpiPID->AddOutput(outMonitorK0sPionPID); } void AddMonitorOutput_K0sAntiPionPID(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lapiPID=0) { AliRsnValueDaughter *axisK0sAntiPionPID = new AliRsnValueDaughter("k0s_antipionPID", AliRsnValueDaughter::kAntiLambdaAntiPionPIDCut); axisK0sAntiPionPID->SetBins(0.0,5,0.01); // output: 2D histogram AliRsnListOutput *outMonitorK0sAntiPionPID = new AliRsnListOutput("K0s_AntiPionPID", AliRsnListOutput::kHistoDefault); outMonitorK0sAntiPionPID->AddValue(axisK0sAntiPionPID); // add outputs to loop if (mon) mon->Add(outMonitorK0sAntiPionPID); if (lapiPID) lpiPID->AddOutput(outMonitorK0sAntiPionPID); } void AddMonitorOutput_MinDCAToVertexXYPtDep(TObjArray *mon=0, TString opt="", AliRsnLoopDaughter *trackDCAXY=0) { // DCAXY of Tracks AliRsnValueDaughter *axisDCATracks = new AliRsnValueDaughter("dcaXY_tracks", AliRsnValueDaughter::kV0DCAXY); axisDCATracks->SetBins(0.0,2,0.001); // output: 2D histogram AliRsnListOutput *outMonitorDCATracks = new AliRsnListOutput("DCAXY_Tracks", AliRsnListOutput::kHistoDefault); outMonitorDCATracks->AddValue(axisDCATracks); // add outputs to loop if (mon) mon->Add(outMonitorDCATracks); if (trackDCAXY) trackDCAXY->AddOutput(outMonitorDCATracks); } // DCA V0 Secondary Tracks to Primary Vertex void AddMonitorOutput_MinDCAToVertexXY(TObjArray *mon=0, TString opt="", AliRsnLoopDaughter *trackDCAXY=0) { // DCAXY of Tracks AliRsnValueDaughter *axisDCATracks = new AliRsnValueDaughter("dcaXY_tracks", AliRsnValueDaughter::kV0DCAXY); axisDCATracks->SetBins(0.0,2,0.001); // output: 2D histogram AliRsnListOutput *outMonitorDCATracks = new AliRsnListOutput("DCAXY_Tracks", AliRsnListOutput::kHistoDefault); outMonitorDCATracks->AddValue(axisDCATracks); // add outputs to loop if (mon) mon->Add(outMonitorDCATracks); if (trackDCAXY) trackDCAXY->AddOutput(outMonitorDCATracks); } // Lifetime of V0 particle. void AddMonitorOutput_K0sfpLife(TObjArray *mon=0, TString opt="", AliRsnLoopDaughter *llifetime=0) { AliRsnValueDaughter *k0slifetime = new AliRsnValueDaughter("lifetime", AliRsnValueDaughter::kV0Lifetime); k0slifetime->SetBins(0.0,200,0.1); // output: 2D histogram AliRsnListOutput *outMonitork0sLifetime = new AliRsnListOutput("k0s", AliRsnListOutput::kHistoDefault); outMonitork0sLifetime->AddValue(k0slifetime); // add outputs to loop if (mon) mon->Add(outMonitork0sLifetime); if (llifetime) llifetime->AddOutput(outMonitork0sLifetime); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AddMonitorOutput_K0sMass_Pt(TObjArray *mon=0, TString opt="", AliRsnLoopDaughter *lMass=0, AliRsnLoopDaughter *lPt=0) { AliRsnValueDaughter *axisMass = new AliRsnValueDaughter("K0s_Mass", AliRsnValueDaughter::kV0Mass); axisMass->SetBins(0.4,0.6,0.001); AliRsnValueDaughter *axisK0sPt = new AliRsnValueDaughter("K0s_Pt", AliRsnValueDaughter::kV0Pt); axisK0sPt->SetBins(0.,30.,0.001); // output: 2D histogram AliRsnListOutput *outMonitorTrMom = new AliRsnListOutput("K0s_Mass_Pt", AliRsnListOutput::kHistoDefault); outMonitorTrMom->AddValue(axisK0sPt); outMonitorTrMom->AddValue(axisMass); // add outputs to loop if (mon) mon->Add(outMonitorTrMom); if (lPt) lpt->AddOutput(outMonitorTrMom); //if (mon) mon->Add(outMonitorM); //if (lMass) lm->AddOutput(outMonitorM); } Bool_t SetCustomQualityCut(AliRsnCutTrackQuality * trkQualityCut, Int_t customQualityCutsID = 0, Int_t customFilterBit = 0) { //Sets configuration for track quality object different from std quality cuts. //Returns kTRUE if track quality cut object is successfully defined, //returns kFALSE if an invalid set of cuts (customQualityCutsID) is chosen or if the //object to be configured does not exist. if ((!trkQualityCut)){ Printf("::::: SetCustomQualityCut:: use default quality cuts specified in task configuration."); return kFALSE; } if(customQualityCutsID>=1 && customQualityCutsID<100 && customQualityCutsID!=2){ trkQualityCut->SetDefaults2011(kTRUE,kTRUE); Printf(Form("::::: SetCustomQualityCut:: using standard 2011 track quality cuts")); if(!customFilterBit){//ESD if(customQualityCutsID==3){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.0150+0.0500/pt^1.1");} else if(customQualityCutsID==4){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.006+0.0200/pt^1.1");} else if(customQualityCutsID==5){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(5.);} else if(customQualityCutsID==6){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(0.2);} else if(customQualityCutsID==7){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(5.);} else if(customQualityCutsID==8){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(2.3);} else if(customQualityCutsID==9){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(60);} else if(customQualityCutsID==10){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(100);} else if(customQualityCutsID==11){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.7);} else if(customQualityCutsID==12){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.9);} else if(customQualityCutsID==13){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(49.);} else if(customQualityCutsID==14){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(4.);} else if(customQualityCutsID==15){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(49.);} else if(customQualityCutsID==16){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(25.);} else if(customQualityCutsID==17){trkQualityCut->GetESDtrackCuts()->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kOff);} else if(customQualityCutsID==56){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(1.);} else if(customQualityCutsID==58){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(3.);} else if(customQualityCutsID==60){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(80);} else if(customQualityCutsID==64){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(25.);} }else{//AOD trkQualityCut->SetCheckOnlyFilterBit(kFALSE); if(customQualityCutsID==4){trkQualityCut->SetDCARPtFormula("0.006+0.0200/pt^1.1");} else if(customQualityCutsID==6){trkQualityCut->SetDCAZmax(0.2);} else if(customQualityCutsID==8){trkQualityCut->SetTrackMaxChi2(2.3);} else if(customQualityCutsID==10){trkQualityCut->SetMinNCrossedRowsTPC(100,kTRUE);} else if(customQualityCutsID==12){trkQualityCut->SetMinNCrossedRowsOverFindableClsTPC(0.9,kTRUE);} else if(customQualityCutsID==56){trkQualityCut->SetDCAZmax(1.);} else if(customQualityCutsID==58){trkQualityCut->SetTrackMaxChi2(3.5);} else if(customQualityCutsID==60){trkQualityCut->SetMinNCrossedRowsTPC(80,kTRUE);} } trkQualityCut->Print(); return kTRUE; }else if(customQualityCutsID==2 || (customQualityCutsID>=100 && customQualityCutsID<200)){ trkQualityCut->SetDefaultsTPCOnly(kTRUE); Printf(Form("::::: SetCustomQualityCut:: using TPC-only track quality cuts")); if(customQualityCutsID==103){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXY(3.);} else if(customQualityCutsID==104){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXY(1.);} else if(customQualityCutsID==105){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(4.);} else if(customQualityCutsID==106){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(1.);} else if(customQualityCutsID==107){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(7.);} else if(customQualityCutsID==108){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(2.5);} else if(customQualityCutsID==109){trkQualityCut->GetESDtrackCuts()->SetMinNClustersTPC(30);} else if(customQualityCutsID==110){trkQualityCut->GetESDtrackCuts()->SetMinNClustersTPC(85);} trkQualityCut->Print(); return kTRUE; }else{ Printf("::::: SetCustomQualityCut:: use default quality cuts specified in task configuration."); return kFALSE; } //for pA 2013 //trkQualityCut->SetDefaults2011();//with filter bit=10 //reset filter bit to very loose cuts trkQualityCut->SetAODTestFilterBit(customFilterBit); //apply all other cuts "by hand" trkQualityCut->SetCheckOnlyFilterBit(kFALSE); trkQualityCut->SetMinNCrossedRowsTPC(70, kTRUE); trkQualityCut->SetMinNCrossedRowsOverFindableClsTPC(0.8, kTRUE); trkQualityCut->SetMaxChi2TPCConstrainedGlobal(36);//used for ESD only - for AOD does not correspond to any cut trkQualityCut->SetTPCmaxChi2(4.0); //already in filter bit 0 trkQualityCut->SetRejectKinkDaughters(kTRUE); //already in filter bit 0 trkQualityCut->SetSPDminNClusters(AliESDtrackCuts::kAny); trkQualityCut->SetITSmaxChi2(36); trkQualityCut->AddStatusFlag(AliESDtrack::kTPCin , kTRUE);//already in defaults 2011 trkQualityCut->AddStatusFlag(AliESDtrack::kTPCrefit, kTRUE);//already in defaults 2011 trkQualityCut->AddStatusFlag(AliESDtrack::kITSrefit, kTRUE);//already in defaults 2011 if (customQualityCutsID==AliRsnCutSetDaughterParticle::kFilterBitCustom) { trkQualityCut->SetCheckOnlyFilterBit(kTRUE); } if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdLooserDCAXY){ trkQualityCut->SetDCARmax(2.4); } else { trkQualityCut->SetDCARPtFormula("0.0105+0.0350/pt^1.1"); } if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdLooserDCAZ){ trkQualityCut->SetDCAZmax(3.2); } else { trkQualityCut->SetDCAZmax(2.0); } if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdCrossedRows60){ trkQualityCut->SetMinNCrossedRowsTPC(60, kTRUE); } if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdCrossedRows80){ trkQualityCut->SetMinNCrossedRowsTPC(80, kTRUE); } if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdRowsToCls075){ trkQualityCut->SetMinNCrossedRowsOverFindableClsTPC(0.75, kTRUE); } if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdRowsToCls085){ trkQualityCut->SetMinNCrossedRowsOverFindableClsTPC(0.85, kTRUE); } if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdCls70){ trkQualityCut->SetAODTestFilterBit(10); trkQualityCut->SetTPCminNClusters(70); } if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdChi2TPCCls35){ trkQualityCut->SetTPCmaxChi2(3.5); } trkQualityCut->SetPtRange(0.15, 20.0); trkQualityCut->SetEtaRange(-0.8, 0.8); Printf(Form("::::: SetCustomQualityCut:: using custom track quality cuts #%i",customQualityCutsID)); trkQualityCut->Print(); return kTRUE; }
{'content_hash': 'dee8418daaae7fd1b79692bcf78ceea1', 'timestamp': '', 'source': 'github', 'line_count': 897, 'max_line_length': 200, 'avg_line_length': 46.96544035674471, 'alnum_prop': 0.6205136726167869, 'repo_name': 'pchrista/AliPhysics', 'id': '1f30da2efd62d3f5a4608f60424f2265b5f1bc45', 'size': '42128', 'binary': False, 'copies': '24', 'ref': 'refs/heads/master', 'path': 'PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusRun2sp_bin.C', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '92852198'}, {'name': 'C++', 'bytes': '192724218'}, {'name': 'CMake', 'bytes': '694146'}, {'name': 'CSS', 'bytes': '5189'}, {'name': 'Fortran', 'bytes': '176927'}, {'name': 'HTML', 'bytes': '34924'}, {'name': 'JavaScript', 'bytes': '3536'}, {'name': 'Makefile', 'bytes': '24994'}, {'name': 'Objective-C', 'bytes': '62560'}, {'name': 'Perl', 'bytes': '18619'}, {'name': 'Python', 'bytes': '797351'}, {'name': 'SWIG', 'bytes': '33320'}, {'name': 'Shell', 'bytes': '1127312'}, {'name': 'TeX', 'bytes': '392122'}]}
import arcpy, os try: mxd = arcpy.mapping.MapDocument("CURRENT") ddp = mxd.dataDrivenPages #Let's make a backup in case we jack something up royally outputPath = os.path.dirname(ddp.indexLayer.dataSource) outputName = os.path.basename(ddp.indexLayer.dataSource) if "." in outputName: outputName = outputName.replace(".","_old.") else: outputName = outputName + "_old" #This bit makes sure the backup filename doesn't already exist while os.path.exists(os.path.join(outputPath, outputName)): fileCounter = 0 outputName = outputName.replace("_old","_old" + str(fileCounter)) backupFC = arcpy.Copy_management(ddp.indexLayer.dataSource, os.path.join(outputPath,outputName)) arcpy.AddMessage("...Backing up original viewport layer") #Add a field to hold the scale fldLst = [f.name for f in arcpy.ListFields(ddp.indexLayer.dataSource)] if "DDP_Scale" not in fldLst: arcpy.AddField_management(ddp.indexLayer, "DDP_Scale", "LONG") #For each shape in the viewport feature class... counter = 1 while counter <= ddp.pageCount: ddp.currentPageID = counter arcpy.AddMessage("...Updating page " + str(ddp.currentPageID)) ddp.refresh() #Grab the extent of the data frame curExtent = ddp.dataFrame.extent pnt1 = arcpy.Point(curExtent .XMin, curExtent .YMin) pnt2 = arcpy.Point(curExtent .XMin, curExtent .YMax) pnt3 = arcpy.Point(curExtent .XMax, curExtent .YMax) pnt4 = arcpy.Point(curExtent .XMax, curExtent .YMin) array = arcpy.Array([pnt1, pnt2, pnt3, pnt4]) polygon = arcpy.Polygon(array) #And the then use it to update the shape rows = arcpy.da.UpdateCursor(ddp.indexLayer,["SHAPE@","DDP_Scale"], '"FID" = ' + str(ddp.pageRow.FID)) # ---> to make this generally useful, you'll have to write something to find the object id field and verify proper syntax to call it based on file type for row in rows: rows.updateRow([polygon, ddp.dataFrame.scale]) counter = counter + 1 arcpy.AddMessage("...Your layer has been updated.") arcpy.AddMessage("...I backed up the old one here: " + os.path.join(outputPath,outputName)) #Cleaning up del row del rows del mxd del ddp except Exception as e: arcpy.AddMessage(e.message)
{'content_hash': '10dc867755b181aba2fc344bf76a0f62', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 159, 'avg_line_length': 39.19672131147541, 'alnum_prop': 0.6629025512337934, 'repo_name': 'sdearmond/arcgis-ddp-ddptoolbox', 'id': 'c98330e4368c4641c6ef152843f5e12463cf8782', 'size': '2962', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'python/UpdateViewportExtent.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '11034'}]}
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>03_polyphony</title> <script src="libraries/p5.js" type="text/javascript"></script> <script src="libraries/p5.dom.js" type="text/javascript"></script> <script src="libraries/p5.sound.js" type="text/javascript"></script> <script src="libraries/p5.serialport.js" type="text/javascript"></script> <script src="sketch.js" type="text/javascript"></script> <style> body {padding: 0; margin: 0;} canvas {vertical-align: top;} </style> </head> <body> </body> </html>
{'content_hash': '66ae3ee108631c65d7e28cea5324a793', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 80, 'avg_line_length': 31.22222222222222, 'alnum_prop': 0.6494661921708185, 'repo_name': 'evejweinberg/ICM', 'id': '1ed06c659398f4fc19fa7cbe0c366bd2ab2562a9', 'size': '562', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '03_WORKSHOPS/p5_soundWorkshop01/04d_polyphony/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '888'}, {'name': 'Arduino', 'bytes': '318'}, {'name': 'Batchfile', 'bytes': '1131'}, {'name': 'C', 'bytes': '80088'}, {'name': 'C++', 'bytes': '116715'}, {'name': 'CSS', 'bytes': '86578'}, {'name': 'GLSL', 'bytes': '40144'}, {'name': 'HTML', 'bytes': '3121081'}, {'name': 'JavaScript', 'bytes': '295222779'}, {'name': 'MAXScript', 'bytes': '75494'}, {'name': 'Makefile', 'bytes': '454'}, {'name': 'Processing', 'bytes': '1890'}, {'name': 'Python', 'bytes': '459091'}, {'name': 'Shell', 'bytes': '10183'}]}
class FunctionType; class BlockExpression; class Declaration; class Type; class FunctionExpression : public Expression { private: FunctionExpression(); friend class ::boost::serialization::access; template<class A> void serialize(A& ar, const unsigned int) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Expression); ar & BOOST_SERIALIZATION_NVP(_body); ar & BOOST_SERIALIZATION_NVP(_symbol); ar & BOOST_SERIALIZATION_NVP(_functionScope); } private: BlockExpression *_body; Symbol *_symbol; SymbolScope *_functionScope; public: FunctionExpression(Symbol *symbol, SymbolScope *functionScope); virtual ~FunctionExpression(); public: virtual Expression* GetLValue(); virtual void Accept(ExpressionVisitor* visitor); virtual Type * GetType(); public: Symbol *GetSymbol(); std::string GetName(); BlockExpression *GetBody(); void SetBody(BlockExpression *body); Type * GetReturnType(); std::vector<Declaration *> *GetParameters(); SymbolScope *GetFunctionScope(); }; #endif // FUNCTIONEXPRESSION_H
{'content_hash': '6cc9c8cb48857f832a7a97b19adf1595', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 67, 'avg_line_length': 26.073170731707318, 'alnum_prop': 0.7202993451824135, 'repo_name': 'layerzero/cc0', 'id': 'b3be0597143ad4dd6e46aa62cb20a6329a45dddf', 'size': '1269', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/toolchain/core/CodeDom/FunctionExpression.h', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Assembly', 'bytes': '37'}, {'name': 'C', 'bytes': '152232'}, {'name': 'C++', 'bytes': '516844'}, {'name': 'GAP', 'bytes': '69898'}, {'name': 'Shell', 'bytes': '1134'}, {'name': 'TeX', 'bytes': '22466'}]}
#ifndef BOOST_HANA_FWD_MAP_HPP #define BOOST_HANA_FWD_MAP_HPP #include <boost/hana/config.hpp> #include <boost/hana/fwd/core/to.hpp> #include <boost/hana/fwd/core/make.hpp> #include <boost/hana/fwd/erase_key.hpp> #include <boost/hana/fwd/insert.hpp> #include <boost/hana/fwd/keys.hpp> #include <utility> BOOST_HANA_NAMESPACE_BEGIN //! Tag representing `hana::map`s. //! @relates hana::map struct map_tag { }; //! @ingroup group-datatypes //! Basic associative container requiring unique, `Comparable` and //! `Hashable` keys. //! //! The order of the elements of the map is unspecified. Also, all the //! keys must be `Hashable`, and any two keys with equal hashes must be //! `Comparable` with each other at compile-time. //! //! Note that the actual representation of a `hana::map` is an implementation //! detail. As such, one should not assume anything more than what is //! explicitly documented as being part of the interface of a map, //! such as: //! - the presence of additional constructors //! - the presence of additional assignment operators //! - the fact that `hana::map<Pairs...>` is, or is not, a dependent type //! //! In particular, the last point is very important; `hana::map<Pairs...>` //! is only a shortcut for //! @code //! decltype(hana::make_pair(std::declval<Pairs>()...)) //! @endcode //! which is not something that can be pattern-matched on during template //! argument deduction, for example. //! //! //! Modeled concepts //! ---------------- //! 1. `Comparable`\n //! Two maps are equal iff all their keys are equal and are associated //! to equal values. //! @include example/map/comparable.cpp //! //! 2. `Searchable`\n //! A map can be searched by its keys with a predicate yielding a //! compile-time `Logical`. Also note that `operator[]` can be used //! instead of `at_key`. //! @include example/map/searchable.cpp //! //! 3. `Foldable`\n //! Folding a map is equivalent to folding a list of the key/value pairs //! it contains. In particular, since that list is not guaranteed to be //! in any specific order, folding a map with an operation that is not //! both commutative and associative will yield non-deterministic behavior. //! @include example/map/foldable.cpp //! //! //! Conversion from any `Foldable` //! ------------------------------ //! Any `Foldable` of `Product`s can be converted to a `hana::map` with //! `hana::to<hana::map_tag>` or, equivalently, `hana::to_map`. If the //! `Foldable` contains duplicate keys, only the value associated to the //! first occurence of each key is kept. //! @include example/map/to.cpp //! //! //! Example //! ------- //! @include example/map/map.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED template <typename ...Pairs> struct map { //! Default-construct a map. This constructor only exists when all the //! elements of the map are default-constructible. constexpr map() = default; //! Copy-construct a map from another map. This constructor only //! exists when all the elements of the map are copy-constructible. constexpr map(map const& other) = default; //! Move-construct a map from another map. This constructor only //! exists when all the elements of the map are move-constructible. constexpr map(map&& other) = default; //! Construct the map from the provided pairs. `P...` must be pairs of //! the same type (modulo ref and cv-qualifiers), and in the same order, //! as those appearing in `Pairs...`. The pairs provided to this //! constructor are emplaced into the map's storage using perfect //! forwarding. template <typename ...P> explicit constexpr map(P&& ...pairs); //! Equivalent to `hana::equal` template <typename X, typename Y> friend constexpr auto operator==(X&& x, Y&& y); //! Equivalent to `hana::not_equal` template <typename X, typename Y> friend constexpr auto operator!=(X&& x, Y&& y); //! Equivalent to `hana::at_key` template <typename Key> constexpr decltype(auto) operator[](Key&& key); }; #else template <typename ...Pairs> using map = decltype(hana::make<map_tag>(std::declval<Pairs>()...)); #endif //! Function object for creating a `hana::map`. //! @relates hana::map //! //! Given zero or more `Product`s representing key/value associations, //! `make<map_tag>` returns a `hana::map` associating these keys to these //! values. //! //! `make<map_tag>` requires all the keys to be unique and to have //! different hashes. If you need to create a map with duplicate keys //! or with keys whose hashes might collide, use `hana::to_map` or //! insert `(key, value)` pairs to an empty map successively. However, //! be aware that doing so will be much more compile-time intensive than //! using `make<map_tag>`, because the uniqueness of keys will have to be //! enforced. //! //! //! Example //! ------- //! @include example/map/make.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED template <> constexpr auto make<map_tag> = [](auto&& ...pairs) { return map<implementation_defined>{forwarded(pairs)...}; }; #endif //! Alias to `make<map_tag>`; provided for convenience. //! @relates hana::map //! //! //! Example //! ------- //! @include example/map/make.cpp constexpr auto make_map = make<map_tag>; //! Equivalent to `to<map_tag>`; provided for convenience. //! @relates hana::map constexpr auto to_map = to<map_tag>; //! Returns a `Sequence` of the keys of the map, in unspecified order. //! @relates hana::map //! //! //! Example //! ------- //! @include example/map/keys.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto keys = [](auto&& map) { return implementation_defined; }; #endif //! Returns a `Sequence` of the values of the map, in unspecified order. //! @relates hana::map //! //! //! Example //! ------- //! @include example/map/values.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto values = [](auto&& map) -> decltype(auto) { return implementation_defined; }; #else struct values_t { template <typename Map> constexpr decltype(auto) operator()(Map&& map) const; }; constexpr values_t values{}; #endif //! Inserts a new key/value pair in a map. //! @relates hana::map //! //! Given a `(key, value)` pair, `insert` inserts this new pair into a //! map. If the map already contains this key, nothing is done and the //! map is returned as-is. //! //! //! @param map //! The map in which to insert a `(key,value)` pair. //! //! @param pair //! An arbitrary `Product` representing a `(key, value)` pair to insert //! in the map. The `key` must be compile-time `Comparable`. //! //! //! Example //! ------- //! @include example/map/insert.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto insert = [](auto&& map, auto&& pair) { return tag-dispatched; }; #endif //! Removes a key/value pair from a map. //! @relates hana::map //! //! Returns a new `hana::map` containing all the elements of the original, //! except for the `(key, value)` pair whose `key` compares `equal` //! to the given key. If the map does not contain such an element, //! a new map equal to the original is returned. //! //! //! @param map //! The map in which to erase a `key`. //! //! @param key //! A key to remove from the map. It must be compile-time `Comparable`. //! //! //! Example //! ------- //! @include example/map/erase_key.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto erase_key = [](auto&& map, auto&& key) { return tag-dispatched; }; #endif BOOST_HANA_NAMESPACE_END #endif // !BOOST_HANA_FWD_MAP_HPP
{'content_hash': '9715f88642d4c38b6feeb4c8679ed076', 'timestamp': '', 'source': 'github', 'line_count': 242, 'max_line_length': 81, 'avg_line_length': 34.099173553719005, 'alnum_prop': 0.6061560833737276, 'repo_name': 'jmanday/Master', 'id': '25ff7add35914b2e0dd1a29869ee26545f212e31', 'size': '8475', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'TFM/library/boost_1_63_0/boost/hana/fwd/map.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '309067'}, {'name': 'Batchfile', 'bytes': '71697'}, {'name': 'C', 'bytes': '3962470'}, {'name': 'C#', 'bytes': '125762'}, {'name': 'C++', 'bytes': '216284659'}, {'name': 'CMake', 'bytes': '1594049'}, {'name': 'CSS', 'bytes': '1737798'}, {'name': 'CWeb', 'bytes': '174166'}, {'name': 'Clojure', 'bytes': '1487'}, {'name': 'Cuda', 'bytes': '1741779'}, {'name': 'DIGITAL Command Language', 'bytes': '6246'}, {'name': 'Fortran', 'bytes': '1856'}, {'name': 'HLSL', 'bytes': '3314'}, {'name': 'HTML', 'bytes': '192312054'}, {'name': 'IDL', 'bytes': '28'}, {'name': 'Java', 'bytes': '1111092'}, {'name': 'JavaScript', 'bytes': '1906363'}, {'name': 'Lex', 'bytes': '1231'}, {'name': 'M4', 'bytes': '29689'}, {'name': 'Makefile', 'bytes': '8410569'}, {'name': 'Max', 'bytes': '36857'}, {'name': 'Objective-C', 'bytes': '12659'}, {'name': 'Objective-C++', 'bytes': '211927'}, {'name': 'PHP', 'bytes': '140802'}, {'name': 'Pascal', 'bytes': '26079'}, {'name': 'Perl', 'bytes': '54411'}, {'name': 'PowerShell', 'bytes': '16406'}, {'name': 'Python', 'bytes': '2808348'}, {'name': 'QML', 'bytes': '593'}, {'name': 'QMake', 'bytes': '16692'}, {'name': 'R', 'bytes': '69855'}, {'name': 'Rebol', 'bytes': '354'}, {'name': 'Roff', 'bytes': '5189'}, {'name': 'Ruby', 'bytes': '9652'}, {'name': 'Scala', 'bytes': '5683'}, {'name': 'Shell', 'bytes': '416161'}, {'name': 'Tcl', 'bytes': '1172'}, {'name': 'TeX', 'bytes': '1096187'}, {'name': 'XSLT', 'bytes': '553585'}, {'name': 'Yacc', 'bytes': '19623'}]}
package org.socialmoms.init; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; /** * Created by: Bilal Clarance, [email protected] * On: 4/27/14 4:31 PM * social-moms */ public class AppInitializer implements WebApplicationInitializer { private static Logger logger = LoggerFactory.getLogger(AppInitializer.class); private static final String CONFIG_LOCATION = "org.socialmoms.config"; private static final String MAPPING_URL = "/*"; @Override public void onStartup(ServletContext servletContext) throws ServletException { WebApplicationContext context = getContext(); servletContext.addListener(new ContextLoaderListener(context)); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping(MAPPING_URL); } private WebApplicationContext getContext() { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.setConfigLocation(CONFIG_LOCATION); return context; } }
{'content_hash': 'd874185605bfc344bc1b2582f3551aaf', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 128, 'avg_line_length': 37.785714285714285, 'alnum_prop': 0.7863894139886578, 'repo_name': 'bclarance/social-moms', 'id': '56de88337354423b182b4af6e9cb07a0e155a471', 'size': '1587', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/socialmoms/init/AppInitializer.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '55'}, {'name': 'Java', 'bytes': '10194'}, {'name': 'JavaScript', 'bytes': '470'}]}
package org.springframework.boot.autoconfigure.data.neo4j; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.TestAutoConfigurationPackage; import org.springframework.boot.autoconfigure.data.empty.EmptyDataPackage; import org.springframework.boot.autoconfigure.data.neo4j.city.City; import org.springframework.boot.autoconfigure.data.neo4j.city.CityRepository; import org.springframework.boot.autoconfigure.data.neo4j.city.ReactiveCityRepository; import org.springframework.boot.autoconfigure.data.neo4j.country.CountryRepository; import org.springframework.boot.autoconfigure.data.neo4j.country.ReactiveCountryRepository; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Configuration; import org.springframework.data.neo4j.core.ReactiveNeo4jTemplate; import org.springframework.data.neo4j.repository.ReactiveNeo4jRepository; import org.springframework.data.neo4j.repository.config.EnableReactiveNeo4jRepositories; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link Neo4jReactiveRepositoriesAutoConfiguration}. * * @author Stephane Nicoll * @author Michael J. Simons */ public class Neo4jReactiveRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(MockedDriverConfiguration.class) .withConfiguration(AutoConfigurations.of(Neo4jDataAutoConfiguration.class, Neo4jReactiveDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class, Neo4jReactiveRepositoriesAutoConfiguration.class)); @Test void configurationWithDefaultRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(ReactiveCityRepository.class)); } @Test void configurationWithNoRepositories() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(ReactiveNeo4jTemplate.class).doesNotHaveBean(ReactiveNeo4jRepository.class)); } @Test void configurationWithDisabledRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.neo4j.repositories.type=none") .run((context) -> assertThat(context).doesNotHaveBean(ReactiveNeo4jRepository.class)); } @Test void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jTemplate.class) .doesNotHaveBean(ReactiveNeo4jRepository.class)); } @Test void shouldRespectAtEnableReactiveNeo4jRepositories() { this.contextRunner .withUserConfiguration(SortOfInvalidCustomConfiguration.class, WithCustomReactiveRepositoryScan.class) .withPropertyValues("spring.data.neo4j.repositories.type=reactive") .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class) .doesNotHaveBean(ReactiveCityRepository.class).doesNotHaveBean(CountryRepository.class) .hasSingleBean(ReactiveCountryRepository.class)); } @Configuration(proxyBeanMethods = false) @TestAutoConfigurationPackage(City.class) static class TestConfiguration { } @Configuration(proxyBeanMethods = false) @TestAutoConfigurationPackage(EmptyDataPackage.class) static class EmptyConfiguration { } @Configuration(proxyBeanMethods = false) @EnableReactiveNeo4jRepositories("foo.bar") @TestAutoConfigurationPackage(Neo4jReactiveRepositoriesAutoConfigurationTests.class) static class SortOfInvalidCustomConfiguration { } @Configuration(proxyBeanMethods = false) @EnableReactiveNeo4jRepositories(basePackageClasses = ReactiveCountryRepository.class) static class WithCustomReactiveRepositoryScan { } }
{'content_hash': '9b2522e14c3142ead2a0e1628c40d791', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 106, 'avg_line_length': 40.5, 'alnum_prop': 0.8372385991433611, 'repo_name': 'philwebb/spring-boot', 'id': '66afb613f5e3f58d700c399d041256e29426a285', 'size': '4590', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveRepositoriesAutoConfigurationTests.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2141'}, {'name': 'CSS', 'bytes': '450'}, {'name': 'Dockerfile', 'bytes': '2237'}, {'name': 'Groovy', 'bytes': '26659'}, {'name': 'HTML', 'bytes': '70165'}, {'name': 'Java', 'bytes': '20003375'}, {'name': 'JavaScript', 'bytes': '37722'}, {'name': 'Kotlin', 'bytes': '63396'}, {'name': 'Mustache', 'bytes': '449'}, {'name': 'Ruby', 'bytes': '7877'}, {'name': 'Shell', 'bytes': '42860'}, {'name': 'Smarty', 'bytes': '2882'}, {'name': 'Vim Snippet', 'bytes': '135'}]}
namespace Microsoft.Azure.Management.Network.Models { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Microsoft.Rest.Azure; /// <summary> /// IPConfiguration in a NetworkInterface /// </summary> public partial class NetworkInterfaceIPConfiguration : SubResource { /// <summary> /// Initializes a new instance of the NetworkInterfaceIPConfiguration /// class. /// </summary> public NetworkInterfaceIPConfiguration() { } /// <summary> /// Initializes a new instance of the NetworkInterfaceIPConfiguration /// class. /// </summary> public NetworkInterfaceIPConfiguration(string name = default(string), string etag = default(string), IList<BackendAddressPool> loadBalancerBackendAddressPools = default(IList<BackendAddressPool>), IList<InboundNatRule> loadBalancerInboundNatRules = default(IList<InboundNatRule>), string privateIPAddress = default(string), string privateIPAllocationMethod = default(string), Subnet subnet = default(Subnet), PublicIPAddress publicIPAddress = default(PublicIPAddress), string provisioningState = default(string)) { Name = name; Etag = etag; LoadBalancerBackendAddressPools = loadBalancerBackendAddressPools; LoadBalancerInboundNatRules = loadBalancerInboundNatRules; PrivateIPAddress = privateIPAddress; PrivateIPAllocationMethod = privateIPAllocationMethod; Subnet = subnet; PublicIPAddress = publicIPAddress; ProvisioningState = provisioningState; } /// <summary> /// Gets name of the resource that is unique within a resource group. /// This name can be used to access the resource /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// A unique read-only string that changes whenever the resource is /// updated /// </summary> [JsonProperty(PropertyName = "etag")] public string Etag { get; set; } /// <summary> /// Gets or sets the reference of LoadBalancerBackendAddressPool /// resource /// </summary> [JsonProperty(PropertyName = "properties.loadBalancerBackendAddressPools")] public IList<BackendAddressPool> LoadBalancerBackendAddressPools { get; set; } /// <summary> /// Gets or sets list of references of LoadBalancerInboundNatRules /// </summary> [JsonProperty(PropertyName = "properties.loadBalancerInboundNatRules")] public IList<InboundNatRule> LoadBalancerInboundNatRules { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "properties.privateIPAddress")] public string PrivateIPAddress { get; set; } /// <summary> /// Gets or sets PrivateIP allocation method (Static/Dynamic). /// Possible values for this property include: 'Static', 'Dynamic'. /// </summary> [JsonProperty(PropertyName = "properties.privateIPAllocationMethod")] public string PrivateIPAllocationMethod { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "properties.subnet")] public Subnet Subnet { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "properties.publicIPAddress")] public PublicIPAddress PublicIPAddress { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; set; } } }
{'content_hash': 'cc14a15a59628bb9dc6409de9a3f90a7', 'timestamp': '', 'source': 'github', 'line_count': 94, 'max_line_length': 520, 'avg_line_length': 40.765957446808514, 'alnum_prop': 0.6471816283924844, 'repo_name': 'devigned/azure-powershell', 'id': '0309dce1bdb037cd14c6aa09ad694f73e1fdf185', 'size': '4153', 'binary': False, 'copies': '5', 'ref': 'refs/heads/preview', 'path': 'src/ResourceManager/Network/Stack/Commands.Network/Generated/Models/NetworkInterfaceIpConfiguration.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '18388'}, {'name': 'C#', 'bytes': '60706952'}, {'name': 'HTML', 'bytes': '209'}, {'name': 'JavaScript', 'bytes': '4979'}, {'name': 'PHP', 'bytes': '41'}, {'name': 'PowerShell', 'bytes': '7187413'}, {'name': 'Ruby', 'bytes': '398'}, {'name': 'Shell', 'bytes': '50'}, {'name': 'Smalltalk', 'bytes': '2510'}, {'name': 'XSLT', 'bytes': '6114'}]}
package com.karenpownall.android.aca.forartssake.model.artworksModels; import javax.annotation.Generated; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; @Generated("org.jsonschema2pojo") public class Self { @SerializedName("href") @Expose private String href; /** * * @return * The href */ public String getHref() { return href; } /** * * @param href * The href */ public void setHref(String href) { this.href = href; } }
{'content_hash': 'ef00e08ca67f5aaaa76044520002d33e', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 70, 'avg_line_length': 17.515151515151516, 'alnum_prop': 0.6089965397923875, 'repo_name': 'knpFletcher/CapstoneProject', 'id': '36811cfb577d19648abdca9c37aa9389dbb876ce', 'size': '578', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ForArtsSake/app/src/main/java/com/karenpownall/android/aca/forartssake/model/artworksModels/Self.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '148733'}]}
layout: "docs" page_title: "Coordinate (HTTP)" sidebar_current: "docs-agent-http-coordinate" description: > The Coordinate endpoint is used to query for the network coordinates for nodes in the local datacenter as well as Consul servers in the local datacenter and remote datacenters. --- # Coordinate HTTP Endpoint The Coordinate endpoint is used to query for the network coordinates for nodes in the local datacenter as well as Consul servers in the local datacenter and remote datacenters. See the [Network Coordinates](/docs/internals/coordinates.html) internals guide for more information on how these coordinates are computed, and for details on how to perform calculations with them. The following endpoints are supported: * [`/v1/coordinate/datacenters`](#coordinate_datacenters) : Queries for WAN coordinates of Consul servers * [`/v1/coordinate/nodes`](#coordinate_nodes) : Queries for LAN coordinates of Consul nodes ### <a name="coordinate_datacenters"></a> /v1/coordinate/datacenters This endpoint is hit with a GET and returns the WAN network coordinates for all Consul servers, organized by DCs. It returns a JSON body like this: ```javascript [ { "Datacenter": "dc1", "Coordinates": [ { "Node": "agent-one", "Coord": { "Adjustment": 0, "Error": 1.5, "Height": 0, "Vec": [0,0,0,0,0,0,0,0] } } ] } ] ``` This endpoint serves data out of the server's local Serf data about the WAN, so its results may vary as requests are handled by different servers in the cluster. Also, it does not support blocking queries or any consistency modes. ### <a name=""coordinate_nodes></a> /v1/coordinate/nodes This endpoint is hit with a GET and returns the LAN network coordinates for all nodes in a given DC. By default, the datacenter of the agent is queried; however, the dc can be provided using the "?dc=" query parameter. It returns a JSON body like this: ```javascript [ { "Node": "agent-one", "Coord": { "Adjustment": 0, "Error": 1.5, "Height": 0, "Vec": [0,0,0,0,0,0,0,0] } } ] ``` This endpoint supports blocking queries and all consistency modes.
{'content_hash': '46a6addd1678711f18a0fa23b680a075', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 105, 'avg_line_length': 28.675324675324674, 'alnum_prop': 0.697463768115942, 'repo_name': 'apihub/apihub', 'id': '06e9f10673d987d34179fa3c32af7bdc5136b24b', 'size': '2212', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/hashicorp/consul/website/source/docs/agent/http/coordinate.html.markdown', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Go', 'bytes': '145580'}, {'name': 'Makefile', 'bytes': '1755'}, {'name': 'Shell', 'bytes': '2229'}]}
<html> <head> <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> <meta NAME="GENERATOR" CONTENT="Microsoft FrontPage 3.0"> <meta NAME="Author" CONTENT="Paul Resnick"> <title>PICS, Censorship, and Intellectual Freedom FAQ</title> </head> <body> <h1>PICS, Censorship, &amp; Intellectual Freedom FAQ</h1> <table width="751"> <tr> <td vAlign="top" width="137"><strong>Version</strong></td> <td vAlign="top" width="323"><strong>Editor</strong></td> <td vAlign="top" width="279"><strong>Date</strong></td> </tr> <tr> <td vAlign="top" width="137"><a href="PICS-FAQ-980126.html">1.0 - 1.14</a></td> <td vAlign="top" width="323"><a href="mailto:[email protected]">Paul Resnick</a>, <br> University of Michigan</td> <td vAlign="top" width="279">last revised 04-Aug-99 </td> </tr> <tr> <td colSpan="3" vAlign="top" width="747">&nbsp;<h2>Status of This Document</h2> <p>This Frequently Asked Question (FAQ) white paper answers common questions about PICS in the context of intellectual freedom and censorship. It has no techincal standing what-so-ever, such information is found in the <a href="http://www.w3.org/PICS/#specs">specifications</a>. This document has no official W3C policy standing beyond describing the position the W3C has taken to date.</p> <p>Please send questions to <a href="mailto:[email protected]">[email protected]</a> .</td> </tr> </table> <h1>Abstract</h1> <p>The published articles describing PICS (<a HREF="http://www.w3.org/pub/WWW/PICS/iacwcv2.htm">Communications of the ACM</a>, <a HREF="http://www.sciam.com/0397issue/0397resnick.html">Scientific American</a>) have focused on individual controls over the materials that are received on a computer. While those articles also mention the possibility of more centralized controls (e.g., by employers or governments), they describe only briefly the technical details and the intellectual freedom implications of such centralized controls. The civil liberties community has raised some alarms about those intellectual freedom implications. The goals for this Frequently Asked Questions (FAQ) document are to: <ul> <li>Clarify some technical questions about individual and centralized content controls based on PICS.</li> <li>Argue that the net impact of PICS will be to shift government policies away from centralized controls and toward individual controls, although this impact may be visible only at the margins.</li> <li>Describe how the <a HREF="http://www.w3.org/">World Wide Web Consortium </a>(W3C) presents PICS in the public policy arena.</li> </ul> <h1>Background</h1> <p>In 1995, policies were proposed in several countries, including the USA, to restrict the distribution of certain kinds of material over the Internet. In many but not all cases, protection of children was the stated goal for such policies (see, for example, <a HREF="http://www.ciec.org/">CIEC: Citizens Internet Empowerment Coalition</a>). </p> <p>The focus on restricting inappropriate materials at their source is not well suited to the international nature of the Internet, where an information source may be in a different legal jurisdiction than the recipient. Moreover, materials may be legal and appropriate for some recipients but not others, so that any decision about whether to block at the source will be incorrect for some audiences. </p> <p><a HREF="http://www.w3.org/pub/WWW/PICS/">PICS, the Platform for Internet Content Selection</a>, is a set of technical specifications that facilitate recipient-centered controls on Internet content, rather than sender-centered controls. The following diagram illustrates recipient-centered controls: </p> <p><img SRC="IMG00001.GIF"> </p> <p>Filtering software sits between a child (or any Internet user) and the available content. It allows access to some materials, and blocks access to other materials. Some filtering software directly analyzes content, typically looking for particular keywords. This FAQ, however, does not deal with that kind of software; it deals, instead, with filtering software that decides what to allow and what to block based on two information sources. <ul> <li>The first source is a set of descriptive labels that are associated with the materials. Those labels may be provided by information publishers who describe their own work, or may be provided by independent reviewers. A single document may have several labels associated with it.</li> <li>The second information source the filter uses is a set of filtering rules, which say what kinds of labels to pay attention to, and what particular values in the labels indicate acceptable or unacceptable materials.</li> </ul> <p>PICS was not the first technology based on the idea of recipient-centered controls. For example, SurfWatch was already on the market in the summer of 1995 when PICS development began. It is based on a particularly simple set of labels: a list of URLs to avoid. As another example, some firewalls that corporations had introduced for security purposes blocked access to certain IP addresses. PICS provides a set of technical specifications so that pieces of the picture could be provided by different entities, yet still work together. </p> <p>The first and most important distinction that PICS introduced is a separation between labeling and filtering. A label describes the content of something. A filter makes the content inaccessible to some audience. While both labeling and filtering may introduce social concerns, the concerns are somewhat different. More generally, there are six roles that could all be filled by different entities: <ol> <li>Set labeling vocabulary and criteria for assigning labels</li> <li>Assign labels</li> <li>Distribute labels</li> <li>Write filtering software</li> <li>Set filtering criteria</li> <li>Install/run filtering software</li> </ol> <b> <p>PICS itself actually fills none of the six roles listed above!</b> PICS is a set of technical specifications that makes it possible for these roles to be played by independent entities. </p> <p>For example, RSACi and SafeSurf have each defined labeling vocabulary and criteria for rating. They each wrote down a vocabulary in a machine-readable format that PICS specifies. RSACi has four categories in its vocabulary, language, nudity, sex, and violence; SafeSurf has more categories. Because they write down their vocabularies in the PICS format, label distribution software (e.g., from IBM and Net Shepherd) and filtering software (e.g., from Microsoft, IBM, and others) can process labels based on those vocabularies. Even though RSACi and SafeSurf have each specified a labeling vocabulary and criteria for assigning labels, neither of them actually assigns labels: they leave it up to the authors of documents to apply to criteria to their own documents, or self-label as PICS documents call it. Other services, such as CyberPatrol and Net Shepherd, take on both of the first two roles, choosing the labeling vocabulary and employing people to actually assign labels. The PICSRules specification provides a common format for expressing filtering criteria, which makes it easy for one entity to set filtering criteria which are then installed and run by someone else. For example, a parent might, with one mouse click install filtering criteria suggested by some trusted organization, say a local church group, even though that organization provides neither rating labels nor the filtering software. </p> <h1>Questions and Answers</h1> <h1>What PICS Enables</h1> <h3>Can PICS be used for more than just content filtering?</h3> <p>Yes. While the motivation for PICS was concern over children accessing inappropriate materials, it is a general &quot;meta-data&quot; system, meaning that labels can provide any kind of descriptive information about Internet materials. For example, a labeling vocabulary could indicate the literary quality of an item rather than its appropriateness for children. Most immediately, PICS labels could help in finding particularly desirable materials (see, for example, <a HREF="http://www.netshepherd.com/">NetShepherd's label-informed Alta Vista search</a>), and this is the main motivation for the ongoing work on a next generation label format that can include arbitrary text strings. More generally, the <a HREF="http://www.w3.org">W3C</a> is working to extend Web meta-data capabilities generally and is applying them specifically in the following projects: <dl> <dt><a HREF="http://www.w3.org/pub/WWW/Security/DSig/Overview.html">Digital Signature Project</a></dt> <dd>coupling the ability to make assertions with a cryptographic signature block that ensures integrity and authenticity.</dd> <dt><a HREF="http://www.w3.org/pub/WWW/IPR/">Intellectual Property Rights Management</a></dt> <dd>using a meta-data system to label Web resources with respect to their authors, owners, and rights management information.</dd> <dt><a HREF="http://www.w3.org/pub/WWW/Privacy/Overview.html">Privacy (P3)</a></dt> <dd>using a meta-data system to allow sites to make assertions about their privacy practices, and for users to express their preferences for the type of interaction they want to have with those sites.</dd> </dl> <p>Regardless of content control, meta-data systems such as PICS are going to be an important part of the Web, because they enable more sophisticated commerce (build and manage trust relationships), communication, indexing, and searching services. </p> <blockquote> <p>&quot;The promise of digital commerce is that it will allow you to use the Internet to purchase the services of the best organic gardening advisors or mad cow disease specialists, whether they live in Santa Clara or Timbuktu. To do this, you need to do more than verify that the person at the other end of the wire is who he says he is. You need to assess competence, reliability, judgment. In other words, you need a system of branding, but applied much more widely for highly specialized and hard-to-evaluate services and products. You need value-added services that will not only lead you to the right product or service but also rate its quality or otherwise vouch for it.&quot;</p> </blockquote> <blockquote> <p>Francis Fukayama</p> </blockquote> <blockquote> <p>(Forbes ASAP 12/96 p 69)</p> </blockquote> <h3>Does PICS enable censorship?</h3> <p>This seemingly straightforward question, upon closer inspection, turns out to be many different questions when asked by different people. Many people are concerned about governments assuming one or more of the roles described in the answer to the previous question. Others are concerned about employers setting filtering rules, abuse of power by independent labelers, or a chilling effect on speech even if speech is not banned outright. People also employ different definitions of censorship. The most expansive definition is, &quot;any action by one person that makes otherwise available information unavailable to another person.&quot; Under this expansive definition, even a parent setting filtering rules for a child would count as censorship. PICS documents have adopted the more restrictive definition of censorship as actions that limit what an individual can distribute, and use the term &quot;access controls&quot; for restrictions on what individuals can receive. But the distinction blurs if a central authority restricts access for a set of people. Finally, people have different definitions of &quot;enable.&quot; Some would say that PICS enables any application that uses PICS-compatible components, while we reserve the term &quot;enables&quot; for applications that can easily be implemented with PICS-compatible components but could not be easily implemented otherwise. </p> <p>Given the variety of implicit questions, it doesn't make sense to provide a blanket answer to the question of whether PICS enables censorship. This FAQ answers many of the specific questions that people often mean when they ask the more general question. For example, we ask questions about whether PICS makes it easier or harder for governments to impose labeling and filtering requirements. If you believe there's another specific question that should be addressed, please send it to <a HREF="mailto:[email protected]">[email protected]</a>, for possible inclusion in a later version. </p> <h3>Could governments encourage or impose receiver-based controls? Does PICS make it easier or harder for governments to do so?</h3> <p>Yes. A government could try to assume any or all of the six roles described above, although some controls might be harder than others to enforce. As described below, governments could assume some of these roles even without PICS, while other roles would be harder to assume if PICS had not been introduced. It's important to note that W3C does not endorse any particular government policy. The purpose of this FAQ is to explain the range of potential policies and to explore some of the impacts of those policies on both the climate of intellectual freedom and the technical infrastructure of the World Wide Web. Potential government policies: <ol> <li>Set labeling vocabulary and criteria. A government could impose a labeling vocabulary and require all publishers (in the government's jurisdiction) to label their own materials according to that vocabulary. Alternatively, a government might try to achieve the same effect by encouraging an industry self-policing organization to choose a vocabulary and require subscribers to label their own materials. Civil liberties advocates in Australia are especially concerned about this (see <a HREF="http://www.pobox.com/~rene/liberty/label.html">The Net Labeling Delusion</a>). PICS makes it somewhat easier for a government to impose a self-labeling requirement: without PICS, a government would have to specify a technical format for the labels, in addition to specifying the vocabulary and criteria, and there might not be any filtering software available that could easily process such labels.</li> <li>Assign labels. A government could assign labels to materials that are illegal or harmful. This option is most likely to be combined with government requirements that such materials be filtered (see #5 below) but it need not be; a government could merely provide such labels as an advisory service to consumers, who would be free to set their own rules, or ignore the labels entirely. If a government merely wants to label, and not impose any filtering criteria, then PICS again provides some assistance because it enables a separation of labeling from filtering. On the other hand, a government that wishes to require filtering of items it labels as illegal gets little benefit from PICS as compared to prior technologies, as discussed below in <a HREF="#firewalls">the question about national firewalls</a>.</li> <li>Distribute labels. A government could operate or finance operation of a Web server to distribute labels (a PICS label bureau); the labels themselves might be provided by authors or independent third parties. Taken on its own, this would actually contribute to freedom of expression, since it would make it easier for independent organizations to express their opinions (in the form of labels) and make those opinions heard. Consumers would be free to ignore any labels they disagreed with. Again, since PICS separates labeling from filtering, it enables a government to assist in label distribution without necessarily imposing filters. If combined with mandatory filtering, however, a government-operated or financed label bureau could contribute to restrictions on intellectual freedom.</li> <li>Write filtering software. It's unlikely that a government would write filtering software rather than buying it; the supplier of filtering software probably has little impact on intellectual freedom.</li> <li>Set filtering criteria. A government could try to impose filtering criteria in several ways, including government-operated proxy servers (a national intranet), mandatory filtering by service providers or public institutions (e.g., schools and libraries), or liability for possession of materials that have been labeled a particular way. In some ways, by enabling independent entities to take on all the other roles, PICS highlights this as the primary political battleground. Each national and local jurisdiction will rely on its political and legal process to answer difficult policy questions: Should there be any government-imposed controls on what can be received in private or public spaces? If so, what should those controls be? Most kinds of mandatory filters could be implemented without PICS. A government could express its required filtering criteria in the form of a PICSRule that everyone would be required to install and run, but without PICSRules a government could express its requirements in less technical form. One potential policy, however, mandatory filtering based on labels provided by non-government sources, would have been difficult to impose without PICS.</li> <li>Install/run filters. A Government could require that filtering software be made available to consumers, without mandating any filtering rules. For example, a government could require that all Internet Service Providers make filtering software available to its customers, or that all PC browsers or operating systems include such software. Absent PICS, governments could have imposed such requirements anyway, since proprietary products such as SurfWatch and NetNanny are available.</li> </ol> <h3>Since PICS makes it easier to implement various kinds of controls, should we expect there to be more such controls overall?</h3> <p>Yes; all other things being equal, when the price of something drops, more of it will be consumed. </p> <h3>Does PICS encourage individual controls rather than government controls?</h3> <p>Yes; for example, a national proxy-server/firewall combination that blocks access to a government-provided list of prohibited sites does not depend on interoperability of labels and filters provided by different organizations. While such a setup could use PICS-compatible technology, a proprietary technology provided by a single vendor would be just as effective. Other controls, based on individual or local choices, benefit more from mixing and matching filtering software and labels that come from different sources, which PICS enables. Thus, there should be some substitution of individual or local controls for centralized controls, although it is not obvious how strong this substitution effect will be. In Europe initial calls for centralized controls gave way to government reports calling for greater reliance on individual recipient controls; the end results of these political processes, however, are yet to be determined. </p> <h1>Labeling</h1> <h3>Does it matter whether labels are applied to IP addresses or to URLs?</h3> <p>An IP address identifies the location of a computer on the Internet. A URL identifies the location of a document. To simplify a little, a URL has the form http://&lt;domain-name&gt;/&lt;filename&gt;. A web browser first resolves (translates) the domain-name into an IP address. It then contacts the computer at that address and asks it to send the particular filename. Thus, a label that applies to an IP address is a very broad label: it applies to every document that can be retrieved from that machine. Labeling of URLs permits more flexibility: different documents or directories of documents can be given different labels. </p> <p>This difference of granularity will, naturally, have an impact on filtering. Filters based on IP addresses will be cruder: if some but not all of the documents available at a particular IP address are undesirable, the filter will have to either block all or none of those documents. PICS, by contrast, permits labeling of individual URLs, and hence permits finer grain filters as well. </p> <h2>Self-labeling</h2> <h3>Does PICS make author self-labeling more effective?</h3> <p>Yes. Without a common format for labels, authors could not label themselves in a way that filtering programs could make use of. PICS provides that format. </p> <h3>Does PICS make a government requirement of self-labeling more practical to implement?</h3> <p>It enables such a requirement to have more impact. A government requirement of self-labeling would have little impact if the labels were not usable by filtering programs. PICS provides the common format so that filtering software from one source can use labels provided by other sources (authors in this case). </p> <h3>Does self-labeling depend on universal agreement on a labeling vocabulary and criteria for assigning labels to materials?</h3> <p>Although universal agreement is not necessary, there does need to be some harmonization of vocabulary and labeling criteria, so that labels provided by different authors can be meaningfully compared. </p> <h3>Does PICS make it easier for governments to cooperate in imposing self-labeling requirements?</h3> <p>Yes. PICS provides a language-independent format for expressing labels. If governments agreed on a common set of criteria for assigning labels, the criteria could be expressed in multiple languages, yet still be used to generate labels that can be compared to each other. </p> <h3>Is it effective for (some) authors to label their own materials as inappropriate for minors? What about labeling appropriate materials?</h3> <p>Both kinds of labeling could be effective, but only if a high percentage of the materials of a particular type are labeled. If the inappropriate materials are labeled, then a filter can block access to the labeled items. If the appropriate materials are labeled, then a filter can block access to all the unlabeled items. </p> <h2>Third-party labeling</h2> <h3>Can an organization I dislike label my web site without my approval?</h3> <p>Yes. Anyone can create a PICS label that describes any URL, and then distribute that label to anyone who wants to use that label. This is analogous to someone publishing a review of your web site in a newspaper or magazine. </p> <h3>Isn't there a danger of abuse if a third-party labeler gets too powerful?</h3> <p>If a lot of people use a particular organization's labels for filtering, that organization will indeed wield a lot of power. Such an organization could, for example, arbitrarily assign negative labels to materials from its commercial or political competitors. The most effective way to combat this danger is to carefully monitor the practices of labeling services, and to ensure diversity in the marketplace for such services, so that consumers can stop using services that abuse their power. </p> <h2>Other Social Concerns About Labeling</h2> <h3>Why did PICS use the term &quot;label&quot;, with all of its negative associations?</h3> <p>PICS documents use the term &quot;label&quot; broadly to refer to any machine-readable information that describes other information. Even information that merely classifies materials by topic or author (traditional card catalog information) would qualify as labels if expressed in a machine-readable format. The PICS developers recognized that the term &quot;label&quot; has a narrower meaning, with negative connotations, for librarians and some other audiences, but it was the most generic term the PICS creators could find without reverting to technical jargon like &quot;metadata.&quot; </p> <p>In media with centralized distribution channels, such as movies, labeling and filtering are not easily separated. For example, unrated movies are simply not shown in many theaters in the USA. In addition to its technical contribution, PICS makes an intellectual contribution by more clearly separating the ideas of labeling and filtering. Many of the negative connotations associated with &quot;labeling&quot; really should be associated with centralized filtering instead. There are, however, some subtle questions about the impact of labeling itself, as articulated in the next two questions. </p> <h3>Does the availability of labels impoverish political discussions about which materials should be filtered?</h3> <p>Matt Blaze (personal communication) describes this concern with an analogy to discussions at local school board meeting about books to be read in a high school English class. Ideally, the discussion about a particular book should focus on the contents of the book, and not on the contents of a review of the book, or, worse yet, a label that says the book contains undesirable words. </p> <p>There will always be a tradeoff, however, between speed of decision-making and the ability to take into account subtleties and context. When a large number of decisions need to be made in a short time, some will have to be made based on less than full information. The challenge for society, then, will be to choose carefully which decisions merit full discussion, in which case labels should be irrelevant, and which decisions can be left to the imperfect summary information that a label can provide. The following excerpt from <a HREF="http://www.sciam.com/0397issue/0397resnick.html">Filtering the Internet</a> summarizes this concern and the need for eternal vigilance: </p> <blockquote> <p>&quot;Another concern is that even without central censorship, any widely adopted vocabulary will encourage people to make lazy decisions that do not reflect their values. Today many parents who may not agree with the criteria used to assign movie ratings still forbid their children to see movies rated PG-13 or R; it is too hard for them to weigh the merits of each movie by themselves.</p> </blockquote> <blockquote> <p>Labeling organizations must choose vocabularies carefully to match the criteria that most people care about, but even so, no single vocabulary can serve everyone's needs. Labels concerned only with rating the level of sexual content at a site will be of no use to someone concerned about hate speech. And no labeling system is a full substitute for a thorough and thoughtful evaluation: movie reviews in a newspaper can be far more enlightening than any set of predefined codes.&quot;</p> </blockquote> <h3>Will the expense of labeling &quot;flatten&quot; speech by leaving non-commercial speech unlabeled, and hence invisible?</h3> <p>This is indeed a serious concern, explored in detail by Jonathan Weinberg in his law review article, <a HREF="http://www.msen.com/~weinberg/rating.htm">Rating the Net</a>. The following excerpt from <a HREF="http://www.sciam.com/0397issue/0397resnick.html">Filtering the Internet</a> acknowledges that materials of limited appeal may not reach even the audiences they would appeal to, but argues that labeling is merely a symptom rather than a cause of this underlying problem: </p> <blockquote> <p>&quot;Perhaps most troubling is the suggestion that any labeling system, no matter how well conceived and executed, will tend to stifle noncommercial communication. Labeling requires human time and energy; many sites of limited interest will probably go unlabeled. Because of safety concerns, some people will block access to materials that are unlabeled or whose labels are untrusted. For such people, the Internet will function more like broadcasting, providing access only to sites with sufficient mass-market appeal to merit the cost of labeling.</p> </blockquote> <blockquote> <p>While lamentable, this problem is an inherent one that is not caused by labeling. In any medium, people tend to avoid the unknown when there are risks involved, and it is far easier to get information about material that is of wide interest than about items that appeal to a small audience.&quot;</p> </blockquote> <h1>Filtering</h1> <h3><a NAME="firewalls"></a>What is PICSRules?</h3> <p>PICSRules is a language for expressing filtering rules (profiles) that allow or block access to URLs based on PICS labels that describe those URLs. The purposes for a common profile-specification language are: </p> <p>&nbsp;&nbsp;&nbsp; <b>Sharing and installation of profiles.</b> Sophisticated profiles may be difficult for end-users to specify, even through <br> &nbsp;&nbsp;&nbsp; well-crafted user interfaces. An organization can create a recommended profile for children of a certain age. Users who <br> &nbsp;&nbsp;&nbsp; trust that organization can install the profile rather than specifying one from scratch.&nbsp; It will be easy to change the active <br> &nbsp;&nbsp;&nbsp; profile on a single computer, or to carry a profile to a new computer. <br> &nbsp;&nbsp;&nbsp; <b>Communication to agents, search engines, proxies, or other servers.</b> Servers of various kinds may wish to tailor <br> &nbsp;&nbsp;&nbsp; their output to better meet users' preferences, as expressed in a profile. For example, a search service can return only <br> &nbsp;&nbsp;&nbsp; links that match a user's profile, which may specify criteria based on quality, privacy, age suitability, or the safety of <br> &nbsp;&nbsp;&nbsp; downloadable code. <br> &nbsp;&nbsp;&nbsp; <b>Portability betwen filtering products.</b> The same profile will work with any PICSRules-compatible product. </p> <h3>Does PICS make national firewalls easier to implement?</h3> <p>No, but an effective national firewall would make it possible for a government to impose PICS-based filtering rules (or non PICS-based filtering rules) on its citizens. A firewall partitions a network into two components and imposes rules about what information flow between the two components. The goal of a national firewall is to put all the computers in the country into one component, and all computers outside the country into the other component. This is difficult to do, especially if people deliberately try to find out connections (e.g., telephone lines) between computers inside the country and those outside the country. Given a successful partition, however, PICS could be used to implement the filtering rules for a firewall. In particular, the government could identify prohibited sites outside the country that people inside the country could not access; such a filtering could be implemented based on PICS-formatted labels or, without relying on PICS-compatible technology, with a simple list of prohibited URLs. </p> <h3>Does PICS make national firewalls easier to implement?</h3> <p>No. PICSRules can provide a way to express filtering preferences, but has no impact on the ability of a government to partition the computers inside a country from those outside the country. </p> <h3>Does PICS enable ISP compliance with government requirements that they prohibit access to specific URLs?</h3> <p>ISP compliance with government prohibition lists is already practical, even without PICS. It would also be possible to comply using PICS-based technologies. PICS does make it easier for ISPs to comply with a government requirement to block access to sites labeled by non-governmental entities (including those that are self-labeled by the authors of the sites). <br> &nbsp; </p> <h3>Does PICSRules enable ISP compliance with government requirements that they prohibit access to specific URLs?</h3> <p>Governments can make such requirements with or without PICSRules. PICSRules does make it possible for governments to precisely state filtering requirements, and perhaps simplify ISP compliance with changing government requirements, if the ISP implements a general interpreter for the PICSRules language. </p> <h3>Are proxy-server based implementations of PICS filters compatible with the principle of individual controls?</h3> <p>Yes. PICS enables mixing and matching of the five roles. In particular, a service provider could install and run filtering software on a proxy server, but allow individuals to choose what filtering rules will be executed for each account. AOL already offers a primitive version of this idea, not based on PICS; parents can turn the preset filtering rules on or off for each member of the family. </p> <h3>Are client based implementations of PICS filters usable only for individual controls?</h3> <p>No. Governments could require the use of filters on clients. The city of Boston, for example, requires public schools to install a client-based filtering product on all computers with Internet access, and requires public libraries to install a client-based filtering product on all computers designated for children. </p> <h3>Does my country have a right to filter what I see?</h3> <p>W3C leaves this question to the political and legal processes of each country. Some people argue that unrestricted access to information is a fundamental human rights question that transcends national sovereignty. W3C has not adopted that position. </p> <h3>Does my employer have a right to filter what I see?</h3> <p>W3C leaves this question to the political and legal processes of each country. </p> <h1>W3C's Roles and Responsibilities</h1> <h3>How does W3C view its role in policy debates about intellectual freedom?</h3> <p>W3C's mission is to &quot;realize the full potential of the Web.&quot; The following two points are taken from a <a HREF="http://www.w3.org/pub/WWW/Talks/970221Policy/">talk </a>by Jim Miller at the WWW6 conference: <ul> <li>We wish to provide tools which encourage all cultures to feel free to use the Web while maintaining an inter-operable network architecture that encourages diversity without cultural fragmentation or domination</li> <li>We provide feedback to policy makers regarding what is technically possible, how effective the technology may be in satisfying policy requirements, and the possible unintended consequences of proposed policies</li> </ul> <p>Thus, for example, when discussing the CDA-type legislation with government officials in the U.S. or abroad, it is appropriate for W3C to point out that sender-based restrictions are not likely to be effective at keeping all materials of a particular kind away from children, and that there could be unintended consequences in terms of chilling free speech or keeping the Web from reaching its full potential as a medium for communication and cultural exchange. W3C does not, however, debate with government officials about their perceived policy requirements. For example, Germany has a policy requirement of restricting access to hate speech while the U.S. does not: W3C does not try to convince either country that the other country's choice of policy requirements is better. </p> <h3>Why does the CACM article suggest that governments might use blocking technology?</h3> <p>Some people(see <a HREF="http://www.thehub.com.au/~rene/liberty/label.html">The Net Labeling Delusion)</a> have criticized the following paragraph from the CACM article on PICS: <ul> <p>Not everyone needs to block reception of the same materials. Parents may not wish to expose their children to sexual or violentimages. Businesses may want to prevent their employees from visiting recreational sites during hours of peak network usage. Governments may want to restrict reception of materials that are legal in other countries but not in their own. The &#147;off&#148; button (or disconnecting from the entire Net) is too crude: there should be some way to block only the inappropriate material. Appropriateness, however, is neither an objective nor a universal measure. It depends on at least three factors:</p> </ul> <ul> <p>1. The supervisor: parenting styles differ, as do philosophies of management and government. <br> 2. The recipient: what&#146;s appropriate for one fifteen year old may not be for an eight-year-old, or even all fifteen-year-olds. <br> 3. The context: a game or chat room that is appropriate to access at home may be inappropriate at work or school.</p> </ul> <p>The main point of this section is to underscore the fact that people disagree about what materials are appropriate in what contexts. This point is illustrated at several levels of granularity: invidual children, organizations, and governments. The critcism focuses on the mention of possible government blocking, which did not appear in an earlier draft of the paper. We believe the example about differences in laws between countries is useful in explaining why there is a need for flexible, receiver-based controls rather than the kind of sender-based controls (e.g., the CDA) that most policy discussions were focusing on at the time. </p> <p>The objection to the use of this example rests on an argument that governments should never designate any content as illegal. That argument is not widely accepted (in the U.S., for example, &quot;obscenity&quot; laws have been deemed constitutional, even though the CDA's &quot;indecency&quot; provisions were not). A more widely held position is that governments should not restrict political materials as a means of controlling their citizens. W3C leaves discussions about which materials should be illegal in a particular country to the political realm rather than the technological realm. W3C does, however, point out to policy makers, however, that it's not necessary to make materials illegal if they are offensive to some people but not others: end-user controls are a more flexible method of handling such materials. </p> <h3>Could W3C have controlled the uses of PICS by licensing the technology?</h3> <p>Licensing such a technology was not considered to be a feasible option during the time of the CDA. Not only would it have undercut the &quot;neutrality&quot; and appeal of the technology, the W3C then would have had to be in the position of determining who should and should not use it; this is not a role the W3C is competent to play. </p> <h3>Is the W3C promoting the development of PICS into proxy server products?</h3> <p>Yes. W3C is pleased that <a HREF="http://www1.raleigh.ibm.com/pics/press/Javelin.html">IBM has introduced a proxy server </a>that can filter based on PICS labels, and encourages the development of other PICS-compatible servers. As discussed above, filter processing can be centralized at a proxy server while still permitting individuals to choose the filtering rules. </p> <h3>What can I do now to promote uses of PICS that promote, rather than harm, intellectual freedom?</h3> <p>In addition to acting in the political arena, it would probably be helpful to implement positive uses of labels, such as searching applications. It is surpassingly difficult for people unfamiliar with computers to imagine new applications. By building prototypes and demonstrating them, it may be possible to focus policy-makers' energies on those uses of technology that accord with your political values. </p> <h3>What else can I read about labeling, filtering, and intellectual freedom?</h3> <h4>Governments</h4> <ul> <li><a HREF="http://www.europarl.eu.int/dg1/a4/en/a4-97/a4-0098.htm">European Commission Report (follow-on document of 20 March, 1997)</a></li> <li><a HREF="http://www.dca.gov.au/aba/invest.htm">Australian Broadcast Authority report on its investigation into on-line services</a></li> <li><a HREF="http://europa.eu.int/en/record/green/gp9610/protec.htm">European Parliament Green Paper: the Protection of Minors and Human Dignity in Audiovisual and Information Services</a></li> <li><a HREF="http://europa.eu.int/en/record/legal/index.htm">European Union Communication on illegal and harmful content on the Internet</a></li> <li><a HREF="http://www2.echo.lu/legal/en/internet/content/wpen.html">Report of European Commission Working party on illegal and harmful content on the internet</a></li> <li><a HREF="http://www2.echo.lu/legal/en/internet/content/wpen.html">Working Party Report</a></li> <li><a HREF="http://www2.echo.lu/best_use/best_use.html">European Commission Forum for Exchange of Information on Internet Best Practices</a></li> </ul> <h4>Media</h4> <ul> <li><a HREF="http://www.wired.com/news/news/technology/story/9176.html">PICS Walks Fine Line on Net Filtering</a></li> <li><a HREF="http://www.hotwired.com/packet/garfinkel/97/05/index2a.html">Good Clean PICS: The most effective censorship technology the Net has ever seen may already be installed on your desktop </a>(Simson Garfinkel in HotWired: February 1997)</li> <li><a HREF="http://www.collegehill.com/ilp-news/reagle.html">College Hill interview with Joseph Reagle, W3C staff member</a></li> </ul> <h4>Individuals and Organizations</h4> <ul> <li><a HREF="http://www.eff.org/policies/filtration_policy.html">EFF's Draft Policy on public interest principles for online filtration, ratings, and labeling systems</a>. Suggested guidelines for responsible use of labeling and filtering.</li> <li><a HREF="http://www.bluehighways.com/tifap/">The Internet Filter Assessment Project.</a> A group of librarians with mixed feelings about filtering examined several products in detail and discussed the issues facing libraries.</li> <li><a HREF="http://www.aclu.org/issues/cyber/burning.html">ACLU White Paper Critical of Labeling and Filtering</a></li> <li><a HREF="http://www.irdu.nus.sg/~wayne/paper.html">PICS-Aware Proxy System vs. Proxy Server Filters.</a> Wayne Salamonsen and Roland Yeo, proceedings of INET '97.</li> <li><a HREF="http://www.ariadne.ac.uk/issue9/pics/">Metadata, PICS and Quality.</a> Chris Armstrong. Ariadne magazine, May 1997.</li> <li><a HREF="http://www.msen.com/~weinberg/rating.htm">Rating the Net</a>. Jonathan Weinberg. in Hasting Communications and Entertainment Law Journal, Vol. 19, No. 2, p. 453-482. (A balanced but critical academic's look at rating systems and their legal and social impact.)</li> <li><a HREF="http://www.pobox.com/~rene/liberty/label.html">The Net Labeling Delusion</a> (anti-PICS web site in Australia)</li> <li><a HREF="http://rene.efa.org.au/liberty/">The Net Censorship Dilemma</a> (anti-censorship site by the same editor as the site above) <li><a HREF="http://www.eff.org/~declan/fight-censorship/">Fight-censorship mailing lists</a> (Declan McCullagh's moderated and unmoderated lists; occasional discussion of PICS and related technologies).</li> </ul> <hr> <address>&lt;<a href="mailto:[email protected]">[email protected]</a>&gt;<br> $Date: 1999/08/04 16:13:19 $ </address> </body> </html>
{'content_hash': 'f2bf7b9de4ae951ccb4ba3229ee47fd3', 'timestamp': '', 'source': 'github', 'line_count': 721, 'max_line_length': 110, 'avg_line_length': 60.36338418862691, 'alnum_prop': 0.7680023895960664, 'repo_name': 'nachocove/MobileHtmlAgilityPack', 'id': 'e6445117bf2402227d2765d4b6964587967d2b17', 'size': '43522', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Test.Mac/TestVectors/www.w3.org/PICS/PICS-FAQ-980126.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '187776'}, {'name': 'CSS', 'bytes': '1384'}, {'name': 'Makefile', 'bytes': '363'}]}
#pragma once #ifndef PBCORE_H #define PBCORE_H #define PBERR errType #ifdef STANDARDSHELL_UI_MODEL #include "resource.h" #endif //#include <assert.h> #include "..\..\Common\Public\PB_Defines.h" #include "..\..\Common\Private\GenericHeader.h" // #include "Eng.h" #include <queue> //#include "XMLReader.h" #include "Meta.h" #include "AppManager.h" #include "Message.h" #include "Paint.h" #include "Generic.h" #include "Sync.h" #include "SyncMsg.h" #include "Send.h" #include "Webserver.h" #ifdef BUILD_AS_RHODES_EXTENSION // Typedefs of functions called back into Rhodes from this Extension typedef BOOL (NAVIGATECALLBACK) (const wchar_t*); typedef BOOL (EXISTSJSCALLBACK) (const wchar_t*); typedef BOOL (INVOKEJSCALLBACK) (const wchar_t*); typedef void (LOGCALLBACK) (int, const wchar_t*, const wchar_t*, const wchar_t*, int); typedef void (GEOLOCATIONCALLBACK) (bool); typedef void (STOPCALLBACK) (); typedef void (HISTORYFORWARDCALLBACK) (); typedef void (HISTORYBACKCALLBACK) (); typedef void (REFRESHCALLBACK) (BOOL); typedef void (QUITCALLBACK) (); typedef void (MINIMIZECALLBACK) (); typedef void (RESTORECALLBACK) (); typedef void (RESIZEBROWSERWINDOWCALLBACK) (RECT); typedef void (ZOOMPAGECALLBACK) (float); typedef void (ZOOMTEXTCALLBACK) (int); typedef int (GETTEXTZOOMCALLBACK) (); typedef void (GETTITLECALLBACK) (wchar_t*, int); typedef void (SETBROWSERGESTURINGCALLBACK) (BOOL); typedef void (SIPPOSITIONCALLBACK) (); typedef BOOL (REGISTERFORMESSAGECALLBACK) (unsigned int); typedef BOOL (DEREGISTERFORMESSAGECALLBACK) (unsigned int); typedef BOOL (REGISTERFORPRIMARYMESSAGECALLBACK) (unsigned int); typedef BOOL (DEREGISTERFORPRIMARYMESSAGECALLBACK) (unsigned int); #endif BOOL BrowserReload (int iAppID,BOOL bCacheLoad,LPCTSTR pCallingModule); BOOL BrowserStop (int iAppID,LPCTSTR pCallingModule); BOOL BrowserBack (int iAppID,LPCTSTR pCallingModule); BOOL BrowserBack (int iAppID,LPCTSTR pCallingModule,int iPagesBack); BOOL BrowserQuit (int iAppID,LPCTSTR pCallingModule); BOOL BrowserHome (int iAppID,LPCTSTR pCallingModule); BOOL BrowserResize (int id, LPCTSTR module, int left, int top, int width, int height); BOOL BrowserMinimize (int iAppID,LPCTSTR pCallingModule); BOOL BrowserRestore (int iAppID,LPCTSTR pCallingModule); double BrowserGetPageZoom (int iAppID,LPCTSTR pCallingModule); BOOL BrowserSetPageZoom (double fZoomFactor,int iAppID,LPCTSTR pCallingModule); DWORD BrowserGetTxtZoom (int iAppID,LPCTSTR pCallingModule);///< returns the current text zoom factor BOOL BrowserSetTxtZoom (int Val,int iAppID,LPCTSTR pCallingModule); BOOL BrowserGetSize (int appid, int *pwidth, int *pheight); BOOL BrowserSetVScroll (int appid, int scroll); BOOL BrowserSetHScroll (int appid, int scroll); /** * Sets the Accelerator Key mode to the new value, ALL, NORM or OFF. * \param eAcceleratorValue mode to set the Accelerator keys to. * \return TRUE if successfully set. */ BOOL BrowserSetAccelerator (AcceleratorValue eAcceleratorValue); BOOL RegisterForMessage (REGISTERMESSAGE *pregister); BOOL DeRegisterForMessage (REGISTERMESSAGE *pregister); BOOL RegisterForPrimaryMessage (UINT iWMMsgID); BOOL DeRegisterForPrimaryMessage (UINT iWMMsgID); BOOL SetPlugProperty (PPBSTRUCT pPBStructure,LPCTSTR pTargetMod,LPCTSTR pParam,LPCTSTR pValue,LPCTSTR pCallingModule); BOOL CallPlugMethod (PPBSTRUCT pPBStructure,LPCTSTR pTargetMod,LPCTSTR pMethod,LPCTSTR pCallingModule); void KillApp (PPBSTRUCT pPBStructure); BOOL RegisterForPaint (REGISTERPAINT *pregister); /********************************************************************************************** * Global Functions **********************************************************************************************/ BOOL Initialise ();///>return 0 if no error BOOL Initialise(LPTSTR lpCmdLine); void DeInitialise ();///>return 0 if no error PBERR OpenConfigFile (LPCTSTR lpConfigFilePath); PBERR InitCoreStruct (); PBERR LoadPlugs (LPCTSTR lpPlugsFile);//< Loads the plugin table referencing the XML file: lpPlugsFile BOOL Log (LogTypeInterface logSeverity,LPCTSTR pLogComment, LPCTSTR pFunctionName, DWORD dwLineNumber,LPCTSTR pCallingModule); void HideSipIfShown (); BOOL PreloadModule(PPBSTRUCT pPBStructure,LPCTSTR pTargetMod); LPWSTR replace(LPWSTR pSzTarget,LPWSTR replaceStr); CEMML *GetEMMLObj(int iTabID); LPCTSTR GetCurrURL(int iAppID); /** * Retrieve the version information from the program, including core exe version, plugin * version and the versions of the individual Plugin DLLs. * \param tcFileVersion [out] The released version of the product (first 4 digits of the * version string, e.g. v.w.x.y) * \param listVersions [out] Must be called with a CVersion object which will act as the * head of a linked list which, after calling, will contain all the component version information * present in the system. Note the caller is responsible for freeing the memory associated * by this method. * \return The length of tcFileVersion. Call this method with tcFileVersion NULL to still * obtain the length of the string to allocate. */ int GetComponentVersions(TCHAR* tcFileVersion, CVersion* listVersions); /** * Inform the core that there has been a change to the SIP Control Meta Tag */ BOOL SipControlChange(SIP_CONTROL_VALUES newVal); /** * Populates the version information for the specified component. This is the full product * version (v.w.x.y.z), not the 4 digit file version returned by GetComponentVersions(). * \param tcFileName Absolute path to the component whose version is to be retrieved. * \param listVersions either a single CVersion object or a list of CVersion objects this method * will create a new CVersion object which is appended to the end of the linked list. * \return true if the version information was successfully obtained. */ BOOL GetProductVersionString(TCHAR* tcFileName, CVersion* listVersions); /** * Function which will be called by plug-ins whenever the device's screen * orientation has been manually changed. This enables Browser to resize * its self to fit to the new screen dimensions. * \return TRUE */ BOOL ResizePB(BOOL bAccountForSIP, BOOL bAccountForIgnoreSettingChange); /** * Converts the command line parameter (currently just the specified start page) * from the string specified by the user into a file or URL which can be * passed to the browser component. Currently the start page provided on the * command line is assumed to apply to all running Browser applications. * \param lpCmdLine The command line parameters as passed to the application on start * \param ptcStartPage [out] web page specified as the start page in the command line. * This will be unchanged if the command line parameter was invalid. * \return Whether or not there was a valid command line parameter present. */ BOOL ParseCommandLine(LPTSTR lpCmdLine, TCHAR* ptcStartPage, WCHAR* szCommandLine); LRESULT CALLBACK TagProc( LPPBNAMEVALUE pNameVal); /** * The following functions are provided to the plugin as function pointers * They will also be called from Application objects - CApp * */ BOOL PageNavigate (int iInstID,LPCTSTR pURI); BOOL Navigate (TCHAR* tcJSONNames[], int iAppID,LPCTSTR lpNavStr,PVARSTRUCT pVARS, LPCTSTR pCallingModule = NULL); BOOL RegisterForEvent (PBModule *pObj,PB_SyncEvent dwEventID,LPCTSTR pCallingModule); BOOL UnRegisterForEvent (PBModule *pObj,PB_SyncEvent dwEventID,LPCTSTR pCallingModule); //IMO: Internal Module Object // will return a reference to a new instance of module or NULL if module cannot be found IMOREF CreateIMO (PPBSTRUCT pPBStructure,LPCTSTR pTargetModuleName,LPCTSTR pCallingModName); BOOL DeleteIMO (IMOREF IMORef); BOOL SetIMOProperty (IMOREF IMORef,LPCTSTR pParam,LPCTSTR pValue); BOOL CallIMOMethod (IMOREF IMORef,LPCTSTR pMethod); BOOL SetIMOCallBack (IMOREF IMORef,IMOEVENTPROC IMOEventProc,LPARAM lParam); //core functions not available in the core structure IMORec *DeleteIMOList (IMORec * pIMORec); IMORec *GetIMOFromID(int iTabID); /*********************************************************************************************/ // Read and write to config.xml; Used by the plugins /*********************************************************************************************/ BOOL SetAppValue (int iAppID,LPCTSTR pXmlPath,LPCTSTR pValue); BOOL SetGlobalValue (LPCTSTR pXmlPath, LPCTSTR pValue); BOOL AddPreload (int iAppID,LPCTSTR pPreloadStr); BOOL AddDefaultMeta (int iAppID,LPCTSTR metaTag); LPCTSTR GetSettingPtr (LPCTSTR pXmlPath,LPTSTR pAttName); LPCTSTR GetAppSettingPtr (int iAppID,LPCTSTR pXmlPath,LPTSTR pAttName); LPCTSTR GetDefaultMetaTagsPtr (int iAppIndex,int iMetaIndex); LPCTSTR GetPreLoadPtr (int iAppID,int iPreLoadIndex); /** * Function to replace insertion specifiers with passed strings. * This function mimics the behaviour of wsprintf by replacing instances * %s and %[number] with the passed optional parameters, which are TCHARs. * Calling function is responsible for allocating the parameterList but this * function will delete the allocated memory. * \param bEscapeOutput Whether the output string should be 'escaped', * i.e. all characters output as the string '%' followed by the Hex * equivilent of their ASCII characters. This allows barcodes containing * character sequences such as '...%de...' to be processed correctly. * \param iNoParams The number of parameters in the 'parameterList' TCHAR** * \param Destination An out parameter where the transformed string will be copied to * \param Format The input string to be parsed * \param parameterList Pointer to array of strings which comprise the substitution values */ void PBformat(BOOL bEscapeOutput, int iNoParams, TCHAR *Destination, TCHAR *Format, TCHAR** parameterList); void BlockNanoSliders(BOOL bBlockSliders); /** * Function to convert the given string to its equivilent in Hex ASCII. * Upto a max length of MAXURL e.g. Escape('hi world'); will convert the * passed string to '%%68%%69%%20%%77%%6f%%72%%69%%64' * \param stringToEscape The string to be converted into Hex ASCII. */ void Escape(TCHAR* stringToEscape); /** * Inserts '\' char before special chars like '\n', '\r' etc while copying * chars from Src to Dst to fix the Javascript errors. */ UINT CopyString (TCHAR *Dst, TCHAR *Src); /** * */ void InitGpsInterfaceToEngine(); BOOL ModuleMessage (MSG *pMsg); DWORD WINAPI LogThread(LPVOID lparam); DWORD WINAPI WindowChangedThread(LPVOID lparam); /** * Navigates resulting from a BadLink call need to be invoked from a separate * thread otherwise the navigation does not succeed. * \param lparam void* of the String to navigate to * \return 0 */ DWORD WINAPI BadLinkNavigateThread(LPVOID lparam); LRESULT CALLBACK onMeta(EngineEventID eeID, LPARAM value, int tabIndex); LRESULT CALLBACK onNavEvent(EngineEventID eeID, LPARAM value, int tabIndex); LRESULT CALLBACK onTopmostWnd(EngineEventID eeID, LPARAM value, int tabIndex); LRESULT CALLBACK onFieldFocus(EngineEventID eeID, LPARAM value, int tabIndex); //LRESULT CALLBACK onPopUp(EngineEventID eeID, LPARAM value, int tabIndex); LRESULT CALLBACK onGeolocation(EngineEventID eeID, LPARAM value, int tabIndex); LRESULT CALLBACK onAuthenticationRequest(EngineEventID eeID, LPARAM value, int tabIndex); /* * Starts the logger * */ PBERR StartLogger(); void CALLBACK OnMemoryLogTimeOut( HWND hwnd,UINT message,UINT idTimer,DWORD dwTime); void LogMemory(); /** * Determines whether or not there is a JavaScript alert shown. Uses a series * of expected window titles to determine whether or not the dialog is * present, e.g. by default the JS alert title will be the page title. * \return TRUE if there is a JS alert shown, else False */ BOOL DetermineJavaScriptAlertShown(); #ifdef BUILD_AS_RHODES_EXTENSION // These functions are added specifically to interface with Rhodes BOOL InitialiseREAsExtension(HINSTANCE hInst, HWND hRhodesWnd, HWND hWndWebKit, LPTSTR szCommandLine, NAVIGATECALLBACK *pNavigateCB, EXISTSJSCALLBACK *pExistsJSCB, INVOKEJSCALLBACK *pInvokeJSCB, LOGCALLBACK *pLogCB, GEOLOCATIONCALLBACK *pGeolocationCB, HISTORYFORWARDCALLBACK *pHistoryForwardCB, HISTORYBACKCALLBACK *pHistoryBackCB, REFRESHCALLBACK *pRefreshCB, QUITCALLBACK *pQuitCB, MINIMIZECALLBACK *pMinimizeCB, RESTORECALLBACK *pRestoreCB, RESIZEBROWSERWINDOWCALLBACK *pResizeBrowserWindowCB, ZOOMPAGECALLBACK *pZoomPageCB, ZOOMTEXTCALLBACK *pZoomTextCB, GETTEXTZOOMCALLBACK *pGetTextZoomCB, GETTITLECALLBACK *pGetTitleCB, SETBROWSERGESTURINGCALLBACK *pSetBrowserGesturingCB, SIPPOSITIONCALLBACK *pPassSipPositionToEngineCB, REGISTERFORMESSAGECALLBACK *pRegisterForMessageCB, DEREGISTERFORMESSAGECALLBACK *pDeRegisterForMessageCB, REGISTERFORPRIMARYMESSAGECALLBACK *pRegisterForPrimaryMessageCB, DEREGISTERFORPRIMARYMESSAGECALLBACK *pDeRegisterForPrimaryMessageCB); LRESULT SendRhoElementsOneMessage(DWORD message, WPARAM wParam, LPARAM lParam, bool bSend); bool ProcessWindowsMessage(MSG& msg); bool ProcessHTMLMessage(MSG& msg); #endif void ProcessAppActivate(bool bActivate); struct stLog{ DWORD dwLogSeverity;//Info, erro, warning, user DWORD dwLineNumber;//line number WCHAR szLogComment[MAX_URL + 1]; WCHAR szFunctionName[100]; WCHAR szCaller[50];//application or module name //WCHAR szTime[20];//2009-12-19 17:55 }; // Global Variables: #endif
{'content_hash': '8ef798e0d2bcb74416985c52ddee5119', 'timestamp': '', 'source': 'github', 'line_count': 322, 'max_line_length': 120, 'avg_line_length': 42.20807453416149, 'alnum_prop': 0.7516003237436539, 'repo_name': 'pslgoh/rhodes', 'id': 'b9fbb5d0d1fb685a14957207d236da39a2f790ad', 'size': '13591', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'neon/Helium/HeliumForWindows/Implementation/PBCore/PBCore/PBCore.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '6153'}, {'name': 'Batchfile', 'bytes': '116099'}, {'name': 'C', 'bytes': '45880240'}, {'name': 'C#', 'bytes': '5207323'}, {'name': 'C++', 'bytes': '15996647'}, {'name': 'COBOL', 'bytes': '187'}, {'name': 'CSS', 'bytes': '641054'}, {'name': 'GAP', 'bytes': '76344'}, {'name': 'Groff', 'bytes': '328967'}, {'name': 'HTML', 'bytes': '1745773'}, {'name': 'Java', 'bytes': '6394915'}, {'name': 'JavaScript', 'bytes': '1631675'}, {'name': 'Makefile', 'bytes': '329909'}, {'name': 'Matlab', 'bytes': '123'}, {'name': 'NSIS', 'bytes': '85322'}, {'name': 'Objective-C', 'bytes': '3261894'}, {'name': 'Objective-C++', 'bytes': '403455'}, {'name': 'PAWN', 'bytes': '3659'}, {'name': 'Perl', 'bytes': '1710'}, {'name': 'QMake', 'bytes': '53576'}, {'name': 'Rebol', 'bytes': '130'}, {'name': 'Ruby', 'bytes': '15073681'}, {'name': 'Shell', 'bytes': '28867'}, {'name': 'XSLT', 'bytes': '4315'}, {'name': 'Yacc', 'bytes': '232442'}]}
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MetroRadiance.Controls { [Obsolete] [EditorBrowsable(EditorBrowsableState.Never)] public interface ITabItem { string Name { get; } int? Badge { get; } bool IsSelected { get; set; } } }
{'content_hash': '369dcf97e4145e98f5799845979f01f3', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 46, 'avg_line_length': 20.61111111111111, 'alnum_prop': 0.7142857142857143, 'repo_name': 'Grabacr07/MetroRadiance', 'id': '6d0dc699bc128e68fc70b46c9e55289a73678113', 'size': '373', 'binary': False, 'copies': '2', 'ref': 'refs/heads/develop', 'path': 'source/RetroRadiance/MetroRadiance/Controls/ITabItem.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '280'}, {'name': 'C#', 'bytes': '535429'}]}
import React, { Component } from 'react' class Dashboard extends Component { render() { return ( <div> <h3>Course Dashboard</h3> </div> ) } } export default Dashboard
{'content_hash': '51825f360b48ef25e0de349f472a252b', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 40, 'avg_line_length': 15.461538461538462, 'alnum_prop': 0.5870646766169154, 'repo_name': 'CanopyTax/single-spa-examples', 'id': '1b0375b702c62b3212eb674687841a275892fb7b', 'size': '201', 'binary': False, 'copies': '11', 'ref': 'refs/heads/master', 'path': 'src/react/routes/Course/components/Dashboard.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1472'}, {'name': 'HTML', 'bytes': '9588'}, {'name': 'JavaScript', 'bytes': '103555'}, {'name': 'TypeScript', 'bytes': '1564'}]}
package ictrobot.gems.magnetic.item; import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import ictrobot.core.Core; public class ItemRing extends BaseRing { public ItemRing(int id, int par2) { super(id, par2, "Item"); } public void tickClient(ItemStack itemStack, World world, Entity entity, int par4, boolean par5) { NBTTagCompound tag = itemStack.getTagCompound(); if (tag!=null) { if (tag.getInteger("Pnum")>0) { for(int i=1; i<=tag.getInteger("Pnum"); i++){ world.spawnParticle("largesmoke", tag.getDouble("P" + i + "x"), tag.getDouble("P" + i + "y"), tag.getDouble("P" + i + "z"), 0, 0.1, 0); } } } } @SuppressWarnings({ "unchecked", "rawtypes" }) public void tickServer(ItemStack itemStack, World world, Entity entity, int par4, boolean par5) { if( itemStack.getTagCompound() == null ) { itemStack.setTagCompound( new NBTTagCompound( )); itemStack.getTagCompound().setInteger("MaxPower", DefaultPower); itemStack.getTagCompound().setInteger("Delay", 10); } NBTTagCompound tag = itemStack.getTagCompound(); EntityPlayer player; if (tag.getBoolean("Enabled") && ((entity instanceof EntityPlayer))) { float radius = tag.getInteger("MaxPower"); player = (EntityPlayer)entity; final List<EntityItem> list = (List<EntityItem>)world.getEntitiesWithinAABB((Class)EntityItem.class, player.boundingBox.expand(radius, radius, radius)); for (final EntityItem e : list) { if (e.age >= tag.getInteger("Delay")) { if (Core.isServer() && player.inventory.addItemStackToInventory(e.getEntityItem())) { world.removeEntity(e); tag.setInteger("Pnum", tag.getInteger("Pnum")+1); tag.setDouble("P" + tag.getInteger("Pnum")+"x", e.posX); tag.setDouble("P" + tag.getInteger("Pnum")+"y", e.posY); tag.setDouble("P" + tag.getInteger("Pnum")+"z", e.posZ); tag.setInteger("P" + tag.getInteger("Pnum") + "t", 1); tag.setBoolean("P" + tag.getInteger("Pnum") + "e", true); } } } } if (tag.getInteger("Pnum")>0) { boolean shouldReset = true; for(int i=1; i<=tag.getInteger("Pnum"); i++){ if (tag.getInteger("P" + i + "t")!=0) { int time = tag.getInteger("P" + i + "t"); time++; if (time>20) { tag.removeTag("P" + i + "t"); tag.removeTag("P" + i + "x"); tag.removeTag("P" + i + "y"); tag.removeTag("P" + i + "z"); tag.setBoolean("P" + i + "e", false); } else { tag.setInteger("P" + i + "t", time); } } if (tag.getBoolean("P" + i + "e")) { shouldReset=false; } } if (shouldReset) { for(int i=1; i<=tag.getInteger("Pnum"); i++){ tag.removeTag("P" + i + "e"); } tag.setInteger("Pnum", 0); } } } public ItemStack rightClickServer(ItemStack itemStack, World world, EntityPlayer player) { if( itemStack.getTagCompound() == null ) { itemStack.setTagCompound( new NBTTagCompound( ) ); itemStack.getTagCompound().setInteger("Delay", 10); } NBTTagCompound tag = itemStack.getTagCompound(); if (player.isSneaking()) { if (!tag.getBoolean("Enabled")) { tag.setBoolean("Enabled", true); player.addChatMessage("\u00A73\u00A7lFlight Ring:\u00A7r\u00A77 Enabled"); } double time = tag.getInteger("Delay"); time = time / 20; time = time + 0.5; if (time>5) { time=0.5; } double ticks = time*20; int t = (int)ticks; tag.setInteger("Delay", t); player.addChatMessage("\u00A73\u00A7lItem Ring:\u00A7r\u00A77 Delay " + time); } else { if (tag.getBoolean("Enabled")) { tag.setBoolean("Enabled", false); player.addChatMessage("\u00A73\u00A7lItem Ring:\u00A7r\u00A77 Disabled"); } else { tag.setBoolean("Enabled", true); player.addChatMessage("\u00A73\u00A7lItem Ring:\u00A7r\u00A77 Enabled"); } } return itemStack; } @SuppressWarnings({ "rawtypes", "unchecked" }) public void addInformation(ItemStack itemStack, EntityPlayer player, List par3List, boolean par4) { if( itemStack.getTagCompound() != null ) { NBTTagCompound tag = itemStack.getTagCompound(); if (tag.getBoolean("Enabled")) { par3List.add("\u00A77Enabled"); double time = tag.getInteger("Delay"); double delay = time/20; par3List.add("\u00A77Range - " + tag.getInteger("MaxPower")); par3List.add("\u00A77Delay - " + delay + " seconds"); } else { par3List.add("\u00A77Disabled"); } if(tag.getBoolean("Modified")) { par3List.add("\u00A77Modified"); } } } }
{'content_hash': '06908668dc1910f71813cf11af0f82b4', 'timestamp': '', 'source': 'github', 'line_count': 136, 'max_line_length': 158, 'avg_line_length': 37.36764705882353, 'alnum_prop': 0.5911058638331366, 'repo_name': 'ictrobot/Gems', 'id': '735dfd2c8a635f41dbe5dce5a9f4484028a61e7a', 'size': '5082', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/ictrobot/gems/magnetic/item/ItemRing.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '150235'}]}
迷宫 (Maze) =========== 迷宫生成与寻路算法 (Maze generation and solving implementation just for fun.) -- MIT license - Copyright (C) 2014 :sparkles:
{'content_hash': '24084258fb2c617390722eb44881c4e5', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 58, 'avg_line_length': 14.2, 'alnum_prop': 0.6690140845070423, 'repo_name': 'niucheng/Maze', 'id': '9121c6689fb52c72ba6b6a03b4b665699cf0ce9a', 'size': '164', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Visual Basic', 'bytes': '3661'}]}
FROM balenalib/orange-pi-one-ubuntu:cosmic-run # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/* # key 63C7CC90: public key "Simon McVittie <[email protected]>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.8.9 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.0.1 ENV SETUPTOOLS_VERSION 56.0.0 RUN set -x \ && buildDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && echo "c5b7c118af6ad28d1b978513451b47e5acca51e3fc469dfc95ccf0ee9036bd82 Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@python" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu cosmic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.8.9, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{'content_hash': '6e27a968c14274ba9273142048badc68', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 708, 'avg_line_length': 51.93589743589744, 'alnum_prop': 0.7079733399160701, 'repo_name': 'nghiant2710/base-images', 'id': 'd65102cf01d3247b5cbf21428123e97dbcf7f6a5', 'size': '4072', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'balena-base-images/python/orange-pi-one/ubuntu/cosmic/3.8.9/run/Dockerfile', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '144558581'}, {'name': 'JavaScript', 'bytes': '16316'}, {'name': 'Shell', 'bytes': '368690'}]}
<?php namespace Figaromedias\Bundle\DsAutomobilesBundle\Controller; use Sonata\AdminBundle\Controller\CRUDController; class DsArticleAdminController extends CRUDController { }
{'content_hash': 'dc2c3c05c2edd01be69f93bf765333eb', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 61, 'avg_line_length': 18.0, 'alnum_prop': 0.85, 'repo_name': 'figaromedias/Ateliers_figaro', 'id': '8bfc2146f56d2c8d60d7f46af3a5d92353d25d62', 'size': '180', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Figaromedias/Bundle/DsAutomobilesBundle/Controller/DsArticleAdminController.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '1223'}, {'name': 'CSS', 'bytes': '1604027'}, {'name': 'HTML', 'bytes': '1332825'}, {'name': 'JavaScript', 'bytes': '3543980'}, {'name': 'PHP', 'bytes': '537359'}, {'name': 'Shell', 'bytes': '167'}]}
function btkSetAnalogDescription(h, idx_or_label, new_desc) %#ok %BTKSETANALOGDESCRIPTION Modify the analog's description and return a list of the updated analog channels. % % BTKSETANALOGDESCRIPTION(H, INDEX, NEWDESC) modifies analog's description by % NEWDESC for the analog channel at the index INDEX. NEWDESC must be a string. % % The point to modify can also be selected by its LABEL. % BTKSETANALOGDESCRIPTION(H, LABEL, NEWDESC) % % This function can also returns an updated list of points. % ANALOGS = BTKSETANALOGDESCRIPTION(H, INDEX, NEWDESC) % ANALOGS = BTKSETANALOGDESCRIPTION(H, LABEL, NEWDESC) % The format of ANALOGS is the same than using the function <a href="matlab:help btkGetAnalogs">btkGetAnalogs</a> % % This function can also returns an updated list of points' informations. % [ANALOGS, ANALOGSINFO] = BTKSETANALOGDESCRIPTION(H, INDEX, NEWDESC) % [ANALOGS, ANALOGSINFO] = BTKSETANALOGDESCRIPTION(H, LABEL, NEWDESC) % The format of ANALOGSINFO is the same than using the function <a href="matlab:help btkGetAnalogs">btkGetAnalogs</a> % % The acquisition is represented by the handle H. This handle is obtained % by the use of a btk* function. % Author: A. Barré % Copyright 2009-2014 Biomechanical ToolKit (BTK). % The following comment, MATLAB compiler pragma, is necessary to avoid % compiling this M-file instead of linking against the MEX-file. Don't remove. %# mex error(generatemsgid('NotSupported'),'MEX file for BTKSETANALOGDESCRIPTION not found'); % [EOF] btkSetAnalogDescription.m
{'content_hash': '1d199be66eefb2376db316542e069a82', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 118, 'avg_line_length': 48.03125, 'alnum_prop': 0.7670787247885491, 'repo_name': 'Biomechanical-ToolKit/BTKCore', 'id': 'd016cf3cd1118b52f0c7dcee51c59621e77f564e', 'size': '1538', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'Documentation/Wrapping/Matlab/btk/@Common/btkSetAnalogDescription.m', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '6020'}, {'name': 'C', 'bytes': '267076'}, {'name': 'C++', 'bytes': '10328663'}, {'name': 'CMake', 'bytes': '131684'}, {'name': 'CSS', 'bytes': '3652'}, {'name': 'HTML', 'bytes': '114481'}, {'name': 'Java', 'bytes': '5610'}, {'name': 'JavaScript', 'bytes': '533'}, {'name': 'M', 'bytes': '5634'}, {'name': 'Makefile', 'bytes': '191'}, {'name': 'Matlab', 'bytes': '442654'}, {'name': 'Objective-C', 'bytes': '2495'}, {'name': 'Python', 'bytes': '272014'}, {'name': 'Shell', 'bytes': '3691'}]}
<?xml version="1.0"?> <menu> <item id="about" text="About..." img="about.gif"/> <item id="help" text="Help" img="help.gif"/> <item id="bug_reporting" text="Bug Reporting" img="bug_reporting.gif"/> </menu>
{'content_hash': 'b05deaa290d64daacd1e6ec081a212fa', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 72, 'avg_line_length': 35.666666666666664, 'alnum_prop': 0.6121495327102804, 'repo_name': 'a10188748/boyee', 'id': 'cad998ed35b792775d3bf668def1215b91b4a7a4', 'size': '214', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'public/dhtmlxSuite/samples/dhtmlxWindows/common/menu/menu2.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '122'}, {'name': 'ApacheConf', 'bytes': '253'}, {'name': 'Batchfile', 'bytes': '403'}, {'name': 'C#', 'bytes': '2182'}, {'name': 'CSS', 'bytes': '1461580'}, {'name': 'HTML', 'bytes': '10488592'}, {'name': 'Java', 'bytes': '3506'}, {'name': 'JavaScript', 'bytes': '3059254'}, {'name': 'PHP', 'bytes': '2399258'}]}
/* All rights reserved. */ /* This file is part of spglib. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* * Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* * Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* * Neither the name of the phonopy project nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */ /* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */ /* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */ /* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */ /* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ #ifndef __spin_H__ #define __spin_H__ #include "mathfunc.h" #include "symmetry.h" #include "cell.h" Symmetry * spn_get_collinear_operations(int equiv_atoms[], const Symmetry *sym_nonspin, const Cell *cell, const double spins[], const double symprec); #endif
{'content_hash': 'c3734b5aa036523cefc0d5e0445ec519', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 74, 'avg_line_length': 43.0625, 'alnum_prop': 0.6734397677793904, 'repo_name': 'jochym/spglib', 'id': 'a99487259986c065b3f825dd120395d2d763adf5', 'size': '2104', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'src/spin.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '246'}, {'name': 'C', 'bytes': '1343452'}, {'name': 'CMake', 'bytes': '3001'}, {'name': 'Fortran', 'bytes': '37033'}, {'name': 'M4', 'bytes': '848'}, {'name': 'Makefile', 'bytes': '1122'}, {'name': 'Python', 'bytes': '251923'}, {'name': 'Ruby', 'bytes': '32153'}, {'name': 'Shell', 'bytes': '2249'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> Class: NewsStrategyFactory &mdash; Documentation by YARD 0.8.7.3 </title> <link rel="stylesheet" href="css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="css/common.css" type="text/css" charset="utf-8" /> <script type="text/javascript" charset="utf-8"> hasFrames = window.top.frames.main ? true : false; relpath = ''; framesUrl = "frames.html#!" + escape(window.location.href); </script> <script type="text/javascript" charset="utf-8" src="js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="js/app.js"></script> </head> <body> <div id="header"> <div id="menu"> <a href="_index.html">Index (N)</a> &raquo; <span class="title">NewsStrategyFactory</span> <div class="noframes"><span class="title">(</span><a href="." target="_top">no frames</a><span class="title">)</span></div> </div> <div id="search"> <a class="full_list_link" id="class_list_link" href="class_list.html"> Class List </a> <a class="full_list_link" id="method_list_link" href="method_list.html"> Method List </a> <a class="full_list_link" id="file_list_link" href="file_list.html"> File List </a> </div> <div class="clear"></div> </div> <iframe id="search_frame"></iframe> <div id="content"><h1>Class: NewsStrategyFactory </h1> <dl class="box"> <dt class="r1">Inherits:</dt> <dd class="r1"> <span class="inheritName">Object</span> <ul class="fullTree"> <li>Object</li> <li class="next">NewsStrategyFactory</li> </ul> <a href="#" class="inheritanceTree">show all</a> </dd> <dt class="r2 last">Defined in:</dt> <dd class="r2 last">lib/news/news_strategies/news_strategy_factory.rb</dd> </dl> <div class="clear"></div> <h2> Class Method Summary <small>(<a href="#" class="summary_toggle">collapse</a>)</small> </h2> <ul class="summary"> <li class="public "> <span class="summary_signature"> <a href="#build_new-class_method" title="build_new (class method)">+ (Object) <strong>build_new</strong>(content) </a> </span> <span class="summary_desc"><div class='inline'></div></span> </li> </ul> <div id="class_method_details" class="method_details_list"> <h2>Class Method Details</h2> <div class="method_details first"> <h3 class="signature first" id="build_new-class_method"> + (<tt>Object</tt>) <strong>build_new</strong>(content) </h3><table class="source_code"> <tr> <td> <pre class="lines"> 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21</pre> </td> <td> <pre class="code"><span class="info file"># File 'lib/news/news_strategies/news_strategy_factory.rb', line 5</span> <span class='kw'>def</span> <span class='kw'>self</span><span class='period'>.</span><span class='id identifier rubyid_build_new'>build_new</span><span class='lparen'>(</span><span class='id identifier rubyid_content'>content</span><span class='rparen'>)</span> <span class='id identifier rubyid_attributes'>attributes</span> <span class='op'>=</span> <span class='lbrace'>{</span> <span class='label'>body:</span> <span class='id identifier rubyid_content'>content</span><span class='period'>.</span><span class='id identifier rubyid_body'>body</span><span class='comma'>,</span> <span class='label'>url:</span> <span class='id identifier rubyid_content'>content</span><span class='period'>.</span><span class='id identifier rubyid_url'>url</span> <span class='rbrace'>}</span> <span class='kw'>case</span> <span class='id identifier rubyid_content'>content</span><span class='period'>.</span><span class='id identifier rubyid_url'>url</span> <span class='kw'>when</span> <span class='const'>New</span><span class='op'>::</span><span class='const'>DiarioJaen</span><span class='period'>.</span><span class='id identifier rubyid_url'>url</span> <span class='const'>New</span><span class='op'>::</span><span class='const'>DiarioJaen</span><span class='period'>.</span><span class='id identifier rubyid_new'>new</span><span class='lparen'>(</span><span class='id identifier rubyid_attributes'>attributes</span><span class='rparen'>)</span> <span class='kw'>when</span> <span class='const'>New</span><span class='op'>::</span><span class='const'>VivaJaen</span><span class='period'>.</span><span class='id identifier rubyid_url'>url</span> <span class='const'>New</span><span class='op'>::</span><span class='const'>VivaJaen</span><span class='period'>.</span><span class='id identifier rubyid_new'>new</span><span class='lparen'>(</span><span class='id identifier rubyid_attributes'>attributes</span><span class='rparen'>)</span> <span class='kw'>when</span> <span class='const'>New</span><span class='op'>::</span><span class='const'>IdealJaen</span><span class='period'>.</span><span class='id identifier rubyid_url'>url</span> <span class='const'>New</span><span class='op'>::</span><span class='const'>IdealJaen</span><span class='period'>.</span><span class='id identifier rubyid_new'>new</span><span class='lparen'>(</span><span class='id identifier rubyid_attributes'>attributes</span><span class='rparen'>)</span> <span class='kw'>else</span> <span class='const'>New</span><span class='op'>::</span><span class='const'>NullNew</span><span class='period'>.</span><span class='id identifier rubyid_new'>new</span><span class='lparen'>(</span><span class='id identifier rubyid_attributes'>attributes</span><span class='rparen'>)</span> <span class='kw'>end</span> <span class='kw'>end</span></pre> </td> </tr> </table> </div> </div> </div> <div id="footer"> Generated on Fri Jan 3 02:08:28 2014 by <a href="http://yardoc.org" title="Yay! A Ruby Documentation Tool" target="_parent">yard</a> 0.8.7.3 (ruby-2.0.0). </div> </body> </html>
{'content_hash': '80a4c595bf746133e553d5bf75d23aea', 'timestamp': '', 'source': 'github', 'line_count': 217, 'max_line_length': 517, 'avg_line_length': 29.46082949308756, 'alnum_prop': 0.6261536055060222, 'repo_name': 'wuiscmc/nyhetis', 'id': 'ec05bb4c8f3ae06372a14a874cad58353ea197d8', 'size': '6393', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/NewsStrategyFactory.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '23435'}, {'name': 'JavaScript', 'bytes': '12293'}, {'name': 'Ruby', 'bytes': '1926122'}, {'name': 'Shell', 'bytes': '759'}]}
// The MIT License (MIT) // // Copyright (c) 2014 Jonas Finnemann Jensen // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. var _ = require('lodash'); var debug = require('debug')('json-parameterization'); var safeEval = require('notevil'); var vm = require('vm'); /** Evaluate an expression in a given context, using two sand boxes :) */ var evalExpr = function(expr, context) { if (typeof(expr) !== 'string') { return expr; } context = _.cloneDeep(context, function(value) { if (typeof(value) === 'function') { return value; } return undefined; }); // Evaluate in a sand box try { return safeEval(expr, context); } catch (err) { var err = new Error("Error interpreting: `" + expression + "` got '" + error.toString() + "'"); err.expression = expr; err.code = 'ParameterizationFailed'; throw err; } }; /** Parameterize input with params */ var parameterize = function(input, params) { // Parameterize a string var parameterizeString = function(str) { // Otherwise treat ${,..} as string interpolations return str.replace(/\${([^}]*)}/g, function(originalText, expr) { try { var val = evalExpr(expr, params); if (typeof(val) !== 'string' && typeof(val) !== 'number') { var error = new Error("Can't substitute " + typeof(val) + " from " + "expression: `" + expr + "` into string: '" + str + "'"); error.expression = expr; error.code = 'ParameterizationFailed'; throw error; } return val; } catch (err) { err.construct = str; throw err; } }); }; // Create clone function var clone = function(value) { // Parameterized strings if (typeof(value) === 'string') { return parameterizeString(value); } // Don't parameterize numbers and booleans if (typeof(value) !== 'object') { return value; } // Parameterize array entries if (value instanceof Array) { // Parameterize array and filter undefined entries return value.map(clone).filter(function(entry) { return entry !== undefined; }); } // Handle if-constructs if (typeof(value['$if']) === 'string') { try { if (evalExpr(value['$if'], params)) { return clone(value['then']); } else { return clone(value['else']); } } catch (err) { err.construct = _.cloneDeep(value); throw err; } } // Handle switch-constructs if (typeof(value['$switch']) === 'string') { try { var label = evalExpr(value['$switch'], params); return clone(value[label]); } catch (err) { err.construct = _.cloneDeep(value); throw err; } } // Handle eval-constructs if (typeof(value['$eval']) === 'string') { try { return evalExpr(value['$eval'], params); } catch (err) { err.construct = _.cloneDeep(value); throw err; } } // Parameterize normal objects, both keys and values var result = {}; for(var k in value) { // Parameterize string var key = parameterizeString(k); if (typeof(key) !== 'string') { key = k; } // Parameterize value var val = clone(value[k]); if (val === undefined) { continue; // Don't assign undefined, use it to delete properties } result[key] = val; } return result; }; // Let's use a top-level sandbox for good measure var result, error; vm.runInNewContext("run()", { run: function() { try { // Create clone result = clone(input); } catch (err) { error = err; } }, }, { displayErrors: false, timeout: 500 }); if (error) { throw error; } return result; }; // Export parameterize module.exports = parameterize;
{'content_hash': '9599f85bb6bfb85d585185ecd0500751', 'timestamp': '', 'source': 'github', 'line_count': 172, 'max_line_length': 80, 'avg_line_length': 29.302325581395348, 'alnum_prop': 0.5869047619047619, 'repo_name': 'jonasfj/json-parameterization', 'id': '44097204b989810501125245796838d4b0dc1f6c', 'size': '5040', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '12694'}]}
from __future__ import absolute_import, division, print_function, unicode_literals from c7n import executor import unittest class Foo(object): def __init__(self, state): self.state = state def abc(self, *args, **kw): return args, kw @staticmethod def run(*args, **kw): return args, kw @classmethod def execute(cls, *args, **kw): return args, kw def __call__(self, *args, **kw): return args, kw class ExecutorBase(object): def test_map_instance(self): with self.executor_factory(max_workers=3) as w: self.assertEqual( list(w.map(Foo("123"), [1, 2, 3])), [((1,), {}), ((2,), {}), ((3,), {})] ) class ProcessExecutorTest(ExecutorBase, unittest.TestCase): executor_factory = executor.ProcessPoolExecutor class ThreadExecutorTest(ExecutorBase, unittest.TestCase): executor_factory = executor.ThreadPoolExecutor class MainExecutorTest(ExecutorBase, unittest.TestCase): executor_factory = executor.MainThreadExecutor if __name__ == "__main__": unittest.main()
{'content_hash': 'c98cfd256d2f27e9a263022ca77a8dda', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 88, 'avg_line_length': 22.18, 'alnum_prop': 0.6266907123534716, 'repo_name': 'taohungyang/cloud-custodian', 'id': '9d45eb16e4d771eaa35991482d6848a3b2b1aedf', 'size': '1699', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'tests/test_executor.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '517'}, {'name': 'Go', 'bytes': '131325'}, {'name': 'HTML', 'bytes': '31'}, {'name': 'Makefile', 'bytes': '10146'}, {'name': 'Python', 'bytes': '3444793'}, {'name': 'Shell', 'bytes': '2294'}]}
package gads import ( "bytes" "encoding/xml" "flag" "fmt" "io/ioutil" "net/http" "testing" ) const ( baseUrl = "https://adwords.google.com/api/adwords/cm/v201506" // used for developpement, if true all unknown field will raise an error StrictMode = false ) type ServiceUrl struct { Url string Name string } // exceptions var ( ERROR_NOT_YET_IMPLEMENTED = fmt.Errorf("Not yet implemented") ) var ( configJson = flag.String("config_json", "./config.json", "API credentials") // service urls adGroupAdServiceUrl = ServiceUrl{baseUrl, "AdGroupAdService"} adGroupBidModifierServiceUrl = ServiceUrl{baseUrl, "AdGroupBidModifierService"} adGroupCriterionServiceUrl = ServiceUrl{baseUrl, "AdGroupCriterionService"} adGroupFeedServiceUrl = ServiceUrl{baseUrl, "AdGroupFeedService"} adGroupServiceUrl = ServiceUrl{baseUrl, "AdGroupService"} adParamServiceUrl = ServiceUrl{baseUrl, "AdParamService"} adwordsUserListServiceUrl = ServiceUrl{baseUrl, "AdwordsUserListService"} biddingStrategyServiceUrl = ServiceUrl{baseUrl, "BiddingStrategyService"} budgetOrderServiceUrl = ServiceUrl{baseUrl, "BudgetOrderService"} budgetServiceUrl = ServiceUrl{baseUrl, "BudgetService"} campaignAdExtensionServiceUrl = ServiceUrl{baseUrl, "CampaignAdExtensionService"} campaignCriterionServiceUrl = ServiceUrl{baseUrl, "CampaignCriterionService"} campaignFeedServiceUrl = ServiceUrl{baseUrl, "CampaignFeedService"} campaignServiceUrl = ServiceUrl{baseUrl, "CampaignService"} campaignExtensionSettingServiceUrl = ServiceUrl{baseUrl, "CampaignExtensionSettingService"} campaignSharedSetServiceUrl = ServiceUrl{baseUrl, "CampaignSharedSetService"} constantDataServiceUrl = ServiceUrl{baseUrl, "ConstantDataService"} conversionTrackerServiceUrl = ServiceUrl{baseUrl, "ConversionTrackerService"} customerFeedServiceUrl = ServiceUrl{baseUrl, "CustomerFeedService"} customerServiceUrl = ServiceUrl{baseUrl, "CustomerService"} customerSyncServiceUrl = ServiceUrl{baseUrl, "CustomerSyncService"} dataServiceUrl = ServiceUrl{baseUrl, "DataService"} experimentServiceUrl = ServiceUrl{baseUrl, "ExperimentService"} feedItemServiceUrl = ServiceUrl{baseUrl, "FeedItemService"} feedMappingServiceUrl = ServiceUrl{baseUrl, "FeedMappingService"} feedServiceUrl = ServiceUrl{baseUrl, "FeedService"} geoLocationServiceUrl = ServiceUrl{baseUrl, "GeoLocationService"} labelServiceUrl = ServiceUrl{baseUrl, "LabelService"} locationCriterionServiceUrl = ServiceUrl{baseUrl, "LocationCriterionService"} managedCustomerServiceUrl = ServiceUrl{baseUrl, "ManagedCustomerService"} mediaServiceUrl = ServiceUrl{baseUrl, "MediaService"} mutateJobServiceUrl = ServiceUrl{baseUrl, "Mutate_JOB_Service"} offlineConversionFeedServiceUrl = ServiceUrl{baseUrl, "OfflineConversionFeedService"} reportDefinitionServiceUrl = ServiceUrl{baseUrl, "ReportDefinitionService"} sharedCriterionServiceUrl = ServiceUrl{baseUrl, "SharedCriterionService"} sharedSetServiceUrl = ServiceUrl{baseUrl, "SharedSetService"} targetingIdeaServiceUrl = ServiceUrl{baseUrl, "TargetingIdeaService"} trafficEstimatorServiceUrl = ServiceUrl{baseUrl, "TrafficEstimatorService"} ) func (s ServiceUrl) String() string { return s.Url + "/" + s.Name } type Auth struct { CustomerId string DeveloperToken string UserAgent string Testing *testing.T `json:"-"` Client *http.Client `json:"-"` } // // Selector structs // type DateRange struct { Min string `xml:"min"` Max string `xml:"max"` } type Predicate struct { Field string `xml:"field"` Operator string `xml:"operator"` Values []string `xml:"values"` } type OrderBy struct { Field string `xml:"field"` SortOrder string `xml:"sortOrder"` } type Paging struct { Offset int64 `xml:"startIndex"` Limit int64 `xml:"numberResults"` } type Selector struct { XMLName xml.Name Fields []string `xml:"fields"` Predicates []Predicate `xml:"predicates"` DateRange *DateRange `xml:"dateRange,omitempty"` Ordering []OrderBy `xml:"ordering"` Paging *Paging `xml:"paging,omitempty"` } // error parsers func selectorError() (err error) { return err } func (a *Auth) request( serviceUrl ServiceUrl, action string, body interface{}, ) (respBody []byte, err error) { type devToken struct { XMLName xml.Name } type soapReqHeader struct { XMLName xml.Name UserAgent string `xml:"userAgent"` DeveloperToken string `xml:"developerToken"` ClientCustomerId string `xml:"clientCustomerId"` } type soapReqBody struct { Body interface{} } type soapReqEnvelope struct { XMLName xml.Name Header soapReqHeader `xml:"Header>RequestHeader"` XSINamespace string `xml:"xmlns:xsi,attr"` Body soapReqBody `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"` } reqBody, err := xml.MarshalIndent( soapReqEnvelope{ XMLName: xml.Name{"http://schemas.xmlsoap.org/soap/envelope/", "Envelope"}, Header: soapReqHeader{ XMLName: xml.Name{serviceUrl.Url, "RequestHeader"}, UserAgent: a.UserAgent, DeveloperToken: a.DeveloperToken, ClientCustomerId: a.CustomerId, }, XSINamespace: "http://www.w3.org/2001/XMLSchema-instance", Body: soapReqBody{body}, }, " ", " ", ) if err != nil { return []byte{}, err } req, err := http.NewRequest("POST", serviceUrl.String(), bytes.NewReader(reqBody)) req.Header.Add("Accept", "text/xml") req.Header.Add("Accept", "multipart/*") req.Header.Add("Content-Type", "text/xml;charset=UTF-8") contentLength := fmt.Sprintf("%d", len(reqBody)) req.Header.Add("Content-length", contentLength) req.Header.Add("SOAPAction", action) if a.Testing != nil { a.Testing.Logf("request ->\n%s\n%#v\n%s\n", req.URL.String(), req.Header, string(reqBody)) } resp, err := a.Client.Do(req) if err != nil { return []byte{}, err } respBody, err = ioutil.ReadAll(resp.Body) if a.Testing != nil { a.Testing.Logf("respBody ->\n%s\n%s\n", string(respBody), resp.Status) } type soapRespHeader struct { RequestId string `xml:"requestId"` ServiceName string `xml:"serviceName"` MethodName string `xml:"methodName"` Operations int64 `xml:"operations"` ResponseTime int64 `xml:"responseTime"` } type soapRespBody struct { Response []byte `xml:",innerxml"` } soapResp := struct { XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"` Header soapRespHeader `xml:"Header>RequestHeader"` Body soapRespBody `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"` }{} err = xml.Unmarshal([]byte(respBody), &soapResp) if err != nil { return respBody, err } if resp.StatusCode == 400 || resp.StatusCode == 401 || resp.StatusCode == 403 || resp.StatusCode == 405 || resp.StatusCode == 500 { fault := Fault{} // fmt.Printf("unknown error ->\n%s\n", string(soapResp.Body.Response)) err = xml.Unmarshal(soapResp.Body.Response, &fault) if err != nil { return respBody, err } return soapResp.Body.Response, &fault.Errors } return soapResp.Body.Response, err }
{'content_hash': '364a4bd1db76b3acec38df979f15cdf4', 'timestamp': '', 'source': 'github', 'line_count': 220, 'max_line_length': 132, 'avg_line_length': 34.231818181818184, 'alnum_prop': 0.6872925242331696, 'repo_name': 'allan-simon/gads', 'id': '74778a3e212e6d9088db1e998ac887fd27d068af', 'size': '7531', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'base.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '163100'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>VO808X: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">VO808X </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('classtesting_1_1internal_1_1_universal_printer.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">testing::internal::UniversalPrinter&lt; T &gt; Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classtesting_1_1internal_1_1_universal_printer.html">testing::internal::UniversalPrinter&lt; T &gt;</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="classtesting_1_1internal_1_1_universal_printer.html#a6a7d29444412467c14931bc55a046138">Print</a>(const T &amp;value,::std::ostream *os)</td><td class="entry"><a class="el" href="classtesting_1_1internal_1_1_universal_printer.html">testing::internal::UniversalPrinter&lt; T &gt;</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">static</span></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.11 </li> </ul> </div> </body> </html>
{'content_hash': '1dbb49a47ffe02822e1a1fffc27b3a88', 'timestamp': '', 'source': 'github', 'line_count': 128, 'max_line_length': 439, 'avg_line_length': 43.1796875, 'alnum_prop': 0.6517097883119233, 'repo_name': 'bhargavipatel/808X_VO', 'id': 'ccd201d046e114ddb6e46b430ebcebbc69609e10', 'size': '5527', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/html/classtesting_1_1internal_1_1_universal_printer-members.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '18150'}, {'name': 'CMake', 'bytes': '9404'}, {'name': 'Matlab', 'bytes': '10128'}, {'name': 'Python', 'bytes': '5095'}]}
import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { ITerminalSimpleLink, TerminalBuiltinLinkType } from 'vs/workbench/contrib/terminal/browser/links/links'; import { TerminalUriLinkDetector } from 'vs/workbench/contrib/terminal/browser/links/terminalUriLinkDetector'; import { assertLinkHelper, resolveLinkForTest } from 'vs/workbench/contrib/terminal/test/browser/links/linkTestUtils'; import { Terminal } from 'xterm'; suite('Workbench - TerminalUriLinkDetector', () => { let configurationService: TestConfigurationService; let detector: TerminalUriLinkDetector; let xterm: Terminal; setup(() => { const instantiationService = new TestInstantiationService(); configurationService = new TestConfigurationService(); instantiationService.stub(IConfigurationService, configurationService); xterm = new Terminal({ cols: 80, rows: 30 }); detector = instantiationService.createInstance(TerminalUriLinkDetector, xterm, resolveLinkForTest); }); async function assertLink( type: TerminalBuiltinLinkType, text: string, expected: (Pick<ITerminalSimpleLink, 'text'> & { range: [number, number][] })[] ) { await assertLinkHelper(text, expected, detector, type); } const linkComputerCases: [TerminalBuiltinLinkType, string, (Pick<ITerminalSimpleLink, 'text'> & { range: [number, number][] })[]][] = [ [TerminalBuiltinLinkType.Url, 'x = "http://foo.bar";', [{ range: [[6, 1], [19, 1]], text: 'http://foo.bar' }]], [TerminalBuiltinLinkType.Url, 'x = (http://foo.bar);', [{ range: [[6, 1], [19, 1]], text: 'http://foo.bar' }]], [TerminalBuiltinLinkType.Url, 'x = \'http://foo.bar\';', [{ range: [[6, 1], [19, 1]], text: 'http://foo.bar' }]], [TerminalBuiltinLinkType.Url, 'x = http://foo.bar ;', [{ range: [[6, 1], [19, 1]], text: 'http://foo.bar' }]], [TerminalBuiltinLinkType.Url, 'x = <http://foo.bar>;', [{ range: [[6, 1], [19, 1]], text: 'http://foo.bar' }]], [TerminalBuiltinLinkType.Url, 'x = {http://foo.bar};', [{ range: [[6, 1], [19, 1]], text: 'http://foo.bar' }]], [TerminalBuiltinLinkType.Url, '(see http://foo.bar)', [{ range: [[6, 1], [19, 1]], text: 'http://foo.bar' }]], [TerminalBuiltinLinkType.Url, '[see http://foo.bar]', [{ range: [[6, 1], [19, 1]], text: 'http://foo.bar' }]], [TerminalBuiltinLinkType.Url, '{see http://foo.bar}', [{ range: [[6, 1], [19, 1]], text: 'http://foo.bar' }]], [TerminalBuiltinLinkType.Url, '<see http://foo.bar>', [{ range: [[6, 1], [19, 1]], text: 'http://foo.bar' }]], [TerminalBuiltinLinkType.Url, '<url>http://foo.bar</url>', [{ range: [[6, 1], [19, 1]], text: 'http://foo.bar' }]], [TerminalBuiltinLinkType.Url, '// Click here to learn more. https://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409', [{ range: [[30, 1], [7, 2]], text: 'https://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409' }]], [TerminalBuiltinLinkType.Url, '// Click here to learn more. https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx', [{ range: [[30, 1], [28, 2]], text: 'https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx' }]], [TerminalBuiltinLinkType.Url, '// https://github.com/projectkudu/kudu/blob/master/Kudu.Core/Scripts/selectNodeVersion.js', [{ range: [[4, 1], [9, 2]], text: 'https://github.com/projectkudu/kudu/blob/master/Kudu.Core/Scripts/selectNodeVersion.js' }]], [TerminalBuiltinLinkType.Url, '<!-- !!! Do not remove !!! WebContentRef(link:https://go.microsoft.com/fwlink/?LinkId=166007, area:Admin, updated:2015, nextUpdate:2016, tags:SqlServer) !!! Do not remove !!! -->', [{ range: [[49, 1], [14, 2]], text: 'https://go.microsoft.com/fwlink/?LinkId=166007' }]], [TerminalBuiltinLinkType.Url, 'For instructions, see https://go.microsoft.com/fwlink/?LinkId=166007.</value>', [{ range: [[23, 1], [68, 1]], text: 'https://go.microsoft.com/fwlink/?LinkId=166007' }]], [TerminalBuiltinLinkType.Url, 'For instructions, see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx.</value>', [{ range: [[23, 1], [21, 2]], text: 'https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx' }]], [TerminalBuiltinLinkType.Url, 'x = "https://en.wikipedia.org/wiki/Zürich";', [{ range: [[6, 1], [41, 1]], text: 'https://en.wikipedia.org/wiki/Zürich' }]], [TerminalBuiltinLinkType.Url, '請參閱 http://go.microsoft.com/fwlink/?LinkId=761051。', [{ range: [[8, 1], [53, 1]], text: 'http://go.microsoft.com/fwlink/?LinkId=761051' }]], [TerminalBuiltinLinkType.Url, '(請參閱 http://go.microsoft.com/fwlink/?LinkId=761051)', [{ range: [[10, 1], [55, 1]], text: 'http://go.microsoft.com/fwlink/?LinkId=761051' }]], [TerminalBuiltinLinkType.LocalFile, 'x = "file:///foo.bar";', [{ range: [[6, 1], [20, 1]], text: 'file:///foo.bar' }]], [TerminalBuiltinLinkType.LocalFile, 'x = "file://c:/foo.bar";', [{ range: [[6, 1], [22, 1]], text: 'file://c:/foo.bar' }]], [TerminalBuiltinLinkType.LocalFile, 'x = "file://shares/foo.bar";', [{ range: [[6, 1], [26, 1]], text: 'file://shares/foo.bar' }]], [TerminalBuiltinLinkType.LocalFile, 'x = "file://shäres/foo.bar";', [{ range: [[6, 1], [26, 1]], text: 'file://shäres/foo.bar' }]], [TerminalBuiltinLinkType.Url, 'Some text, then http://www.bing.com.', [{ range: [[17, 1], [35, 1]], text: 'http://www.bing.com' }]], [TerminalBuiltinLinkType.Url, 'let url = `http://***/_api/web/lists/GetByTitle(\'Teambuildingaanvragen\')/items`;', [{ range: [[12, 1], [78, 1]], text: 'http://***/_api/web/lists/GetByTitle(\'Teambuildingaanvragen\')/items' }]], [TerminalBuiltinLinkType.Url, '7. At this point, ServiceMain has been called. There is no functionality presently in ServiceMain, but you can consult the [MSDN documentation](https://msdn.microsoft.com/en-us/library/windows/desktop/ms687414(v=vs.85).aspx) to add functionality as desired!', [{ range: [[66, 2], [64, 3]], text: 'https://msdn.microsoft.com/en-us/library/windows/desktop/ms687414(v=vs.85).aspx' }]], [TerminalBuiltinLinkType.Url, 'let x = "http://[::1]:5000/connect/token"', [{ range: [[10, 1], [40, 1]], text: 'http://[::1]:5000/connect/token' }]], [TerminalBuiltinLinkType.Url, '2. Navigate to **https://portal.azure.com**', [{ range: [[18, 1], [41, 1]], text: 'https://portal.azure.com' }]], [TerminalBuiltinLinkType.Url, 'POST|https://portal.azure.com|2019-12-05|', [{ range: [[6, 1], [29, 1]], text: 'https://portal.azure.com' }]], [TerminalBuiltinLinkType.Url, 'aa https://foo.bar/[this is foo site] aa', [{ range: [[5, 1], [38, 1]], text: 'https://foo.bar/[this is foo site]' }]] ]; for (const c of linkComputerCases) { test('link computer case: `' + c[1] + '`', async () => { await assertLink(c[0], c[1], c[2]); }); } test('should support multiple link results', async () => { await assertLink(TerminalBuiltinLinkType.Url, 'http://foo.bar http://bar.foo', [ { range: [[1, 1], [14, 1]], text: 'http://foo.bar' }, { range: [[16, 1], [29, 1]], text: 'http://bar.foo' } ]); }); test('should detect file:// links with :line suffix', async () => { await assertLink(TerminalBuiltinLinkType.LocalFile, 'file:///c:/folder/file:23', [ { range: [[1, 1], [25, 1]], text: 'file:///c:/folder/file:23' } ]); }); test('should detect file:// links with :line:col suffix', async () => { await assertLink(TerminalBuiltinLinkType.LocalFile, 'file:///c:/folder/file:23:10', [ { range: [[1, 1], [28, 1]], text: 'file:///c:/folder/file:23:10' } ]); }); test('should filter out https:// link that exceed 4096 characters', async () => { // 8 + 200 * 10 = 2008 characters await assertLink(TerminalBuiltinLinkType.Url, `https://${'foobarbaz/'.repeat(200)}`, [{ range: [[1, 1], [8, 26]], text: `https://${'foobarbaz/'.repeat(200)}` }]); // 8 + 450 * 10 = 4508 characters await assertLink(TerminalBuiltinLinkType.Url, `https://${'foobarbaz/'.repeat(450)}`, []); }); test('should filter out file:// links that exceed 4096 characters', async () => { // 8 + 200 * 10 = 2008 characters await assertLink(TerminalBuiltinLinkType.LocalFile, `file:///${'foobarbaz/'.repeat(200)}`, [{ text: `file:///${'foobarbaz/'.repeat(200)}`, range: [[1, 1], [8, 26]] }]); // 8 + 450 * 10 = 4508 characters await assertLink(TerminalBuiltinLinkType.LocalFile, `file:///${'foobarbaz/'.repeat(450)}`, []); }); });
{'content_hash': 'd35e00e398e3b0fbcd2bbec7141873a0', 'timestamp': '', 'source': 'github', 'line_count': 107, 'max_line_length': 416, 'avg_line_length': 79.66355140186916, 'alnum_prop': 0.650398873768184, 'repo_name': 'eamodio/vscode', 'id': 'e7a39a54056296825a9b4dbc4d37da23ff604384', 'size': '8897', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'src/vs/workbench/contrib/terminal/test/browser/links/terminalUriLinkDetector.test.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '19196'}, {'name': 'C', 'bytes': '818'}, {'name': 'C#', 'bytes': '709'}, {'name': 'C++', 'bytes': '2745'}, {'name': 'CSS', 'bytes': '620323'}, {'name': 'Clojure', 'bytes': '1206'}, {'name': 'CoffeeScript', 'bytes': '590'}, {'name': 'Cuda', 'bytes': '3634'}, {'name': 'Dart', 'bytes': '324'}, {'name': 'Dockerfile', 'bytes': '475'}, {'name': 'F#', 'bytes': '634'}, {'name': 'Go', 'bytes': '652'}, {'name': 'Groovy', 'bytes': '3928'}, {'name': 'HLSL', 'bytes': '184'}, {'name': 'HTML', 'bytes': '380999'}, {'name': 'Hack', 'bytes': '16'}, {'name': 'Handlebars', 'bytes': '1064'}, {'name': 'Inno Setup', 'bytes': '304239'}, {'name': 'Java', 'bytes': '599'}, {'name': 'JavaScript', 'bytes': '1413253'}, {'name': 'Julia', 'bytes': '940'}, {'name': 'Jupyter Notebook', 'bytes': '929'}, {'name': 'Less', 'bytes': '1029'}, {'name': 'Lua', 'bytes': '252'}, {'name': 'Makefile', 'bytes': '2252'}, {'name': 'Objective-C', 'bytes': '1387'}, {'name': 'Objective-C++', 'bytes': '1387'}, {'name': 'PHP', 'bytes': '998'}, {'name': 'Perl', 'bytes': '1922'}, {'name': 'PowerShell', 'bytes': '12409'}, {'name': 'Pug', 'bytes': '654'}, {'name': 'Python', 'bytes': '2405'}, {'name': 'R', 'bytes': '362'}, {'name': 'Roff', 'bytes': '351'}, {'name': 'Ruby', 'bytes': '1703'}, {'name': 'Rust', 'bytes': '532'}, {'name': 'SCSS', 'bytes': '6732'}, {'name': 'ShaderLab', 'bytes': '330'}, {'name': 'Shell', 'bytes': '57256'}, {'name': 'Swift', 'bytes': '284'}, {'name': 'TeX', 'bytes': '1602'}, {'name': 'TypeScript', 'bytes': '41954506'}, {'name': 'Visual Basic .NET', 'bytes': '893'}]}
package cmd import ( "strings" "github.com/golang/glog" "github.com/spf13/cobra" "github.com/spf13/viper" "k8s.io/minikube/pkg/minikube/cluster" "k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/cruntime" "k8s.io/minikube/pkg/minikube/driver" "k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/machine" "k8s.io/minikube/pkg/minikube/mustload" "k8s.io/minikube/pkg/minikube/out" ) var ( namespaces []string allNamespaces bool ) // pauseCmd represents the docker-pause command var pauseCmd = &cobra.Command{ Use: "pause", Short: "pause containers", Run: runPause, } func runPause(cmd *cobra.Command, args []string) { co := mustload.Running(ClusterFlagValue()) for _, n := range co.Config.Nodes { host, err := machine.LoadHost(co.API, driver.MachineName(*co.Config, n)) if err != nil { exit.WithError("Error getting host", err) } r, err := machine.CommandRunner(host) if err != nil { exit.WithError("Failed to get command runner", err) } cr, err := cruntime.New(cruntime.Config{Type: co.Config.KubernetesConfig.ContainerRuntime, Runner: r}) if err != nil { exit.WithError("Failed runtime", err) } glog.Infof("namespaces: %v keys: %v", namespaces, viper.AllSettings()) if allNamespaces { namespaces = nil //all } else if len(namespaces) == 0 { exit.WithCodeT(exit.BadUsage, "Use -A to specify all namespaces") } ids, err := cluster.Pause(cr, r, namespaces) if err != nil { exit.WithError("Pause", err) } if namespaces == nil { out.T(out.Unpause, "Paused kubelet and {{.count}} containers", out.V{"count": len(ids)}) } else { out.T(out.Unpause, "Paused kubelet and {{.count}} containers in: {{.namespaces}}", out.V{"count": len(ids), "namespaces": strings.Join(namespaces, ", ")}) } } } func init() { pauseCmd.Flags().StringSliceVarP(&namespaces, "--namespaces", "n", constants.DefaultNamespaces, "namespaces to pause") pauseCmd.Flags().BoolVarP(&allNamespaces, "all-namespaces", "A", false, "If set, pause all namespaces") }
{'content_hash': '9661fce46cf9051825046e5b499f8c00', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 157, 'avg_line_length': 27.144736842105264, 'alnum_prop': 0.6839554047503635, 'repo_name': 'dlorenc/minikube', 'id': 'd7b090ce8383c333f931e08ade2b9d254a3f96e8', 'size': '2652', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cmd/minikube/cmd/pause.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '156'}, {'name': 'C++', 'bytes': '645'}, {'name': 'CSS', 'bytes': '4799'}, {'name': 'Dockerfile', 'bytes': '3837'}, {'name': 'Go', 'bytes': '1155042'}, {'name': 'HTML', 'bytes': '8042'}, {'name': 'JavaScript', 'bytes': '958'}, {'name': 'Makefile', 'bytes': '41883'}, {'name': 'NSIS', 'bytes': '8081'}, {'name': 'PHP', 'bytes': '1598'}, {'name': 'PowerShell', 'bytes': '7610'}, {'name': 'Python', 'bytes': '10043'}, {'name': 'Shell', 'bytes': '59519'}]}
<?php defined('PHPFOX') or exit('NO DICE!'); ?> <div class="warning"> {phrase var='user.member_snoop_text' user_name=$user_name full_name=$full_name user_link=$user_link} <br /><br /> <form action="{url link='admincp.user.snoop' user=$aUser.user_id}" method="post"> <input type="hidden" name="action" value="proceed"> <a class="button linkAway" href="{url link='admincp'}">{phrase var='user.abort_log_in_as_this_user'} </a> - <input type="submit" class="btnSubmit button" value="{phrase var='user.log'}"> </form> </div>
{'content_hash': 'bf58eab9d346890b13733fe2dfa87b29', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 107, 'avg_line_length': 40.84615384615385, 'alnum_prop': 0.664783427495292, 'repo_name': 'edbiler/BazaarCorner', 'id': 'ae712387b48fbfcd047563cac68a67adb4f9ad23', 'size': '734', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'module/user/template/default/controller/admincp/snoop.html.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1407330'}, {'name': 'JavaScript', 'bytes': '1999377'}, {'name': 'PHP', 'bytes': '23310671'}, {'name': 'Visual Basic', 'bytes': '1274'}]}
require 'spec_helper' describe "The CVE-2011-5036 vulnerability" do before(:all) do @check = Dawn::Kb::CVE_2011_5036.new # @check.debug = true end it "is reported when the vulnerable gem is detected - 1.0.1" do @check.dependencies = [{:name=>"rack", :version=>"1.0.1"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 0.9.1" do @check.dependencies = [{:name=>"rack", :version=>"0.9.1"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 0.9" do @check.dependencies = [{:name=>"rack", :version=>"0.9"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 0.4" do @check.dependencies = [{:name=>"rack", :version=>"0.4"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 0.3" do @check.dependencies = [{:name=>"rack", :version=>"0.3"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 0.2" do @check.dependencies = [{:name=>"rack", :version=>"0.2"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 0.1" do @check.dependencies = [{:name=>"rack", :version=>"0.1"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.0.0" do @check.dependencies = [{:name=>"rack", :version=>"1.0.0"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.1.0" do @check.dependencies = [{:name=>"rack", :version=>"1.1.0"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.1.2" do @check.dependencies = [{:name=>"rack", :version=>"1.1.2"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.2.0" do @check.dependencies = [{:name=>"rack", :version=>"1.2.0"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.2.1" do @check.dependencies = [{:name=>"rack", :version=>"1.2.1"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.2.2" do @check.dependencies = [{:name=>"rack", :version=>"1.2.2"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.2.3" do @check.dependencies = [{:name=>"rack", :version=>"1.2.3"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.2.4" do @check.dependencies = [{:name=>"rack", :version=>"1.2.4"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.3.0" do @check.dependencies = [{:name=>"rack", :version=>"1.3.0"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.3.1" do @check.dependencies = [{:name=>"rack", :version=>"1.3.1"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.3.2" do @check.dependencies = [{:name=>"rack", :version=>"1.3.2"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.3.3" do @check.dependencies = [{:name=>"rack", :version=>"1.3.3"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.3.4" do @check.dependencies = [{:name=>"rack", :version=>"1.3.4"}] expect(@check.vuln?).to eq(true) end it "is reported when the vulnerable gem is detected - 1.3.5" do @check.dependencies = [{:name=>"rack", :version=>"1.3.5"}] expect(@check.vuln?).to eq(true) end end
{'content_hash': '65aa14a3ef16e2d93b6a9fe62d49592c', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 65, 'avg_line_length': 40.01052631578948, 'alnum_prop': 0.6229939489607997, 'repo_name': 'jasnow/dawnscanner', 'id': 'f5c2c8f3cdb695c30f1041f5785975f153453672', 'size': '3801', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/lib/kb/cve_2011_5036_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '915'}, {'name': 'Ruby', 'bytes': '610111'}]}
echo Building GUI call pyuic4 mainwindow.ui > mainwindow.py ::echo Building resource file ::call pyrcc4 icons/tow_resources.qrc -o tow_resources_rc.py echo Done
{'content_hash': '42ec137d13d3cac1c2172467190e0c31', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 60, 'avg_line_length': 18.22222222222222, 'alnum_prop': 0.7804878048780488, 'repo_name': 'petebachant/Nortek-Python', 'id': '1e7fbca5a56a1057c44fdfbdafa5fed9d7a6313b', 'size': '164', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'examples/PyQt/buildgui.bat', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '92085'}, {'name': 'Shell', 'bytes': '164'}]}
/* http://www.cgsoso.com/forum-211-1.html CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源! CGSOSO 主打游戏开发,影视设计等CG资源素材。 插件如若商用,请务必官网购买! daily assets update for try. U should buy the asset from home store if u use it in your project! */ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Globalization; using System.IO; using System.Text; using Org.BouncyCastle.Utilities.Encoders; namespace Org.BouncyCastle.Asn1.X509 { /** * It turns out that the number of standard ways the fields in a DN should be * encoded into their ASN.1 counterparts is rapidly approaching the * number of machines on the internet. By default the X509Name class * will produce UTF8Strings in line with the current recommendations (RFC 3280). * <p> * An example of an encoder look like below: * <pre> * public class X509DirEntryConverter * : X509NameEntryConverter * { * public Asn1Object GetConvertedValue( * DerObjectIdentifier oid, * string value) * { * if (str.Length() != 0 &amp;&amp; str.charAt(0) == '#') * { * return ConvertHexEncoded(str, 1); * } * if (oid.Equals(EmailAddress)) * { * return new DerIA5String(str); * } * else if (CanBePrintable(str)) * { * return new DerPrintableString(str); * } * else if (CanBeUTF8(str)) * { * return new DerUtf8String(str); * } * else * { * return new DerBmpString(str); * } * } * } * </pre> * </p> */ public abstract class X509NameEntryConverter { /** * Convert an inline encoded hex string rendition of an ASN.1 * object back into its corresponding ASN.1 object. * * @param str the hex encoded object * @param off the index at which the encoding starts * @return the decoded object */ protected Asn1Object ConvertHexEncoded( string hexString, int offset) { string str = hexString.Substring(offset); return Asn1Object.FromByteArray(Hex.Decode(str)); } /** * return true if the passed in string can be represented without * loss as a PrintableString, false otherwise. */ protected bool CanBePrintable( string str) { return DerPrintableString.IsPrintableString(str); } /** * Convert the passed in string value into the appropriate ASN.1 * encoded object. * * @param oid the oid associated with the value in the DN. * @param value the value of the particular DN component. * @return the ASN.1 equivalent for the value. */ public abstract Asn1Object GetConvertedValue(DerObjectIdentifier oid, string value); } } #endif
{'content_hash': '4ee4300aca9669c8f5aa9a8b9dcaf899', 'timestamp': '', 'source': 'github', 'line_count': 106, 'max_line_length': 92, 'avg_line_length': 29.047169811320753, 'alnum_prop': 0.5709645988957454, 'repo_name': 'SeongBongJang/amuzlabBonRepo', 'id': '372c84deff15074ae27f16d79c1a5f15981bff25', 'size': '3173', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'NGUI_Test/NGUI_Sample/Assets/Best HTTP (Pro)/BestHTTP/SecureProtocol/asn1/x509/X509NameEntryConverter.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '10179144'}, {'name': 'CSS', 'bytes': '95737'}, {'name': 'GLSL', 'bytes': '200778'}, {'name': 'HTML', 'bytes': '39430'}, {'name': 'JavaScript', 'bytes': '366148'}, {'name': 'Objective-C', 'bytes': '768'}, {'name': 'Objective-C++', 'bytes': '6612'}, {'name': 'Python', 'bytes': '7443'}, {'name': 'Shell', 'bytes': '254'}]}
namespace Kvasir { //Real-time clock namespace RtcTr{ ///<time register using Addr = Register::Address<0x40002800,0xff808080,0x00000000,unsigned>; ///AM/PM notation constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> pm{}; ///Hour tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> ht{}; ///Hour units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> hu{}; ///Minute tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> mnt{}; ///Minute units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> mnu{}; ///Second tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> st{}; ///Second units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> su{}; } namespace RtcDr{ ///<date register using Addr = Register::Address<0x40002804,0xff0000c0,0x00000000,unsigned>; ///Year tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,20),Register::ReadWriteAccess,unsigned> yt{}; ///Year units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> yu{}; ///Week day units constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,13),Register::ReadWriteAccess,unsigned> wdu{}; ///Month tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> mt{}; ///Month units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> mu{}; ///Date tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> dt{}; ///Date units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> du{}; } namespace RtcCr{ ///<control register using Addr = Register::Address<0x40002808,0xff000080,0x00000000,unsigned>; ///Wakeup clock selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> wcksel{}; ///Time-stamp event active edge constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> tsedge{}; ///Reference clock detection enable (50 or 60 Hz) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> refckon{}; ///Bypass the shadow registers constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> bypshad{}; ///Hour format constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> fmt{}; ///Alarm A enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> alrae{}; ///Alarm B enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> alrbe{}; ///Wakeup timer enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> wute{}; ///Time stamp enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> tse{}; ///Alarm A interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> alraie{}; ///Alarm B interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> alrbie{}; ///Wakeup timer interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> wutie{}; ///Time-stamp interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> tsie{}; ///Add 1 hour (summer time change) constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> add1h{}; ///Subtract 1 hour (winter time change) constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> sub1h{}; ///Backup constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> bkp{}; ///Calibration output selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> cosel{}; ///Output polarity constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> pol{}; ///Output selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,unsigned> osel{}; ///Calibration output enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> coe{}; } namespace RtcIsr{ ///<initialization and status register using Addr = Register::Address<0x4000280c,0xfffe0000,0x00000000,unsigned>; ///Alarm A write flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> alrawf{}; ///Alarm B write flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> alrbwf{}; ///Wakeup timer write flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> wutwf{}; ///Shift operation pending constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> shpf{}; ///Initialization status flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> inits{}; ///Registers synchronization flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> rsf{}; ///Initialization flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> initf{}; ///Initialization mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> init{}; ///Alarm A flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> alraf{}; ///Alarm B flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> alrbf{}; ///Wakeup timer flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> wutf{}; ///Time-stamp flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> tsf{}; ///Time-stamp overflow flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> tsovf{}; ///Tamper detection flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> tamp1f{}; ///RTC_TAMP2 detection flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> tamp2f{}; ///RTC_TAMP3 detection flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> tamp3f{}; ///Recalibration pending Flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> recalpf{}; } namespace RtcPrer{ ///<prescaler register using Addr = Register::Address<0x40002810,0xff808000,0x00000000,unsigned>; ///Asynchronous prescaler factor constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,16),Register::ReadWriteAccess,unsigned> predivA{}; ///Synchronous prescaler factor constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,0),Register::ReadWriteAccess,unsigned> predivS{}; } namespace RtcWutr{ ///<wakeup timer register using Addr = Register::Address<0x40002814,0xffff0000,0x00000000,unsigned>; ///Wakeup auto-reload value bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> wut{}; } namespace RtcAlrmar{ ///<alarm A register using Addr = Register::Address<0x4000281c,0x00000000,0x00000000,unsigned>; ///Alarm A date mask constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> msk4{}; ///Week day selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> wdsel{}; ///Date tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,unsigned> dt{}; ///Date units or day in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> du{}; ///Alarm A hours mask constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> msk3{}; ///AM/PM notation constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> pm{}; ///Hour tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> ht{}; ///Hour units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> hu{}; ///Alarm A minutes mask constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> msk2{}; ///Minute tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> mnt{}; ///Minute units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> mnu{}; ///Alarm A seconds mask constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> msk1{}; ///Second tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> st{}; ///Second units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> su{}; } namespace RtcAlrmbr{ ///<alarm B register using Addr = Register::Address<0x40002820,0x00000000,0x00000000,unsigned>; ///Alarm B date mask constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> msk4{}; ///Week day selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> wdsel{}; ///Date tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,unsigned> dt{}; ///Date units or day in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> du{}; ///Alarm B hours mask constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> msk3{}; ///AM/PM notation constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> pm{}; ///Hour tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> ht{}; ///Hour units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> hu{}; ///Alarm B minutes mask constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> msk2{}; ///Minute tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> mnt{}; ///Minute units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> mnu{}; ///Alarm B seconds mask constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> msk1{}; ///Second tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> st{}; ///Second units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> su{}; } namespace RtcWpr{ ///<write protection register using Addr = Register::Address<0x40002824,0xffffff00,0x00000000,unsigned>; ///Write protection key constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> key{}; } namespace RtcSsr{ ///<sub second register using Addr = Register::Address<0x40002828,0xffff0000,0x00000000,unsigned>; ///Sub second value constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> ss{}; } namespace RtcShiftr{ ///<shift control register using Addr = Register::Address<0x4000282c,0x7fff8000,0x00000000,unsigned>; ///Add one second constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> add1s{}; ///Subtract a fraction of a second constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,0),Register::ReadWriteAccess,unsigned> subfs{}; } namespace RtcTstr{ ///<time stamp time register using Addr = Register::Address<0x40002830,0xff808080,0x00000000,unsigned>; ///Second units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> su{}; ///Second tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> st{}; ///Minute units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> mnu{}; ///Minute tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> mnt{}; ///Hour units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> hu{}; ///Hour tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> ht{}; ///AM/PM notation constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> pm{}; } namespace RtcTsdr{ ///<time stamp date register using Addr = Register::Address<0x40002834,0xffff00c0,0x00000000,unsigned>; ///Week day units constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,13),Register::ReadWriteAccess,unsigned> wdu{}; ///Month tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> mt{}; ///Month units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> mu{}; ///Date tens in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> dt{}; ///Date units in BCD format constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> du{}; } namespace RtcTsssr{ ///<timestamp sub second register using Addr = Register::Address<0x40002838,0xffff0000,0x00000000,unsigned>; ///Sub second value constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> ss{}; } namespace RtcCalr{ ///<calibration register using Addr = Register::Address<0x4000283c,0xffff1e00,0x00000000,unsigned>; ///Increase frequency of RTC by 488.5 ppm constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> calp{}; ///Use an 8-second calibration cycle period constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> calw8{}; ///Use a 16-second calibration cycle period constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> calw16{}; ///Calibration minus constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,0),Register::ReadWriteAccess,unsigned> calm{}; } namespace RtcTafcr{ ///<tamper and alternate function configuration register using Addr = Register::Address<0x40002840,0xff030000,0x00000000,unsigned>; ///Tamper 1 detection enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tamp1e{}; ///Active level for tamper 1 constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> tamp1trg{}; ///Tamper interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tampie{}; ///Tamper 2 detection enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> tamp2e{}; ///Active level for tamper 2 constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tamp2trg{}; ///Tamper 3 detection enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> tamp3e{}; ///Active level for tamper 3 constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tamp3trg{}; ///Activate timestamp on tamper detection event constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> tampts{}; ///Tamper sampling frequency constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,unsigned> tampfreq{}; ///Tamper filter count constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,11),Register::ReadWriteAccess,unsigned> tampflt{}; ///Tamper precharge duration constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,13),Register::ReadWriteAccess,unsigned> tampprch{}; ///TAMPER pull-up disable constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> tamppudis{}; ///PC13 value constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> pc13value{}; ///PC13 mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> pc13mode{}; ///PC14 value constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> pc14value{}; ///PC 14 mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> pc14mode{}; ///PC15 value constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> pc15value{}; ///PC15 mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> pc15mode{}; } namespace RtcAlrmassr{ ///<alarm A sub second register using Addr = Register::Address<0x40002844,0xf0ff8000,0x00000000,unsigned>; ///Mask the most-significant bits starting at this bit constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> maskss{}; ///Sub seconds value constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,0),Register::ReadWriteAccess,unsigned> ss{}; } namespace RtcAlrmbssr{ ///<alarm B sub second register using Addr = Register::Address<0x40002848,0xf0ff8000,0x00000000,unsigned>; ///Mask the most-significant bits starting at this bit constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> maskss{}; ///Sub seconds value constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,0),Register::ReadWriteAccess,unsigned> ss{}; } namespace RtcBkp0r{ ///<backup register using Addr = Register::Address<0x40002850,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp1r{ ///<backup register using Addr = Register::Address<0x40002854,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp2r{ ///<backup register using Addr = Register::Address<0x40002858,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp3r{ ///<backup register using Addr = Register::Address<0x4000285c,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp4r{ ///<backup register using Addr = Register::Address<0x40002860,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp5r{ ///<backup register using Addr = Register::Address<0x40002864,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp6r{ ///<backup register using Addr = Register::Address<0x40002868,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp7r{ ///<backup register using Addr = Register::Address<0x4000286c,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp8r{ ///<backup register using Addr = Register::Address<0x40002870,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp9r{ ///<backup register using Addr = Register::Address<0x40002874,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp10r{ ///<backup register using Addr = Register::Address<0x40002878,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp11r{ ///<backup register using Addr = Register::Address<0x4000287c,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp12r{ ///<backup register using Addr = Register::Address<0x40002880,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp13r{ ///<backup register using Addr = Register::Address<0x40002884,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp14r{ ///<backup register using Addr = Register::Address<0x40002888,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp15r{ ///<backup register using Addr = Register::Address<0x4000288c,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp16r{ ///<backup register using Addr = Register::Address<0x40002890,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp17r{ ///<backup register using Addr = Register::Address<0x40002894,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp18r{ ///<backup register using Addr = Register::Address<0x40002898,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp19r{ ///<backup register using Addr = Register::Address<0x4000289c,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp20r{ ///<backup register using Addr = Register::Address<0x400028a0,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp21r{ ///<backup register using Addr = Register::Address<0x400028a4,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp22r{ ///<backup register using Addr = Register::Address<0x400028a8,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp23r{ ///<backup register using Addr = Register::Address<0x400028ac,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp24r{ ///<backup register using Addr = Register::Address<0x400028b0,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp25r{ ///<backup register using Addr = Register::Address<0x400028b4,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp26r{ ///<backup register using Addr = Register::Address<0x400028b8,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp27r{ ///<backup register using Addr = Register::Address<0x400028bc,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp28r{ ///<backup register using Addr = Register::Address<0x400028c0,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp29r{ ///<backup register using Addr = Register::Address<0x400028c4,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp30r{ ///<backup register using Addr = Register::Address<0x400028c8,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } namespace RtcBkp31r{ ///<backup register using Addr = Register::Address<0x400028cc,0x00000000,0x00000000,unsigned>; ///BKP constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> bkp{}; } }
{'content_hash': 'cd4c9044984b82731bc1d276387d9de7', 'timestamp': '', 'source': 'github', 'line_count': 467, 'max_line_length': 222, 'avg_line_length': 68.29122055674519, 'alnum_prop': 0.7043145616455537, 'repo_name': 'kvasir-io/Kvasir', 'id': '79e46adfa9747dda71002bd97ff95725e87f1ec9', 'size': '31938', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'Lib/Chip/Unknown/STMicro/STM32F303xE/RTC.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '16510'}, {'name': 'C++', 'bytes': '763432371'}, {'name': 'CMake', 'bytes': '1504'}, {'name': 'Python', 'bytes': '13502'}]}
package com.simpligility.maven.plugins.android.phase01generatesources; import com.simpligility.maven.plugins.android.AbstractAndroidMojo; import com.simpligility.maven.plugins.android.phase01generatesources.GenerateSourcesMojo; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import java.io.File; import java.lang.reflect.Method; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Covers method {@link GenerateSourcesMojo#getPackageCompareMap(Set)} with tests * * @author Oleg Green <[email protected]> */ @RunWith( PowerMockRunner.class ) @PrepareForTest( GenerateSourcesMojo.class ) public class GetPackageCompareMapTest { public static final String PROJECT_ARTIFACT_ID = "main_application"; public static final String PROJECT_PACKAGE_NAME = "com.jayway.maven.application"; public static final String COM_JAYWAY_MAVEN_LIBRARY_PACKAGE = "com.jayway.maven.library"; public static final String COM_JAYWAY_MAVEN_LIBRARY2_PACKAGE = "com.jayway.maven.library2"; public static final String COM_JAYWAY_MAVEN_LIBRARY3_PACKAGE = "com.jayway.maven.library3"; public static final Artifact LIBRARY1_ARTIFACT = createArtifact("library1"); public static final Artifact LIBRARY2_ARTIFACT = createArtifact("library2"); public static final Artifact LIBRARY3_ARTIFACT = createArtifact("library3"); public static final Map<Artifact, String > TEST_DATA_1 = new HashMap<Artifact, String>() { { put( LIBRARY1_ARTIFACT, COM_JAYWAY_MAVEN_LIBRARY_PACKAGE ); put( LIBRARY2_ARTIFACT, PROJECT_PACKAGE_NAME ); put( LIBRARY3_ARTIFACT, COM_JAYWAY_MAVEN_LIBRARY_PACKAGE ); } }; public static final Map<Artifact, String > TEST_DATA_2 = new HashMap<Artifact, String>() { { put( LIBRARY1_ARTIFACT, COM_JAYWAY_MAVEN_LIBRARY_PACKAGE ); put( LIBRARY2_ARTIFACT, COM_JAYWAY_MAVEN_LIBRARY2_PACKAGE ); put( LIBRARY3_ARTIFACT, COM_JAYWAY_MAVEN_LIBRARY3_PACKAGE ); } }; private MavenProject project; private Artifact projectArtifact; private GenerateSourcesMojo mojo; @Before public void setUp() throws Exception { mojo = PowerMock.createPartialMock( GenerateSourcesMojo.class, "extractPackageNameFromAndroidManifest", "extractPackageNameFromAndroidArtifact" ); setUpMainProject(); Whitebox.setInternalState(mojo, "project", project); Method extractPackageNameFromAndroidManifestMethod = Whitebox.getMethod( AbstractAndroidMojo.class, "extractPackageNameFromAndroidManifest", File.class ); PowerMock.expectPrivate( mojo, extractPackageNameFromAndroidManifestMethod, EasyMock.anyObject( File.class ) ).andReturn(PROJECT_PACKAGE_NAME).once(); } @Test(expected = IllegalArgumentException.class) public void testNoDependencies() throws MojoExecutionException { PowerMock.replay( mojo ); mojo.getPackageCompareMap(null); } @Test public void testEmptyDependencies() throws MojoExecutionException { PowerMock.replay( mojo ); Map<String, Set<Artifact>> map = mojo.getPackageCompareMap( new HashSet<Artifact>() ); assertNotNull( map ); assertEquals( 1, map.size() ); assertTrue( map.containsKey( PROJECT_PACKAGE_NAME ) ); Set<Artifact> artifactSet = map.get( PROJECT_PACKAGE_NAME ); assertEquals( 1, artifactSet.size() ); assertTrue( artifactSet.contains( projectArtifact ) ); } @Test public void testData1() throws Exception { mockExtractPackageNameFromArtifactMethod( TEST_DATA_1 ); PowerMock.replay( mojo ); Map<String, Set<Artifact>> map = mojo.getPackageCompareMap( TEST_DATA_1.keySet() ); assertNotNull( map ); assertEquals( 2, map.size() ); assertTrue( map.containsKey( PROJECT_PACKAGE_NAME ) ); assertTrue( map.containsKey( COM_JAYWAY_MAVEN_LIBRARY_PACKAGE ) ); Set<Artifact> artifactSet1 = map.get( PROJECT_PACKAGE_NAME ); assertEquals( 2, artifactSet1.size() ); assertTrue( artifactSet1.contains( LIBRARY2_ARTIFACT ) ); assertTrue( artifactSet1.contains( projectArtifact ) ); Set<Artifact> artifactSet2 = map.get( COM_JAYWAY_MAVEN_LIBRARY_PACKAGE ); assertEquals( 2, artifactSet2.size() ); assertTrue( artifactSet2.contains( LIBRARY1_ARTIFACT ) ); assertTrue( artifactSet2.contains( LIBRARY3_ARTIFACT ) ); PowerMock.verify( mojo ); EasyMock.verify( project, projectArtifact ); } @Test public void testData2() throws Exception { mockExtractPackageNameFromArtifactMethod( TEST_DATA_2 ); PowerMock.replay( mojo ); Map<String, Set<Artifact>> map = mojo.getPackageCompareMap( TEST_DATA_2.keySet() ); assertNotNull( map ); assertEquals( 4, map.size() ); assertTrue( map.containsKey( PROJECT_PACKAGE_NAME ) ); Set<Artifact> artifactSet1 = map.get( PROJECT_PACKAGE_NAME ); assertEquals( 1, artifactSet1.size() ); assertTrue( artifactSet1.contains( projectArtifact ) ); Set<Artifact> artifactSet2 = map.get( COM_JAYWAY_MAVEN_LIBRARY_PACKAGE ); assertEquals( 1, artifactSet2.size() ); assertTrue( artifactSet2.contains( LIBRARY1_ARTIFACT ) ); Set<Artifact> artifactSet3 = map.get( COM_JAYWAY_MAVEN_LIBRARY2_PACKAGE ); assertEquals( 1, artifactSet3.size() ); assertTrue( artifactSet3.contains( LIBRARY2_ARTIFACT ) ); Set<Artifact> artifactSet4 = map.get( COM_JAYWAY_MAVEN_LIBRARY3_PACKAGE ); assertEquals( 1, artifactSet4.size() ); assertTrue( artifactSet4.contains( LIBRARY3_ARTIFACT ) ); PowerMock.verify( mojo ); EasyMock.verify( project, projectArtifact ); } private void setUpMainProject() { projectArtifact = EasyMock.createMock( Artifact.class ); EasyMock.expect( projectArtifact.getArtifactId() ).andReturn( PROJECT_ARTIFACT_ID ).anyTimes(); EasyMock.replay( projectArtifact ); project = EasyMock.createNiceMock( MavenProject.class ); EasyMock.expect( project.getArtifact() ).andReturn( projectArtifact ); EasyMock.replay( project ); } private void mockExtractPackageNameFromArtifactMethod( final Map<Artifact, String> testData ) throws Exception { Method extractPackageNameFromAndroidArtifact = Whitebox.getMethod( AbstractAndroidMojo.class, "extractPackageNameFromAndroidArtifact", Artifact.class ); PowerMock.expectPrivate( mojo, extractPackageNameFromAndroidArtifact, EasyMock.anyObject( Artifact.class ) ).andAnswer(new IAnswer<String>() { @Override public String answer() throws Throwable { final Object[] args = EasyMock.getCurrentArguments(); final Artifact inputArtifact = (Artifact)args[0]; return testData.get(inputArtifact); } }).anyTimes(); } private static Artifact createArtifact( String artifactId ) { Artifact artifactMock = EasyMock.createMock( Artifact.class ); EasyMock.expect( artifactMock.getArtifactId() ).andReturn( artifactId ).anyTimes(); EasyMock.replay( artifactMock ); return artifactMock; } }
{'content_hash': '2caed4c04222a5fba3517a30e1db629c', 'timestamp': '', 'source': 'github', 'line_count': 211, 'max_line_length': 115, 'avg_line_length': 38.81990521327014, 'alnum_prop': 0.6817238432425833, 'repo_name': 'WonderCsabo/maven-android-plugin', 'id': '160ef32da6b97d6ce53caaa5d954128f51534f55', 'size': '8191', 'binary': False, 'copies': '17', 'ref': 'refs/heads/master', 'path': 'src/test/java/com/simpligility/maven/plugins/android/phase01generatesources/GetPackageCompareMapTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '8046'}, {'name': 'Java', 'bytes': '3068765'}, {'name': 'Makefile', 'bytes': '5665'}, {'name': 'Scala', 'bytes': '277'}]}
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit) // Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus // Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues // License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE // More projects: http://www.zzzprojects.com/ // Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved. using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Z.EntityFramework.Plus; namespace Z.Test.EntityFramework.Plus { public partial class QueryIncludeOptimized_AllowIncludeSubPath_Null_Executor { [TestMethod] public void Single_Many_Single_Many_Null() { try { QueryIncludeOptimizedManager.AllowIncludeSubPath = true; QueryIncludeOptimizedHelper.InsertOneToOneAndMany(single1: true, many2: true, single3: true, many4: false); using (var ctx = new TestContext()) { var left = ctx.Association_OneToSingleAndMany_Lefts .IncludeOptimized(x => x.Single_Right.Many_RightRight.Select(y => y.Single_RightRightRight.Many_RightRightRightRight)) .First(); var list1 = new List<Association_OneToSingleAndMany_Right>(); var list2 = new List<Association_OneToSingleAndMany_RightRight>(); var list3 = new List<Association_OneToSingleAndMany_RightRightRight>(); // Level 1 { Assert.IsNotNull(left.Single_Right); Assert.IsNull(left.Many_Right); list1.Add(left.Single_Right); } // Level 2 { foreach (var item in list1) { Assert.IsNull(item.Single_RightRight); Assert.AreEqual(1, item.Many_RightRight.Count); list2.AddRange(item.Many_RightRight); } } // Level 3 { foreach (var item in list2) { Assert.IsNotNull(item.Single_RightRightRight); Assert.IsNull(item.Many_RightRightRight); list3.Add(item.Single_RightRightRight); } } // Level 4 { foreach (var item in list3) { Assert.IsNull(item.Single_RightRightRightRight); Assert.AreEqual(0, item.Many_RightRightRightRight.Count); } } } } finally { QueryIncludeOptimizedManager.AllowIncludeSubPath = false; } } } }
{'content_hash': '4748dfe25f902a43846fc0708d98b3f0', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 191, 'avg_line_length': 40.111111111111114, 'alnum_prop': 0.5183133271775932, 'repo_name': 'zzzprojects/EntityFramework-Plus', 'id': 'cf06f32b20b8f0999c907ed50d671de01b66b5e9', 'size': '3252', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/test/Z.Test.EntityFramework.Plus.EF6/QueryIncludeOptimized/AllowIncludeSubPath/Null_Executor/Single_Many_Single_Many_Null.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '7438029'}]}
package org.apache.camel.component.cxf.jaxrs; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.CookieStore; import java.net.HttpCookie; import java.net.URLDecoder; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.Entity; import javax.ws.rs.client.InvocationCallback; import javax.ws.rs.client.ResponseProcessingException; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import org.apache.camel.AsyncCallback; import org.apache.camel.AsyncProcessor; import org.apache.camel.CamelExchangeException; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.component.cxf.CxfEndpointUtils; import org.apache.camel.component.cxf.CxfOperationException; import org.apache.camel.component.cxf.common.message.CxfConstants; import org.apache.camel.http.common.cookie.CookieHandler; import org.apache.camel.impl.DefaultProducer; import org.apache.camel.util.IOHelper; import org.apache.camel.util.LRUSoftCache; import org.apache.camel.util.ObjectHelper; import org.apache.cxf.Bus; import org.apache.cxf.jaxrs.JAXRSServiceFactoryBean; import org.apache.cxf.jaxrs.client.Client; import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean; import org.apache.cxf.jaxrs.client.WebClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * CxfRsProducer binds a Camel exchange to a CXF exchange, acts as a CXF * JAXRS client, it will turn the normal Object invocation to a RESTful request * according to resource annotation. Any response will be bound to Camel exchange. */ public class CxfRsProducer extends DefaultProducer implements AsyncProcessor { private static final Logger LOG = LoggerFactory.getLogger(CxfRsProducer.class); private boolean throwException; // using a cache of factory beans instead of setting the address of a single cfb // to avoid concurrent issues private ClientFactoryBeanCache clientFactoryBeanCache; public CxfRsProducer(CxfRsEndpoint endpoint) { super(endpoint); this.throwException = endpoint.isThrowExceptionOnFailure(); clientFactoryBeanCache = new ClientFactoryBeanCache(endpoint.getMaxClientCacheSize()); } protected void doStart() throws Exception { clientFactoryBeanCache.start(); super.doStart(); } protected void doStop() throws Exception { super.doStop(); clientFactoryBeanCache.stop(); } public void process(Exchange exchange) throws Exception { Message inMessage = exchange.getIn(); Boolean httpClientAPI = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.class); // set the value with endpoint's option if (httpClientAPI == null) { httpClientAPI = ((CxfRsEndpoint) getEndpoint()).isHttpClientAPI(); } if (httpClientAPI.booleanValue()) { invokeHttpClient(exchange); } else { invokeProxyClient(exchange); } } public boolean process(Exchange exchange, AsyncCallback callback) { try { Message inMessage = exchange.getIn(); Boolean httpClientAPI = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.class); // set the value with endpoint's option if (httpClientAPI == null) { httpClientAPI = ((CxfRsEndpoint) getEndpoint()).isHttpClientAPI(); } if (httpClientAPI.booleanValue()) { invokeAsyncHttpClient(exchange, callback); } else { invokeAsyncProxyClient(exchange, callback); } return false; } catch (Exception exception) { LOG.error("Error invoking request", exception); exchange.setException(exception); callback.done(true); return true; } } protected void invokeAsyncHttpClient(Exchange exchange, final AsyncCallback callback) throws Exception { Message inMessage = exchange.getIn(); JAXRSClientFactoryBean cfb = clientFactoryBeanCache.get(CxfEndpointUtils .getEffectiveAddress(exchange, ((CxfRsEndpoint) getEndpoint()).getAddress())); Bus bus = ((CxfRsEndpoint) getEndpoint()).getBus(); // We need to apply the bus setting from the CxfRsEndpoint which is not use the default bus if (bus != null) { cfb.setBus(bus); } WebClient client = cfb.createWebClient(); ((CxfRsEndpoint) getEndpoint()).getChainedCxfRsEndpointConfigurer().configureClient(client); String httpMethod = inMessage.getHeader(Exchange.HTTP_METHOD, String.class); Class<?> responseClass = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Class.class); Type genericType = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_GENERIC_TYPE, Type.class); Object[] pathValues = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_VAR_VALUES, Object[].class); String path = inMessage.getHeader(Exchange.HTTP_PATH, String.class); if (LOG.isTraceEnabled()) { LOG.trace("HTTP method = {}", httpMethod); LOG.trace("path = {}", path); LOG.trace("responseClass = {}", responseClass); } // set the path if (path != null) { if (ObjectHelper.isNotEmpty(pathValues) && pathValues.length > 0) { client.path(path, pathValues); } else { client.path(path); } } CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint(); CxfRsBinding binding = cxfRsEndpoint.getBinding(); Object body = getBody(exchange, inMessage, httpMethod, cxfRsEndpoint, binding); setupClientMatrix(client, exchange); setupClientQueryAndHeaders(client, exchange); //Build message entity Entity<Object> entity = binding.bindCamelMessageToRequestEntity(body, inMessage, exchange); // handle cookies CookieHandler cookieHandler = ((CxfRsEndpoint)getEndpoint()).getCookieHandler(); loadCookies(exchange, client, cookieHandler); // invoke the client client.async().method(httpMethod, entity, new CxfInvocationCallback(client, exchange, cxfRsEndpoint, responseClass, callback, genericType)); } protected void invokeAsyncProxyClient(Exchange exchange, final AsyncCallback callback) throws Exception { Message inMessage = exchange.getIn(); Object[] varValues = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_VAR_VALUES, Object[].class); String methodName = inMessage.getHeader(CxfConstants.OPERATION_NAME, String.class); Client target; JAXRSClientFactoryBean cfb = clientFactoryBeanCache.get(CxfEndpointUtils .getEffectiveAddress(exchange, ((CxfRsEndpoint)getEndpoint()).getAddress())); Bus bus = ((CxfRsEndpoint)getEndpoint()).getBus(); // We need to apply the bus setting from the CxfRsEndpoint which is not use the default bus if (bus != null) { cfb.setBus(bus); } if (varValues == null) { target = cfb.create(); } else { target = cfb.createWithValues(varValues); } setupClientHeaders(target, exchange); // find out the method which we want to invoke JAXRSServiceFactoryBean sfb = cfb.getServiceFactory(); sfb.getResourceClasses(); // check the null body first Object[] parameters = null; if (inMessage.getBody() != null) { parameters = inMessage.getBody(Object[].class); } // get the method Method method = findRightMethod(sfb.getResourceClasses(), methodName, getParameterTypes(parameters)); CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint(); final CxfProxyInvocationCallback invocationCallback = new CxfProxyInvocationCallback(target, exchange, cxfRsEndpoint, callback); WebClient.getConfig(target).getRequestContext().put(InvocationCallback.class.getName(), invocationCallback); // handle cookies CookieHandler cookieHandler = ((CxfRsEndpoint)getEndpoint()).getCookieHandler(); loadCookies(exchange, target, cookieHandler); method.invoke(target, parameters); } @SuppressWarnings("unchecked") protected void setupClientQueryAndHeaders(WebClient client, Exchange exchange) throws Exception { Message inMessage = exchange.getIn(); CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint(); // check if there is a query map in the message header Map<String, String> maps = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_QUERY_MAP, Map.class); if (maps == null) { // Get the map from HTTP_QUERY header String queryString = inMessage.getHeader(Exchange.HTTP_QUERY, String.class); if (queryString != null) { maps = getQueryParametersFromQueryString(queryString, IOHelper.getCharsetName(exchange)); } } if (maps == null) { maps = cxfRsEndpoint.getParameters(); } if (maps != null) { for (Map.Entry<String, String> entry : maps.entrySet()) { client.query(entry.getKey(), entry.getValue()); } } setupClientHeaders(client, exchange); } protected void setupClientMatrix(WebClient client, Exchange exchange) throws Exception { org.apache.cxf.message.Message cxfMessage = (org.apache.cxf.message.Message) exchange.getIn().getHeader("CamelCxfMessage"); if (cxfMessage != null) { String requestURL = (String)cxfMessage.get("org.apache.cxf.request.uri"); String matrixParam = null; int matrixStart = requestURL.indexOf(";"); int matrixEnd = requestURL.indexOf("?") > -1 ? requestURL.indexOf("?") : requestURL.length(); Map<String, String> maps = null; if (requestURL != null && matrixStart > 0) { matrixParam = requestURL.substring(matrixStart + 1, matrixEnd); if (matrixParam != null) { maps = getMatrixParametersFromMatrixString(matrixParam, IOHelper.getCharsetName(exchange)); } } if (maps != null) { for (Map.Entry<String, String> entry : maps.entrySet()) { client.matrix(entry.getKey(), entry.getValue()); LOG.debug("Matrix param " + entry.getKey() + " :: " + entry.getValue()); } } } } protected void setupClientHeaders(Client client, Exchange exchange) throws Exception { Message inMessage = exchange.getIn(); CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint(); CxfRsBinding binding = cxfRsEndpoint.getBinding(); // set headers client.headers(binding.bindCamelHeadersToRequestHeaders(inMessage.getHeaders(), exchange)); } protected void invokeHttpClient(Exchange exchange) throws Exception { Message inMessage = exchange.getIn(); JAXRSClientFactoryBean cfb = clientFactoryBeanCache.get(CxfEndpointUtils .getEffectiveAddress(exchange, ((CxfRsEndpoint)getEndpoint()).getAddress())); Bus bus = ((CxfRsEndpoint)getEndpoint()).getBus(); // We need to apply the bus setting from the CxfRsEndpoint which is not use the default bus if (bus != null) { cfb.setBus(bus); } WebClient client = cfb.createWebClient(); ((CxfRsEndpoint) getEndpoint()).getChainedCxfRsEndpointConfigurer().configureClient(client); String httpMethod = inMessage.getHeader(Exchange.HTTP_METHOD, String.class); Class<?> responseClass = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Class.class); Type genericType = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_GENERIC_TYPE, Type.class); Object[] pathValues = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_VAR_VALUES, Object[].class); String path = inMessage.getHeader(Exchange.HTTP_PATH, String.class); if (LOG.isTraceEnabled()) { LOG.trace("HTTP method = {}", httpMethod); LOG.trace("path = {}", path); LOG.trace("responseClass = {}", responseClass); } // set the path if (path != null) { if (ObjectHelper.isNotEmpty(pathValues) && pathValues.length > 0) { client.path(path, pathValues); } else { client.path(path); } } CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint(); CxfRsBinding binding = cxfRsEndpoint.getBinding(); Object body = getBody(exchange, inMessage, httpMethod, cxfRsEndpoint, binding); setupClientMatrix(client, exchange); setupClientQueryAndHeaders(client, exchange); // handle cookies CookieHandler cookieHandler = ((CxfRsEndpoint)getEndpoint()).getCookieHandler(); loadCookies(exchange, client, cookieHandler); // invoke the client Object response = null; if (responseClass == null || Response.class.equals(responseClass)) { response = client.invoke(httpMethod, body); } else { if (Collection.class.isAssignableFrom(responseClass)) { if (genericType instanceof ParameterizedType) { // Get the collection member type first Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments(); response = client.invokeAndGetCollection(httpMethod, body, (Class<?>) actualTypeArguments[0]); } else { throw new CamelExchangeException("Header " + CxfConstants.CAMEL_CXF_RS_RESPONSE_GENERIC_TYPE + " not found in message", exchange); } } else { response = client.invoke(httpMethod, body, responseClass); } } int statesCode = client.getResponse().getStatus(); // handle cookies saveCookies(exchange, client, cookieHandler); //Throw exception on a response > 207 //http://en.wikipedia.org/wiki/List_of_HTTP_status_codes if (throwException) { if (response instanceof Response) { Integer respCode = ((Response) response).getStatus(); if (respCode > 207) { throw populateCxfRsProducerException(exchange, (Response) response, respCode); } } } // set response if (exchange.getPattern().isOutCapable()) { LOG.trace("Response body = {}", response); exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders()); exchange.getOut().setBody(binding.bindResponseToCamelBody(response, exchange)); exchange.getOut().getHeaders().putAll(binding.bindResponseHeadersToCamelHeaders(response, exchange)); exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, statesCode); } else { // just close the input stream of the response object if (response instanceof Response) { ((Response)response).close(); } } } private void saveCookies(Exchange exchange, Client client, CookieHandler cookieHandler) { if (cookieHandler != null) { CookieStore cookieStore = cookieHandler.getCookieStore(exchange); for (NewCookie newCookie: client.getResponse().getCookies().values()) { HttpCookie cookie = new HttpCookie(newCookie.getName(), newCookie.getValue()); cookie.setComment(newCookie.getComment()); cookie.setDomain(newCookie.getDomain()); cookie.setHttpOnly(newCookie.isHttpOnly()); cookie.setMaxAge(newCookie.getMaxAge()); cookie.setPath(newCookie.getPath()); cookie.setSecure(newCookie.isSecure()); cookie.setVersion(newCookie.getVersion()); cookieStore.add(client.getCurrentURI(), cookie); } } } private void loadCookies(Exchange exchange, Client client, CookieHandler cookieHandler) throws IOException { if (cookieHandler != null) { for (Map.Entry<String, List<String>> cookie : cookieHandler.loadCookies(exchange, client.getCurrentURI()).entrySet()) { if (cookie.getValue().size() > 0) { client.header(cookie.getKey(), cookie.getValue()); } } } } protected void invokeProxyClient(Exchange exchange) throws Exception { Message inMessage = exchange.getIn(); Object[] varValues = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_VAR_VALUES, Object[].class); String methodName = inMessage.getHeader(CxfConstants.OPERATION_NAME, String.class); Client target = null; JAXRSClientFactoryBean cfb = clientFactoryBeanCache.get(CxfEndpointUtils .getEffectiveAddress(exchange, ((CxfRsEndpoint)getEndpoint()).getAddress())); Bus bus = ((CxfRsEndpoint)getEndpoint()).getBus(); // We need to apply the bus setting from the CxfRsEndpoint which is not use the default bus if (bus != null) { cfb.setBus(bus); } if (varValues == null) { target = cfb.create(); } else { target = cfb.createWithValues(varValues); } setupClientHeaders(target, exchange); // find out the method which we want to invoke JAXRSServiceFactoryBean sfb = cfb.getServiceFactory(); sfb.getResourceClasses(); // check the null body first Object[] parameters = null; if (inMessage.getBody() != null) { parameters = inMessage.getBody(Object[].class); } // get the method Method method = findRightMethod(sfb.getResourceClasses(), methodName, getParameterTypes(parameters)); // handle cookies CookieHandler cookieHandler = ((CxfRsEndpoint)getEndpoint()).getCookieHandler(); loadCookies(exchange, target, cookieHandler); // Will send out the message to // Need to deal with the sub resource class Object response = method.invoke(target, parameters); int statesCode = target.getResponse().getStatus(); // handle cookies saveCookies(exchange, target, cookieHandler); if (throwException) { if (response instanceof Response) { Integer respCode = ((Response) response).getStatus(); if (respCode > 207) { throw populateCxfRsProducerException(exchange, (Response) response, respCode); } } } CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint(); CxfRsBinding binding = cxfRsEndpoint.getBinding(); if (exchange.getPattern().isOutCapable()) { LOG.trace("Response body = {}", response); exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders()); exchange.getOut().setBody(binding.bindResponseToCamelBody(response, exchange)); exchange.getOut().getHeaders().putAll(binding.bindResponseHeadersToCamelHeaders(response, exchange)); exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, statesCode); } else { // just close the input stream of the response object if (response instanceof Response) { ((Response)response).close(); } } } protected ClientFactoryBeanCache getClientFactoryBeanCache() { return clientFactoryBeanCache; } private Map<String, String> getQueryParametersFromQueryString(String queryString, String charset) throws UnsupportedEncodingException { Map<String, String> answer = new LinkedHashMap<String, String>(); for (String param : queryString.split("&")) { String[] pair = param.split("=", 2); if (pair.length == 2) { String name = URLDecoder.decode(pair[0], charset); String value = URLDecoder.decode(pair[1], charset); answer.put(name, value); } else { throw new IllegalArgumentException("Invalid parameter, expected to be a pair but was " + param); } } return answer; } private Method findRightMethod(List<Class<?>> resourceClasses, String methodName, Class<?>[] parameterTypes) throws NoSuchMethodException { for (Class<?> clazz : resourceClasses) { try { Method[] m = clazz.getMethods(); iterate_on_methods: for (Method method : m) { if (!method.getName().equals(methodName)) { continue; } Class<?>[] params = method.getParameterTypes(); if (params.length != parameterTypes.length) { continue; } for (int i = 0; i < parameterTypes.length; i++) { if (!params[i].isAssignableFrom(parameterTypes[i])) { continue iterate_on_methods; } } return method; } } catch (SecurityException ex) { // keep looking } } throw new NoSuchMethodException("Cannot find method with name: " + methodName + " having parameters assignable from: " + arrayToString(parameterTypes)); } private Class<?>[] getParameterTypes(Object[] objects) { // We need to handle the void parameter situation. if (objects == null) { return new Class[]{}; } Class<?>[] answer = new Class[objects.length]; int i = 0; for (Object obj : objects) { answer[i] = obj.getClass(); i++; } return answer; } private Map<String, String> getMatrixParametersFromMatrixString(String matrixString, String charset) throws UnsupportedEncodingException { Map<String, String> answer = new LinkedHashMap<String, String>(); for (String param : matrixString.split(";")) { String[] pair = param.split("=", 2); if (pair.length == 2) { String name = URLDecoder.decode(pair[0], charset); String value = URLDecoder.decode(pair[1], charset); answer.put(name, value); } else { throw new IllegalArgumentException("Invalid parameter, expected to be a pair but was " + param); } } return answer; } private String arrayToString(Object[] array) { StringBuilder buffer = new StringBuilder("["); for (Object obj : array) { if (buffer.length() > 2) { buffer.append(","); } buffer.append(obj.toString()); } buffer.append("]"); return buffer.toString(); } protected CxfOperationException populateCxfRsProducerException(Exchange exchange, Response response, int responseCode) { CxfOperationException exception; String uri = exchange.getFromEndpoint().getEndpointUri(); String statusText = statusTextFromResponseCode(responseCode); Map<String, String> headers = parseResponseHeaders(response, exchange); //Get the response detail string String copy = exchange.getContext().getTypeConverter().convertTo(String.class, response.getEntity()); if (responseCode >= 300 && responseCode < 400) { String redirectLocation; if (response.getMetadata().getFirst("Location") != null) { redirectLocation = response.getMetadata().getFirst("location").toString(); exception = new CxfOperationException(uri, responseCode, statusText, redirectLocation, headers, copy); } else { //no redirect location exception = new CxfOperationException(uri, responseCode, statusText, null, headers, copy); } } else { //internal server error(error code 500) exception = new CxfOperationException(uri, responseCode, statusText, null, headers, copy); } return exception; } /** * Convert the given HTTP response code to its corresponding status text or * response category. This is useful to avoid creating NPEs if this producer * is presented with an HTTP response code that the JAX-RS API doesn't know. * * @param responseCode the HTTP response code to be converted to status text * @return the status text for the code, or, if JAX-RS doesn't know the code, * the status category as text */ String statusTextFromResponseCode(int responseCode) { Response.Status status = Response.Status.fromStatusCode(responseCode); return status != null ? status.toString() : responseCategoryFromCode(responseCode); } /** * Return the category of the given HTTP response code, as text. Invalid * codes will result in appropriate text; this method never returns null. * * @param responseCode HTTP response code whose category is to be returned * @return the category of the give response code; never {@code null}. */ private String responseCategoryFromCode(int responseCode) { return Response.Status.Family.familyOf(responseCode).name(); } protected Map<String, String> parseResponseHeaders(Object response, Exchange camelExchange) { Map<String, String> answer = new HashMap<String, String>(); if (response instanceof Response) { for (Map.Entry<String, List<Object>> entry : ((Response) response).getMetadata().entrySet()) { LOG.trace("Parse external header {}={}", entry.getKey(), entry.getValue()); answer.put(entry.getKey(), entry.getValue().get(0).toString()); } } return answer; } private Object getBody(Exchange exchange, Message inMessage, String httpMethod, CxfRsEndpoint cxfRsEndpoint, CxfRsBinding binding) throws Exception { Object body = null; if (!"GET".equals(httpMethod)) { // need to check the request object if the http Method is not GET if ("DELETE".equals(httpMethod) && cxfRsEndpoint.isIgnoreDeleteMethodMessageBody()) { // just ignore the message body if the ignoreDeleteMethodMessageBody is true } else { body = binding.bindCamelMessageBodyToRequestBody(inMessage, exchange); if (LOG.isTraceEnabled()) { LOG.trace("Request body = " + body); } } } return body; } private final class CxfInvocationCallback implements InvocationCallback<Response> { private final Exchange exchange; private final CxfRsEndpoint cxfRsEndpoint; private final Class<?> responseClass; private final AsyncCallback callback; private final Type genericType; private final Client client; private CxfInvocationCallback(Client client, Exchange exchange, CxfRsEndpoint cxfRsEndpoint, Class<?> responseClass, AsyncCallback callback, Type genericType) { this.exchange = exchange; this.cxfRsEndpoint = cxfRsEndpoint; this.responseClass = responseClass; this.callback = callback; this.genericType = genericType; this.client = client; } @Override public void completed(Response response) { try { if (shouldHandleError(response)) { handleError(response); return; } // handle cookies saveCookies(exchange, client, cxfRsEndpoint.getCookieHandler()); if (!exchange.getPattern().isOutCapable()) { return; } LOG.trace("Response body = {}", response); exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders()); final CxfRsBinding binding = cxfRsEndpoint.getBinding(); exchange.getOut().getHeaders().putAll(binding.bindResponseHeadersToCamelHeaders(response, exchange)); if (genericType != null && !genericType.equals(Void.TYPE)) { GenericType genericType = new GenericType(this.genericType); exchange.getOut().setBody(binding.bindResponseToCamelBody(response.readEntity(genericType), exchange)); } else if (responseClass != null && !responseClass.equals(Void.TYPE)) { exchange.getOut().setBody(binding.bindResponseToCamelBody(response.readEntity(responseClass), exchange)); } else { exchange.getOut().setBody(binding.bindResponseToCamelBody(response, exchange)); } exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, response.getStatus()); } catch (Exception exception) { LOG.error("Error while processing response", exception); fail(exception); } finally { callback.done(false); } } @Override public void failed(Throwable throwable) { LOG.error("Failed request ", throwable); try { // handle cookies saveCookies(exchange, client, cxfRsEndpoint.getCookieHandler()); fail(throwable); } catch (Exception error) { LOG.error("Error while processing failed request", error); } finally { callback.done(false); } } private void fail(Throwable throwable) { if (throwable.getClass().isInstance(WebApplicationException.class)) { final WebApplicationException cast = WebApplicationException.class.cast(throwable); final Response response = cast.getResponse(); if (shouldHandleError(response)) { handleError(response); } } else if (throwable.getClass().isInstance(ResponseProcessingException.class)) { final ResponseProcessingException cast = ResponseProcessingException.class.cast(throwable); final Response response = cast.getResponse(); if (shouldHandleError(response)) { handleError(response); } } else { exchange.setException(throwable); } } private boolean shouldHandleError(Response response) { //Throw exception on a response > 207 //http://en.wikipedia.org/wiki/List_of_HTTP_status_codes if (response != null && throwException) { Integer respCode = response.getStatus(); if (respCode > 207) { return true; } } return false; } private void handleError(Response response) { exchange.setException(populateCxfRsProducerException(exchange, response, response.getStatus())); } } private final class CxfProxyInvocationCallback implements InvocationCallback<Object> { private final Exchange exchange; private final CxfRsEndpoint cxfRsEndpoint; private final AsyncCallback callback; private final Client client; private CxfProxyInvocationCallback(Client client, Exchange exchange, CxfRsEndpoint cxfRsEndpoint, AsyncCallback callback) { this.exchange = exchange; this.cxfRsEndpoint = cxfRsEndpoint; this.callback = callback; this.client = client; } @Override public void completed(Object body) { try { Response response = client.getResponse(); // handle cookies saveCookies(exchange, client, cxfRsEndpoint.getCookieHandler()); //handle error if (shouldHandleError(response)) { handleError(response); return; } if (!exchange.getPattern().isOutCapable()) { return; } LOG.trace("Response body = {}", response); exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders()); final CxfRsBinding binding = cxfRsEndpoint.getBinding(); exchange.getOut().getHeaders().putAll(binding.bindResponseHeadersToCamelHeaders(response, exchange)); exchange.getOut().setBody(binding.bindResponseToCamelBody(body, exchange)); exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, response.getStatus()); } catch (Exception exception) { LOG.error("Error while processing response", exception); fail(exception); } finally { callback.done(false); } } @Override public void failed(Throwable throwable) { LOG.error("Failed request ", throwable); try { // handle cookies saveCookies(exchange, client, cxfRsEndpoint.getCookieHandler()); fail(throwable); } catch (Exception error) { LOG.error("Error while processing failed request", error); } finally { callback.done(false); } } private void fail(Throwable throwable) { if (throwable.getClass().isInstance(WebApplicationException.class)) { final WebApplicationException cast = WebApplicationException.class.cast(throwable); final Response response = cast.getResponse(); if (shouldHandleError(response)) { handleError(response); } } else if (throwable.getClass().isInstance(ResponseProcessingException.class)) { final ResponseProcessingException cast = ResponseProcessingException.class.cast(throwable); final Response response = cast.getResponse(); if (shouldHandleError(response)) { handleError(response); } } else { exchange.setException(throwable); } } private void handleError(Response response) { exchange.setException(populateCxfRsProducerException(exchange, response, response.getStatus())); } private boolean shouldHandleError(Response response) { //Throw exception on a response > 207 //http://en.wikipedia.org/wiki/List_of_HTTP_status_codes if (response != null && throwException) { Integer respCode = response.getStatus(); if (respCode > 207) { return true; } } return false; } } /** * Cache contains {@link org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean} */ class ClientFactoryBeanCache { private LRUSoftCache<String, JAXRSClientFactoryBean> cache; ClientFactoryBeanCache(final int maxCacheSize) { this.cache = new LRUSoftCache<String, JAXRSClientFactoryBean>(maxCacheSize); } public void start() throws Exception { cache.resetStatistics(); } public void stop() throws Exception { cache.clear(); } public JAXRSClientFactoryBean get(String address) throws Exception { JAXRSClientFactoryBean retVal = null; synchronized (cache) { retVal = cache.get(address); if (retVal == null) { retVal = ((CxfRsEndpoint)getEndpoint()).createJAXRSClientFactoryBean(address); cache.put(address, retVal); LOG.trace("Created client factory bean and add to cache for address '{}'", address); } else { LOG.trace("Retrieved client factory bean from cache for address '{}'", address); } } return retVal; } } }
{'content_hash': 'db7248a10e6470402e3bd8fc68c7adf0', 'timestamp': '', 'source': 'github', 'line_count': 853, 'max_line_length': 168, 'avg_line_length': 43.875732708089096, 'alnum_prop': 0.6079196280660504, 'repo_name': 'acartapanis/camel', 'id': '50aece0fd8c47c5f8a0f888b5b7ea35cf755857a', 'size': '38229', 'binary': False, 'copies': '25', 'ref': 'refs/heads/master', 'path': 'components/camel-cxf/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducer.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Apex', 'bytes': '6519'}, {'name': 'Batchfile', 'bytes': '683'}, {'name': 'CSS', 'bytes': '30373'}, {'name': 'Elm', 'bytes': '10852'}, {'name': 'FreeMarker', 'bytes': '11410'}, {'name': 'Groovy', 'bytes': '49890'}, {'name': 'HTML', 'bytes': '179541'}, {'name': 'Java', 'bytes': '62612883'}, {'name': 'JavaScript', 'bytes': '90232'}, {'name': 'Protocol Buffer', 'bytes': '578'}, {'name': 'Python', 'bytes': '36'}, {'name': 'Ruby', 'bytes': '4802'}, {'name': 'Scala', 'bytes': '323653'}, {'name': 'Shell', 'bytes': '16830'}, {'name': 'Tcl', 'bytes': '4974'}, {'name': 'XQuery', 'bytes': '546'}, {'name': 'XSLT', 'bytes': '284394'}]}
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Class XML_RPC_Message | Practica2_Servidor</title> <link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e"> </head> <body> <div id="left"> <div id="menu"> <a href="index.html" title="Overview"><span>Overview</span></a> <div id="groups"> <h3>Namespaces</h3> <ul> <li> <a href="namespace-Composer.html"> Composer<span></span> </a> <ul> <li> <a href="namespace-Composer.Autoload.html"> Autoload </a> </li> </ul></li> <li class="active"> <a href="namespace-None.html"> None </a> </li> <li> <a href="namespace-org.html"> org<span></span> </a> <ul> <li> <a href="namespace-org.bovigo.html"> bovigo<span></span> </a> <ul> <li> <a href="namespace-org.bovigo.vfs.html"> vfs<span></span> </a> <ul> <li> <a href="namespace-org.bovigo.vfs.example.html"> example </a> </li> <li> <a href="namespace-org.bovigo.vfs.visitor.html"> visitor </a> </li> </ul></li></ul></li></ul></li> <li> <a href="namespace-PHP.html"> PHP </a> </li> </ul> </div> <hr> <div id="elements"> <h3>Classes</h3> <ul> <li><a href="class-AdvancedValueBinderTest.html">AdvancedValueBinderTest</a></li> <li><a href="class-Agregador.html" class="invalid">Agregador</a></li> <li><a href="class-AutofilterColumnTest.html">AutofilterColumnTest</a></li> <li><a href="class-AutoFilterTest.html">AutoFilterTest</a></li> <li><a href="class-AutoloaderTest.html">AutoloaderTest</a></li> <li><a href="class-CalculationTest.html">CalculationTest</a></li> <li><a href="class-Camiseta.html">Camiseta</a></li> <li><a href="class-Carrito.html">Carrito</a></li> <li><a href="class-Carro.html">Carro</a></li> <li><a href="class-Categorias.html">Categorias</a></li> <li><a href="class-CellCollectionTest.html">CellCollectionTest</a></li> <li><a href="class-CellTest.html">CellTest</a></li> <li><a href="class-CholeskyDecomposition.html">CholeskyDecomposition</a></li> <li><a href="class-CI_Benchmark.html" class="invalid">CI_Benchmark</a></li> <li><a href="class-CI_Cache.html" class="invalid">CI_Cache</a></li> <li><a href="class-CI_Cache_apc.html" class="invalid">CI_Cache_apc</a></li> <li><a href="class-CI_Cache_dummy.html" class="invalid">CI_Cache_dummy</a></li> <li><a href="class-CI_Cache_file.html" class="invalid">CI_Cache_file</a></li> <li><a href="class-CI_Cache_memcached.html" class="invalid">CI_Cache_memcached</a></li> <li><a href="class-CI_Cache_redis.html">CI_Cache_redis</a></li> <li><a href="class-CI_Cache_wincache.html">CI_Cache_wincache</a></li> <li><a href="class-CI_Calendar.html" class="invalid">CI_Calendar</a></li> <li><a href="class-CI_Cart.html" class="invalid">CI_Cart</a></li> <li><a href="class-CI_Config.html" class="invalid">CI_Config</a></li> <li><a href="class-CI_Controller.html" class="invalid">CI_Controller</a></li> <li><a href="class-CI_DB_active_record.html">CI_DB_active_record</a></li> <li><a href="class-CI_DB_Cache.html" class="invalid">CI_DB_Cache</a></li> <li><a href="class-CI_DB_cubrid_driver.html" class="invalid">CI_DB_cubrid_driver</a></li> <li><a href="class-CI_DB_cubrid_forge.html" class="invalid">CI_DB_cubrid_forge</a></li> <li><a href="class-CI_DB_cubrid_result.html" class="invalid">CI_DB_cubrid_result</a></li> <li><a href="class-CI_DB_cubrid_utility.html" class="invalid">CI_DB_cubrid_utility</a></li> <li><a href="class-CI_DB_driver.html" class="invalid">CI_DB_driver</a></li> <li><a href="class-CI_DB_forge.html" class="invalid">CI_DB_forge</a></li> <li><a href="class-CI_DB_ibase_driver.html">CI_DB_ibase_driver</a></li> <li><a href="class-CI_DB_ibase_forge.html">CI_DB_ibase_forge</a></li> <li><a href="class-CI_DB_ibase_result.html">CI_DB_ibase_result</a></li> <li><a href="class-CI_DB_ibase_utility.html">CI_DB_ibase_utility</a></li> <li><a href="class-CI_DB_mssql_driver.html" class="invalid">CI_DB_mssql_driver</a></li> <li><a href="class-CI_DB_mssql_forge.html" class="invalid">CI_DB_mssql_forge</a></li> <li><a href="class-CI_DB_mssql_result.html" class="invalid">CI_DB_mssql_result</a></li> <li><a href="class-CI_DB_mssql_utility.html" class="invalid">CI_DB_mssql_utility</a></li> <li><a href="class-CI_DB_mysql_driver.html" class="invalid">CI_DB_mysql_driver</a></li> <li><a href="class-CI_DB_mysql_forge.html" class="invalid">CI_DB_mysql_forge</a></li> <li><a href="class-CI_DB_mysql_result.html" class="invalid">CI_DB_mysql_result</a></li> <li><a href="class-CI_DB_mysql_utility.html" class="invalid">CI_DB_mysql_utility</a></li> <li><a href="class-CI_DB_mysqli_driver.html" class="invalid">CI_DB_mysqli_driver</a></li> <li><a href="class-CI_DB_mysqli_forge.html" class="invalid">CI_DB_mysqli_forge</a></li> <li><a href="class-CI_DB_mysqli_result.html" class="invalid">CI_DB_mysqli_result</a></li> <li><a href="class-CI_DB_mysqli_utility.html" class="invalid">CI_DB_mysqli_utility</a></li> <li><a href="class-CI_DB_oci8_driver.html" class="invalid">CI_DB_oci8_driver</a></li> <li><a href="class-CI_DB_oci8_forge.html" class="invalid">CI_DB_oci8_forge</a></li> <li><a href="class-CI_DB_oci8_result.html" class="invalid">CI_DB_oci8_result</a></li> <li><a href="class-CI_DB_oci8_utility.html" class="invalid">CI_DB_oci8_utility</a></li> <li><a href="class-CI_DB_odbc_driver.html" class="invalid">CI_DB_odbc_driver</a></li> <li><a href="class-CI_DB_odbc_forge.html" class="invalid">CI_DB_odbc_forge</a></li> <li><a href="class-CI_DB_odbc_result.html" class="invalid">CI_DB_odbc_result</a></li> <li><a href="class-CI_DB_odbc_utility.html" class="invalid">CI_DB_odbc_utility</a></li> <li><a href="class-CI_DB_pdo_4d_driver.html">CI_DB_pdo_4d_driver</a></li> <li><a href="class-CI_DB_pdo_4d_forge.html">CI_DB_pdo_4d_forge</a></li> <li><a href="class-CI_DB_pdo_cubrid_driver.html">CI_DB_pdo_cubrid_driver</a></li> <li><a href="class-CI_DB_pdo_cubrid_forge.html">CI_DB_pdo_cubrid_forge</a></li> <li><a href="class-CI_DB_pdo_dblib_driver.html">CI_DB_pdo_dblib_driver</a></li> <li><a href="class-CI_DB_pdo_dblib_forge.html">CI_DB_pdo_dblib_forge</a></li> <li><a href="class-CI_DB_pdo_driver.html" class="invalid">CI_DB_pdo_driver</a></li> <li><a href="class-CI_DB_pdo_firebird_driver.html">CI_DB_pdo_firebird_driver</a></li> <li><a href="class-CI_DB_pdo_firebird_forge.html">CI_DB_pdo_firebird_forge</a></li> <li><a href="class-CI_DB_pdo_forge.html" class="invalid">CI_DB_pdo_forge</a></li> <li><a href="class-CI_DB_pdo_ibm_driver.html">CI_DB_pdo_ibm_driver</a></li> <li><a href="class-CI_DB_pdo_ibm_forge.html">CI_DB_pdo_ibm_forge</a></li> <li><a href="class-CI_DB_pdo_informix_driver.html">CI_DB_pdo_informix_driver</a></li> <li><a href="class-CI_DB_pdo_informix_forge.html">CI_DB_pdo_informix_forge</a></li> <li><a href="class-CI_DB_pdo_mysql_driver.html">CI_DB_pdo_mysql_driver</a></li> <li><a href="class-CI_DB_pdo_mysql_forge.html">CI_DB_pdo_mysql_forge</a></li> <li><a href="class-CI_DB_pdo_oci_driver.html">CI_DB_pdo_oci_driver</a></li> <li><a href="class-CI_DB_pdo_oci_forge.html">CI_DB_pdo_oci_forge</a></li> <li><a href="class-CI_DB_pdo_odbc_driver.html">CI_DB_pdo_odbc_driver</a></li> <li><a href="class-CI_DB_pdo_odbc_forge.html">CI_DB_pdo_odbc_forge</a></li> <li><a href="class-CI_DB_pdo_pgsql_driver.html">CI_DB_pdo_pgsql_driver</a></li> <li><a href="class-CI_DB_pdo_pgsql_forge.html">CI_DB_pdo_pgsql_forge</a></li> <li><a href="class-CI_DB_pdo_result.html" class="invalid">CI_DB_pdo_result</a></li> <li><a href="class-CI_DB_pdo_sqlite_driver.html">CI_DB_pdo_sqlite_driver</a></li> <li><a href="class-CI_DB_pdo_sqlite_forge.html">CI_DB_pdo_sqlite_forge</a></li> <li><a href="class-CI_DB_pdo_sqlsrv_driver.html">CI_DB_pdo_sqlsrv_driver</a></li> <li><a href="class-CI_DB_pdo_sqlsrv_forge.html">CI_DB_pdo_sqlsrv_forge</a></li> <li><a href="class-CI_DB_pdo_utility.html" class="invalid">CI_DB_pdo_utility</a></li> <li><a href="class-CI_DB_postgre_driver.html" class="invalid">CI_DB_postgre_driver</a></li> <li><a href="class-CI_DB_postgre_forge.html" class="invalid">CI_DB_postgre_forge</a></li> <li><a href="class-CI_DB_postgre_result.html" class="invalid">CI_DB_postgre_result</a></li> <li><a href="class-CI_DB_postgre_utility.html" class="invalid">CI_DB_postgre_utility</a></li> <li><a href="class-CI_DB_query_builder.html">CI_DB_query_builder</a></li> <li><a href="class-CI_DB_result.html" class="invalid">CI_DB_result</a></li> <li><a href="class-CI_DB_sqlite3_driver.html">CI_DB_sqlite3_driver</a></li> <li><a href="class-CI_DB_sqlite3_forge.html">CI_DB_sqlite3_forge</a></li> <li><a href="class-CI_DB_sqlite3_result.html">CI_DB_sqlite3_result</a></li> <li><a href="class-CI_DB_sqlite3_utility.html">CI_DB_sqlite3_utility</a></li> <li><a href="class-CI_DB_sqlite_driver.html" class="invalid">CI_DB_sqlite_driver</a></li> <li><a href="class-CI_DB_sqlite_forge.html" class="invalid">CI_DB_sqlite_forge</a></li> <li><a href="class-CI_DB_sqlite_result.html" class="invalid">CI_DB_sqlite_result</a></li> <li><a href="class-CI_DB_sqlite_utility.html" class="invalid">CI_DB_sqlite_utility</a></li> <li><a href="class-CI_DB_sqlsrv_driver.html" class="invalid">CI_DB_sqlsrv_driver</a></li> <li><a href="class-CI_DB_sqlsrv_forge.html" class="invalid">CI_DB_sqlsrv_forge</a></li> <li><a href="class-CI_DB_sqlsrv_result.html" class="invalid">CI_DB_sqlsrv_result</a></li> <li><a href="class-CI_DB_sqlsrv_utility.html" class="invalid">CI_DB_sqlsrv_utility</a></li> <li><a href="class-CI_DB_utility.html" class="invalid">CI_DB_utility</a></li> <li><a href="class-CI_Driver.html" class="invalid">CI_Driver</a></li> <li><a href="class-CI_Driver_Library.html" class="invalid">CI_Driver_Library</a></li> <li><a href="class-CI_Email.html" class="invalid">CI_Email</a></li> <li><a href="class-CI_Encrypt.html" class="invalid">CI_Encrypt</a></li> <li><a href="class-CI_Encryption.html">CI_Encryption</a></li> <li><a href="class-CI_Exceptions.html" class="invalid">CI_Exceptions</a></li> <li><a href="class-CI_Form_validation.html" class="invalid">CI_Form_validation</a></li> <li><a href="class-CI_FTP.html" class="invalid">CI_FTP</a></li> <li><a href="class-CI_Hooks.html" class="invalid">CI_Hooks</a></li> <li><a href="class-CI_Image_lib.html" class="invalid">CI_Image_lib</a></li> <li><a href="class-CI_Input.html" class="invalid">CI_Input</a></li> <li><a href="class-CI_Javascript.html" class="invalid">CI_Javascript</a></li> <li><a href="class-CI_Jquery.html" class="invalid">CI_Jquery</a></li> <li><a href="class-CI_Lang.html" class="invalid">CI_Lang</a></li> <li><a href="class-CI_Loader.html" class="invalid">CI_Loader</a></li> <li><a href="class-CI_Log.html" class="invalid">CI_Log</a></li> <li><a href="class-CI_Migration.html" class="invalid">CI_Migration</a></li> <li><a href="class-CI_Model.html" class="invalid">CI_Model</a></li> <li><a href="class-CI_Output.html" class="invalid">CI_Output</a></li> <li><a href="class-CI_Pagination.html" class="invalid">CI_Pagination</a></li> <li><a href="class-CI_Parser.html" class="invalid">CI_Parser</a></li> <li><a href="class-CI_Profiler.html" class="invalid">CI_Profiler</a></li> <li><a href="class-CI_Router.html" class="invalid">CI_Router</a></li> <li><a href="class-CI_Security.html" class="invalid">CI_Security</a></li> <li><a href="class-CI_Session.html" class="invalid">CI_Session</a></li> <li><a href="class-CI_Session_database_driver.html">CI_Session_database_driver</a></li> <li><a href="class-CI_Session_driver.html">CI_Session_driver</a></li> <li><a href="class-CI_Session_files_driver.html">CI_Session_files_driver</a></li> <li><a href="class-CI_Session_memcached_driver.html">CI_Session_memcached_driver</a></li> <li><a href="class-CI_Session_redis_driver.html">CI_Session_redis_driver</a></li> <li><a href="class-CI_SHA1.html">CI_SHA1</a></li> <li><a href="class-CI_Table.html" class="invalid">CI_Table</a></li> <li><a href="class-CI_Trackback.html" class="invalid">CI_Trackback</a></li> <li><a href="class-CI_Typography.html" class="invalid">CI_Typography</a></li> <li><a href="class-CI_Unit_test.html" class="invalid">CI_Unit_test</a></li> <li><a href="class-CI_Upload.html" class="invalid">CI_Upload</a></li> <li><a href="class-CI_URI.html" class="invalid">CI_URI</a></li> <li><a href="class-CI_User_agent.html" class="invalid">CI_User_agent</a></li> <li><a href="class-CI_Utf8.html" class="invalid">CI_Utf8</a></li> <li><a href="class-CI_Xmlrpc.html" class="invalid">CI_Xmlrpc</a></li> <li><a href="class-CI_Xmlrpcs.html" class="invalid">CI_Xmlrpcs</a></li> <li><a href="class-CI_Zip.html" class="invalid">CI_Zip</a></li> <li><a href="class-CodePageTest.html">CodePageTest</a></li> <li><a href="class-ColorTest.html">ColorTest</a></li> <li><a href="class-ColumnCellIteratorTest.html">ColumnCellIteratorTest</a></li> <li><a href="class-ColumnIteratorTest.html">ColumnIteratorTest</a></li> <li><a href="class-Complex.html">Complex</a></li> <li><a href="class-complexAssert.html">complexAssert</a></li> <li><a href="class-ComposerAutoloaderInit03216eaa5a0e5a7f5bbbeeae5708a458.html">ComposerAutoloaderInit03216eaa5a0e5a7f5bbbeeae5708a458</a></li> <li><a href="class-DataSeriesValuesTest.html">DataSeriesValuesTest</a></li> <li><a href="class-DataTypeTest.html">DataTypeTest</a></li> <li><a href="class-DateTest.html">DateTest</a></li> <li><a href="class-DateTimeTest.html">DateTimeTest</a></li> <li><a href="class-DefaultValueBinderTest.html">DefaultValueBinderTest</a></li> <li><a href="class-EigenvalueDecomposition.html">EigenvalueDecomposition</a></li> <li><a href="class-EliminarUsuario.html">EliminarUsuario</a></li> <li><a href="class-EngineeringTest.html">EngineeringTest</a></li> <li><a href="class-Error404.html">Error404</a></li> <li><a href="class-Excel.html">Excel</a></li> <li><a href="class-FileTest.html">FileTest</a></li> <li><a href="class-FinancialTest.html">FinancialTest</a></li> <li><a href="class-FontTest.html">FontTest</a></li> <li><a href="class-FPDF.html">FPDF</a></li> <li><a href="class-FunctionsTest.html">FunctionsTest</a></li> <li><a href="class-Gestor_Tiendas_Model.html">Gestor_Tiendas_Model</a></li> <li><a href="class-HyperlinkTest.html">HyperlinkTest</a></li> <li><a href="class-JSON_WebClient.html">JSON_WebClient</a></li> <li><a href="class-JSON_WebServer_Controller.html" class="invalid">JSON_WebServer_Controller</a></li> <li><a href="class-LayoutTest.html">LayoutTest</a></li> <li><a href="class-LegendTest.html">LegendTest</a></li> <li><a href="class-LogicalTest.html">LogicalTest</a></li> <li><a href="class-Login.html">Login</a></li> <li><a href="class-LookupRefTest.html">LookupRefTest</a></li> <li><a href="class-Main.html">Main</a></li> <li><a href="class-MathTrigTest.html">MathTrigTest</a></li> <li><a href="class-Mdl_Agregador.html">Mdl_Agregador</a></li> <li><a href="class-Mdl_camiseta.html">Mdl_camiseta</a></li> <li><a href="class-Mdl_carrito.html">Mdl_carrito</a></li> <li><a href="class-Mdl_categorias.html">Mdl_categorias</a></li> <li><a href="class-Mdl_MisPedidos.html">Mdl_MisPedidos</a></li> <li><a href="class-Mdl_pedidos.html">Mdl_pedidos</a></li> <li><a href="class-Mdl_provincias.html">Mdl_provincias</a></li> <li><a href="class-Mdl_restablecerCont.html">Mdl_restablecerCont</a></li> <li><a href="class-Mdl_seleccionadas.html">Mdl_seleccionadas</a></li> <li><a href="class-Mdl_usuarios.html">Mdl_usuarios</a></li> <li><a href="class-Mdl_xml.html">Mdl_xml</a></li> <li><a href="class-MisPedidos.html">MisPedidos</a></li> <li><a href="class-ModificarCorrecto.html">ModificarCorrecto</a></li> <li><a href="class-ModificarUsuario.html">ModificarUsuario</a></li> <li><a href="class-Monedas.html">Monedas</a></li> <li><a href="class-MyReadFilter.html">MyReadFilter</a></li> <li><a href="class-NumberFormatTest.html">NumberFormatTest</a></li> <li><a href="class-PasswordHasherTest.html">PasswordHasherTest</a></li> <li><a href="class-PclZip.html">PclZip</a></li> <li><a href="class-PDF.html" class="invalid">PDF</a></li> <li><a href="class-Pedidos.html">Pedidos</a></li> <li><a href="class-PHPExcel.html">PHPExcel</a></li> <li><a href="class-PHPExcel_Autoloader.html">PHPExcel_Autoloader</a></li> <li><a href="class-PHPExcel_Best_Fit.html">PHPExcel_Best_Fit</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_APC.html">PHPExcel_CachedObjectStorage_APC</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_CacheBase.html">PHPExcel_CachedObjectStorage_CacheBase</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_DiscISAM.html">PHPExcel_CachedObjectStorage_DiscISAM</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_Igbinary.html">PHPExcel_CachedObjectStorage_Igbinary</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_Memcache.html">PHPExcel_CachedObjectStorage_Memcache</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_Memory.html">PHPExcel_CachedObjectStorage_Memory</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_MemoryGZip.html">PHPExcel_CachedObjectStorage_MemoryGZip</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_MemorySerialized.html">PHPExcel_CachedObjectStorage_MemorySerialized</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_PHPTemp.html">PHPExcel_CachedObjectStorage_PHPTemp</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_SQLite.html">PHPExcel_CachedObjectStorage_SQLite</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_SQLite3.html">PHPExcel_CachedObjectStorage_SQLite3</a></li> <li><a href="class-PHPExcel_CachedObjectStorage_Wincache.html">PHPExcel_CachedObjectStorage_Wincache</a></li> <li><a href="class-PHPExcel_CachedObjectStorageFactory.html">PHPExcel_CachedObjectStorageFactory</a></li> <li><a href="class-PHPExcel_CalcEngine_CyclicReferenceStack.html">PHPExcel_CalcEngine_CyclicReferenceStack</a></li> <li><a href="class-PHPExcel_CalcEngine_Logger.html">PHPExcel_CalcEngine_Logger</a></li> <li><a href="class-PHPExcel_Calculation.html">PHPExcel_Calculation</a></li> <li><a href="class-PHPExcel_Calculation_Database.html">PHPExcel_Calculation_Database</a></li> <li><a href="class-PHPExcel_Calculation_DateTime.html">PHPExcel_Calculation_DateTime</a></li> <li><a href="class-PHPExcel_Calculation_Engineering.html">PHPExcel_Calculation_Engineering</a></li> <li><a href="class-PHPExcel_Calculation_ExceptionHandler.html">PHPExcel_Calculation_ExceptionHandler</a></li> <li><a href="class-PHPExcel_Calculation_Financial.html">PHPExcel_Calculation_Financial</a></li> <li><a href="class-PHPExcel_Calculation_FormulaParser.html">PHPExcel_Calculation_FormulaParser</a></li> <li><a href="class-PHPExcel_Calculation_FormulaToken.html">PHPExcel_Calculation_FormulaToken</a></li> <li><a href="class-PHPExcel_Calculation_Function.html">PHPExcel_Calculation_Function</a></li> <li><a href="class-PHPExcel_Calculation_Functions.html">PHPExcel_Calculation_Functions</a></li> <li><a href="class-PHPExcel_Calculation_Logical.html">PHPExcel_Calculation_Logical</a></li> <li><a href="class-PHPExcel_Calculation_LookupRef.html">PHPExcel_Calculation_LookupRef</a></li> <li><a href="class-PHPExcel_Calculation_MathTrig.html">PHPExcel_Calculation_MathTrig</a></li> <li><a href="class-PHPExcel_Calculation_Statistical.html">PHPExcel_Calculation_Statistical</a></li> <li><a href="class-PHPExcel_Calculation_TextData.html">PHPExcel_Calculation_TextData</a></li> <li><a href="class-PHPExcel_Calculation_Token_Stack.html">PHPExcel_Calculation_Token_Stack</a></li> <li><a href="class-PHPExcel_Cell.html">PHPExcel_Cell</a></li> <li><a href="class-PHPExcel_Cell_AdvancedValueBinder.html">PHPExcel_Cell_AdvancedValueBinder</a></li> <li><a href="class-PHPExcel_Cell_DataType.html">PHPExcel_Cell_DataType</a></li> <li><a href="class-PHPExcel_Cell_DataValidation.html">PHPExcel_Cell_DataValidation</a></li> <li><a href="class-PHPExcel_Cell_DefaultValueBinder.html">PHPExcel_Cell_DefaultValueBinder</a></li> <li><a href="class-PHPExcel_Cell_Hyperlink.html">PHPExcel_Cell_Hyperlink</a></li> <li><a href="class-PHPExcel_Chart.html">PHPExcel_Chart</a></li> <li><a href="class-PHPExcel_Chart_Axis.html">PHPExcel_Chart_Axis</a></li> <li><a href="class-PHPExcel_Chart_DataSeries.html">PHPExcel_Chart_DataSeries</a></li> <li><a href="class-PHPExcel_Chart_DataSeriesValues.html">PHPExcel_Chart_DataSeriesValues</a></li> <li><a href="class-PHPExcel_Chart_GridLines.html">PHPExcel_Chart_GridLines</a></li> <li><a href="class-PHPExcel_Chart_Layout.html">PHPExcel_Chart_Layout</a></li> <li><a href="class-PHPExcel_Chart_Legend.html">PHPExcel_Chart_Legend</a></li> <li><a href="class-PHPExcel_Chart_PlotArea.html">PHPExcel_Chart_PlotArea</a></li> <li><a href="class-PHPExcel_Chart_Renderer_jpgraph.html">PHPExcel_Chart_Renderer_jpgraph</a></li> <li><a href="class-PHPExcel_Chart_Title.html">PHPExcel_Chart_Title</a></li> <li><a href="class-PHPExcel_Comment.html">PHPExcel_Comment</a></li> <li><a href="class-PHPExcel_DocumentProperties.html">PHPExcel_DocumentProperties</a></li> <li><a href="class-PHPExcel_DocumentSecurity.html">PHPExcel_DocumentSecurity</a></li> <li><a href="class-PHPExcel_Exponential_Best_Fit.html">PHPExcel_Exponential_Best_Fit</a></li> <li><a href="class-PHPExcel_HashTable.html">PHPExcel_HashTable</a></li> <li><a href="class-PHPExcel_Helper_HTML.html">PHPExcel_Helper_HTML</a></li> <li><a href="class-PHPExcel_IOFactory.html">PHPExcel_IOFactory</a></li> <li><a href="class-PHPExcel_Linear_Best_Fit.html">PHPExcel_Linear_Best_Fit</a></li> <li><a href="class-PHPExcel_Logarithmic_Best_Fit.html">PHPExcel_Logarithmic_Best_Fit</a></li> <li><a href="class-PHPExcel_NamedRange.html">PHPExcel_NamedRange</a></li> <li><a href="class-PHPExcel_Polynomial_Best_Fit.html">PHPExcel_Polynomial_Best_Fit</a></li> <li><a href="class-PHPExcel_Power_Best_Fit.html">PHPExcel_Power_Best_Fit</a></li> <li><a href="class-PHPExcel_Properties.html">PHPExcel_Properties</a></li> <li><a href="class-PHPExcel_Reader_Abstract.html">PHPExcel_Reader_Abstract</a></li> <li><a href="class-PHPExcel_Reader_CSV.html">PHPExcel_Reader_CSV</a></li> <li><a href="class-PHPExcel_Reader_DefaultReadFilter.html">PHPExcel_Reader_DefaultReadFilter</a></li> <li><a href="class-PHPExcel_Reader_Excel2003XML.html">PHPExcel_Reader_Excel2003XML</a></li> <li><a href="class-PHPExcel_Reader_Excel2007.html">PHPExcel_Reader_Excel2007</a></li> <li><a href="class-PHPExcel_Reader_Excel2007_Chart.html">PHPExcel_Reader_Excel2007_Chart</a></li> <li><a href="class-PHPExcel_Reader_Excel2007_Theme.html">PHPExcel_Reader_Excel2007_Theme</a></li> <li><a href="class-PHPExcel_Reader_Excel5.html">PHPExcel_Reader_Excel5</a></li> <li><a href="class-PHPExcel_Reader_Excel5_Escher.html">PHPExcel_Reader_Excel5_Escher</a></li> <li><a href="class-PHPExcel_Reader_Excel5_MD5.html">PHPExcel_Reader_Excel5_MD5</a></li> <li><a href="class-PHPExcel_Reader_Excel5_RC4.html">PHPExcel_Reader_Excel5_RC4</a></li> <li><a href="class-PHPExcel_Reader_Gnumeric.html">PHPExcel_Reader_Gnumeric</a></li> <li><a href="class-PHPExcel_Reader_HTML.html">PHPExcel_Reader_HTML</a></li> <li><a href="class-PHPExcel_Reader_OOCalc.html">PHPExcel_Reader_OOCalc</a></li> <li><a href="class-PHPExcel_Reader_SYLK.html">PHPExcel_Reader_SYLK</a></li> <li><a href="class-PHPExcel_ReferenceHelper.html">PHPExcel_ReferenceHelper</a></li> <li><a href="class-PHPExcel_RichText.html">PHPExcel_RichText</a></li> <li><a href="class-PHPExcel_RichText_Run.html">PHPExcel_RichText_Run</a></li> <li><a href="class-PHPExcel_RichText_TextElement.html">PHPExcel_RichText_TextElement</a></li> <li><a href="class-PHPExcel_Settings.html">PHPExcel_Settings</a></li> <li><a href="class-PHPExcel_Shared_CodePage.html">PHPExcel_Shared_CodePage</a></li> <li><a href="class-PHPExcel_Shared_Date.html">PHPExcel_Shared_Date</a></li> <li><a href="class-PHPExcel_Shared_Drawing.html">PHPExcel_Shared_Drawing</a></li> <li><a href="class-PHPExcel_Shared_Escher.html">PHPExcel_Shared_Escher</a></li> <li><a href="class-PHPExcel_Shared_Escher_DgContainer.html">PHPExcel_Shared_Escher_DgContainer</a></li> <li><a href="class-PHPExcel_Shared_Escher_DgContainer_SpgrContainer.html">PHPExcel_Shared_Escher_DgContainer_SpgrContainer</a></li> <li><a href="class-PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer.html">PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer</a></li> <li><a href="class-PHPExcel_Shared_Escher_DggContainer.html">PHPExcel_Shared_Escher_DggContainer</a></li> <li><a href="class-PHPExcel_Shared_Escher_DggContainer_BstoreContainer.html">PHPExcel_Shared_Escher_DggContainer_BstoreContainer</a></li> <li><a href="class-PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE.html">PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE</a></li> <li><a href="class-PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip.html">PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip</a></li> <li><a href="class-PHPExcel_Shared_Excel5.html">PHPExcel_Shared_Excel5</a></li> <li><a href="class-PHPExcel_Shared_File.html">PHPExcel_Shared_File</a></li> <li><a href="class-PHPExcel_Shared_Font.html">PHPExcel_Shared_Font</a></li> <li><a href="class-PHPExcel_Shared_JAMA_LUDecomposition.html">PHPExcel_Shared_JAMA_LUDecomposition</a></li> <li><a href="class-PHPExcel_Shared_JAMA_Matrix.html">PHPExcel_Shared_JAMA_Matrix</a></li> <li><a href="class-PHPExcel_Shared_JAMA_QRDecomposition.html">PHPExcel_Shared_JAMA_QRDecomposition</a></li> <li><a href="class-PHPExcel_Shared_OLE.html">PHPExcel_Shared_OLE</a></li> <li><a href="class-PHPExcel_Shared_OLE_ChainedBlockStream.html">PHPExcel_Shared_OLE_ChainedBlockStream</a></li> <li><a href="class-PHPExcel_Shared_OLE_PPS.html">PHPExcel_Shared_OLE_PPS</a></li> <li><a href="class-PHPExcel_Shared_OLE_PPS_File.html">PHPExcel_Shared_OLE_PPS_File</a></li> <li><a href="class-PHPExcel_Shared_OLE_PPS_Root.html">PHPExcel_Shared_OLE_PPS_Root</a></li> <li><a href="class-PHPExcel_Shared_OLERead.html">PHPExcel_Shared_OLERead</a></li> <li><a href="class-PHPExcel_Shared_PasswordHasher.html">PHPExcel_Shared_PasswordHasher</a></li> <li><a href="class-PHPExcel_Shared_String.html">PHPExcel_Shared_String</a></li> <li><a href="class-PHPExcel_Shared_TimeZone.html">PHPExcel_Shared_TimeZone</a></li> <li><a href="class-PHPExcel_Shared_XMLWriter.html">PHPExcel_Shared_XMLWriter</a></li> <li><a href="class-PHPExcel_Shared_ZipArchive.html">PHPExcel_Shared_ZipArchive</a></li> <li><a href="class-PHPExcel_Shared_ZipStreamWrapper.html">PHPExcel_Shared_ZipStreamWrapper</a></li> <li><a href="class-PHPExcel_Style.html">PHPExcel_Style</a></li> <li><a href="class-PHPExcel_Style_Alignment.html">PHPExcel_Style_Alignment</a></li> <li><a href="class-PHPExcel_Style_Border.html">PHPExcel_Style_Border</a></li> <li><a href="class-PHPExcel_Style_Borders.html">PHPExcel_Style_Borders</a></li> <li><a href="class-PHPExcel_Style_Color.html">PHPExcel_Style_Color</a></li> <li><a href="class-PHPExcel_Style_Conditional.html">PHPExcel_Style_Conditional</a></li> <li><a href="class-PHPExcel_Style_Fill.html">PHPExcel_Style_Fill</a></li> <li><a href="class-PHPExcel_Style_Font.html">PHPExcel_Style_Font</a></li> <li><a href="class-PHPExcel_Style_NumberFormat.html">PHPExcel_Style_NumberFormat</a></li> <li><a href="class-PHPExcel_Style_Protection.html">PHPExcel_Style_Protection</a></li> <li><a href="class-PHPExcel_Style_Supervisor.html">PHPExcel_Style_Supervisor</a></li> <li><a href="class-PHPExcel_Worksheet.html">PHPExcel_Worksheet</a></li> <li><a href="class-PHPExcel_Worksheet_AutoFilter.html">PHPExcel_Worksheet_AutoFilter</a></li> <li><a href="class-PHPExcel_Worksheet_AutoFilter_Column.html">PHPExcel_Worksheet_AutoFilter_Column</a></li> <li><a href="class-PHPExcel_Worksheet_AutoFilter_Column_Rule.html">PHPExcel_Worksheet_AutoFilter_Column_Rule</a></li> <li><a href="class-PHPExcel_Worksheet_BaseDrawing.html">PHPExcel_Worksheet_BaseDrawing</a></li> <li><a href="class-PHPExcel_Worksheet_CellIterator.html">PHPExcel_Worksheet_CellIterator</a></li> <li><a href="class-PHPExcel_Worksheet_Column.html">PHPExcel_Worksheet_Column</a></li> <li><a href="class-PHPExcel_Worksheet_ColumnCellIterator.html">PHPExcel_Worksheet_ColumnCellIterator</a></li> <li><a href="class-PHPExcel_Worksheet_ColumnDimension.html">PHPExcel_Worksheet_ColumnDimension</a></li> <li><a href="class-PHPExcel_Worksheet_ColumnIterator.html">PHPExcel_Worksheet_ColumnIterator</a></li> <li><a href="class-PHPExcel_Worksheet_Drawing.html">PHPExcel_Worksheet_Drawing</a></li> <li><a href="class-PHPExcel_Worksheet_Drawing_Shadow.html">PHPExcel_Worksheet_Drawing_Shadow</a></li> <li><a href="class-PHPExcel_Worksheet_HeaderFooter.html">PHPExcel_Worksheet_HeaderFooter</a></li> <li><a href="class-PHPExcel_Worksheet_HeaderFooterDrawing.html">PHPExcel_Worksheet_HeaderFooterDrawing</a></li> <li><a href="class-PHPExcel_Worksheet_MemoryDrawing.html">PHPExcel_Worksheet_MemoryDrawing</a></li> <li><a href="class-PHPExcel_Worksheet_PageMargins.html">PHPExcel_Worksheet_PageMargins</a></li> <li><a href="class-PHPExcel_Worksheet_PageSetup.html">PHPExcel_Worksheet_PageSetup</a></li> <li><a href="class-PHPExcel_Worksheet_Protection.html">PHPExcel_Worksheet_Protection</a></li> <li><a href="class-PHPExcel_Worksheet_Row.html">PHPExcel_Worksheet_Row</a></li> <li><a href="class-PHPExcel_Worksheet_RowCellIterator.html">PHPExcel_Worksheet_RowCellIterator</a></li> <li><a href="class-PHPExcel_Worksheet_RowDimension.html">PHPExcel_Worksheet_RowDimension</a></li> <li><a href="class-PHPExcel_Worksheet_RowIterator.html">PHPExcel_Worksheet_RowIterator</a></li> <li><a href="class-PHPExcel_Worksheet_SheetView.html">PHPExcel_Worksheet_SheetView</a></li> <li><a href="class-PHPExcel_WorksheetIterator.html">PHPExcel_WorksheetIterator</a></li> <li><a href="class-PHPExcel_Writer_Abstract.html">PHPExcel_Writer_Abstract</a></li> <li><a href="class-PHPExcel_Writer_CSV.html">PHPExcel_Writer_CSV</a></li> <li><a href="class-PHPExcel_Writer_Excel2007.html">PHPExcel_Writer_Excel2007</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_Chart.html">PHPExcel_Writer_Excel2007_Chart</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_Comments.html">PHPExcel_Writer_Excel2007_Comments</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_ContentTypes.html">PHPExcel_Writer_Excel2007_ContentTypes</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_DocProps.html">PHPExcel_Writer_Excel2007_DocProps</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_Drawing.html">PHPExcel_Writer_Excel2007_Drawing</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_Rels.html">PHPExcel_Writer_Excel2007_Rels</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_RelsRibbon.html">PHPExcel_Writer_Excel2007_RelsRibbon</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_RelsVBA.html">PHPExcel_Writer_Excel2007_RelsVBA</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_StringTable.html">PHPExcel_Writer_Excel2007_StringTable</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_Style.html">PHPExcel_Writer_Excel2007_Style</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_Theme.html">PHPExcel_Writer_Excel2007_Theme</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_Workbook.html">PHPExcel_Writer_Excel2007_Workbook</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_Worksheet.html">PHPExcel_Writer_Excel2007_Worksheet</a></li> <li><a href="class-PHPExcel_Writer_Excel2007_WriterPart.html">PHPExcel_Writer_Excel2007_WriterPart</a></li> <li><a href="class-PHPExcel_Writer_Excel5.html">PHPExcel_Writer_Excel5</a></li> <li><a href="class-PHPExcel_Writer_Excel5_BIFFwriter.html">PHPExcel_Writer_Excel5_BIFFwriter</a></li> <li><a href="class-PHPExcel_Writer_Excel5_Escher.html">PHPExcel_Writer_Excel5_Escher</a></li> <li><a href="class-PHPExcel_Writer_Excel5_Font.html">PHPExcel_Writer_Excel5_Font</a></li> <li><a href="class-PHPExcel_Writer_Excel5_Parser.html">PHPExcel_Writer_Excel5_Parser</a></li> <li><a href="class-PHPExcel_Writer_Excel5_Workbook.html">PHPExcel_Writer_Excel5_Workbook</a></li> <li><a href="class-PHPExcel_Writer_Excel5_Worksheet.html">PHPExcel_Writer_Excel5_Worksheet</a></li> <li><a href="class-PHPExcel_Writer_Excel5_Xf.html">PHPExcel_Writer_Excel5_Xf</a></li> <li><a href="class-PHPExcel_Writer_HTML.html">PHPExcel_Writer_HTML</a></li> <li><a href="class-PHPExcel_Writer_OpenDocument.html">PHPExcel_Writer_OpenDocument</a></li> <li><a href="class-PHPExcel_Writer_OpenDocument_Cell_Comment.html">PHPExcel_Writer_OpenDocument_Cell_Comment</a></li> <li><a href="class-PHPExcel_Writer_OpenDocument_Content.html">PHPExcel_Writer_OpenDocument_Content</a></li> <li><a href="class-PHPExcel_Writer_OpenDocument_Meta.html">PHPExcel_Writer_OpenDocument_Meta</a></li> <li><a href="class-PHPExcel_Writer_OpenDocument_MetaInf.html">PHPExcel_Writer_OpenDocument_MetaInf</a></li> <li><a href="class-PHPExcel_Writer_OpenDocument_Mimetype.html">PHPExcel_Writer_OpenDocument_Mimetype</a></li> <li><a href="class-PHPExcel_Writer_OpenDocument_Settings.html">PHPExcel_Writer_OpenDocument_Settings</a></li> <li><a href="class-PHPExcel_Writer_OpenDocument_Styles.html">PHPExcel_Writer_OpenDocument_Styles</a></li> <li><a href="class-PHPExcel_Writer_OpenDocument_Thumbnails.html">PHPExcel_Writer_OpenDocument_Thumbnails</a></li> <li><a href="class-PHPExcel_Writer_OpenDocument_WriterPart.html">PHPExcel_Writer_OpenDocument_WriterPart</a></li> <li><a href="class-PHPExcel_Writer_PDF.html">PHPExcel_Writer_PDF</a></li> <li><a href="class-PHPExcel_Writer_PDF_Core.html">PHPExcel_Writer_PDF_Core</a></li> <li><a href="class-PHPExcel_Writer_PDF_DomPDF.html">PHPExcel_Writer_PDF_DomPDF</a></li> <li><a href="class-PHPExcel_Writer_PDF_mPDF.html">PHPExcel_Writer_PDF_mPDF</a></li> <li><a href="class-PHPExcel_Writer_PDF_tcPDF.html">PHPExcel_Writer_PDF_tcPDF</a></li> <li><a href="class-ReferenceHelperTest.html">ReferenceHelperTest</a></li> <li><a href="class-Registro.html">Registro</a></li> <li><a href="class-RestablecerContrasenha.html">RestablecerContrasenha</a></li> <li><a href="class-RowCellIteratorTest.html">RowCellIteratorTest</a></li> <li><a href="class-RowIteratorTest.html">RowIteratorTest</a></li> <li><a href="class-RuleTest.html">RuleTest</a></li> <li><a href="class-SesionNoIniciada.html">SesionNoIniciada</a></li> <li><a href="class-SingularValueDecomposition.html">SingularValueDecomposition</a></li> <li><a href="class-StringTest.html">StringTest</a></li> <li><a href="class-testDataFileIterator.html">testDataFileIterator</a></li> <li><a href="class-TextDataTest.html">TextDataTest</a></li> <li><a href="class-Tienda01.html">Tienda01</a></li> <li><a href="class-Tienda02.html">Tienda02</a></li> <li><a href="class-Tiendas_Model.html">Tiendas_Model</a></li> <li><a href="class-TimeZoneTest.html">TimeZoneTest</a></li> <li><a href="class-trendClass.html">trendClass</a></li> <li><a href="class-TTFParser.html">TTFParser</a></li> <li><a href="class-WorksheetColumnTest.html">WorksheetColumnTest</a></li> <li><a href="class-WorksheetRowTest.html">WorksheetRowTest</a></li> <li><a href="class-XEEValidatorTest.html">XEEValidatorTest</a></li> <li><a href="class-XML.html">XML</a></li> <li><a href="class-XML_RPC_Client.html" class="invalid">XML_RPC_Client</a></li> <li class="active"><a href="class-XML_RPC_Message.html" class="invalid">XML_RPC_Message</a></li> <li><a href="class-XML_RPC_Response.html" class="invalid">XML_RPC_Response</a></li> <li><a href="class-XML_RPC_Values.html" class="invalid">XML_RPC_Values</a></li> </ul> <h3>Interfaces</h3> <ul> <li><a href="class-PHPExcel_CachedObjectStorage_ICache.html">PHPExcel_CachedObjectStorage_ICache</a></li> <li><a href="class-PHPExcel_Cell_IValueBinder.html">PHPExcel_Cell_IValueBinder</a></li> <li><a href="class-PHPExcel_IComparable.html">PHPExcel_IComparable</a></li> <li><a href="class-PHPExcel_Reader_IReader.html">PHPExcel_Reader_IReader</a></li> <li><a href="class-PHPExcel_Reader_IReadFilter.html">PHPExcel_Reader_IReadFilter</a></li> <li><a href="class-PHPExcel_RichText_ITextElement.html">PHPExcel_RichText_ITextElement</a></li> <li><a href="class-PHPExcel_Writer_IWriter.html">PHPExcel_Writer_IWriter</a></li> <li><a href="class-SessionHandlerInterface.html">SessionHandlerInterface</a></li> </ul> <h3>Exceptions</h3> <ul> <li><a href="class-PHPExcel_Calculation_Exception.html">PHPExcel_Calculation_Exception</a></li> <li><a href="class-PHPExcel_Chart_Exception.html">PHPExcel_Chart_Exception</a></li> <li><a href="class-PHPExcel_Exception.html">PHPExcel_Exception</a></li> <li><a href="class-PHPExcel_Reader_Exception.html">PHPExcel_Reader_Exception</a></li> <li><a href="class-PHPExcel_Writer_Exception.html">PHPExcel_Writer_Exception</a></li> </ul> <h3>Functions</h3> <ul> <li><a href="function-_attributes_to_string.html" class="invalid">_attributes_to_string</a></li> <li><a href="function-_error_handler.html">_error_handler</a></li> <li><a href="function-_exception_handler.html" class="invalid">_exception_handler</a></li> <li><a href="function-_get_smiley_array.html" class="invalid">_get_smiley_array</a></li> <li><a href="function-_get_validation_object.html" class="invalid">_get_validation_object</a></li> <li><a href="function-_list.html" class="invalid">_list</a></li> <li><a href="function-_parse_attributes.html">_parse_attributes</a></li> <li><a href="function-_parse_form_attributes.html" class="invalid">_parse_form_attributes</a></li> <li><a href="function-_shutdown_handler.html">_shutdown_handler</a></li> <li><a href="function-_stringify_attributes.html">_stringify_attributes</a></li> <li><a href="function-acosh.html">acosh</a></li> <li><a href="function-alternator.html" class="invalid">alternator</a></li> <li><a href="function-anchor.html" class="invalid">anchor</a></li> <li><a href="function-anchor_popup.html" class="invalid">anchor_popup</a></li> <li><a href="function-array_column.html">array_column</a></li> <li><a href="function-array_replace.html">array_replace</a></li> <li><a href="function-array_replace_recursive.html">array_replace_recursive</a></li> <li><a href="function-ascii_to_entities.html" class="invalid">ascii_to_entities</a></li> <li><a href="function-asinh.html">asinh</a></li> <li><a href="function-atanh.html">atanh</a></li> <li><a href="function-auto_link.html" class="invalid">auto_link</a></li> <li><a href="function-auto_typography.html" class="invalid">auto_typography</a></li> <li><a href="function-base_url.html" class="invalid">base_url</a></li> <li><a href="function-br.html" class="invalid">br</a></li> <li><a href="function-byte_format.html" class="invalid">byte_format</a></li> <li><a href="function-cambiaFormatoFecha.html">cambiaFormatoFecha</a></li> <li><a href="function-camelize.html" class="invalid">camelize</a></li> <li><a href="function-character_limiter.html" class="invalid">character_limiter</a></li> <li><a href="function-claves_check.html">claves_check</a></li> <li><a href="function-composerRequire03216eaa5a0e5a7f5bbbeeae5708a458.html">composerRequire03216eaa5a0e5a7f5bbbeeae5708a458</a></li> <li><a href="function-config_item.html" class="invalid">config_item</a></li> <li><a href="function-convert_accented_characters.html" class="invalid">convert_accented_characters</a></li> <li><a href="function-CreaArrayParaSelect.html">CreaArrayParaSelect</a></li> <li><a href="function-CreaSelect.html">CreaSelect</a></li> <li><a href="function-CreaSelectMod.html">CreaSelectMod</a></li> <li><a href="function-create_captcha.html" class="invalid">create_captcha</a></li> <li><a href="function-current_url.html" class="invalid">current_url</a></li> <li><a href="function-date_range.html">date_range</a></li> <li><a href="function-days_in_month.html" class="invalid">days_in_month</a></li> <li><a href="function-DB.html" class="invalid">DB</a></li> <li><a href="function-delete_cookie.html" class="invalid">delete_cookie</a></li> <li><a href="function-delete_files.html" class="invalid">delete_files</a></li> <li><a href="function-directory_map.html" class="invalid">directory_map</a></li> <li><a href="function-dni_LetraNIF.html">dni_LetraNIF</a></li> <li><a href="function-do_hash.html" class="invalid">do_hash</a></li> <li><a href="function-doctype.html" class="invalid">doctype</a></li> <li><a href="function-element.html" class="invalid">element</a></li> <li><a href="function-elements.html" class="invalid">elements</a></li> <li><a href="function-ellipsize.html" class="invalid">ellipsize</a></li> <li><a href="function-encode_php_tags.html" class="invalid">encode_php_tags</a></li> <li><a href="function-entities_to_ascii.html" class="invalid">entities_to_ascii</a></li> <li><a href="function-entity_decode.html" class="invalid">entity_decode</a></li> <li><a href="function-Error.html">Error</a></li> <li><a href="function-force_download.html" class="invalid">force_download</a></li> <li><a href="function-form_button.html" class="invalid">form_button</a></li> <li><a href="function-form_checkbox.html" class="invalid">form_checkbox</a></li> <li><a href="function-form_close.html" class="invalid">form_close</a></li> <li><a href="function-form_dropdown.html" class="invalid">form_dropdown</a></li> <li><a href="function-form_error.html" class="invalid">form_error</a></li> <li><a href="function-form_fieldset.html" class="invalid">form_fieldset</a></li> <li><a href="function-form_fieldset_close.html" class="invalid">form_fieldset_close</a></li> <li><a href="function-form_hidden.html" class="invalid">form_hidden</a></li> <li><a href="function-form_input.html" class="invalid">form_input</a></li> <li><a href="function-form_label.html" class="invalid">form_label</a></li> <li><a href="function-form_multiselect.html" class="invalid">form_multiselect</a></li> <li><a href="function-form_open.html" class="invalid">form_open</a></li> <li><a href="function-form_open_multipart.html" class="invalid">form_open_multipart</a></li> <li><a href="function-form_password.html" class="invalid">form_password</a></li> <li><a href="function-form_prep.html" class="invalid">form_prep</a></li> <li><a href="function-form_radio.html" class="invalid">form_radio</a></li> <li><a href="function-form_reset.html" class="invalid">form_reset</a></li> <li><a href="function-form_submit.html" class="invalid">form_submit</a></li> <li><a href="function-form_textarea.html" class="invalid">form_textarea</a></li> <li><a href="function-form_upload.html" class="invalid">form_upload</a></li> <li><a href="function-function_usable.html">function_usable</a></li> <li><a href="function-get_clickable_smileys.html" class="invalid">get_clickable_smileys</a></li> <li><a href="function-get_config.html" class="invalid">get_config</a></li> <li><a href="function-get_cookie.html" class="invalid">get_cookie</a></li> <li><a href="function-get_dir_file_info.html" class="invalid">get_dir_file_info</a></li> <li><a href="function-get_file_info.html" class="invalid">get_file_info</a></li> <li><a href="function-get_filenames.html" class="invalid">get_filenames</a></li> <li><a href="function-get_instance.html" class="invalid">get_instance</a></li> <li><a href="function-get_mime_by_extension.html" class="invalid">get_mime_by_extension</a></li> <li><a href="function-get_mimes.html">get_mimes</a></li> <li><a href="function-getFicheroXML_Monedas.html">getFicheroXML_Monedas</a></li> <li><a href="function-GetInfoFromTrueType.html">GetInfoFromTrueType</a></li> <li><a href="function-GetInfoFromType1.html">GetInfoFromType1</a></li> <li><a href="function-getPrecioFinal.html">getPrecioFinal</a></li> <li><a href="function-gmt_to_local.html" class="invalid">gmt_to_local</a></li> <li><a href="function-hash_equals.html">hash_equals</a></li> <li><a href="function-hash_pbkdf2.html">hash_pbkdf2</a></li> <li><a href="function-heading.html" class="invalid">heading</a></li> <li><a href="function-hex2bin.html">hex2bin</a></li> <li><a href="function-highlight_code.html" class="invalid">highlight_code</a></li> <li><a href="function-highlight_phrase.html" class="invalid">highlight_phrase</a></li> <li><a href="function-html_escape.html" class="invalid">html_escape</a></li> <li><a href="function-human_to_unix.html" class="invalid">human_to_unix</a></li> <li><a href="function-humanize.html" class="invalid">humanize</a></li> <li><a href="function-hypo.html">hypo</a></li> <li><a href="function-img.html" class="invalid">img</a></li> <li><a href="function-increment_string.html" class="invalid">increment_string</a></li> <li><a href="function-index_page.html" class="invalid">index_page</a></li> <li><a href="function-is_cli.html">is_cli</a></li> <li><a href="function-is_countable.html">is_countable</a></li> <li><a href="function-is_false.html" class="invalid">is_false</a></li> <li><a href="function-is_https.html">is_https</a></li> <li><a href="function-is_loaded.html" class="invalid">is_loaded</a></li> <li><a href="function-is_php.html" class="invalid">is_php</a></li> <li><a href="function-is_really_writable.html" class="invalid">is_really_writable</a></li> <li><a href="function-is_true.html" class="invalid">is_true</a></li> <li><a href="function-JAMAError.html">JAMAError</a></li> <li><a href="function-js_insert_smiley.html">js_insert_smiley</a></li> <li><a href="function-lang.html" class="invalid">lang</a></li> <li><a href="function-link_tag.html" class="invalid">link_tag</a></li> <li><a href="function-load_class.html" class="invalid">load_class</a></li> <li><a href="function-LoadMap.html">LoadMap</a></li> <li><a href="function-local_to_gmt.html" class="invalid">local_to_gmt</a></li> <li><a href="function-log_message.html" class="invalid">log_message</a></li> <li><a href="function-mailto.html" class="invalid">mailto</a></li> <li><a href="function-MakeDefinitionFile.html">MakeDefinitionFile</a></li> <li><a href="function-MakeFont.html">MakeFont</a></li> <li><a href="function-MakeFontDescriptor.html">MakeFontDescriptor</a></li> <li><a href="function-MakeFontEncoding.html">MakeFontEncoding</a></li> <li><a href="function-MakeUnicodeArray.html">MakeUnicodeArray</a></li> <li><a href="function-MakeWidthArray.html">MakeWidthArray</a></li> <li><a href="function-mb_str_replace.html">mb_str_replace</a></li> <li><a href="function-mb_strlen.html">mb_strlen</a></li> <li><a href="function-mb_strpos.html">mb_strpos</a></li> <li><a href="function-mb_substr.html">mb_substr</a></li> <li><a href="function-mdate.html" class="invalid">mdate</a></li> <li><a href="function-Message.html">Message</a></li> <li><a href="function-meta.html" class="invalid">meta</a></li> <li><a href="function-MostrarDescuento.html">MostrarDescuento</a></li> <li><a href="function-MuestraMonedas.html">MuestraMonedas</a></li> <li><a href="function-mysql_to_unix.html" class="invalid">mysql_to_unix</a></li> <li><a href="function-nbs.html" class="invalid">nbs</a></li> <li><a href="function-nice_date.html">nice_date</a></li> <li><a href="function-nl2br_except_pre.html" class="invalid">nl2br_except_pre</a></li> <li><a href="function-Notice.html">Notice</a></li> <li><a href="function-now.html" class="invalid">now</a></li> <li><a href="function-octal_permissions.html" class="invalid">octal_permissions</a></li> <li><a href="function-odbc_fetch_array.html">odbc_fetch_array</a></li> <li><a href="function-odbc_fetch_object.html">odbc_fetch_object</a></li> <li><a href="function-ol.html" class="invalid">ol</a></li> <li><a href="function-parse_smileys.html" class="invalid">parse_smileys</a></li> <li><a href="function-password_get_info.html">password_get_info</a></li> <li><a href="function-password_hash.html">password_hash</a></li> <li><a href="function-password_needs_rehash.html">password_needs_rehash</a></li> <li><a href="function-password_verify.html">password_verify</a></li> <li><a href="function-PclZipUtilCopyBlock.html">PclZipUtilCopyBlock</a></li> <li><a href="function-PclZipUtilOptionText.html">PclZipUtilOptionText</a></li> <li><a href="function-PclZipUtilPathInclusion.html">PclZipUtilPathInclusion</a></li> <li><a href="function-PclZipUtilPathReduction.html">PclZipUtilPathReduction</a></li> <li><a href="function-PclZipUtilRename.html">PclZipUtilRename</a></li> <li><a href="function-PclZipUtilTranslateWinPath.html">PclZipUtilTranslateWinPath</a></li> <li><a href="function-plural.html" class="invalid">plural</a></li> <li><a href="function-prep_url.html" class="invalid">prep_url</a></li> <li><a href="function-quoted_printable_encode.html">quoted_printable_encode</a></li> <li><a href="function-quotes_to_entities.html" class="invalid">quotes_to_entities</a></li> <li><a href="function-random_element.html" class="invalid">random_element</a></li> <li><a href="function-random_string.html" class="invalid">random_string</a></li> <li><a href="function-read_file.html" class="invalid">read_file</a></li> <li><a href="function-redirect.html" class="invalid">redirect</a></li> <li><a href="function-reduce_double_slashes.html" class="invalid">reduce_double_slashes</a></li> <li><a href="function-reduce_multiples.html" class="invalid">reduce_multiples</a></li> <li><a href="function-remove_invisible_characters.html" class="invalid">remove_invisible_characters</a></li> <li><a href="function-repeater.html" class="invalid">repeater</a></li> <li><a href="function-safe_mailto.html" class="invalid">safe_mailto</a></li> <li><a href="function-sanitize_filename.html" class="invalid">sanitize_filename</a></li> <li><a href="function-SaveToFile.html">SaveToFile</a></li> <li><a href="function-send_email.html" class="invalid">send_email</a></li> <li><a href="function-SesionIniciadaCheck.html">SesionIniciadaCheck</a></li> <li><a href="function-set_checkbox.html" class="invalid">set_checkbox</a></li> <li><a href="function-set_cookie.html" class="invalid">set_cookie</a></li> <li><a href="function-set_radio.html" class="invalid">set_radio</a></li> <li><a href="function-set_realpath.html" class="invalid">set_realpath</a></li> <li><a href="function-set_select.html" class="invalid">set_select</a></li> <li><a href="function-set_status_header.html" class="invalid">set_status_header</a></li> <li><a href="function-set_value.html" class="invalid">set_value</a></li> <li><a href="function-show_404.html" class="invalid">show_404</a></li> <li><a href="function-show_error.html" class="invalid">show_error</a></li> <li><a href="function-singular.html" class="invalid">singular</a></li> <li><a href="function-site_url.html" class="invalid">site_url</a></li> <li><a href="function-smiley_js.html" class="invalid">smiley_js</a></li> <li><a href="function-standard_date.html" class="invalid">standard_date</a></li> <li><a href="function-strip_image_tags.html" class="invalid">strip_image_tags</a></li> <li><a href="function-strip_quotes.html" class="invalid">strip_quotes</a></li> <li><a href="function-strip_slashes.html" class="invalid">strip_slashes</a></li> <li><a href="function-symbolic_permissions.html" class="invalid">symbolic_permissions</a></li> <li><a href="function-timespan.html" class="invalid">timespan</a></li> <li><a href="function-timezone_menu.html" class="invalid">timezone_menu</a></li> <li><a href="function-timezones.html" class="invalid">timezones</a></li> <li><a href="function-transpose.html">transpose</a></li> <li><a href="function-trim_slashes.html" class="invalid">trim_slashes</a></li> <li><a href="function-ul.html" class="invalid">ul</a></li> <li><a href="function-underscore.html" class="invalid">underscore</a></li> <li><a href="function-unix_to_human.html" class="invalid">unix_to_human</a></li> <li><a href="function-uri_string.html" class="invalid">uri_string</a></li> <li><a href="function-url_title.html" class="invalid">url_title</a></li> <li><a href="function-valid_email.html" class="invalid">valid_email</a></li> <li><a href="function-validation_errors.html" class="invalid">validation_errors</a></li> <li><a href="function-Warning.html">Warning</a></li> <li><a href="function-word_censor.html" class="invalid">word_censor</a></li> <li><a href="function-word_limiter.html" class="invalid">word_limiter</a></li> <li><a href="function-word_wrap.html" class="invalid">word_wrap</a></li> <li><a href="function-write_file.html" class="invalid">write_file</a></li> <li><a href="function-xml_convert.html" class="invalid">xml_convert</a></li> <li><a href="function-xss_clean.html" class="invalid">xss_clean</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <form id="search"> <input type="hidden" name="cx" value=""> <input type="hidden" name="ie" value="UTF-8"> <input type="text" name="q" class="text" placeholder="Search"> </form> <div id="navigation"> <ul> <li> <a href="index.html" title="Overview"><span>Overview</span></a> </li> <li> <a href="namespace-None.html" title="Summary of None"><span>Namespace</span></a> </li> <li class="active"> <span>Class</span> </li> </ul> <ul> <li> <a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a> </li> </ul> <ul> </ul> </div> <div id="content" class="class"> <h1>Class XML_RPC_Message</h1> <div class="invalid"> <p> Documentation of this class could not be generated. </p> <p> Class was originally declared in Otros/Agregador_Tiendas/system/libraries/Xmlrpc.php and is invalid because of: </p> <ul> </ul> </div> </div> <div id="footer"> Practica2_Servidor API documentation generated by <a href="http://apigen.org">ApiGen</a> </div> </div> </div> <script src="resources/combined.js"></script> <script src="elementlist.js"></script> </body> </html>
{'content_hash': '48b2a1331b57cc634b1b32eb37a87286', 'timestamp': '', 'source': 'github', 'line_count': 787, 'max_line_length': 159, 'avg_line_length': 71.01143583227446, 'alnum_prop': 0.6867372866191891, 'repo_name': 'isacm94/Practica2_Servidor', 'id': '55aeef19a40ed7ddb4d5cc920160bf1881531afe', 'size': '55886', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/class-XML_RPC_Message.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '266'}, {'name': 'CSS', 'bytes': '92316'}, {'name': 'HTML', 'bytes': '8301247'}, {'name': 'JavaScript', 'bytes': '72095'}, {'name': 'PHP', 'bytes': '3199138'}]}
package org.fcrepo.kernel.utils; import static com.hp.hpl.jena.rdf.model.ModelFactory.createDefaultModel; import static com.hp.hpl.jena.rdf.model.ResourceFactory.createResource; import static com.hp.hpl.jena.vocabulary.RDF.type; import static javax.jcr.PropertyType.STRING; import static javax.jcr.PropertyType.URI; import static org.fcrepo.kernel.RdfLexicon.COULD_NOT_STORE_PROPERTY; import static org.fcrepo.kernel.RdfLexicon.RESTAPI_NAMESPACE; import static org.fcrepo.kernel.utils.TestHelpers.setField; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.slf4j.LoggerFactory.getLogger; import java.util.Collections; import java.util.Map; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Workspace; import javax.jcr.nodetype.NodeTypeManager; import org.fcrepo.kernel.rdf.GraphSubjects; import org.fcrepo.kernel.rdf.JcrRdfTools; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.slf4j.Logger; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; @RunWith(PowerMockRunner.class) @PowerMockIgnore({"org.slf4j.*", "javax.xml.parsers.*", "org.apache.xerces.*"}) @PrepareForTest({JcrRdfTools.class}) public class JcrPropertyStatementListenerTest { private static final Logger LOGGER = getLogger(JcrPropertyStatementListenerTest.class); private JcrPropertyStatementListener testObj; @Mock private Node mockNode; @Mock private Session mockSession; @Mock private GraphSubjects mockSubjects; @Mock private Statement mockStatement; @Mock private Resource mockSubject; @Mock private Property mockPredicate; @Mock private Node mockSubjectNode; @Mock private Model mockProblems; @Mock private JcrRdfTools mockJcrRdfTools; @Mock private Workspace mockWorkspace; @Mock private NodeTypeManager mockNodeTypeManager; @Mock private Model mockModel; private Map<String, String> mockNsMapping = Collections.emptyMap(); @Mock private NodePropertiesTools mockPropertiesTools; @Before public void setUp() throws RepositoryException, NoSuchFieldException { initMocks(this); mockStatic(JcrRdfTools.class); when(JcrRdfTools.withContext(mockSubjects, mockSession)).thenReturn(mockJcrRdfTools); when(mockNode.getSession()).thenReturn(mockSession); testObj = JcrPropertyStatementListener.getListener(mockSubjects, mockSession, mockProblems); when(mockStatement.getSubject()).thenReturn(mockSubject); when(mockStatement.getPredicate()).thenReturn(mockPredicate); setField(testObj, "propertiesTools", mockPropertiesTools); when(mockStatement.getModel()).thenReturn(mockModel); when(mockModel.getNsPrefixMap()).thenReturn(mockNsMapping); } @Test public void testAddedIrrelevantStatement() throws RepositoryException { when(mockSubjects.isFedoraGraphSubject(mockSubject)).thenReturn(false); testObj.addedStatement(mockStatement); // this was ignored, but not a problem verify(mockProblems, never()).add(any(Resource.class), any(Property.class), any(String.class)); } @Test public void testAddedProhibitedStatement() throws RepositoryException { mockStatic(JcrRdfTools.class); when(mockSubjects.isFedoraGraphSubject(mockSubject)).thenReturn(true); when(mockSubjects.getNodeFromGraphSubject(mockSubject)) .thenReturn(mockSubjectNode); when(mockJcrRdfTools.isInternalProperty(mockSubjectNode, mockPredicate)).thenReturn(true); when(mockPredicate.getURI()).thenReturn("x"); testObj.addedStatement(mockStatement); verify(mockProblems).add(any(Resource.class), eq(COULD_NOT_STORE_PROPERTY), eq("x")); } @Test public void testAddedStatement() throws RepositoryException { mockStatic(JcrRdfTools.class); when(mockSubjects.isFedoraGraphSubject(mockSubject)).thenReturn(true); when(mockSubjects.getNodeFromGraphSubject(mockSubject)) .thenReturn(mockSubjectNode); final String mockPropertyName = "mock:property"; when( mockJcrRdfTools.getPropertyNameFromPredicate(mockSubjectNode, mockPredicate, mockNsMapping)).thenReturn( mockPropertyName); when(mockPropertiesTools.getPropertyType(mockSubjectNode, mockPropertyName)) .thenReturn(STRING); testObj.addedStatement(mockStatement); verify(mockProblems, times(0)).add(any(Resource.class), any(Property.class), any(String.class)); LOGGER.debug("Finished testAddedStatement()"); } @Test(expected = RuntimeException.class) public void testAddedStatementRepositoryException() throws RepositoryException { mockStatic(JcrRdfTools.class); when(mockSubjects.isFedoraGraphSubject(mockSubject)).thenReturn(true); when(mockSubjects.getNodeFromGraphSubject(mockSubject)) .thenReturn(mockSubjectNode); when(mockJcrRdfTools.getPropertyNameFromPredicate(mockSubjectNode, mockPredicate, mockNsMapping)) .thenThrow(new RepositoryException()); testObj.addedStatement(mockStatement); verify(mockProblems, times(0)).add(any(Resource.class), any(Property.class), any(String.class)); } @Test public void testRemovedStatement() throws RepositoryException { mockStatic(JcrRdfTools.class); when(mockSubjects.isFedoraGraphSubject(mockSubject)).thenReturn(true); when(mockSubjects.getNodeFromGraphSubject(mockSubject)) .thenReturn(mockSubjectNode); final String mockPropertyName = "mock:property"; when(mockJcrRdfTools.getPropertyNameFromPredicate(mockSubjectNode, mockPredicate)) .thenReturn(mockPropertyName); when(mockSubjectNode.hasProperty(mockPropertyName)).thenReturn(true); when(mockPropertiesTools.getPropertyType(mockSubjectNode, mockPropertyName)).thenReturn( STRING); testObj.removedStatement(mockStatement); verify(mockProblems, times(0)).add(any(Resource.class), any(Property.class), any(String.class)); } @Test(expected = RuntimeException.class) public void testRemovedStatementRepositoryException() throws RepositoryException { mockStatic(JcrRdfTools.class); when(mockSubjects.isFedoraGraphSubject(mockSubject)).thenReturn(true); when(mockSubjects.getNodeFromGraphSubject(mockSubject)) .thenReturn(mockSubjectNode); when(mockJcrRdfTools.getPropertyNameFromPredicate(mockSubjectNode, mockPredicate)) .thenThrow(new RepositoryException()); testObj.removedStatement(mockStatement); verify(mockProblems, times(0)).add(any(Resource.class), any(Property.class), any(String.class)); } @Test public void testRemovedProhibitedStatement() throws RepositoryException { mockStatic(JcrRdfTools.class); when(mockSubjects.isFedoraGraphSubject(mockSubject)).thenReturn(true); when(mockSubjects.getNodeFromGraphSubject(mockSubject)) .thenReturn(mockSubjectNode); when(mockPredicate.getURI()).thenReturn("x"); final String mockPropertyName = "jcr:property"; when(mockJcrRdfTools.getPropertyNameFromPredicate(mockSubjectNode, mockPredicate)) .thenReturn(mockPropertyName); when(mockJcrRdfTools.isInternalProperty(mockSubjectNode, mockPredicate)).thenReturn(true); when(mockSubjectNode.hasProperty(mockPropertyName)).thenReturn(true); when(mockPropertiesTools.getPropertyType(mockSubjectNode, mockPropertyName)).thenReturn( STRING); testObj.removedStatement(mockStatement); verify(mockProblems).add(any(Resource.class), eq(COULD_NOT_STORE_PROPERTY), eq("x")); } @Test public void testRemovedIrrelevantStatement() throws RepositoryException { when(mockSubjects.isFedoraGraphSubject(mockSubject)).thenReturn(false); testObj.removedStatement(mockStatement); // this was ignored, but not a problem verify(mockProblems, times(0)).add(any(Resource.class), any(Property.class), any(String.class)); } @Test public void testAddRdfType() throws RepositoryException { final Resource resource = createResource(); when(mockSubjects.isFedoraGraphSubject(resource)).thenReturn(true); when(mockSubjects.getNodeFromGraphSubject(resource)) .thenReturn(mockSubjectNode); when(mockSubjectNode.getSession()).thenReturn(mockSession); when(mockSession.getWorkspace()).thenReturn(mockWorkspace); when(mockWorkspace.getNodeTypeManager()).thenReturn(mockNodeTypeManager); when(mockNodeTypeManager.hasNodeType("fedora:object")).thenReturn(true); when(mockSession.getNamespacePrefix(RESTAPI_NAMESPACE)) .thenReturn("fedora"); final Model model = ModelFactory.createDefaultModel(); model.add(resource, type, model.createResource(RESTAPI_NAMESPACE + "object")); when(mockSubjectNode.canAddMixin("fedora:object")).thenReturn(true); testObj.addedStatements(model); verify(mockSubjectNode).addMixin("fedora:object"); } @Test public void testRemoveRdfType() throws RepositoryException { final Resource resource = createResource(); when(mockSubjects.isFedoraGraphSubject(resource)).thenReturn(true); when(mockSubjects.getNodeFromGraphSubject(resource)) .thenReturn(mockSubjectNode); when(mockSubjectNode.getSession()).thenReturn(mockSession); when(mockSession.getWorkspace()).thenReturn(mockWorkspace); when(mockWorkspace.getNodeTypeManager()).thenReturn(mockNodeTypeManager); when(mockNodeTypeManager.hasNodeType("fedora:object")).thenReturn(true); when(mockSession.getNamespacePrefix(RESTAPI_NAMESPACE)).thenReturn( "fedora"); final Model model = createDefaultModel(); model.add(resource, type, model.createResource(RESTAPI_NAMESPACE+"object")); testObj.removedStatements(model); verify(mockSubjectNode).removeMixin("fedora:object"); } @Test public void testAddRdfTypeForNonMixin() throws RepositoryException { final Resource resource = createResource(); when(mockSubjects.isFedoraGraphSubject(resource)).thenReturn(true); when(mockSubjects.getNodeFromGraphSubject(resource)) .thenReturn(mockSubjectNode); when(mockSubjectNode.getSession()).thenReturn(mockSession); when(mockSession.getWorkspace()).thenReturn(mockWorkspace); when(mockWorkspace.getNodeTypeManager()).thenReturn(mockNodeTypeManager); when(mockNodeTypeManager.hasNodeType("fedora:object")).thenReturn(false); when(mockPropertiesTools.getPropertyType(mockSubjectNode, "rdf:type")) .thenReturn(URI); when(mockSession.getNamespacePrefix(RESTAPI_NAMESPACE)) .thenReturn("fedora"); final Model model = createDefaultModel(); model.add(resource, type, model.createResource(RESTAPI_NAMESPACE+"object")); when(mockSubjectNode.canAddMixin("fedora:object")).thenReturn(true); testObj.addedStatements(model); verify(mockSubjectNode, never()).addMixin("fedora:object"); verify(mockProblems, times(0)).add(any(Resource.class), any(Property.class), any(String.class)); } @Test public void testRemoveRdfTypeForNonMixin() throws RepositoryException { final Resource resource = createResource(); when(mockSubjects.isFedoraGraphSubject(resource)).thenReturn(true); when(mockSubjects.getNodeFromGraphSubject(resource)) .thenReturn(mockSubjectNode); when(mockSubjectNode.getSession()).thenReturn(mockSession); when(mockSession.getWorkspace()).thenReturn(mockWorkspace); when(mockWorkspace.getNodeTypeManager()).thenReturn(mockNodeTypeManager); when(mockNodeTypeManager.hasNodeType("fedora:object")).thenReturn(false); when(mockSession.getNamespacePrefix(RESTAPI_NAMESPACE)).thenReturn("fedora"); final Model model = createDefaultModel(); model.add(resource, type, model.createResource(RESTAPI_NAMESPACE+"object")); testObj.removedStatements(model); verify(mockSubjectNode, never()).removeMixin("fedora:object"); verify(mockProblems, times(0)).add(any(Resource.class), any(Property.class), any(String.class)); } }
{'content_hash': '8e1ec500e0aa562ba35309836fdf0e84', 'timestamp': '', 'source': 'github', 'line_count': 315, 'max_line_length': 105, 'avg_line_length': 42.542857142857144, 'alnum_prop': 0.7253190060443251, 'repo_name': 'barmintor/fcrepo4', 'id': '10c2b885a137744a93dff2722eccf4975f67fb95', 'size': '14000', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'fcrepo-kernel/src/test/java/org/fcrepo/kernel/utils/JcrPropertyStatementListenerTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '837'}, {'name': 'Java', 'bytes': '1971408'}, {'name': 'JavaScript', 'bytes': '6786'}, {'name': 'XSLT', 'bytes': '0'}]}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context=".SplashActivity" > <RelativeLayout android:id="@+id/stamp_top_bar" android:layout_width="match_parent" android:layout_height="50dip" android:background="#5a5a5a" android:orientation="horizontal" > <TextView android:id="@+id/app_name" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_centerHorizontal="true" android:ellipsize="end" android:gravity="center" android:lines="1" android:text="@string/app_name" android:textColor="@android:color/white" android:textStyle="bold" /> <LinearLayout android:id="@+id/btn_close_layout" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_marginBottom="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" > <Button android:id="@+id/btn_close_stamp" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginBottom="1dp" android:gravity="center_vertical|center_horizontal" android:paddingLeft="10dp" android:paddingRight="10dp" android:textColor="@android:color/white" android:textStyle="bold" /> </LinearLayout> </RelativeLayout> <RelativeLayout android:id="@+id/stamp_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/stamp_top_bar" android:orientation="horizontal" > <HorizontalScrollView android:id="@+id/stamp_tab" android:layout_width="match_parent" android:layout_height="wrap_content" > <LinearLayout android:id="@+id/stamp_tab_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > </LinearLayout> </HorizontalScrollView> <ScrollView android:id="@+id/stamp_list" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/stamp_tab"> <LinearLayout android:id="@+id/stamp_list_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > </LinearLayout> </ScrollView> </RelativeLayout> </RelativeLayout>
{'content_hash': '7f94693fae28cde41934dc13639e188c', 'timestamp': '', 'source': 'github', 'line_count': 86, 'max_line_length': 74, 'avg_line_length': 37.47674418604651, 'alnum_prop': 0.5646912814148309, 'repo_name': 'huydx/vlcamera', 'id': 'cfc8e6bb97cd99362c0c0259220a96fae46392ad', 'size': '3223', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'res/layout/activity_stamp.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '47609'}]}
layout: post title: November Meeting&#58; Agile Panel of Coaches and Experienced Practitioners --- <p>Come and ask those hard questions. Come and have conversations with others that are practicing agile. Come and see what it is all about.</p> <p><strong>Date/Time:</strong><br /> Thursday November 15<sup>th</sup> from 11:30 - 1:00</p> <p><strong>Location:</strong><br /> Principal Financial Group<br /> 801 Grand Ave<br /> Room G-1114</p> <p>Guests will need to check in at the security desk on the north side of the building, street level.</p> <p><strong>Panel Members:</strong><br /> Susan Banks<br /> Kent McDonald<br /> Mike Prior<br /> Sangeetha Walajabad<br /> Shawn Whitmore</p>
{'content_hash': '2f681491bd6af8f324a00b00e97f924c', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 143, 'avg_line_length': 40.411764705882355, 'alnum_prop': 0.727802037845706, 'repo_name': 'agileiowa/jekyll-web', 'id': '2d11b9f944aa61ee9d42629c46fddd97c799e434', 'size': '691', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_posts/2012-11-01-november-meeting-agile-panel-of-coaches-and-experienced-practitioners.markdown', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '138774'}, {'name': 'HTML', 'bytes': '12497'}, {'name': 'JavaScript', 'bytes': '74'}, {'name': 'Ruby', 'bytes': '12330'}, {'name': 'Shell', 'bytes': '127'}]}
package com.facebook.buck.android; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.facebook.buck.dalvik.ZipSplitter; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.TestSourcePath; import com.facebook.buck.step.ExecutionContext; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.io.CharStreams; import org.easymock.EasyMock; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.objectweb.asm.tree.ClassNode; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class SplitZipStepTest { @Rule public TemporaryFolder tempDir = new TemporaryFolder(); @Test public void testMetaList() throws IOException { Path outJar = tempDir.newFile("test.jar").toPath(); ZipOutputStream zipOut = new ZipOutputStream( new BufferedOutputStream(Files.newOutputStream(outJar))); Map<String, String> fileToClassName = ImmutableMap.of( "com/facebook/foo.class", "com.facebook.foo", "bar.class", "bar"); try { for (String entry : fileToClassName.keySet()) { zipOut.putNextEntry(new ZipEntry(entry)); zipOut.write(new byte[] { 0 }); } } finally { zipOut.close(); } StringWriter stringWriter = new StringWriter(); BufferedWriter writer = new BufferedWriter(stringWriter); try { SplitZipStep.writeMetaList(writer, ImmutableList.of(outJar), DexStore.JAR); } finally { writer.close(); } List<String> lines = CharStreams.readLines(new StringReader(stringWriter.toString())); assertEquals(1, lines.size()); String line = Iterables.getFirst(lines, null); String[] data = line.split(" "); assertEquals(3, data.length); // Note that we cannot test data[1] (the hash) because zip files change their hash each // time they are written due to timestamps written into the file. assertEquals("secondary-1.dex.jar", data[0]); assertTrue(String.format("Unexpected class: %s", data[2]), fileToClassName.values().contains(data[2])); } @Test public void testRequiredInPrimaryZipPredicate() throws IOException { Path primaryDexClassesFile = Paths.get("the/manifest.txt"); List<String> linesInManifestFile = ImmutableList.of( "com/google/common/collect/ImmutableSortedSet", " com/google/common/collect/ImmutableSet", "# com/google/common/collect/ImmutableMap"); ProjectFilesystem projectFilesystem = EasyMock.createMock(ProjectFilesystem.class); EasyMock.expect(projectFilesystem.readLines(primaryDexClassesFile)) .andReturn(linesInManifestFile); SplitZipStep splitZipStep = new SplitZipStep( projectFilesystem, /* inputPathsToSplit */ ImmutableSet.<Path>of(), /* secondaryJarMetaPath */ Paths.get(""), /* primaryJarPath */ Paths.get(""), /* secondaryJarDir */ Paths.get(""), /* secondaryJarPattern */ "", /* proguardFullConfigFile */ Optional.<Path>absent(), /* proguardMappingFile */ Optional.<Path>absent(), new DexSplitMode( /* shouldSplitDex */ true, ZipSplitter.DexSplitStrategy.MAXIMIZE_PRIMARY_DEX_SIZE, DexStore.JAR, /* useLinearAllocSplitDex */ true, /* linearAllocHardLimit */ 4 * 1024 * 1024, /* primaryDexPatterns */ ImmutableSet.of("List"), Optional.<SourcePath>of(new TestSourcePath("the/manifest.txt")), /* primaryDexScenarioFile */ Optional.<SourcePath>absent(), /* isPrimaryDexScenarioOverflowAllowed */ false, /* secondaryDexHeadClassesFile */ Optional.<SourcePath>absent(), /* secondaryDexTailClassesFile */ Optional.<SourcePath>absent()), Optional.<Path>absent(), Optional.of(Paths.get("the/manifest.txt")), Optional.<Path>absent(), Optional.<Path>absent(), /* pathToReportDir */ Paths.get("")); ExecutionContext context = EasyMock.createMock(ExecutionContext.class); EasyMock.replay(projectFilesystem, context); Predicate<String> requiredInPrimaryZipPredicate = splitZipStep .createRequiredInPrimaryZipPredicate( ProguardTranslatorFactory.createForTest(Optional.<Map<String, String>>absent()), Suppliers.ofInstance(ImmutableList.<ClassNode>of())); assertTrue( "All non-.class files should be accepted.", requiredInPrimaryZipPredicate.apply("apples.txt")); assertTrue( "com/google/common/collect/ImmutableSortedSet.class is listed in the manifest verbatim.", requiredInPrimaryZipPredicate.apply("com/google/common/collect/ImmutableSortedSet.class")); assertTrue( "com/google/common/collect/ImmutableSet.class is in the manifest with whitespace.", requiredInPrimaryZipPredicate.apply("com/google/common/collect/ImmutableSet.class")); assertFalse( "com/google/common/collect/ImmutableSet.class cannot have whitespace as param.", requiredInPrimaryZipPredicate.apply(" com/google/common/collect/ImmutableSet.class")); assertFalse( "com/google/common/collect/ImmutableMap.class is commented out.", requiredInPrimaryZipPredicate.apply("com/google/common/collect/ImmutableMap.class")); assertFalse( "com/google/common/collect/Iterables.class is not even mentioned.", requiredInPrimaryZipPredicate.apply("com/google/common/collect/Iterables.class")); assertTrue( "java/awt/List.class matches the substring 'List'.", requiredInPrimaryZipPredicate.apply("java/awt/List.class")); assertFalse( "Substring matching is case-sensitive.", requiredInPrimaryZipPredicate.apply("shiny/Glistener.class")); EasyMock.verify(projectFilesystem, context); } @Test public void testRequiredInPrimaryZipPredicateWithProguard() throws IOException { List<String> linesInMappingFile = ImmutableList.of( "foo.bar.MappedPrimary -> foo.bar.a:", "foo.bar.MappedSecondary -> foo.bar.b:", "foo.bar.UnmappedPrimary -> foo.bar.UnmappedPrimary:", "foo.bar.UnmappedSecondary -> foo.bar.UnmappedSecondary:", "foo.primary.MappedPackage -> x.a:", "foo.secondary.MappedPackage -> x.b:", "foo.primary.UnmappedPackage -> foo.primary.UnmappedPackage:"); List<String> linesInManifestFile = ImmutableList.of( // Actual primary dex classes. "foo/bar/MappedPrimary", "foo/bar/UnmappedPrimary", // Red herrings! "foo/bar/b", "x/b"); Path proguardConfigFile = Paths.get("the/configuration.txt"); Path proguardMappingFile = Paths.get("the/mapping.txt"); Path primaryDexClassesFile = Paths.get("the/manifest.txt"); ProjectFilesystem projectFilesystem = EasyMock.createMock(ProjectFilesystem.class); EasyMock.expect(projectFilesystem.readLines(primaryDexClassesFile)) .andReturn(linesInManifestFile); EasyMock.expect(projectFilesystem.readLines(proguardConfigFile)) .andReturn(ImmutableList.<String>of()); EasyMock.expect(projectFilesystem.readLines(proguardMappingFile)) .andReturn(linesInMappingFile); SplitZipStep splitZipStep = new SplitZipStep( projectFilesystem, /* inputPathsToSplit */ ImmutableSet.<Path>of(), /* secondaryJarMetaPath */ Paths.get(""), /* primaryJarPath */ Paths.get(""), /* secondaryJarDir */ Paths.get(""), /* secondaryJarPattern */ "", /* proguardFullConfigFile */ Optional.of(proguardConfigFile), /* proguardMappingFile */ Optional.of(proguardMappingFile), new DexSplitMode( /* shouldSplitDex */ true, ZipSplitter.DexSplitStrategy.MAXIMIZE_PRIMARY_DEX_SIZE, DexStore.JAR, /* useLinearAllocSplitDex */ true, /* linearAllocHardLimit */ 4 * 1024 * 1024, /* primaryDexPatterns */ ImmutableSet.of("/primary/", "x/"), Optional.<SourcePath>of(new TestSourcePath("the/manifest.txt")), /* primaryDexScenarioFile */ Optional.<SourcePath>absent(), /* isPrimaryDexScenarioOverflowAllowed */ false, /* secondaryDexHeadClassesFile */ Optional.<SourcePath>absent(), /* secondaryDexTailClassesFile */ Optional.<SourcePath>absent()), Optional.<Path>absent(), Optional.of(Paths.get("the/manifest.txt")), Optional.<Path>absent(), Optional.<Path>absent(), /* pathToReportDir */ Paths.get("")); ExecutionContext context = EasyMock.createMock(ExecutionContext.class); EasyMock.replay(projectFilesystem, context); ProguardTranslatorFactory translatorFactory = ProguardTranslatorFactory.create( projectFilesystem, Optional.of(proguardConfigFile), Optional.of(proguardMappingFile)); Predicate<String> requiredInPrimaryZipPredicate = splitZipStep .createRequiredInPrimaryZipPredicate( translatorFactory, Suppliers.ofInstance(ImmutableList.<ClassNode>of())); assertTrue( "Mapped class from primary list should be in primary.", requiredInPrimaryZipPredicate.apply("foo/bar/a.class")); assertTrue( "Unmapped class from primary list should be in primary.", requiredInPrimaryZipPredicate.apply("foo/bar/UnmappedPrimary.class")); assertTrue( "Mapped class from substring should be in primary.", requiredInPrimaryZipPredicate.apply("x/a.class")); assertTrue( "Unmapped class from substring should be in primary.", requiredInPrimaryZipPredicate.apply("foo/primary/UnmappedPackage.class")); assertFalse( "Mapped class with obfuscated name match should not be in primary.", requiredInPrimaryZipPredicate.apply("foo/bar/b.class")); assertFalse( "Unmapped class name should not randomly be in primary.", requiredInPrimaryZipPredicate.apply("foo/bar/UnmappedSecondary.class")); assertFalse( "Map class with obfuscated name substring should not be in primary.", requiredInPrimaryZipPredicate.apply("x/b.class")); EasyMock.verify(projectFilesystem, context); } @Test public void testNonObfuscatedBuild() throws IOException { Path proguardConfigFile = Paths.get("the/configuration.txt"); Path proguardMappingFile = Paths.get("the/mapping.txt"); ProjectFilesystem projectFilesystem = EasyMock.createMock(ProjectFilesystem.class); EasyMock.expect(projectFilesystem.readLines(proguardConfigFile)) .andReturn(ImmutableList.of("-dontobfuscate")); SplitZipStep splitZipStep = new SplitZipStep( projectFilesystem, /* inputPathsToSplit */ ImmutableSet.<Path>of(), /* secondaryJarMetaPath */ Paths.get(""), /* primaryJarPath */ Paths.get(""), /* secondaryJarDir */ Paths.get(""), /* secondaryJarPattern */ "", /* proguardFullConfigFile */ Optional.of(proguardConfigFile), /* proguardMappingFile */ Optional.of(proguardMappingFile), new DexSplitMode( /* shouldSplitDex */ true, ZipSplitter.DexSplitStrategy.MAXIMIZE_PRIMARY_DEX_SIZE, DexStore.JAR, /* useLinearAllocSplitDex */ true, /* linearAllocHardLimit */ 4 * 1024 * 1024, /* primaryDexPatterns */ ImmutableSet.of("primary"), /* primaryDexClassesFile */ Optional.<SourcePath>absent(), /* primaryDexScenarioFile */ Optional.<SourcePath>absent(), /* isPrimaryDexScenarioOverflowAllowed */ false, /* secondaryDexHeadClassesFile */ Optional.<SourcePath>absent(), /* secondaryDexTailClassesFile */ Optional.<SourcePath>absent()), Optional.<Path>absent(), Optional.<Path>absent(), Optional.<Path>absent(), Optional.<Path>absent(), /* pathToReportDir */ Paths.get("")); ExecutionContext context = EasyMock.createMock(ExecutionContext.class); EasyMock.replay(projectFilesystem, context); ProguardTranslatorFactory translatorFactory = ProguardTranslatorFactory.create( projectFilesystem, Optional.of(proguardConfigFile), Optional.of(proguardMappingFile)); Predicate<String> requiredInPrimaryZipPredicate = splitZipStep .createRequiredInPrimaryZipPredicate( translatorFactory, Suppliers.ofInstance(ImmutableList.<ClassNode>of())); assertTrue( "Primary class should be in primary.", requiredInPrimaryZipPredicate.apply("primary.class")); assertFalse( "Secondary class should be in secondary.", requiredInPrimaryZipPredicate.apply("secondary.class")); EasyMock.verify(projectFilesystem, context); } @Test public void testClassFilePattern() { assertTrue(SplitZipStep.CLASS_FILE_PATTERN.matcher( "com/facebook/orca/threads/ParticipantInfo.class").matches()); assertTrue(SplitZipStep.CLASS_FILE_PATTERN.matcher( "com/facebook/orca/threads/ParticipantInfo$1.class").matches()); } }
{'content_hash': 'bb883e8c7295f0665a9a2feb0f30b897', 'timestamp': '', 'source': 'github', 'line_count': 314, 'max_line_length': 99, 'avg_line_length': 43.847133757961785, 'alnum_prop': 0.6938553166763509, 'repo_name': 'pwz3n0/buck', 'id': '0e5a467468e2eb1b3c6c2d80a65b58ceecceec26', 'size': '14373', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'test/com/facebook/buck/android/SplitZipStepTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '87'}, {'name': 'Batchfile', 'bytes': '683'}, {'name': 'C', 'bytes': '245856'}, {'name': 'C#', 'bytes': '237'}, {'name': 'C++', 'bytes': '3765'}, {'name': 'CSS', 'bytes': '54863'}, {'name': 'D', 'bytes': '623'}, {'name': 'DIGITAL Command Language', 'bytes': '47'}, {'name': 'Go', 'bytes': '419'}, {'name': 'Groff', 'bytes': '440'}, {'name': 'HTML', 'bytes': '4938'}, {'name': 'IDL', 'bytes': '128'}, {'name': 'Java', 'bytes': '10529834'}, {'name': 'JavaScript', 'bytes': '931231'}, {'name': 'Lex', 'bytes': '2442'}, {'name': 'Makefile', 'bytes': '1791'}, {'name': 'Matlab', 'bytes': '47'}, {'name': 'OCaml', 'bytes': '2956'}, {'name': 'Objective-C', 'bytes': '77169'}, {'name': 'Objective-C++', 'bytes': '34'}, {'name': 'PowerShell', 'bytes': '143'}, {'name': 'Python', 'bytes': '202866'}, {'name': 'Rust', 'bytes': '938'}, {'name': 'Shell', 'bytes': '31126'}, {'name': 'Smalltalk', 'bytes': '438'}, {'name': 'Yacc', 'bytes': '323'}]}
package storage import ( "strings" "testing" "golang.org/x/net/context" apiequality "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/diff" genericapirequest "k8s.io/apiserver/pkg/endpoints/request" "k8s.io/apiserver/pkg/registry/generic" "k8s.io/apiserver/pkg/registry/rest" "k8s.io/apiserver/pkg/storage" storeerr "k8s.io/apiserver/pkg/storage/errors" etcdtesting "k8s.io/apiserver/pkg/storage/etcd/testing" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/registry/registrytest" "k8s.io/kubernetes/pkg/securitycontext" ) func newStorage(t *testing.T) (*REST, *BindingREST, *StatusREST, *etcdtesting.EtcdTestServer) { etcdStorage, server := registrytest.NewEtcdStorage(t, "") restOptions := generic.RESTOptions{ StorageConfig: etcdStorage, Decorator: generic.UndecoratedStorage, DeleteCollectionWorkers: 3, ResourcePrefix: "pods", } storage := NewStorage(restOptions, nil, nil, nil) return storage.Pod, storage.Binding, storage.Status, server } func validNewPod() *api.Pod { grace := int64(30) return &api.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "foo", Namespace: metav1.NamespaceDefault, }, Spec: api.PodSpec{ RestartPolicy: api.RestartPolicyAlways, DNSPolicy: api.DNSClusterFirst, TerminationGracePeriodSeconds: &grace, Containers: []api.Container{ { Name: "foo", Image: "test", ImagePullPolicy: api.PullAlways, TerminationMessagePath: api.TerminationMessagePathDefault, TerminationMessagePolicy: api.TerminationMessageReadFile, SecurityContext: securitycontext.ValidInternalSecurityContextWithContainerDefaults(), }, }, SecurityContext: &api.PodSecurityContext{}, SchedulerName: api.DefaultSchedulerName, }, } } func validChangedPod() *api.Pod { pod := validNewPod() pod.Labels = map[string]string{ "foo": "bar", } return pod } func TestCreate(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() test := registrytest.New(t, storage.Store) pod := validNewPod() pod.ObjectMeta = metav1.ObjectMeta{} // Make an invalid pod with an an incorrect label. invalidPod := validNewPod() invalidPod.Namespace = test.TestNamespace() invalidPod.Labels = map[string]string{ "invalid/label/to/cause/validation/failure": "bar", } test.TestCreate( // valid pod, // invalid (empty contains list) &api.Pod{ Spec: api.PodSpec{ Containers: []api.Container{}, }, }, // invalid (invalid labels) invalidPod, ) } func TestUpdate(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() test := registrytest.New(t, storage.Store) test.TestUpdate( // valid validNewPod(), // updateFunc func(obj runtime.Object) runtime.Object { object := obj.(*api.Pod) object.Labels = map[string]string{"a": "b"} return object }, ) } func TestDelete(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() test := registrytest.New(t, storage.Store).ReturnDeletedObject() test.TestDelete(validNewPod()) scheduledPod := validNewPod() scheduledPod.Spec.NodeName = "some-node" test.TestDeleteGraceful(scheduledPod, 30) } type FailDeletionStorage struct { storage.Interface Called *bool } func (f FailDeletionStorage) Delete(ctx context.Context, key string, out runtime.Object, precondition *storage.Preconditions) error { *f.Called = true return storage.NewKeyNotFoundError(key, 0) } func newFailDeleteStorage(t *testing.T, called *bool) (*REST, *etcdtesting.EtcdTestServer) { etcdStorage, server := registrytest.NewEtcdStorage(t, "") restOptions := generic.RESTOptions{ StorageConfig: etcdStorage, Decorator: generic.UndecoratedStorage, DeleteCollectionWorkers: 3, ResourcePrefix: "pods", } storage := NewStorage(restOptions, nil, nil, nil) storage.Pod.Store.Storage = FailDeletionStorage{storage.Pod.Store.Storage, called} return storage.Pod, server } func TestIgnoreDeleteNotFound(t *testing.T) { pod := validNewPod() testContext := genericapirequest.WithNamespace(genericapirequest.NewContext(), metav1.NamespaceDefault) called := false registry, server := newFailDeleteStorage(t, &called) defer server.Terminate(t) defer registry.Store.DestroyFunc() // should fail if pod A is not created yet. _, err := registry.Delete(testContext, pod.Name, nil) if !errors.IsNotFound(err) { t.Errorf("Unexpected error: %v", err) } // create pod _, err = registry.Create(testContext, pod) if err != nil { t.Errorf("Unexpected error: %v", err) } // delete object with grace period 0, storage will return NotFound, but the // registry shouldn't get any error since we ignore the NotFound error. zero := int64(0) opt := &metav1.DeleteOptions{GracePeriodSeconds: &zero} obj, err := registry.Delete(testContext, pod.Name, opt) if err != nil { t.Fatalf("Unexpected error: %v", err) } if !called { t.Fatalf("expect the overriding Delete method to be called") } deletedPod, ok := obj.(*api.Pod) if !ok { t.Fatalf("expect a pod is returned") } if deletedPod.DeletionTimestamp == nil { t.Errorf("expect the DeletionTimestamp to be set") } if deletedPod.DeletionGracePeriodSeconds == nil { t.Fatalf("expect the DeletionGracePeriodSeconds to be set") } if *deletedPod.DeletionGracePeriodSeconds != 0 { t.Errorf("expect the DeletionGracePeriodSeconds to be 0, got %d", *deletedPod.DeletionTimestamp) } } func TestCreateSetsFields(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() pod := validNewPod() _, err := storage.Create(genericapirequest.NewDefaultContext(), pod) if err != nil { t.Fatalf("unexpected error: %v", err) } ctx := genericapirequest.NewDefaultContext() object, err := storage.Get(ctx, "foo", &metav1.GetOptions{}) if err != nil { t.Errorf("unexpected error: %v", err) } actual := object.(*api.Pod) if actual.Name != pod.Name { t.Errorf("unexpected pod: %#v", actual) } if len(actual.UID) == 0 { t.Errorf("expected pod UID to be set: %#v", actual) } } func TestResourceLocation(t *testing.T) { expectedIP := "1.2.3.4" testCases := []struct { pod api.Pod query string location string }{ { pod: api.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Status: api.PodStatus{PodIP: expectedIP}, }, query: "foo", location: expectedIP, }, { pod: api.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Status: api.PodStatus{PodIP: expectedIP}, }, query: "foo:12345", location: expectedIP + ":12345", }, { pod: api.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "ctr"}, }, }, Status: api.PodStatus{PodIP: expectedIP}, }, query: "foo", location: expectedIP, }, { pod: api.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "ctr", Ports: []api.ContainerPort{{ContainerPort: 9376}}}, }, }, Status: api.PodStatus{PodIP: expectedIP}, }, query: "foo", location: expectedIP + ":9376", }, { pod: api.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "ctr", Ports: []api.ContainerPort{{ContainerPort: 9376}}}, }, }, Status: api.PodStatus{PodIP: expectedIP}, }, query: "foo:12345", location: expectedIP + ":12345", }, { pod: api.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "ctr1"}, {Name: "ctr2", Ports: []api.ContainerPort{{ContainerPort: 9376}}}, }, }, Status: api.PodStatus{PodIP: expectedIP}, }, query: "foo", location: expectedIP + ":9376", }, { pod: api.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "ctr1", Ports: []api.ContainerPort{{ContainerPort: 9376}}}, {Name: "ctr2", Ports: []api.ContainerPort{{ContainerPort: 1234}}}, }, }, Status: api.PodStatus{PodIP: expectedIP}, }, query: "foo", location: expectedIP + ":9376", }, } ctx := genericapirequest.NewDefaultContext() for _, tc := range testCases { storage, _, _, server := newStorage(t) key, _ := storage.KeyFunc(ctx, tc.pod.Name) if err := storage.Storage.Create(ctx, key, &tc.pod, nil, 0); err != nil { t.Fatalf("unexpected error: %v", err) } redirector := rest.Redirector(storage) location, _, err := redirector.ResourceLocation(genericapirequest.NewDefaultContext(), tc.query) if err != nil { t.Errorf("Unexpected error: %v", err) } if location == nil { t.Errorf("Unexpected nil: %v", location) } if location.Scheme != "" { t.Errorf("Expected '%v', but got '%v'", "", location.Scheme) } if location.Host != tc.location { t.Errorf("Expected %v, but got %v", tc.location, location.Host) } server.Terminate(t) } } func TestGet(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() test := registrytest.New(t, storage.Store) test.TestGet(validNewPod()) } func TestList(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() test := registrytest.New(t, storage.Store) test.TestList(validNewPod()) } func TestWatch(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() test := registrytest.New(t, storage.Store) test.TestWatch( validNewPod(), // matching labels []labels.Set{}, // not matching labels []labels.Set{ {"foo": "bar"}, }, // matching fields []fields.Set{ {"metadata.name": "foo"}, }, // not matchin fields []fields.Set{ {"metadata.name": "bar"}, }, ) } func TestEtcdCreate(t *testing.T) { storage, bindingStorage, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() ctx := genericapirequest.NewDefaultContext() _, err := storage.Create(ctx, validNewPod()) if err != nil { t.Fatalf("unexpected error: %v", err) } // Suddenly, a wild scheduler appears: _, err = bindingStorage.Create(ctx, &api.Binding{ ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceDefault, Name: "foo"}, Target: api.ObjectReference{Name: "machine"}, }) if err != nil { t.Fatalf("unexpected error: %v", err) } _, err = storage.Get(ctx, "foo", &metav1.GetOptions{}) if err != nil { t.Fatalf("Unexpected error %v", err) } } // Ensure that when scheduler creates a binding for a pod that has already been deleted // by the API server, API server returns not-found error. func TestEtcdCreateBindingNoPod(t *testing.T) { storage, bindingStorage, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() ctx := genericapirequest.NewDefaultContext() // Assume that a pod has undergone the following: // - Create (apiserver) // - Schedule (scheduler) // - Delete (apiserver) _, err := bindingStorage.Create(ctx, &api.Binding{ ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceDefault, Name: "foo"}, Target: api.ObjectReference{Name: "machine"}, }) if err == nil { t.Fatalf("Expected not-found-error but got nothing") } if !errors.IsNotFound(storeerr.InterpretGetError(err, api.Resource("pods"), "foo")) { t.Fatalf("Unexpected error returned: %#v", err) } _, err = storage.Get(ctx, "foo", &metav1.GetOptions{}) if err == nil { t.Fatalf("Expected not-found-error but got nothing") } if !errors.IsNotFound(storeerr.InterpretGetError(err, api.Resource("pods"), "foo")) { t.Fatalf("Unexpected error: %v", err) } } func TestEtcdCreateFailsWithoutNamespace(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() pod := validNewPod() pod.Namespace = "" _, err := storage.Create(genericapirequest.NewContext(), pod) // Accept "namespace" or "Namespace". if err == nil || !strings.Contains(err.Error(), "amespace") { t.Fatalf("expected error that namespace was missing from context, got: %v", err) } } func TestEtcdCreateWithContainersNotFound(t *testing.T) { storage, bindingStorage, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() ctx := genericapirequest.NewDefaultContext() _, err := storage.Create(ctx, validNewPod()) if err != nil { t.Fatalf("unexpected error: %v", err) } // Suddenly, a wild scheduler appears: _, err = bindingStorage.Create(ctx, &api.Binding{ ObjectMeta: metav1.ObjectMeta{ Namespace: metav1.NamespaceDefault, Name: "foo", Annotations: map[string]string{"label1": "value1"}, }, Target: api.ObjectReference{Name: "machine"}, }) if err != nil { t.Fatalf("unexpected error: %v", err) } obj, err := storage.Get(ctx, "foo", &metav1.GetOptions{}) if err != nil { t.Fatalf("Unexpected error %v", err) } pod := obj.(*api.Pod) if !(pod.Annotations != nil && pod.Annotations["label1"] == "value1") { t.Fatalf("Pod annotations don't match the expected: %v", pod.Annotations) } } func TestEtcdCreateWithConflict(t *testing.T) { storage, bindingStorage, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() ctx := genericapirequest.NewDefaultContext() _, err := storage.Create(ctx, validNewPod()) if err != nil { t.Fatalf("unexpected error: %v", err) } // Suddenly, a wild scheduler appears: binding := api.Binding{ ObjectMeta: metav1.ObjectMeta{ Namespace: metav1.NamespaceDefault, Name: "foo", Annotations: map[string]string{"label1": "value1"}, }, Target: api.ObjectReference{Name: "machine"}, } _, err = bindingStorage.Create(ctx, &binding) if err != nil { t.Fatalf("unexpected error: %v", err) } _, err = bindingStorage.Create(ctx, &binding) if err == nil || !errors.IsConflict(err) { t.Fatalf("expected resource conflict error, not: %v", err) } } func TestEtcdCreateWithExistingContainers(t *testing.T) { storage, bindingStorage, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() ctx := genericapirequest.NewDefaultContext() _, err := storage.Create(ctx, validNewPod()) if err != nil { t.Fatalf("unexpected error: %v", err) } // Suddenly, a wild scheduler appears: _, err = bindingStorage.Create(ctx, &api.Binding{ ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceDefault, Name: "foo"}, Target: api.ObjectReference{Name: "machine"}, }) if err != nil { t.Fatalf("unexpected error: %v", err) } _, err = storage.Get(ctx, "foo", &metav1.GetOptions{}) if err != nil { t.Fatalf("Unexpected error %v", err) } } func TestEtcdCreateBinding(t *testing.T) { ctx := genericapirequest.NewDefaultContext() testCases := map[string]struct { binding api.Binding errOK func(error) bool }{ "noName": { binding: api.Binding{ ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceDefault, Name: "foo"}, Target: api.ObjectReference{}, }, errOK: func(err error) bool { return err != nil }, }, "badKind": { binding: api.Binding{ ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceDefault, Name: "foo"}, Target: api.ObjectReference{Name: "machine1", Kind: "unknown"}, }, errOK: func(err error) bool { return err != nil }, }, "emptyKind": { binding: api.Binding{ ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceDefault, Name: "foo"}, Target: api.ObjectReference{Name: "machine2"}, }, errOK: func(err error) bool { return err == nil }, }, "kindNode": { binding: api.Binding{ ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceDefault, Name: "foo"}, Target: api.ObjectReference{Name: "machine3", Kind: "Node"}, }, errOK: func(err error) bool { return err == nil }, }, } for k, test := range testCases { storage, bindingStorage, _, server := newStorage(t) if _, err := storage.Create(ctx, validNewPod()); err != nil { t.Fatalf("%s: unexpected error: %v", k, err) } if _, err := bindingStorage.Create(ctx, &test.binding); !test.errOK(err) { t.Errorf("%s: unexpected error: %v", k, err) } else if err == nil { // If bind succeeded, verify Host field in pod's Spec. pod, err := storage.Get(ctx, validNewPod().ObjectMeta.Name, &metav1.GetOptions{}) if err != nil { t.Errorf("%s: unexpected error: %v", k, err) } else if pod.(*api.Pod).Spec.NodeName != test.binding.Target.Name { t.Errorf("%s: expected: %v, got: %v", k, pod.(*api.Pod).Spec.NodeName, test.binding.Target.Name) } } storage.Store.DestroyFunc() server.Terminate(t) } } func TestEtcdUpdateNotScheduled(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() ctx := genericapirequest.NewDefaultContext() if _, err := storage.Create(ctx, validNewPod()); err != nil { t.Fatalf("unexpected error: %v", err) } podIn := validChangedPod() _, _, err := storage.Update(ctx, podIn.Name, rest.DefaultUpdatedObjectInfo(podIn, api.Scheme)) if err != nil { t.Errorf("Unexpected error: %v", err) } obj, err := storage.Get(ctx, validNewPod().ObjectMeta.Name, &metav1.GetOptions{}) if err != nil { t.Errorf("unexpected error: %v", err) } podOut := obj.(*api.Pod) // validChangedPod only changes the Labels, so were checking the update was valid if !apiequality.Semantic.DeepEqual(podIn.Labels, podOut.Labels) { t.Errorf("objects differ: %v", diff.ObjectDiff(podOut, podIn)) } } func TestEtcdUpdateScheduled(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() ctx := genericapirequest.NewDefaultContext() key, _ := storage.KeyFunc(ctx, "foo") err := storage.Storage.Create(ctx, key, &api.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "foo", Namespace: metav1.NamespaceDefault, }, Spec: api.PodSpec{ NodeName: "machine", Containers: []api.Container{ { Name: "foobar", Image: "foo:v1", SecurityContext: securitycontext.ValidInternalSecurityContextWithContainerDefaults(), }, }, SecurityContext: &api.PodSecurityContext{}, SchedulerName: api.DefaultSchedulerName, }, }, nil, 1) if err != nil { t.Errorf("Unexpected error: %v", err) } grace := int64(30) podIn := api.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "foo", Labels: map[string]string{ "foo": "bar", }, }, Spec: api.PodSpec{ NodeName: "machine", Containers: []api.Container{{ Name: "foobar", Image: "foo:v2", ImagePullPolicy: api.PullIfNotPresent, TerminationMessagePath: api.TerminationMessagePathDefault, TerminationMessagePolicy: api.TerminationMessageReadFile, SecurityContext: securitycontext.ValidInternalSecurityContextWithContainerDefaults(), }}, RestartPolicy: api.RestartPolicyAlways, DNSPolicy: api.DNSClusterFirst, TerminationGracePeriodSeconds: &grace, SecurityContext: &api.PodSecurityContext{}, SchedulerName: api.DefaultSchedulerName, }, } _, _, err = storage.Update(ctx, podIn.Name, rest.DefaultUpdatedObjectInfo(&podIn, api.Scheme)) if err != nil { t.Errorf("Unexpected error: %v", err) } obj, err := storage.Get(ctx, "foo", &metav1.GetOptions{}) if err != nil { t.Errorf("Unexpected error: %v", err) } podOut := obj.(*api.Pod) // Check to verify the Spec and Label updates match from change above. Those are the fields changed. if !apiequality.Semantic.DeepEqual(podOut.Spec, podIn.Spec) || !apiequality.Semantic.DeepEqual(podOut.Labels, podIn.Labels) { t.Errorf("objects differ: %v", diff.ObjectDiff(podOut, podIn)) } } func TestEtcdUpdateStatus(t *testing.T) { storage, _, statusStorage, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() ctx := genericapirequest.NewDefaultContext() key, _ := storage.KeyFunc(ctx, "foo") podStart := api.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "foo", Namespace: metav1.NamespaceDefault, }, Spec: api.PodSpec{ NodeName: "machine", Containers: []api.Container{ { Image: "foo:v1", SecurityContext: securitycontext.ValidInternalSecurityContextWithContainerDefaults(), }, }, SecurityContext: &api.PodSecurityContext{}, SchedulerName: api.DefaultSchedulerName, }, } err := storage.Storage.Create(ctx, key, &podStart, nil, 0) if err != nil { t.Errorf("unexpected error: %v", err) } podIn := api.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "foo", Labels: map[string]string{ "foo": "bar", }, }, Spec: api.PodSpec{ NodeName: "machine", Containers: []api.Container{ { Image: "foo:v2", ImagePullPolicy: api.PullIfNotPresent, TerminationMessagePath: api.TerminationMessagePathDefault, }, }, SecurityContext: &api.PodSecurityContext{}, SchedulerName: api.DefaultSchedulerName, }, Status: api.PodStatus{ Phase: api.PodRunning, PodIP: "127.0.0.1", Message: "is now scheduled", }, } expected := podStart expected.ResourceVersion = "2" grace := int64(30) expected.Spec.TerminationGracePeriodSeconds = &grace expected.Spec.RestartPolicy = api.RestartPolicyAlways expected.Spec.DNSPolicy = api.DNSClusterFirst expected.Spec.Containers[0].ImagePullPolicy = api.PullIfNotPresent expected.Spec.Containers[0].TerminationMessagePath = api.TerminationMessagePathDefault expected.Spec.Containers[0].TerminationMessagePolicy = api.TerminationMessageReadFile expected.Labels = podIn.Labels expected.Status = podIn.Status _, _, err = statusStorage.Update(ctx, podIn.Name, rest.DefaultUpdatedObjectInfo(&podIn, api.Scheme)) if err != nil { t.Fatalf("Unexpected error: %v", err) } obj, err := storage.Get(ctx, "foo", &metav1.GetOptions{}) if err != nil { t.Errorf("unexpected error: %v", err) } podOut := obj.(*api.Pod) // Check to verify the Label, and Status updates match from change above. Those are the fields changed. if !apiequality.Semantic.DeepEqual(podOut.Spec, expected.Spec) || !apiequality.Semantic.DeepEqual(podOut.Labels, expected.Labels) || !apiequality.Semantic.DeepEqual(podOut.Status, expected.Status) { t.Errorf("objects differ: %v", diff.ObjectDiff(podOut, expected)) } } func TestShortNames(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() expected := []string{"po"} registrytest.AssertShortNames(t, storage, expected) }
{'content_hash': '0f2ea0b4277f3157d635ed560e79cf92', 'timestamp': '', 'source': 'github', 'line_count': 791, 'max_line_length': 133, 'avg_line_length': 29.303413400758533, 'alnum_prop': 0.6752664049355019, 'repo_name': 'sarat-k/kubernetes', 'id': '9c0a27ac2e5f859594263b4f21213451992c1a00', 'size': '23748', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'pkg/registry/core/pod/storage/storage_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '2539'}, {'name': 'Go', 'bytes': '43422352'}, {'name': 'HTML', 'bytes': '2601882'}, {'name': 'Makefile', 'bytes': '78947'}, {'name': 'Nginx', 'bytes': '1608'}, {'name': 'PowerShell', 'bytes': '4261'}, {'name': 'Protocol Buffer', 'bytes': '655881'}, {'name': 'Python', 'bytes': '1365409'}, {'name': 'SaltStack', 'bytes': '55288'}, {'name': 'Shell', 'bytes': '1737979'}]}
<?php class Google_Service_Bigquery_ClusteringMetrics extends Google_Model { public $daviesBouldinIndex; public $meanSquaredDistance; public function setDaviesBouldinIndex($daviesBouldinIndex) { $this->daviesBouldinIndex = $daviesBouldinIndex; } public function getDaviesBouldinIndex() { return $this->daviesBouldinIndex; } public function setMeanSquaredDistance($meanSquaredDistance) { $this->meanSquaredDistance = $meanSquaredDistance; } public function getMeanSquaredDistance() { return $this->meanSquaredDistance; } }
{'content_hash': '5eb503b8880482d09be9b6ce64acdff0', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 68, 'avg_line_length': 22.76, 'alnum_prop': 0.7574692442882249, 'repo_name': 'reactexcel/ReactReduxHR', 'id': '6feaeba73c86694877aba4ffac2a68cab7f303a4', 'size': '1159', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'backend/attendance/sal_info/google-api/vendor/google/apiclient-services/src/Google/Service/Bigquery/ClusteringMetrics.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '205756'}, {'name': 'HTML', 'bytes': '1098124'}, {'name': 'JavaScript', 'bytes': '1323356'}, {'name': 'PHP', 'bytes': '3157401'}, {'name': 'Shell', 'bytes': '8049'}]}
/* * Program: SSL authentication/encryption module for Windows 9x and NT * * Author: Mark Crispin * * Date: 22 September 1998 * Last Edited: 8 November 2009 * * Previous versions of this file were * * Copyright 1988-2008 University of Washington * * 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 * */ #ifdef ENABLE_WINDOWS_LIBRESSL #define crypt ssl_private_crypt #define STRING OPENSSL_STRING #include <x509v3.h> #include <ssl.h> #include <err.h> #include <pem.h> #include <buffer.h> #include <bio.h> #include <crypto.h> #include <rand.h> #ifdef OPENSSL_1_1_0 #include <rsa.h> #include <bn.h> #endif /* OPENSSL_1_1_0 */ #undef STRING #undef crypt #define SSLBUFLEN 8192 /* * PCI auditing compliance, disable: * SSLv2 * anonymous D-H (no certificate * export encryption ciphers (40 and 56 bits) * low encryption cipher suites (40 and 56 bits, excluding export) * null encryption (disabling implied by "ALL") * * UW imapd just disables low-grade and null ("ALL:!LOW"). This setting * will break clients that attempt to use the newly-prohibited mechanisms. * * I question the value of disabling SSLv2, as opposed to disabling the SSL * ports (e.g., 993 for IMAP, 995 for POP3) and using TLS exclusively. */ #define SSLCIPHERLIST "ALL:!SSLv2:!ADH:!EXP:!LOW" /* SSL I/O stream */ typedef struct ssl_stream { TCPSTREAM *tcpstream; /* TCP stream */ SSL_CTX *context; /* SSL context */ SSL *con; /* SSL connection */ int ictr; /* input counter */ char *iptr; /* input pointer */ char ibuf[SSLBUFLEN]; /* input buffer */ } SSLSTREAM; #include "sslio.h" /* Function prototypes */ const SSL_METHOD *ssl_connect_mthd(int flag); static SSLSTREAM *ssl_start(TCPSTREAM *tstream,char *host,unsigned long flags); static char *ssl_start_work (SSLSTREAM *stream,char *host,unsigned long flags); static int ssl_open_verify (int ok,X509_STORE_CTX *ctx); static char *ssl_validate_cert (X509 *cert,char *host); static long ssl_compare_hostnames (unsigned char *s,unsigned char *pat); static char *ssl_getline_work (SSLSTREAM *stream,unsigned long *size, long *contd); static long ssl_abort (SSLSTREAM *stream); #ifdef OPENSSL_1_1_0 #define SSL_CTX_TYPE SSL_CTX #else #define SSL_CTX_TYPE SSL #endif /* OPENSSL_1_1_0 */ static RSA *ssl_genkey (SSL_CTX_TYPE *con,int export,int keylength); typedef struct ssl_versions_s { char *name; int version; } SSL_VERSIONS_S; int pith_ssl_encryption_version(char *s) { SSL_VERSIONS_S ssl_versions[] = { { "no_min", 0 }, { "ssl3", SSL3_VERSION }, { "tls1", TLS1_VERSION }, { "tls1_1", TLS1_1_VERSION }, { "tls1_2", TLS1_2_VERSION }, #ifdef TLS1_3_VERSION { "tls1_3", TLS1_3_VERSION }, #endif /* TLS1_3_VERSION */ { "no_max", 0 }, /* set this last in the list */ { NULL, 0 }, }; int i; if (s == NULL || *s == '\0') return -1; for (i = 0; ssl_versions[i].name != NULL; i++) if (strcmp(ssl_versions[i].name, s) == 0) break; if (strcmp(s, "no_max") == 0) i--; return ssl_versions[i].name != NULL ? ssl_versions[i].version : -1; } /* Secure Sockets Layer network driver dispatch */ static struct ssl_driver ssldriver = { ssl_open, /* open connection */ ssl_aopen, /* open preauthenticated connection */ ssl_getline, /* get a line */ ssl_getbuffer, /* get a buffer */ ssl_soutr, /* output pushed data */ ssl_sout, /* output string */ ssl_close, /* close connection */ ssl_host, /* return host name */ ssl_remotehost, /* return remote host name */ ssl_port, /* return port number */ ssl_localhost /* return local host name */ }; /* non-NIL if doing SSL primary I/O */ static SSLSTDIOSTREAM *sslstdio = NIL; static char *start_tls = NIL; /* non-NIL if start TLS requested */ /* One-time SSL initialization */ static int sslonceonly = 0; void ssl_onceonlyinit (void) { if (!sslonceonly++) { /* only need to call it once */ int fd; char tmp[MAILTMPLEN]; struct stat sbuf; /* if system doesn't have /dev/urandom */ if (stat ("/dev/urandom",&sbuf)) { strcpy(tmp, "SSLXXXXXX"); fd = fopen(tmp,"a"); unlink (tmp); /* don't need the file */ fstat (fd,&sbuf); /* get information about the file */ close (fd); /* flush descriptor */ /* not great but it'll have to do */ sprintf (tmp + strlen (tmp),"%.80s%lx%.80s%lx%lx%lx%lx%lx", tcp_serveraddr (),(unsigned long) tcp_serverport (), tcp_clientaddr (),(unsigned long) tcp_clientport (), (unsigned long) sbuf.st_ino,(unsigned long) time (0), (unsigned long) gethostid (),(unsigned long) getpid ()); RAND_seed (tmp,strlen (tmp)); } /* apply runtime linkage */ mail_parameters (NIL,SET_SSLDRIVER,(void *) &ssldriver); mail_parameters (NIL,SET_SSLSTART,(void *) ssl_start); #ifdef OPENSSL_1_1_0 OPENSSL_init_ssl(0, NULL); #else SSL_library_init (); /* add all algorithms */ #endif /* OPENSSL_1_1_0 */ } } /* SSL open * Accepts: host name * contact service name * contact port number * Returns: SSL stream if success else NIL */ SSLSTREAM *ssl_open (char *host,char *service,unsigned long port) { TCPSTREAM *stream = tcp_open (host,service,port); return stream ? ssl_start (stream,host,port) : NIL; } /* SSL authenticated open * Accepts: host name * service name * returned user name buffer * Returns: SSL stream if success else NIL */ SSLSTREAM *ssl_aopen (NETMBX *mb,char *service,char *usrbuf) { return NIL; /* don't use this mechanism with SSL */ } typedef struct ssl_disable_s { int version; int disable_code; } SSL_DISABLE_S; SSL_DISABLE_S ssl_disable[] = { { SSL2_VERSION, SSL_OP_NO_SSLv2 }, { SSL3_VERSION, SSL_OP_NO_SSLv3 }, { TLS1_VERSION, SSL_OP_NO_TLSv1 }, { TLS1_1_VERSION, SSL_OP_NO_TLSv1_1 }, { TLS1_2_VERSION, SSL_OP_NO_TLSv1_2 }, #ifdef TLS1_3_VERSION { TLS1_3_VERSION, SSL_OP_NO_TLSv1_3 }, #endif /* TLS1_3_VERSION */ { 0, 0 } }; #define NUMBER_SSL_VERSIONS (sizeof(ssl_disable)/sizeof(ssl_disable[0]) - 1) /* returns the mask to disable a specific version. * If version not found, returns 0. * * Arguments: version, and direction. * If direction is -1, returns mask to disable versions less than given version. * If direction is +1, returns mask to disable versions bigger than given version. */ int ssl_disable_mask(int ssl_version, int direction) { int rv = 0; int i; for (i = 0; ssl_disable[i].version != 0 && ssl_disable[i].version != ssl_version; i++); if (i == 0 || i == NUMBER_SSL_VERSIONS - 1 || ssl_disable[i].version == 0) return rv; i += direction; /* move in the direction */ for (; i >= 0 && i <= NUMBER_SSL_VERSIONS - 1; i += direction) rv |= ssl_disable[i].disable_code; return rv; } /* ssl_connect_mthd: returns a context pointer to the connection to * a ssl server */ const SSL_METHOD *ssl_connect_mthd(int flag, int *min, int *max) { int client_request; client_request = (flag & NET_TRYTLS1) ? TLS1_VERSION : (flag & NET_TRYTLS1_1) ? TLS1_1_VERSION : (flag & NET_TRYTLS1_2) ? TLS1_2_VERSION #ifdef TLS1_3_VERSION : (flag & NET_TRYTLS1_3) ? TLS1_3_VERSION #else : (flag & NET_TRYTLS1_3) ? -2 #endif : 0; *min = *(int *)mail_parameters(NULL, GET_ENCRYPTION_RANGE_MIN, NULL); *max = *(int *)mail_parameters(NULL, GET_ENCRYPTION_RANGE_MAX, NULL); /* * if no special request, negotiate the maximum the client is configured * to negotiate */ if (client_request == 0) client_request = *max; if (client_request < *min || client_request > *max) return NIL; /* out of range? bail out */ /* Some Linux distributors seem to believe that it is ok to disable some of * these methods for their users, so we have to test that every requested * method has actually been compiled in into their openssl/libressl library. * Oh well... */ #ifndef OPENSSL_1_1_0 if (client_request == SSL3_VERSION) #ifndef OPENSSL_NO_SSL3_METHOD return SSLv3_client_method(); #else return NIL; #endif /* OPENSSL_NO_SSL3_METHOD */ else if (client_request == TLS1_VERSION) #ifndef OPENSSL_NO_TLS1_METHOD return TLSv1_client_method(); #else return NIL; #endif /* OPENSSL_NO_TLS1_METHOD */ else if (client_request == TLS1_1_VERSION) #ifndef OPENSSL_NO_TLS1_1_METHOD return TLSv1_1_client_method(); #else return NIL; #endif /* OPENSSL_NO_TLS1_1_METHOD */ else if (client_request == TLS1_2_VERSION) #ifndef OPENSSL_NO_TLS1_2_METHOD return TLSv1_2_client_method(); #else return NIL; #endif /* OPENSSL_NO_TLS1_2_METHOD */ #ifdef TLS1_3_VERSION /* this is only reachable if TLS1_3 support exists */ else if (client_request == TLS1_3_VERSION) #ifndef OPENSSL_NO_TLS1_3_METHOD return TLS_client_method(); #else return NIL; #endif /* #ifndef OPENSSL_NO_TLS1_2_METHOD */ #endif /* TLS1_3_VERSION */ #endif /* ifndef OPENSSL_1_1_0 */ return SSLv23_client_method(); } /* Start SSL/TLS negotiations * Accepts: open TCP stream of session * user's host name * flags * Returns: SSL stream if success else NIL */ static SSLSTREAM *ssl_start (TCPSTREAM *tstream,char *host,unsigned long flags) { char *reason,tmp[MAILTMPLEN]; sslfailure_t sf = (sslfailure_t) mail_parameters (NIL,GET_SSLFAILURE,NIL); blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL); void *data = (*bn) (BLOCK_SENSITIVE,NIL); SSLSTREAM *stream = (SSLSTREAM *) memset (fs_get (sizeof (SSLSTREAM)),0, sizeof (SSLSTREAM)); stream->tcpstream = tstream; /* bind TCP stream */ /* do the work */ reason = ssl_start_work (stream,host,flags); (*bn) (BLOCK_NONSENSITIVE,data); if (reason) { /* failed? */ ssl_close (stream); /* failed to do SSL */ stream = NIL; /* no stream returned */ switch (*reason) { /* analyze reason */ case '*': /* certificate failure */ ++reason; /* skip over certificate failure indication */ /* pass to error callback */ if (sf) (*sf) (host,reason,flags); else { /* no error callback, build error message */ sprintf (tmp,"Certificate failure for %.80s: %.512s",host,reason); mm_log (tmp,ERROR); } case '\0': /* user answered no to certificate callback */ if (flags & NET_TRYSSL) /* return dummy stream to stop tryssl */ stream = (SSLSTREAM *) memset (fs_get (sizeof (SSLSTREAM)),0, sizeof (SSLSTREAM)); break; default: /* non-certificate failure */ if (flags & NET_TRYSSL); /* no error output if tryssl */ /* pass to error callback */ else if (sf) (*sf) (host,reason,flags); else { /* no error callback, build error message */ sprintf (tmp,"TLS/SSL failure for %.80s: %.512s",host,reason); mm_log (tmp,ERROR); } break; } } return stream; } /* Start SSL/TLS negotiations worker routine * Accepts: SSL stream * user's host name * flags * Returns: NIL if success, else error reason */ /* evil but I had no choice */ static char *ssl_last_error = NIL; static char *ssl_last_host = NIL; static char *ssl_start_work(SSLSTREAM *stream, char *host, unsigned long flags) { BIO *bio; X509 *cert; unsigned long sl, tl; int min, max; int masklow, maskhigh; char *s, *t, *err, tmp[MAILTMPLEN], buf[256]; sslcertificatequery_t scq = (sslcertificatequery_t)mail_parameters(NIL, GET_SSLCERTIFICATEQUERY, NIL); sslclientcert_t scc = (sslclientcert_t)mail_parameters(NIL, GET_SSLCLIENTCERT, NIL); sslclientkey_t sck = (sslclientkey_t)mail_parameters(NIL, GET_SSLCLIENTKEY, NIL); if (ssl_last_error) fs_give((void **)&ssl_last_error); ssl_last_host = host; if (!(stream->context = SSL_CTX_new(ssl_connect_mthd(flags, &min, &max)))) return "SSL context failed"; SSL_CTX_set_options(stream->context, 0); masklow = ssl_disable_mask(min, -1); maskhigh = ssl_disable_mask(max, 1); SSL_CTX_set_options(stream->context, masklow | maskhigh); /* disable certificate validation? */ if (flags & NET_NOVALIDATECERT) SSL_CTX_set_verify(stream->context, SSL_VERIFY_NONE, NIL); else SSL_CTX_set_verify(stream->context, SSL_VERIFY_PEER, ssl_open_verify); /* set default paths to CAs... */ SSL_CTX_set_default_verify_paths(stream->context); /* ...unless a non-standard path desired */ if ((s = (char *)mail_parameters(NIL, GET_SSLCAPATH, NIL)) != NULL) SSL_CTX_load_verify_locations(stream->context, NIL, s); /* want to send client certificate? */ if (scc && (s = (*scc) ()) && (sl = strlen(s))) { if ((cert = PEM_read_bio_X509(bio = BIO_new_mem_buf(s, sl), NIL, NIL, NIL)) != NULL) { SSL_CTX_use_certificate(stream->context, cert); X509_free(cert); } BIO_free(bio); if (!cert) return "SSL client certificate failed"; /* want to supply private key? */ if ((t = (sck ? (*sck) () : s)) && (tl = strlen(t))) { EVP_PKEY *key; if ((key = PEM_read_bio_PrivateKey(bio = BIO_new_mem_buf(t, tl), NIL, NIL, "")) != NULL) { SSL_CTX_use_PrivateKey(stream->context, key); EVP_PKEY_free(key); } BIO_free(bio); memset(t, 0, tl); /* erase key */ } if (s != t) memset(s, 0, sl);/* erase certificate if different from key */ } /* create connection */ if (!(stream->con = (SSL *)SSL_new(stream->context))) return "SSL connection failed"; if (host && !SSL_set_tlsext_host_name(stream->con, host)) { return "Server Name Identification (SNI) failed"; } bio = BIO_new_socket(stream->tcpstream->tcpsi, BIO_NOCLOSE); SSL_set_bio(stream->con, bio, bio); SSL_set_connect_state(stream->con); if (SSL_in_init(stream->con)) SSL_total_renegotiations(stream->con); /* now negotiate SSL */ if (SSL_write(stream->con, "", 0) < 0) return ssl_last_error ? ssl_last_error : "SSL negotiation failed"; /* need to validate host names? */ if (!(flags & NET_NOVALIDATECERT) && (err = ssl_validate_cert(cert = SSL_get_peer_certificate(stream->con), host))) { /* application callback */ X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); if (scq) return (*scq) (err, host, cert ? buf : "???") ? NIL : ""; /* error message to return via mm_log() */ sprintf(tmp, "*%.128s: %.255s", err, cert ? buf : "???"); return ssl_last_error = cpystr(tmp); } return NIL; } /* SSL certificate verification callback * Accepts: error flag * X509 context * Returns: error flag */ static int ssl_open_verify (int ok,X509_STORE_CTX *ctx) { char *err,cert[256],tmp[MAILTMPLEN]; sslcertificatequery_t scq = (sslcertificatequery_t) mail_parameters (NIL,GET_SSLCERTIFICATEQUERY,NIL); if (!ok) { /* in case failure */ err = (char *) X509_verify_cert_error_string (X509_STORE_CTX_get_error (ctx)); X509_NAME_oneline (X509_get_subject_name (X509_STORE_CTX_get_current_cert (ctx)),cert,255); if (!scq) { /* mm_log() error message if no callback */ sprintf (tmp,"*%.128s: %.255s",err,cert); ssl_last_error = cpystr (tmp); } /* ignore error if application says to */ else if ((*scq) (err,ssl_last_host,cert)) ok = T; /* application wants punt */ else ssl_last_error = cpystr (""); } return ok; } /* SSL validate certificate * Accepts: certificate * host to validate against * Returns: NIL if validated, else string of error message */ static char *ssl_validate_cert (X509 *cert,char *host) { int i,j,n, m = 0;; char *s=NULL,*t,*ret = NIL; void *ext; GENERAL_NAME *name; X509_NAME *cname; X509_NAME_ENTRY *e; char buf[256]; /* make sure have a certificate */ if (!cert) return "No certificate from server"; /* Method 1: locate CN */ #ifndef OPENSSL_1_1_0 if (cert->name == NIL) ret = "No name in certificate"; else if ((s = strstr (cert->name,"/CN=")) != NIL) { m++; /* count that we tried this method */ if (t = strchr (s += 4,'/')) *t = '\0'; /* host name matches pattern? */ ret = ssl_compare_hostnames (host,s) ? NIL : "Server name does not match certificate"; if (t) *t = '/'; /* restore smashed delimiter */ /* if mismatch, see if in extensions */ if (ret && (ext = X509_get_ext_d2i (cert,NID_subject_alt_name,NIL,NIL)) && (n = sk_GENERAL_NAME_num (ext))) /* older versions of OpenSSL use "ia5" instead of dNSName */ for (i = 0; ret && (i < n); i++) if ((name = sk_GENERAL_NAME_value (ext,i)) && (name->type = GEN_DNS) && (s = name->d.ia5->data) && ssl_compare_hostnames (host,s)) ret = NIL; } #endif /* OPENSSL_1_1_0 */ /* Method 2, use Cname */ if(m == 0 || ret != NIL){ cname = X509_get_subject_name(cert); for(j = 0, ret = NIL; j < X509_NAME_entry_count(cname) && ret == NIL; j++){ if((e = X509_NAME_get_entry(cname, j)) != NULL){ X509_NAME_get_text_by_OBJ(cname, X509_NAME_ENTRY_get_object(e), buf, sizeof(buf)); s = (char *) buf; } else s = NIL; if (s != NIL) { /* host name matches pattern? */ ret = ssl_compare_hostnames (host,s) ? NIL : "Server name does not match certificate"; /* if mismatch, see if in extensions */ if (ret && (ext = X509_get_ext_d2i (cert,NID_subject_alt_name,NIL,NIL)) && (n = sk_GENERAL_NAME_num (ext))) /* older versions of OpenSSL use "ia5" instead of dNSName */ for (i = 0; ret && (i < n); i++) if ((name = sk_GENERAL_NAME_value (ext,i)) && (name->type = GEN_DNS) && (s = name->d.ia5->data) && ssl_compare_hostnames (host,s)) ret = NIL; } } } if (ret == NIL #ifndef OPENSSL_1_1_0 && !cert->name #endif /* OPENSSL_1_1_9 */ && !X509_get_subject_name(cert)) ret = "No name in certificate"; if (ret == NIL && s == NIL) ret = "Unable to locate common name in certificate"; return ret; } /* Case-independent wildcard pattern match * Accepts: base string * pattern string * Returns: T if pattern matches base, else NIL */ static long ssl_compare_hostnames (unsigned char *s,unsigned char *pat) { long ret = NIL; switch (*pat) { case '*': /* wildcard */ if (pat[1]) { /* there must be a pattern suffix */ /* there is, scan base against it */ do if (ssl_compare_hostnames (s,pat+1)) ret = LONGT; while (!ret && (*s != '.') && *s++); } break; case '\0': /* end of pattern */ if (!*s) ret = LONGT; /* success if base is also at end */ break; default: /* non-wildcard, recurse if match */ if (!compare_uchar (*pat,*s)) ret = ssl_compare_hostnames (s+1,pat+1); break; } return ret; } /* SSL receive line * Accepts: SSL stream * Returns: text line string or NIL if failure */ char *ssl_getline (SSLSTREAM *stream) { unsigned long n,contd; char *ret = ssl_getline_work (stream,&n,&contd); if (ret && contd) { /* got a line needing continuation? */ STRINGLIST *stl = mail_newstringlist (); STRINGLIST *stc = stl; do { /* collect additional lines */ stc->text.data = (unsigned char *) ret; stc->text.size = n; stc = stc->next = mail_newstringlist (); ret = ssl_getline_work (stream,&n,&contd); } while (ret && contd); if (ret) { /* stash final part of line on list */ stc->text.data = (unsigned char *) ret; stc->text.size = n; /* determine how large a buffer we need */ for (n = 0, stc = stl; stc; stc = stc->next) n += stc->text.size; ret = fs_get (n + 1); /* copy parts into buffer */ for (n = 0, stc = stl; stc; n += stc->text.size, stc = stc->next) memcpy (ret + n,stc->text.data,stc->text.size); ret[n] = '\0'; } mail_free_stringlist (&stl);/* either way, done with list */ } return ret; } /* SSL receive line or partial line * Accepts: SSL stream * pointer to return size * pointer to return continuation flag * Returns: text line string, size and continuation flag, or NIL if failure */ static char *ssl_getline_work (SSLSTREAM *stream,unsigned long *size, long *contd) { unsigned long n; char *s,*ret,c,d; *contd = NIL; /* assume no continuation */ /* make sure have data */ if (!ssl_getdata (stream)) return NIL; for (s = stream->iptr, n = 0, c = '\0'; stream->ictr--; n++, c = d) { d = *stream->iptr++; /* slurp another character */ if ((c == '\015') && (d == '\012')) { ret = (char *) fs_get (n--); memcpy (ret,s,*size = n); /* copy into a free storage string */ ret[n] = '\0'; /* tie off string with null */ return ret; } } /* copy partial string from buffer */ memcpy ((ret = (char *) fs_get (n)),s,*size = n); /* get more data from the net */ if (!ssl_getdata (stream)) fs_give ((void **) &ret); /* special case of newline broken by buffer */ else if ((c == '\015') && (*stream->iptr == '\012')) { stream->iptr++; /* eat the line feed */ stream->ictr--; ret[*size = --n] = '\0'; /* tie off string with null */ } else *contd = LONGT; /* continuation needed */ return ret; } /* SSL receive buffer * Accepts: SSL stream * size in bytes * buffer to read into * Returns: T if success, NIL otherwise */ long ssl_getbuffer (SSLSTREAM *stream,unsigned long size,char *buffer) { unsigned long n; while (size > 0) { /* until request satisfied */ if (!ssl_getdata (stream)) return NIL; n = min (size,stream->ictr);/* number of bytes to transfer */ /* do the copy */ memcpy (buffer,stream->iptr,n); buffer += n; /* update pointer */ stream->iptr += n; size -= n; /* update # of bytes to do */ stream->ictr -= n; } buffer[0] = '\0'; /* tie off string */ return T; } /* SSL receive data * Accepts: TCP/IP stream * Returns: T if success, NIL otherwise */ #ifdef FD_SETSIZE #undef FD_SETSIZE #endif /* FD_SETSIZE */ #define FD_SETSIZE 16384 long ssl_getdata (SSLSTREAM *stream) { int i,sock; fd_set fds,efds; struct timeval tmo; tcptimeout_t tmoh = (tcptimeout_t) mail_parameters (NIL,GET_TIMEOUT,NIL); long ttmo_read = (long) mail_parameters (NIL,GET_READTIMEOUT,NIL); time_t t = time (0); blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL); if (!stream->con || ((sock = SSL_get_fd (stream->con)) < 0)) return NIL; /* tcp_unix should have prevented this */ if (sock >= FD_SETSIZE) fatal ("unselectable socket in ssl_getdata()"); (*bn) (BLOCK_TCPREAD,NIL); while (stream->ictr < 1) { /* if nothing in the buffer */ time_t tl = time (0); /* start of request */ time_t now = tl; int ti = ttmo_read ? now + ttmo_read : 0; if (SSL_pending (stream->con)) i = 1; else { if (tcpdebug) mm_log ("Reading SSL data",TCPDEBUG); tmo.tv_usec = 0; FD_ZERO (&fds); /* initialize selection vector */ FD_ZERO (&efds); /* handle errors too */ FD_SET (sock,&fds); /* set bit in selection vector */ FD_SET (sock,&efds); /* set bit in error selection vector */ errno = NIL; /* block and read */ do { /* block under timeout */ tmo.tv_sec = ti ? ti - now : 0; i = select (sock+1,&fds,0,&efds,ti ? &tmo : 0); now = time (0); /* fake timeout if interrupt & time expired */ if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0; } while ((i < 0) && (errno == EINTR)); } if (i) { /* non-timeout result from select? */ errno = 0; /* just in case */ if (i > 0) /* read what we can */ while (((i = SSL_read (stream->con,stream->ibuf,SSLBUFLEN)) < 0) && ((errno == EINTR) || (SSL_get_error (stream->con,i) == SSL_ERROR_WANT_READ))); if (i <= 0) { /* error seen? */ if (tcpdebug) { char *s,tmp[MAILTMPLEN]; if (i) sprintf (s = tmp,"SSL data read I/O error %d SSL error %d", errno,SSL_get_error (stream->con,i)); else s = "SSL data read end of file"; mm_log (s,TCPDEBUG); } return ssl_abort (stream); } stream->iptr = stream->ibuf;/* point at TCP buffer */ stream->ictr = i; /* set new byte count */ if (tcpdebug) mm_log ("Successfully read SSL data",TCPDEBUG); } /* timeout, punt unless told not to */ else if (!tmoh || !(*tmoh) (now - t,now - tl, stream->tcpstream->host)) { if (tcpdebug) mm_log ("SSL data read timeout",TCPDEBUG); return ssl_abort (stream); } } (*bn) (BLOCK_NONE,NIL); return T; } /* SSL send string as record * Accepts: SSL stream * string pointer * Returns: T if success else NIL */ long ssl_soutr (SSLSTREAM *stream,char *string) { return ssl_sout (stream,string,(unsigned long) strlen (string)); } /* SSL send string * Accepts: SSL stream * string pointer * byte count * Returns: T if success else NIL */ long ssl_sout (SSLSTREAM *stream,char *string,unsigned long size) { long i; blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL); if (!stream->con) return NIL; (*bn) (BLOCK_TCPWRITE,NIL); if (tcpdebug) mm_log ("Writing to SSL",TCPDEBUG); /* until request satisfied */ for (i = 0; size > 0; string += i,size -= i) /* write as much as we can */ if ((i = SSL_write (stream->con,string,(int) min (SSLBUFLEN,size))) < 0) { if (tcpdebug) { char tmp[MAILTMPLEN]; sprintf (tmp,"SSL data write I/O error %d SSL error %d", errno,SSL_get_error (stream->con,i)); mm_log (tmp,TCPDEBUG); } return ssl_abort (stream);/* write failed */ } if (tcpdebug) mm_log ("successfully wrote to TCP",TCPDEBUG); (*bn) (BLOCK_NONE,NIL); return LONGT; /* all done */ } /* SSL close * Accepts: SSL stream */ void ssl_close (SSLSTREAM *stream) { ssl_abort (stream); /* nuke the stream */ fs_give ((void **) &stream); /* flush the stream */ } /* SSL abort stream * Accepts: SSL stream * Returns: NIL always */ static long ssl_abort (SSLSTREAM *stream) { blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL); if (stream->con) { /* close SSL connection */ SSL_shutdown (stream->con); SSL_free (stream->con); stream->con = NIL; } if (stream->context) { /* clean up context */ SSL_CTX_free (stream->context); stream->context = NIL; } if (stream->tcpstream) { /* close TCP stream */ tcp_close (stream->tcpstream); stream->tcpstream = NIL; } (*bn) (BLOCK_NONE,NIL); return NIL; } /* SSL get host name * Accepts: SSL stream * Returns: host name for this stream */ char *ssl_host (SSLSTREAM *stream) { return stream ? tcp_host (stream->tcpstream) : "UNKNOWN"; } /* SSL get remote host name * Accepts: SSL stream * Returns: host name for this stream */ char *ssl_remotehost (SSLSTREAM *stream) { return tcp_remotehost (stream->tcpstream); } /* SSL return port for this stream * Accepts: SSL stream * Returns: port number for this stream */ unsigned long ssl_port (SSLSTREAM *stream) { return tcp_port (stream->tcpstream); } /* SSL get local host name * Accepts: SSL stream * Returns: local host name */ char *ssl_localhost (SSLSTREAM *stream) { return tcp_localhost (stream->tcpstream); } #ifdef SSL_CERT_DIRECTORY #undef SSL_CERT_DIRECTORY #endif /* SSL_CERT_DIRECTORY */ #define SSL_CERT_DIRECTORY "C:\\\\libressl\\ssl\\certs" #ifdef SSL_KEY_DIRECTORY #undef SSL_KEY_DIRECTORY #endif /* SSL_KEY_DIRECTORY */ #define SSL_KEY_DIRECTORY "C:\\\\libressl\\ssl\\private" /* Start TLS * Accepts: /etc/services service name * Returns: cpystr'd error string if TLS failed, else NIL for success */ char *ssl_start_tls (char *server) { char tmp[MAILTMPLEN]; struct stat sbuf; if (sslstdio) return cpystr ("Already in an SSL session"); if (start_tls) return cpystr ("TLS already started"); if (server) { /* build specific certificate/key file name */ sprintf (tmp,"%s\\%s-%s.pem",SSL_CERT_DIRECTORY,server,tcp_serveraddr ()); if (stat (tmp,&sbuf)) { /* use non-specific name if no specific file */ sprintf (tmp,"%s\\%s.pem",SSL_CERT_DIRECTORY,server); if (stat (tmp,&sbuf)) return cpystr ("Server certificate not installed"); } start_tls = server; /* switch to STARTTLS mode */ } return NIL; } /* Init server for SSL * Accepts: server name */ void ssl_server_init (char *server) { char cert[MAILTMPLEN],key[MAILTMPLEN]; unsigned long i; struct stat sbuf; SSLSTREAM *stream = (SSLSTREAM *) memset (fs_get (sizeof (SSLSTREAM)),0, sizeof (SSLSTREAM)); ssl_onceonlyinit (); /* make sure algorithms added */ #ifdef OPENSSL_1_1_0 OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS|OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); #else ERR_load_crypto_strings (); SSL_load_error_strings (); #endif /* OPENSSL_1_1_0 */ /* build specific certificate/key file names */ sprintf (cert,"%s\\%s-%s.pem",SSL_CERT_DIRECTORY,server,tcp_serveraddr ()); sprintf (key,"%s\\%s-%s.pem",SSL_KEY_DIRECTORY,server,tcp_serveraddr ()); /* use non-specific name if no specific cert */ if (stat (cert,&sbuf)) sprintf (cert,"%s\\%s.pem",SSL_CERT_DIRECTORY,server); if (stat (key,&sbuf)) { /* use non-specific name if no specific key */ sprintf (key,"%s\\%s.pem",SSL_KEY_DIRECTORY,server); /* use cert file as fallback for key */ if (stat (key,&sbuf)) strcpy (key,cert); } /* create context */ #ifdef OPENSSL_1_1_0 if (!(stream->context = SSL_CTX_new (start_tls ? TLS_server_method () : SSLv23_server_method ()))) #else if (!(stream->context = SSL_CTX_new (start_tls ? TLSv1_server_method () : SSLv23_server_method ()))) #endif /* OPENSSL_1_1_0 */ syslog (LOG_ALERT,"Unable to create SSL context, host=%.80s", tcp_clienthost ()); else { /* set context options */ SSL_CTX_set_options (stream->context,SSL_OP_ALL); /* set cipher list */ if (!SSL_CTX_set_cipher_list (stream->context,SSLCIPHERLIST)) syslog (LOG_ALERT,"Unable to set cipher list %.80s, host=%.80s", SSLCIPHERLIST,tcp_clienthost ()); /* load certificate */ else if (!SSL_CTX_use_certificate_chain_file (stream->context,cert)) syslog (LOG_ALERT,"Unable to load certificate from %.80s, host=%.80s", cert,tcp_clienthost ()); /* load key */ else if (!(SSL_CTX_use_RSAPrivateKey_file (stream->context,key, SSL_FILETYPE_PEM))) syslog (LOG_ALERT,"Unable to load private key from %.80s, host=%.80s", key,tcp_clienthost ()); else { /* generate key if needed */ #ifdef OPENSSL_1_1_0 if (0) ssl_genkey(stream->context, 0, 0); #else if (SSL_CTX_need_tmp_RSA (stream->context)) SSL_CTX_set_tmp_rsa_callback (stream->context,ssl_genkey); #endif /* OPENSSL_1_1_0 */ /* create new SSL connection */ if (!(stream->con = SSL_new (stream->context))) syslog (LOG_ALERT,"Unable to create SSL connection, host=%.80s", tcp_clienthost ()); else { /* set file descriptor */ SSL_set_fd (stream->con,0); /* all OK if accepted */ if (SSL_accept (stream->con) < 0) syslog (LOG_INFO,"Unable to accept SSL connection, host=%.80s", tcp_clienthost ()); else { /* server set up */ sslstdio = (SSLSTDIOSTREAM *) memset (fs_get (sizeof(SSLSTDIOSTREAM)),0,sizeof (SSLSTDIOSTREAM)); sslstdio->sslstream = stream; /* available space in output buffer */ sslstdio->octr = SSLBUFLEN; /* current output buffer pointer */ sslstdio->optr = sslstdio->obuf; /* allow plaintext if disable value was 2 */ if ((long) mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL) > 1) mail_parameters (NIL,SET_DISABLEPLAINTEXT,NIL); /* unhide PLAIN SASL authenticator */ mail_parameters (NIL,UNHIDE_AUTHENTICATOR,"PLAIN"); mail_parameters (NIL,UNHIDE_AUTHENTICATOR,"LOGIN"); return; } } } } while ((i = ERR_get_error ()) != 0L) /* SSL failure */ syslog (LOG_ERR,"SSL error status: %.80s",ERR_error_string (i,NIL)); ssl_close (stream); /* punt stream */ exit (1); /* punt this program too */ } /* Generate one-time key for server * Accepts: SSL connection * export flag * keylength * Returns: generated key, always */ static RSA *ssl_genkey (SSL_CTX_TYPE *con,int export,int keylength) { unsigned long i; static RSA *key = NIL; if (!key) { /* if don't have a key already */ /* generate key */ #ifdef OPENSSL_1_1_0 BIGNUM *e = BN_new(); if (!RSA_generate_key_ex (key, export ? keylength : 1024, e,NIL)) { #else if (!(key = RSA_generate_key (export ? keylength : 1024,RSA_F4,NIL,NIL))) { #endif /* OPENSSL_1_1_0 */ syslog (LOG_ALERT,"Unable to generate temp key, host=%.80s", tcp_clienthost ()); while ((i = ERR_get_error ()) != 0L) syslog (LOG_ALERT,"SSL error status: %s",ERR_error_string (i,NIL)); exit (1); } #ifdef OPENSSL_1_1_0 BN_free(e); e = NULL; #endif /* OPENSSL_1_1_0 */ } return key; } /* Wait for stdin input * Accepts: timeout in seconds * Returns: T if have input on stdin, else NIL */ long ssl_server_input_wait (long seconds) { int i,sock; fd_set fds,efd; struct timeval tmo; SSLSTREAM *stream; if (!sslstdio) return server_input_wait (seconds); /* input available in buffer */ if (((stream = sslstdio->sslstream)->ictr > 0) || !stream->con || ((sock = SSL_get_fd (stream->con)) < 0)) return LONGT; /* sock ought to be 0 always */ if (sock >= FD_SETSIZE) fatal ("unselectable socket in ssl_getdata()"); /* input available from SSL */ if (SSL_pending (stream->con) && ((i = SSL_read (stream->con,stream->ibuf,SSLBUFLEN)) > 0)) { stream->iptr = stream->ibuf;/* point at TCP buffer */ stream->ictr = i; /* set new byte count */ return LONGT; } FD_ZERO (&fds); /* initialize selection vector */ FD_ZERO (&efd); /* initialize selection vector */ FD_SET (sock,&fds); /* set bit in selection vector */ FD_SET (sock,&efd); /* set bit in selection vector */ tmo.tv_sec = seconds; tmo.tv_usec = 0; /* see if input available from the socket */ return select (sock+1,&fds,0,&efd,&tmo) ? LONGT : NIL; } #include "sslstdio.c" #else /* ENABLE_WINDOWS_LIBRESSL */ #define SECURITY_WIN32 #include <sspi.h> #include <schannel.h> #define SSLBUFLEN 8192 /* SSL I/O stream */ typedef struct ssl_stream { TCPSTREAM *tcpstream; /* TCP stream */ CredHandle cred; /* SSL credentials */ CtxtHandle context; /* SSL context */ /* stream encryption sizes */ SecPkgContext_StreamSizes sizes; size_t bufsize; int ictr; /* input counter */ char *iptr; /* input pointer */ int iextractr; /* extra input counter */ char *iextraptr; /* extra input pointer */ char *ibuf; /* input buffer */ char *obuf; /* output buffer */ } SSLSTREAM; #include "sslio.h" /* Function prototypes */ static SSLSTREAM *ssl_start(TCPSTREAM *tstream,char *host,unsigned long flags); static char *ssl_analyze_status (SECURITY_STATUS err,char *buf); static char *ssl_getline_work (SSLSTREAM *stream,unsigned long *size, long *contd); static long ssl_abort (SSLSTREAM *stream); /* Secure Sockets Layer network driver dispatch */ static struct ssl_driver ssldriver = { ssl_open, /* open connection */ ssl_aopen, /* open preauthenticated connection */ ssl_getline, /* get a line */ ssl_getbuffer, /* get a buffer */ ssl_soutr, /* output pushed data */ ssl_sout, /* output string */ ssl_close, /* close connection */ ssl_host, /* return host name */ ssl_remotehost, /* return remote host name */ ssl_port, /* return port number */ ssl_localhost /* return local host name */ }; /* security function table */ static SecurityFunctionTable *sft = NIL; static unsigned long ssltsz = 0;/* SSL maximum token length */ /* Define crypt32.dll stuff here in case a pre-IE5 Win9x system */ typedef DWORD (CALLBACK *CNTS) (DWORD,PCERT_NAME_BLOB,DWORD,LPSTR,DWORD); typedef BOOL (CALLBACK *CGCC) (HCERTCHAINENGINE,PCCERT_CONTEXT,LPFILETIME, HCERTSTORE,PCERT_CHAIN_PARA,DWORD,LPVOID, PCCERT_CHAIN_CONTEXT *); typedef BOOL (CALLBACK *CVCCP) (LPCSTR,PCCERT_CHAIN_CONTEXT, PCERT_CHAIN_POLICY_PARA, PCERT_CHAIN_POLICY_STATUS); typedef VOID (CALLBACK *CFCC) (PCCERT_CHAIN_CONTEXT); typedef BOOL (CALLBACK *CFCCX) (PCCERT_CONTEXT); static CNTS certNameToStr = NIL; static CGCC certGetCertificateChain = NIL; static CVCCP certVerifyCertificateChainPolicy = NIL; static CFCC certFreeCertificateChain = NIL; static CFCCX certFreeCertificateContext = NIL; /* One-time SSL initialization */ static int sslonceonly = 0; void ssl_onceonlyinit (void) { if (!sslonceonly++) { /* only need to call it once */ HINSTANCE lib; FARPROC pi; ULONG np; SecPkgInfo *pp; int i; /* get security library */ if (((lib = LoadLibrary ("schannel.dll")) || (lib = LoadLibrary ("security.dll"))) && (pi = GetProcAddress (lib,SECURITY_ENTRYPOINT)) && (sft = (SecurityFunctionTable *) pi ()) && !(sft->EnumerateSecurityPackages (&np,&pp))) { /* look for an SSL package */ for (i = 0; (i < (int) np); i++) if (!strcmp (pp[i].Name,UNISP_NAME)) { /* note maximum token size and name */ ssltsz = pp[i].cbMaxToken; /* apply runtime linkage */ mail_parameters (NIL,SET_SSLDRIVER,(void *) &ssldriver); mail_parameters (NIL,SET_SSLSTART,(void *) ssl_start); if ((lib = LoadLibrary ("crypt32.dll")) && (certGetCertificateChain = (CGCC) GetProcAddress (lib,"CertGetCertificateChain")) && (certVerifyCertificateChainPolicy = (CVCCP) GetProcAddress (lib,"CertVerifyCertificateChainPolicy")) && (certFreeCertificateChain = (CFCC) GetProcAddress (lib,"CertFreeCertificateChain")) && (certFreeCertificateContext = (CFCCX) GetProcAddress (lib,"CertFreeCertificateContext"))) certNameToStr = (CNTS) GetProcAddress (lib,"CertNameToStrA"); return; /* all done */ } } } } /* SSL open * Accepts: host name * contact service name * contact port number * Returns: SSL stream if success else NIL */ SSLSTREAM *ssl_open (char *host,char *service,unsigned long port) { TCPSTREAM *stream = tcp_open (host,service,port); return stream ? ssl_start (stream,host,port) : NIL; } /* SSL authenticated open * Accepts: host name * service name * returned user name buffer * Returns: SSL stream if success else NIL */ SSLSTREAM *ssl_aopen (NETMBX *mb,char *service,char *usrbuf) { return NIL; /* don't use this mechanism with SSL */ } /* Start SSL/TLS negotiations * Accepts: open TCP stream of session * user's host name * flags * Returns: SSL stream if success else NIL */ static SSLSTREAM *ssl_start (TCPSTREAM *tstream,char *host,unsigned long flags) { SECURITY_STATUS e; ULONG a; TimeStamp t; SecBuffer ibuf[2],obuf[1]; SecBufferDesc ibufs,obufs; SCHANNEL_CRED tlscred; CERT_CONTEXT *cert = NIL; CERT_CHAIN_PARA chparam; CERT_CHAIN_CONTEXT *chain; SSL_EXTRA_CERT_CHAIN_POLICY_PARA policy; CERT_CHAIN_POLICY_PARA polparam; CERT_CHAIN_POLICY_STATUS status; char tmp[MAILTMPLEN],certname[256]; char *reason = NIL; ULONG req = ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_REQ_USE_SESSION_KEY | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM | ISC_REQ_EXTENDED_ERROR | ISC_REQ_MANUAL_CRED_VALIDATION; LPSTR usage[] = { szOID_PKIX_KP_SERVER_AUTH, szOID_SERVER_GATED_CRYPTO, szOID_SGC_NETSCAPE }; PWSTR whost = NIL; char *buf = (char *) fs_get (ssltsz); unsigned long size = 0; sslcertificatequery_t scq = (sslcertificatequery_t) mail_parameters (NIL,GET_SSLCERTIFICATEQUERY,NIL); sslfailure_t sf = (sslfailure_t) mail_parameters (NIL,GET_SSLFAILURE,NIL); SSLSTREAM *stream = (SSLSTREAM *) memset (fs_get (sizeof (SSLSTREAM)),0, sizeof (SSLSTREAM)); stream->tcpstream = tstream; /* bind TCP stream */ /* initialize TLS credential */ memset (&tlscred,0,sizeof (SCHANNEL_CRED)); tlscred.dwVersion = SCHANNEL_CRED_VERSION; tlscred.grbitEnabledProtocols = SP_PROT_TLS1; /* acquire credentials */ if (sft->AcquireCredentialsHandle (NIL,UNISP_NAME,SECPKG_CRED_OUTBOUND,NIL,(flags & NET_TLSCLIENT) ? &tlscred : NIL,NIL,NIL,&stream->cred,&t) != SEC_E_OK) reason = "Acquire credentials handle failed"; else while (!reason) { /* negotiate security context */ /* initialize buffers */ ibuf[0].cbBuffer = size; ibuf[0].pvBuffer = buf; ibuf[1].cbBuffer = 0; ibuf[1].pvBuffer = NIL; obuf[0].cbBuffer = 0; obuf[0].pvBuffer = NIL; ibuf[0].BufferType = obuf[0].BufferType = SECBUFFER_TOKEN; ibuf[1].BufferType = SECBUFFER_EMPTY; /* initialize buffer descriptors */ ibufs.ulVersion = obufs.ulVersion = SECBUFFER_VERSION; ibufs.cBuffers = 2; obufs.cBuffers = 1; ibufs.pBuffers = ibuf; obufs.pBuffers = obuf; /* negotiate security */ e = sft->InitializeSecurityContext (&stream->cred,size ? &stream->context : NIL,host,req,0, SECURITY_NETWORK_DREP,size? &ibufs:NIL,0,&stream->context,&obufs,&a,&t); /* have an output buffer we need to send? */ if (obuf[0].pvBuffer && obuf[0].cbBuffer) { if (!tcp_sout (stream->tcpstream,obuf[0].pvBuffer,obuf[0].cbBuffer)) reason = "Unexpected TCP output disconnect"; /* free the buffer */ sft->FreeContextBuffer (obuf[0].pvBuffer); } if (!reason) switch (e) { /* negotiation state */ case SEC_I_INCOMPLETE_CREDENTIALS: break; /* server wants client auth */ case SEC_I_CONTINUE_NEEDED: if (size) { /* continue, read any data? */ /* yes, anything regurgiated back to us? */ if (ibuf[1].BufferType == SECBUFFER_EXTRA) { /* yes, set this as the new data */ memmove (buf,buf + size - ibuf[1].cbBuffer,ibuf[1].cbBuffer); size = ibuf[1].cbBuffer; break; } size = 0; /* otherwise, read more stuff from server */ } case SEC_E_INCOMPLETE_MESSAGE: /* need to read more data from server */ if (!tcp_getdata (stream->tcpstream)) reason = "Unexpected TCP input disconnect"; else { memcpy (buf+size,stream->tcpstream->iptr,stream->tcpstream->ictr); size += stream->tcpstream->ictr; /* empty it from TCP's buffers */ stream->tcpstream->iptr += stream->tcpstream->ictr; stream->tcpstream->ictr = 0; } break; case SEC_E_OK: /* success, any data to be regurgitated? */ if (ibuf[1].BufferType == SECBUFFER_EXTRA) { /* yes, set this as the new data */ memmove (stream->tcpstream->iptr = stream->tcpstream->ibuf, buf + size - ibuf[1].cbBuffer,ibuf[1].cbBuffer); stream->tcpstream->ictr = ibuf[1].cbBuffer; } if (certNameToStr && !(flags & NET_NOVALIDATECERT)) { /* need validation, make wchar of host */ if (!((size = MultiByteToWideChar (CP_ACP,0,host,-1,NIL,0)) && (whost = (PWSTR) fs_get (size*sizeof (WCHAR))) && MultiByteToWideChar (CP_ACP,0,host,-1,whost,size))) fatal ("Can't make wchar of host name!"); /* get certificate */ if ((sft->QueryContextAttributes (&stream->context,SECPKG_ATTR_REMOTE_CERT_CONTEXT,&cert) != SEC_E_OK) || !cert) { reason = "*Unable to get certificate"; strcpy (certname,"<no certificate>"); } else { /* get certificate subject name */ (*certNameToStr) (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, &cert->pCertInfo->Subject,CERT_X500_NAME_STR, certname,255); /* build certificate chain */ memset (&chparam,0,sizeof (chparam)); chparam.cbSize = sizeof (chparam); chparam.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR; chparam.RequestedUsage.Usage.rgpszUsageIdentifier = usage; chparam.RequestedUsage.Usage.cUsageIdentifier = sizeof (usage) / sizeof (LPSTR); if (!(*certGetCertificateChain) (NIL,cert,NIL,cert->hCertStore,&chparam,NIL,NIL,&chain)) reason = ssl_analyze_status (GetLastError (),tmp); else { /* validate certificate chain */ memset (&policy,0,sizeof (SSL_EXTRA_CERT_CHAIN_POLICY_PARA)); policy.cbStruct = sizeof (SSL_EXTRA_CERT_CHAIN_POLICY_PARA); policy.dwAuthType = AUTHTYPE_SERVER; policy.fdwChecks = NIL; policy.pwszServerName = whost; memset (&polparam,0,sizeof (polparam)); polparam.cbSize = sizeof (polparam); polparam.pvExtraPolicyPara = &policy; memset (&status,0,sizeof (status)); status.cbSize = sizeof (status); if (!(*certVerifyCertificateChainPolicy) (CERT_CHAIN_POLICY_SSL,chain,&polparam,&status)) reason = ssl_analyze_status (GetLastError (),tmp); else if (status.dwError) reason = ssl_analyze_status (status.dwError,tmp); (*certFreeCertificateChain) (chain); } (*certFreeCertificateContext) (cert); } if (whost) fs_give ((void **) &whost); if (reason) { /* got an error? */ /* application callback */ if (scq) reason = (*scq) ((*reason == '*') ? reason + 1 : reason, host,certname) ? NIL : ""; else if (*certname) { /* error message to return via mm_log() */ sprintf (buf,"*%.128s: %.255s", (*reason == '*') ? reason + 1 : reason,certname); reason = buf; } } } if (reason || (reason = ssl_analyze_status (sft->QueryContextAttributes (&stream->context,SECPKG_ATTR_STREAM_SIZES,&stream->sizes),buf))) break; /* error in certificate or getting sizes */ fs_give ((void **) &buf); /* flush temporary buffer */ /* make maximum-sized buffers */ stream->bufsize = stream->sizes.cbHeader + stream->sizes.cbMaximumMessage + stream->sizes.cbTrailer; if (stream->sizes.cbMaximumMessage < SSLBUFLEN) fatal ("cbMaximumMessage is less than SSLBUFLEN!"); else if (stream->sizes.cbMaximumMessage < 16384) { sprintf (tmp,"WINDOWS BUG: cbMaximumMessage = %ld, should be 16384", (long) stream->sizes.cbMaximumMessage); mm_log (tmp,NIL); } stream->ibuf = (char *) fs_get (stream->bufsize); stream->obuf = (char *) fs_get (stream->bufsize); return stream; default: reason = ssl_analyze_status (e,buf); } } ssl_close (stream); /* failed to do SSL */ stream = NIL; /* no stream returned */ switch (*reason) { /* analyze reason */ case '*': /* certificate failure */ ++reason; /* skip over certificate failure indication */ /* pass to error callback */ if (sf) (*sf) (host,reason,flags); else { /* no error callback, build error message */ sprintf (tmp,"Certificate failure for %.80s: %.512s",host,reason); mm_log (tmp,ERROR); } case '\0': /* user answered no to certificate callback */ if (flags & NET_TRYSSL) /* return dummy stream to stop tryssl */ stream = (SSLSTREAM *) memset (fs_get (sizeof (SSLSTREAM)),0, sizeof (SSLSTREAM)); break; default: /* non-certificate failure */ if (flags & NET_TRYSSL); /* no error output if tryssl */ /* pass to error callback */ else if (sf) (*sf) (host,reason,flags); else { /* no error callback, build error message */ sprintf (tmp,"TLS/SSL failure for %.80s: %.512s",host,reason); mm_log (tmp,ERROR); } break; } fs_give ((void **) &buf); /* flush temporary buffer */ return stream; } /* Generate error text from SSL error code * Accepts: SSL status * scratch buffer * Returns: text if error status, else NIL */ static char *ssl_analyze_status (SECURITY_STATUS err,char *buf) { switch (err) { case SEC_E_OK: /* no error */ case SEC_I_CONTINUE_NEEDED: case SEC_I_INCOMPLETE_CREDENTIALS: case SEC_E_INCOMPLETE_MESSAGE: return NIL; case SEC_E_NO_AUTHENTICATING_AUTHORITY: mm_log ("unexpected SEC_E_NO_AUTHENTICATING_AUTHORITY",NIL); return "*No authority could be contacted for authentication"; case SEC_E_WRONG_PRINCIPAL: mm_log ("unexpected SEC_E_WRONG_PRINCIPAL",NIL); case CERT_E_CN_NO_MATCH: return "*Server name does not match certificate"; case SEC_E_UNTRUSTED_ROOT: mm_log ("unexpected SEC_E_UNTRUSTED_ROOT",NIL); case CERT_E_UNTRUSTEDROOT: return "*Self-signed certificate or untrusted authority"; case SEC_E_CERT_EXPIRED: mm_log ("unexpected SEC_E_CERT_EXPIRED",NIL); case CERT_E_EXPIRED: return "*Certificate has expired"; case CERT_E_REVOKED: return "*Certificate revoked"; case SEC_E_INVALID_TOKEN: return "Invalid token, probably not an SSL server"; case SEC_E_UNSUPPORTED_FUNCTION: return "SSL not supported on this machine - upgrade your system software"; } sprintf (buf,"Unexpected SSPI or certificate error %lx - report this",err); return buf; } /* SSL receive line * Accepts: SSL stream * Returns: text line string or NIL if failure */ char *ssl_getline (SSLSTREAM *stream) { unsigned long n,contd; char *ret = ssl_getline_work (stream,&n,&contd); if (ret && contd) { /* got a line needing continuation? */ STRINGLIST *stl = mail_newstringlist (); STRINGLIST *stc = stl; do { /* collect additional lines */ stc->text.data = (unsigned char *) ret; stc->text.size = n; stc = stc->next = mail_newstringlist (); ret = ssl_getline_work (stream,&n,&contd); } while (ret && contd); if (ret) { /* stash final part of line on list */ stc->text.data = (unsigned char *) ret; stc->text.size = n; /* determine how large a buffer we need */ for (n = 0, stc = stl; stc; stc = stc->next) n += stc->text.size; ret = fs_get (n + 1); /* copy parts into buffer */ for (n = 0, stc = stl; stc; n += stc->text.size, stc = stc->next) memcpy (ret + n,stc->text.data,stc->text.size); ret[n] = '\0'; } mail_free_stringlist (&stl);/* either way, done with list */ } return ret; } /* SSL receive line or partial line * Accepts: SSL stream * pointer to return size * pointer to return continuation flag * Returns: text line string, size and continuation flag, or NIL if failure */ static char *ssl_getline_work (SSLSTREAM *stream,unsigned long *size, long *contd) { unsigned long n; char *s,*ret,c,d; *contd = NIL; /* assume no continuation */ /* make sure have data */ if (!ssl_getdata (stream)) return NIL; for (s = stream->iptr, n = 0, c = '\0'; stream->ictr--; n++, c = d) { d = *stream->iptr++; /* slurp another character */ if ((c == '\015') && (d == '\012')) { ret = (char *) fs_get (n--); memcpy (ret,s,*size = n); /* copy into a free storage string */ ret[n] = '\0'; /* tie off string with null */ return ret; } } /* copy partial string from buffer */ memcpy ((ret = (char *) fs_get (n)),s,*size = n); /* get more data from the net */ if (!ssl_getdata (stream)) fs_give ((void **) &ret); /* special case of newline broken by buffer */ else if ((c == '\015') && (*stream->iptr == '\012')) { stream->iptr++; /* eat the line feed */ stream->ictr--; ret[*size = --n] = '\0'; /* tie off string with null */ } else *contd = LONGT; /* continuation needed */ return ret; } /* SSL receive buffer * Accepts: SSL stream * size in bytes * buffer to read into * Returns: T if success, NIL otherwise */ long ssl_getbuffer (SSLSTREAM *stream,unsigned long size,char *buffer) { unsigned long n; while (size > 0) { /* until request satisfied */ if (!ssl_getdata (stream)) return NIL; n = min (size,stream->ictr);/* number of bytes to transfer */ /* do the copy */ memcpy (buffer,stream->iptr,n); buffer += n; /* update pointer */ stream->iptr += n; size -= n; /* update # of bytes to do */ stream->ictr -= n; } buffer[0] = '\0'; /* tie off string */ return T; } /* SSL receive data * Accepts: TCP/IP stream * Returns: T if success, NIL otherwise */ long ssl_getdata (SSLSTREAM *stream) { while (stream->ictr < 1) { /* decrypted buffer empty? */ SECURITY_STATUS status; SecBuffer buf[4]; SecBufferDesc msg; size_t i; size_t n = 0; /* initially no bytes to decrypt */ if (!stream->tcpstream) return NIL; do { /* yes, make sure have data from TCP */ if (stream->iextractr) { /* have previous unread data? */ memcpy (stream->ibuf + n,stream->iextraptr,stream->iextractr); n += stream->iextractr; /* update number of bytes read */ stream->iextractr = 0; /* no more extra data */ } else { /* read from TCP */ if (!tcp_getdata (stream->tcpstream)) return ssl_abort (stream); /* maximum amount of data to copy */ if (!(i = min (stream->bufsize - n,stream->tcpstream->ictr))) fatal ("incomplete SecBuffer exceeds maximum buffer size"); /* do the copy */ memcpy (stream->ibuf + n,stream->tcpstream->iptr,i); stream->tcpstream->iptr += i; stream->tcpstream->ictr -= i; n += i; /* update number of bytes to decrypt */ } buf[0].cbBuffer = n; /* first SecBuffer gets data */ buf[0].pvBuffer = stream->ibuf; buf[0].BufferType = SECBUFFER_DATA; /* subsequent ones are for spares */ buf[1].BufferType = buf[2].BufferType = buf[3].BufferType = SECBUFFER_EMPTY; msg.ulVersion = SECBUFFER_VERSION; msg.cBuffers = 4; /* number of SecBuffers */ msg.pBuffers = buf; /* first SecBuffer */ } while ((status = ((DECRYPT_MESSAGE_FN) sft->Reserved4) (&stream->context,&msg,0,NIL)) == SEC_E_INCOMPLETE_MESSAGE); switch (status) { case SEC_E_OK: /* won */ case SEC_I_RENEGOTIATE: /* won but lost it after this buffer */ /* hunt for a buffer */ for (i = 0; (i < 4) && (buf[i].BufferType != SECBUFFER_DATA) ; i++); if (i < 4) { /* found a buffer? */ /* yes, set up pointer and counter */ stream->iptr = buf[i].pvBuffer; stream->ictr = buf[i].cbBuffer; /* any unprocessed data? */ while (++i < 4) if (buf[i].BufferType == SECBUFFER_EXTRA) { /* yes, note for next time around */ stream->iextraptr = buf[i].pvBuffer; stream->iextractr = buf[i].cbBuffer; } } break; default: /* anything else means we've lost */ return ssl_abort (stream); } } return LONGT; } /* SSL send string as record * Accepts: SSL stream * string pointer * Returns: T if success else NIL */ long ssl_soutr (SSLSTREAM *stream,char *string) { return ssl_sout (stream,string,(unsigned long) strlen (string)); } /* SSL send string * Accepts: SSL stream * string pointer * byte count * Returns: T if success else NIL */ long ssl_sout (SSLSTREAM *stream,char *string,unsigned long size) { SecBuffer buf[4]; SecBufferDesc msg; char *s; size_t n; if (!stream->tcpstream) return NIL; /* until request satisfied */ for (s = stream->ibuf,n = 0; size;) { /* header */ buf[0].BufferType = SECBUFFER_STREAM_HEADER; memset (buf[0].pvBuffer = stream->obuf,0, buf[0].cbBuffer = stream->sizes.cbHeader); /* message (up to maximum size) */ buf[1].BufferType = SECBUFFER_DATA; memcpy (buf[1].pvBuffer = stream->obuf + stream->sizes.cbHeader,string, buf[1].cbBuffer = min (size,SSLBUFLEN)); /* trailer */ buf[2].BufferType = SECBUFFER_STREAM_TRAILER; memset (buf[2].pvBuffer = ((char *) buf[1].pvBuffer) + buf[1].cbBuffer,0, buf[2].cbBuffer = stream->sizes.cbTrailer); /* spare */ buf[3].BufferType = SECBUFFER_EMPTY; msg.ulVersion = SECBUFFER_VERSION; msg.cBuffers = 4; /* number of SecBuffers */ msg.pBuffers = buf; /* first SecBuffer */ string += buf[1].cbBuffer; size -= buf[1].cbBuffer; /* this many bytes processed */ /* encrypt and send message */ if ((((ENCRYPT_MESSAGE_FN) sft->Reserved3) (&stream->context,0,&msg,NIL) != SEC_E_OK) || !tcp_sout (stream->tcpstream,stream->obuf, buf[0].cbBuffer + buf[1].cbBuffer + buf[2].cbBuffer)) return ssl_abort (stream);/* encryption or sending failed */ } return LONGT; } /* SSL close * Accepts: SSL stream */ void ssl_close (SSLSTREAM *stream) { ssl_abort (stream); /* nuke the stream */ fs_give ((void **) &stream); /* flush the stream */ } /* SSL abort stream * Accepts: SSL stream * Returns: NIL always */ static long ssl_abort (SSLSTREAM *stream) { if (stream->tcpstream) { /* close TCP stream */ sft->DeleteSecurityContext (&stream->context); sft->FreeCredentialHandle (&stream->cred); tcp_close (stream->tcpstream); stream->tcpstream = NIL; } if (stream->ibuf) fs_give ((void **) &stream->ibuf); if (stream->obuf) fs_give ((void **) &stream->obuf); return NIL; } /* SSL get host name * Accepts: SSL stream * Returns: host name for this stream */ char *ssl_host (SSLSTREAM *stream) { return stream ? tcp_host (stream->tcpstream) : "UNKNOWN"; } /* SSL get remote host name * Accepts: SSL stream * Returns: host name for this stream */ char *ssl_remotehost (SSLSTREAM *stream) { return tcp_remotehost (stream->tcpstream); } /* SSL return port for this stream * Accepts: SSL stream * Returns: port number for this stream */ unsigned long ssl_port (SSLSTREAM *stream) { return tcp_port (stream->tcpstream); } /* SSL get local host name * Accepts: SSL stream * Returns: local host name */ char *ssl_localhost (SSLSTREAM *stream) { return tcp_localhost (stream->tcpstream); } #include "ssl_none.c" /* currently no server support */ #endif /* ENABLE_WINDOWS_LIBRESSL */
{'content_hash': '34b542083543d5cffcaa785fc8b73f7f', 'timestamp': '', 'source': 'github', 'line_count': 1811, 'max_line_length': 93, 'avg_line_length': 31.55494202098288, 'alnum_prop': 0.6319427431491268, 'repo_name': '0xkag/alpine', 'id': 'd39fdf08f71627a233a2a3930b5316e2084ecd30', 'size': '57370', 'binary': False, 'copies': '1', 'ref': 'refs/heads/custom-2.21.x', 'path': 'imap/src/osdep/nt/ssl_nt.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '32879'}, {'name': 'C', 'bytes': '16755141'}, {'name': 'C++', 'bytes': '138789'}, {'name': 'CSS', 'bytes': '41883'}, {'name': 'DIGITAL Command Language', 'bytes': '9086'}, {'name': 'HTML', 'bytes': '371561'}, {'name': 'Inno Setup', 'bytes': '2757'}, {'name': 'JavaScript', 'bytes': '132406'}, {'name': 'M4', 'bytes': '204908'}, {'name': 'Makefile', 'bytes': '457300'}, {'name': 'Objective-C', 'bytes': '8592'}, {'name': 'Perl', 'bytes': '8402'}, {'name': 'Python', 'bytes': '20877'}, {'name': 'Roff', 'bytes': '40357'}, {'name': 'Shell', 'bytes': '452568'}, {'name': 'Tcl', 'bytes': '1049849'}, {'name': 'sed', 'bytes': '370'}]}
package middleware import ( "bufio" "fmt" "net" "net/http" "github.com/uber-go/tally" ) type recordStatusWriter struct { http.ResponseWriter status int } func (mw *recordStatusWriter) WriteHeader(status int) { mw.status = status mw.ResponseWriter.WriteHeader(status) } func (mw *recordStatusWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return mw.ResponseWriter.(http.Hijacker).Hijack() } func Metrics(metricsScope tally.Scope) func(http.Handler) http.Handler { requestsMetric := metricsScope.Counter("requests") return func(next http.Handler) http.Handler { return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { w := &recordStatusWriter{ResponseWriter: writer} next.ServeHTTP(w, request) requestsMetric.Inc(1) metricsScope.Counter(request.Method + "_requests").Inc(1) metricsScope.Counter(fmt.Sprintf("%d_responses", w.status)).Inc(1) }) } }
{'content_hash': 'a1d132522537f83f5b75d88b6366f89f', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 83, 'avg_line_length': 24.83783783783784, 'alnum_prop': 0.7388465723612623, 'repo_name': 'nadeemsyed/hummingbird', 'id': 'd664ecf42d33666d9272c8a6f5795a16626f5ef5', 'size': '919', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'middleware/metrics.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '2179745'}, {'name': 'Makefile', 'bytes': '1575'}, {'name': 'Shell', 'bytes': '335'}]}
<?php namespace app\modules\auth\models; use Yii; /** * This is the model class for table "auth_assignment". * * @property string $item_name * @property string $user_id * @property integer $created_at * * @property AuthItem $itemName */ class AuthAssignment extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'auth_assignment'; } /** * @inheritdoc */ public function rules() { return [ [['item_name', 'user_id'], 'required'], [['created_at'], 'integer'], [['item_name', 'user_id'], 'string', 'max' => 64] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'item_name' => 'Item Name', 'user_id' => 'User ID', 'created_at' => 'Created At', ]; } /** * @return \yii\db\ActiveQuery */ public function getItemName() { return $this->hasOne(AuthItem::className(), ['name' => 'item_name']); } }
{'content_hash': '91460b7190f6832ebabc53227b80aea7', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 77, 'avg_line_length': 19.105263157894736, 'alnum_prop': 0.5068870523415978, 'repo_name': 'sanreqi/yamy', 'id': 'f4ddd3e8bacb15773a911c9066fa9ae4212afbad', 'size': '1089', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/auth/models/AuthAssignment.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '41943'}, {'name': 'Batchfile', 'bytes': '1056'}, {'name': 'CSS', 'bytes': '222740'}, {'name': 'HTML', 'bytes': '46494'}, {'name': 'Java', 'bytes': '10698'}, {'name': 'JavaScript', 'bytes': '1114245'}, {'name': 'PHP', 'bytes': '402151'}]}
package org.apache.pig.backend.hadoop.executionengine.fetch; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.PigProgressable; /** * A dummy ProgressableReporter used for fetch tasks * */ public class FetchProgressableReporter implements PigProgressable { private static final Log LOG = LogFactory.getLog(FetchProgressableReporter.class); public void progress() { } public void progress(String msg) { LOG.info(msg); } }
{'content_hash': '442903fb52d3f9fb1678f29dbf42c83d', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 86, 'avg_line_length': 23.416666666666668, 'alnum_prop': 0.7580071174377224, 'repo_name': 'netxillon/pig', 'id': '7b28a76dc957c2d7228eb1fba0bd5ba102effb3f', 'size': '1367', 'binary': False, 'copies': '26', 'ref': 'refs/heads/trunk', 'path': 'src/org/apache/pig/backend/hadoop/executionengine/fetch/FetchProgressableReporter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5964'}, {'name': 'GAP', 'bytes': '160931'}, {'name': 'HTML', 'bytes': '14000'}, {'name': 'Java', 'bytes': '14122684'}, {'name': 'JavaScript', 'bytes': '4954'}, {'name': 'Perl', 'bytes': '669886'}, {'name': 'PigLatin', 'bytes': '106111'}, {'name': 'Python', 'bytes': '53916'}, {'name': 'Ruby', 'bytes': '21893'}, {'name': 'Shell', 'bytes': '68218'}, {'name': 'XSLT', 'bytes': '5489'}]}
package net.tomp2p.tracker; import net.tomp2p.peers.Number160; import net.tomp2p.rpc.SimpleBloomFilter; import java.util.Set; public class GetTrackerBuilder extends TrackerBuilder<GetTrackerBuilder> { private Set<Number160> knownPeers; private boolean expectAttachment = false; public GetTrackerBuilder(PeerTracker peer, Number160 locationKey) { super(peer, locationKey); self(this); } public boolean isExpectAttachment() { return expectAttachment; } public GetTrackerBuilder expectAttachment() { this.expectAttachment = true; return this; } public GetTrackerBuilder expectAttachment(boolean expectAttachment) { this.expectAttachment = expectAttachment; return this; } public FutureTracker start() { if (peer.peer().isShutdown()) { return FUTURE_TRACKER_SHUTDOWN; } if(!expectAttachment) { forceUDP(true); } preBuild("get-tracker-builder"); if (knownPeers == null) { knownPeers = new SimpleBloomFilter<Number160>(1024, 1024); } return peer.distributedTracker().get(this); } }
{'content_hash': '174ce043f72dc59d6c6438f5a8828625', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 74, 'avg_line_length': 23.384615384615383, 'alnum_prop': 0.6398026315789473, 'repo_name': 'jonaswagner/TomP2P', 'id': 'c776c368e784a573b864631474de4a51bf47b759', 'size': '1810', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tracker/src/main/java/net/tomp2p/tracker/GetTrackerBuilder.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '2944486'}, {'name': 'C++', 'bytes': '25257'}, {'name': 'CMake', 'bytes': '16865'}, {'name': 'CSS', 'bytes': '3780'}, {'name': 'HTML', 'bytes': '15123'}, {'name': 'Java', 'bytes': '2656348'}, {'name': 'JavaScript', 'bytes': '5252'}, {'name': 'M4', 'bytes': '7069'}, {'name': 'Makefile', 'bytes': '232366'}, {'name': 'Roff', 'bytes': '1045440'}, {'name': 'Shell', 'bytes': '897743'}, {'name': 'TeX', 'bytes': '57163'}]}
package com.navercorp.pinpoint.plugin.grpc.interceptor.server; import com.navercorp.pinpoint.bootstrap.logging.PLogger; import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory; import com.navercorp.pinpoint.common.plugin.util.HostAndPort; import com.navercorp.pinpoint.common.util.ArrayUtils; import com.navercorp.pinpoint.plugin.grpc.GrpcConstants; import io.grpc.Attributes; import io.grpc.Grpc; import io.grpc.Metadata; import io.grpc.internal.ServerStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Iterator; import java.util.Objects; /** * @author Taejin Koo */ public class GrpcServerStreamRequest { private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); private final ServerStream serverStream; private final String methodName; private final Metadata metadata; static GrpcServerStreamRequest create(Object[] args) { if (validate(args)) { return new GrpcServerStreamRequest((ServerStream) args[0], (String) args[1], (Metadata) args[2]); } return null; } static boolean validate(Object[] args) { if (ArrayUtils.getLength(args) == 3) { if (!(args[0] instanceof ServerStream)) { return false; } if (!(args[1] instanceof String)) { return false; } if (!(args[2] instanceof Metadata)) { return false; } return true; } return false; } GrpcServerStreamRequest(ServerStream serverStream, String methodName, Metadata metadata) { this.serverStream = Objects.requireNonNull(serverStream, "serverStream"); this.methodName = Objects.requireNonNull(methodName, "methodName"); this.metadata = Objects.requireNonNull(metadata, "metadata"); } public ServerStream getServerStream() { return serverStream; } public String getMethodName() { return methodName; } public String getHeader(String name) { final Metadata.Key<String> key = Metadata.Key.of(name, Metadata.ASCII_STRING_MARSHALLER); final Iterable<String> headerValues = metadata.removeAll(key); if (headerValues == null) { return null; } String headerValue = null; Iterator<String> iterator = headerValues.iterator(); if (iterator.hasNext()) { headerValue = iterator.next(); if (iterator.hasNext()) { headerValue = null; } } return headerValue; } String getRemoteAddress() { final Attributes attributes = serverStream.getAttributes(); if (attributes == null) { return null; } try { final SocketAddress remoteAddress = attributes.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR); if (remoteAddress == null) { if (isDebug) { logger.debug("remote-addr is null"); } return null; } return getSocketAddressAsString(remoteAddress); } catch (Exception e) { if (isDebug) { logger.debug("can't find remote-addr key"); } } return GrpcConstants.UNKNOWN_ADDRESS; } public static String getSocketAddressAsString(SocketAddress socketAddress) { if (socketAddress instanceof InetSocketAddress) { final InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress; final InetAddress remoteAddress = inetSocketAddress.getAddress(); if (remoteAddress != null) { return HostAndPort.toHostAndPortString(remoteAddress.getHostAddress(), inetSocketAddress.getPort()); } } return GrpcConstants.UNKNOWN_ADDRESS; } String getServerAddress() { return serverStream.getAuthority(); } }
{'content_hash': 'a6acd5b5bc10feb740e2f65900f4c79b', 'timestamp': '', 'source': 'github', 'line_count': 132, 'max_line_length': 116, 'avg_line_length': 30.75, 'alnum_prop': 0.6309435821630943, 'repo_name': 'naver/pinpoint', 'id': '6226a22a24f1410de68b08a15bb90238372f3f85', 'size': '4653', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'plugins/grpc/src/main/java/com/navercorp/pinpoint/plugin/grpc/interceptor/server/GrpcServerStreamRequest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '22629'}, {'name': 'CSS', 'bytes': '386346'}, {'name': 'Groovy', 'bytes': '1423'}, {'name': 'HTML', 'bytes': '155936'}, {'name': 'Java', 'bytes': '16572538'}, {'name': 'JavaScript', 'bytes': '5349'}, {'name': 'PLSQL', 'bytes': '4156'}, {'name': 'Shell', 'bytes': '30236'}, {'name': 'TSQL', 'bytes': '4759'}, {'name': 'Thrift', 'bytes': '15284'}, {'name': 'TypeScript', 'bytes': '1358173'}]}
// (C) Copyright 2015 Martin Dougiamas // // 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 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. angular.module('mm.core.settings') /** * Controller to handle the app 'About' section in settings. * * @module mm.core.settings * @ngdoc controller * @name mmSettingsAboutCtrl */ .controller('mmSettingsAboutCtrl', function($scope, $mmConfig, $translate, $window, $mmApp, $ionicPlatform, $mmLang, $mmFS, $mmLocalNotifications) { $mmConfig.get('versionname').then(function(versionname) { $scope.versionname = versionname; $translate('mm.settings.appname', {version: versionname}).then(function(appName) { $scope.appname = appName; }); }); $mmConfig.get('versioncode').then(function(versioncode) { $scope.versioncode = versioncode; }); $scope.navigator = $window.navigator; if ($window.location && $window.location.href) { var url = $window.location.href; $scope.locationhref = url.substr(0, url.indexOf('#/site/')); } $scope.appready = $mmApp.isReady() ? 'mm.core.yes' : 'mm.core.no'; $scope.devicetype = $ionicPlatform.isTablet() ? 'mm.core.tablet' : 'mm.core.phone'; if (ionic.Platform.isAndroid()) { $scope.deviceos = 'mm.core.android'; } else if (ionic.Platform.isIOS()) { $scope.deviceos = 'mm.core.ios'; } else if (ionic.Platform.isWindowsPhone()) { $scope.deviceos = 'mm.core.windowsphone'; } else { var matches = navigator.userAgent.match(/\(([^\)]*)\)/); if (matches && matches.length > 1) { $scope.deviceos = matches[1] } else { $scope.deviceos = 'mm.core.unknown'; } } $mmLang.getCurrentLanguage().then(function(lang) { $scope.currentlanguage = lang; }); $scope.networkstatus = $mmApp.isOnline() ? 'mm.core.online' : 'mm.core.offline'; $scope.wificonnection = $mmApp.isNetworkAccessLimited() ? 'mm.core.no' : 'mm.core.yes'; $scope.devicewebworkers = !!window.Worker && !!window.URL ? 'mm.core.yes' : 'mm.core.no'; $scope.device = ionic.Platform.device(); if ($mmFS.isAvailable()) { $mmFS.getBasePath().then(function(basepath) { $scope.filesystemroot = basepath; }); } $scope.storagetype = $mmApp.getDB().getType(); $scope.localnotifavailable = $mmLocalNotifications.isAvailable() ? 'mm.core.yes' : 'mm.core.no'; });
{'content_hash': 'a966f0bb03ef2230d0d1dea975a0ec43', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 123, 'avg_line_length': 37.0, 'alnum_prop': 0.6400957919945262, 'repo_name': 'ardock/moodlemobile2', 'id': 'de4c49add9ae342b4c3f4d35421d7770178e67e1', 'size': '2923', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'www/core/components/settings/controllers/about.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '235934'}, {'name': 'HTML', 'bytes': '95174'}, {'name': 'JavaScript', 'bytes': '971813'}]}
package org.lwjgl.opengl; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.JNI.*; /** * Native bindings to the <a href="http://www.opengl.org/registry/specs/NV/conservative_raster_dilate.txt">NV_conservative_raster_dilate</a> extension. * * <p>This extension extends the conservative rasterization funtionality provided by NV_conservative_raster. It provides a new control to generate an * "over-conservative" rasterization by dilating primitives prior to rasterization.</p> * * <p>When using conservative raster to bin geometry, this extension provides a programmable overlap region between adjacent primitives. Regular * rasterization bins triangles with a shared edge uniquely into pixels. Conservative raster has a one-pixel overlap along the shared edge. Using a * half-pixel raster dilation, this overlap region increases to two pixels.</p> * * <p>Requires {@link NVConservativeRaster NV_conservative_raster}.</p> */ public class NVConservativeRasterDilate { /** Accepted by the {@code pname} parameter of ConservativeRasterParameterfNV, GetBooleanv, GetIntegerv, GetInteger64v, GetFloatv, and GetDoublev. */ public static final int GL_CONSERVATIVE_RASTER_DILATE_NV = 0x9379, GL_CONSERVATIVE_RASTER_DILATE_RANGE_NV = 0x937A, GL_CONSERVATIVE_RASTER_DILATE_GRANULARITY_NV = 0x937B; protected NVConservativeRasterDilate() { throw new UnsupportedOperationException(); } static boolean isAvailable(GLCapabilities caps) { return checkFunctions( caps.glConservativeRasterParameterfNV ); } // --- [ glConservativeRasterParameterfNV ] --- public static void glConservativeRasterParameterfNV(int pname, float value) { long __functionAddress = GL.getCapabilities().glConservativeRasterParameterfNV; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, pname, value); } }
{'content_hash': 'd2e8ae9bb789ec393ef2cb8175a52cd6', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 151, 'avg_line_length': 41.06521739130435, 'alnum_prop': 0.7691900476442562, 'repo_name': 'MatthijsKamstra/haxejava', 'id': 'eca330369a2ba7908601772a77fa065c15c574c0', 'size': '2022', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '04lwjgl/code/lwjgl/org/lwjgl/opengl/NVConservativeRasterDilate.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '122'}, {'name': 'Haxe', 'bytes': '1163'}, {'name': 'JavaScript', 'bytes': '724'}, {'name': 'PHP', 'bytes': '25278'}]}
declare namespace Jymfony.Component.PropertyAccess.Exception { export class InvalidPropertyPathException extends RuntimeException { } }
{'content_hash': 'bc29a246c23fdd9f5e8d5c72c6d5ae61', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 72, 'avg_line_length': 36.0, 'alnum_prop': 0.8125, 'repo_name': 'jymfony/jymfony', 'id': '329bb858f4fffa57f81c31e0a78419cc1d0250f4', 'size': '144', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Component/PropertyAccess/types/Exception/InvalidPropertyPathException.d.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '16998'}, {'name': 'JavaScript', 'bytes': '11149225'}, {'name': 'TypeScript', 'bytes': '566'}]}
package April2021Leetcode; public class _0396RotateFunction { public static void main(String[] args) { System.out.println(maxRotateFunction(new int[] { 4, 3, 2, 6 })); } public static int maxRotateFunction(int[] A) { } }
{'content_hash': 'bff4917039fda0863fb5c6dd0e519e49', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 66, 'avg_line_length': 19.416666666666668, 'alnum_prop': 0.6952789699570815, 'repo_name': 'darshanhs90/Java-InterviewPrep', 'id': '0edbe81f1f3879d790566da46272a8b9af521fc1', 'size': '233', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/April2021Leetcode/_0396RotateFunction.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1870066'}]}
GEO2DPolygonData::~GEO2DPolygonData() { #ifdef C_CODE if (_holesCoordinatesArray != NULL) { const size_t holesCoordinatesArraySize = _holesCoordinatesArray->size(); for (size_t j = 0; j < holesCoordinatesArraySize; j++) { const std::vector<Geodetic2D*>* holeCoordinates = _holesCoordinatesArray->at(j); const size_t holeCoordinatesCount = holeCoordinates->size(); for (size_t i =0; i < holeCoordinatesCount; i++) { const Geodetic2D* holeCoordinate = holeCoordinates->at(i); delete holeCoordinate; } delete holeCoordinates; } delete _holesCoordinatesArray; } #endif #ifdef JAVA_CODE super.dispose(); #endif } long long GEO2DPolygonData::getCoordinatesCount() const { long long result = GEO2DCoordinatesData::getCoordinatesCount(); if (_holesCoordinatesArray != NULL) { const size_t holesCoordinatesArraySize = _holesCoordinatesArray->size(); for (size_t j = 0; j < holesCoordinatesArraySize; j++) { const std::vector<Geodetic2D*>* holeCoordinates = _holesCoordinatesArray->at(j); result += holeCoordinates->size(); } } return result; } bool GEO2DPolygonData::contains(const std::vector<Geodetic2D*>* coordinates, const Geodetic2D& point) const { int sidesCrossedMovingRight = 0; const size_t coordinatesCount = coordinates->size(); size_t previousIndex = coordinatesCount - 1; for (size_t index = 0; index < coordinatesCount; index++) { Geodetic2D* firstCoordinate = coordinates->at(previousIndex); Geodetic2D* secondCoordinate = coordinates->at(index); if (!firstCoordinate->isEquals(*secondCoordinate)) { if (firstCoordinate->isEquals(point)){ return true; } const double pointLatInDegrees = point._latitude._degrees; const double firstCoorLatInDegrees = firstCoordinate->_latitude._degrees; const double secondCoorLatInDegrees = secondCoordinate->_latitude._degrees; const double pointLonInDegrees = point._longitude._degrees; const double firstCoorLonInDegrees = firstCoordinate->_longitude._degrees; const double secondCoorLonInDegrees = secondCoordinate->_longitude._degrees; if ((firstCoorLatInDegrees <= pointLatInDegrees && pointLatInDegrees < secondCoorLatInDegrees) || (secondCoorLatInDegrees <= pointLatInDegrees && pointLatInDegrees < firstCoorLatInDegrees)) { double intersectLongitudInDegrees = (secondCoorLonInDegrees - firstCoorLonInDegrees) * (pointLatInDegrees - firstCoorLatInDegrees) / (secondCoorLatInDegrees - firstCoorLatInDegrees) + firstCoorLonInDegrees; if (pointLonInDegrees <= intersectLongitudInDegrees) { sidesCrossedMovingRight++; } } } previousIndex = index; } if (sidesCrossedMovingRight == 0) { return false; } return sidesCrossedMovingRight % 2 == 1; } bool GEO2DPolygonData::contains(const Geodetic2D& point) const { if (getSector()->contains(point)) { if (_holesCoordinatesArray != NULL) { const size_t holesCoordinatesArraySize = _holesCoordinatesArray->size(); for (size_t j = 0; j < holesCoordinatesArraySize; j++) { const std::vector<Geodetic2D*>* holeCoordinates = _holesCoordinatesArray->at(j); if (contains(holeCoordinates, point)) { return false; } } } return contains(getCoordinates(), point); } return false; }
{'content_hash': '49bb244da65778a95e4ae7295f514288', 'timestamp': '', 'source': 'github', 'line_count': 100, 'max_line_length': 214, 'avg_line_length': 34.62, 'alnum_prop': 0.6871750433275563, 'repo_name': 'AeroGlass/g3m', 'id': '7c3c79c9c6d77b3d2737fad82430f7213d2b3913', 'size': '3641', 'binary': False, 'copies': '2', 'ref': 'refs/heads/purgatory', 'path': 'iOS/G3MiOSSDK/Commons/GEO/GEO2DPolygonData.cpp', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Batchfile', 'bytes': '7767'}, {'name': 'C', 'bytes': '12488'}, {'name': 'C++', 'bytes': '2483573'}, {'name': 'CSS', 'bytes': '854'}, {'name': 'HTML', 'bytes': '29099'}, {'name': 'Java', 'bytes': '2678952'}, {'name': 'JavaScript', 'bytes': '13022'}, {'name': 'Objective-C', 'bytes': '152753'}, {'name': 'Objective-C++', 'bytes': '344579'}, {'name': 'PostScript', 'bytes': '693603'}, {'name': 'Python', 'bytes': '26399'}]}
import axios from 'axios'; import express from 'express'; const router = express.Router(); router.post('/api/verify-other-repos', (req, res) => { const { repo_path, host_site } = req.body; axios.get(`${host_site}/${repo_path}`) .then((response) => { if (response.request._redirectCount === 0) { res.json({ validPublicRepo: 'true' }); } else { res.json({ validPublicRepo: 'false' }); } }) .catch((err) => { if (err) {res.json({ validPublicRepo: 'false' });} }); }); export default router;
{'content_hash': '63a5b929a79726f1e7e6b9ae77ad44df', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 54, 'avg_line_length': 23.17391304347826, 'alnum_prop': 0.5891181988742964, 'repo_name': 'no-stack-dub-sack/alumni-network', 'id': '9f988bf6fa9b0781615671865467997bdce23f9c', 'size': '533', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'server/helpers/gitlabRoute.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '3073'}, {'name': 'HTML', 'bytes': '1336'}, {'name': 'JavaScript', 'bytes': '292785'}, {'name': 'Shell', 'bytes': '175'}]}
from gi.repository import Gtk from src.model_mapper import ModelMapper class DeleteDatabasesDialog: def __init__(self, builder): self._win = builder.get_object('dialog_delete_databases', target=self, include_children=True) self._databases = None self._selected_databases = None def run(self, databases): self._databases = databases self._selected_databases = None result = self._win.run() self._win.hide() self._databases = None if result == Gtk.ResponseType.OK: self._selected_databases = self._get_selected_databases() return result def _get_selected_databases(self): selected_databases = [] model = self.treeview_delete_databases.get_model() itr = model.get_iter_first() while itr is not None: if model.get_value(itr, 1): path = model.get_path(itr) row = model[path] db = ModelMapper.get_item_instance(row) selected_databases.append(db) itr = model.iter_next(itr) return selected_databases def set_button_ok_active_state(self): sensitive = len(self._get_selected_databases()) > 0 self.button_delete_databases_dialog_ok.set_sensitive(sensitive) # region Properties @property def selected_databases(self): return self._selected_databases # endregion # region Events def on_dialog_delete_databases_show(self, dialog): model = Gtk.ListStore(str, bool, object) for db in self._databases: mapper = ModelMapper(db, [lambda i: i.db_name, lambda i: True]) model.append(mapper) self.treeview_delete_databases.set_model(model) model.connect('row-changed', self.on_row_changed) self.set_button_ok_active_state() def on_button_delete_databases_dialog_ok(self, button): self._win.response(Gtk.ResponseType.OK) def on_button_delete_databases_dialog_cancel(self, button): self._win.response(Gtk.ResponseType.CANCEL) def on_cellrenderertoggle_delete_toggled(self, widget, path): model = self.treeview_delete_databases.get_model() itr = model.get_iter(path) val = model.get_value(itr, 1) model.set(itr, 1, not val) def on_row_changed(self, model, path, iter): self.set_button_ok_active_state() # endregion
{'content_hash': 'f508c21c4a763815a894d1d9d0cc9b37', 'timestamp': '', 'source': 'github', 'line_count': 72, 'max_line_length': 101, 'avg_line_length': 33.75, 'alnum_prop': 0.6275720164609053, 'repo_name': 'RipcordSoftware/avancedb-replication-monitor', 'id': 'e30d4ceeab9e0447373929f5bd93971e67a54b1e', 'size': '2430', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'ui/dialogs/delete_databases_dialog.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '88'}, {'name': 'Python', 'bytes': '97413'}]}
/* @test * @bug 5097131 6299047 * @summary Test jvmti hprof * * @compile -g HelloWorld.java DefineClass.java ../DemoRun.java * @build CpuTimesDefineClassTest * @run main CpuTimesDefineClassTest DefineClass * * */ public class CpuTimesDefineClassTest { public static void main(String args[]) throws Exception { DemoRun hprof; /* Run JVMTI hprof agent with cpu=times */ hprof = new DemoRun("hprof", "cpu=times"); hprof.runit(args[0]); /* Make sure patterns in output look ok */ if (hprof.output_contains("ERROR")) { throw new RuntimeException("Test failed - ERROR seen in output"); } /* Must be a pass. */ System.out.println("Test passed - cleanly terminated"); } }
{'content_hash': 'f42b06eb3ae790e57edb0d6058f30db8', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 77, 'avg_line_length': 24.15625, 'alnum_prop': 0.6261319534282018, 'repo_name': 'rokn/Count_Words_2015', 'id': '97c50eb39984f77605d238b8ef88852c372bcf26', 'size': '1829', 'binary': False, 'copies': '51', 'ref': 'refs/heads/master', 'path': 'testing/openjdk2/jdk/test/demo/jvmti/hprof/CpuTimesDefineClassTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '61802'}, {'name': 'Ruby', 'bytes': '18888605'}]}
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Permissions_model extends BF_Model { /** * @var string User Table Name */ protected $table_name = 'permissions'; protected $key = 'id_permission'; /** * @var string Field name to use for the created time column in the DB table * if $set_created is enabled. */ protected $created_field = 'created_on'; /** * @var string Field name to use for the modified time column in the DB * table if $set_modified is enabled. */ protected $modified_field = 'modified_on'; /** * @var bool Set the created time automatically on a new record (if true) */ protected $set_created = FALSE; /** * @var bool Set the modified time automatically on editing a record (if true) */ protected $set_modified = FALSE; /** * @var bool Enable/Disable soft deletes. * If false, the delete() method will perform a delete of that row. * If true, the value in $deleted_field will be set to 1. */ protected $soft_deletes = FALSE; /** * @var string The type of date/time field used for $created_field and $modified_field. * Valid values are 'int', 'datetime', 'date'. */ protected $date_format = 'datetime'; //-------------------------------------------------------------------- /** * @var bool If true, will log user id in $created_by_field, $modified_by_field, * and $deleted_by_field. */ protected $log_user = FALSE; /** * Function construct used to load some library, do some actions, etc. */ public function __construct() { parent::__construct(); } }
{'content_hash': '8411246dc3a8f2964f8d92a0e0b62f28', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 91, 'avg_line_length': 27.93548387096774, 'alnum_prop': 0.5779445727482679, 'repo_name': 'tae089/report-document', 'id': 'c73ed5ffc60292996b7f1410793a856694123ee2', 'size': '1855', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'application/modules/users/models/Permissions_model.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '3625'}, {'name': 'CSS', 'bytes': '949477'}, {'name': 'HTML', 'bytes': '11457600'}, {'name': 'JavaScript', 'bytes': '3437558'}, {'name': 'PHP', 'bytes': '2007685'}, {'name': 'Python', 'bytes': '49829'}, {'name': 'Shell', 'bytes': '177'}]}
namespace sky { namespace shell { class ShellView; class TestRunner { public: static TestRunner& Shared(); struct TestDescriptor { std::string path; std::string package_root; bool is_snapshot = false; }; void Run(const TestDescriptor& test); private: TestRunner(); ~TestRunner(); scoped_ptr<ShellView> shell_view_; SkyEnginePtr sky_engine_; base::WeakPtrFactory<TestRunner> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(TestRunner); }; } // namespace shell } // namespace sky #endif // SKY_SHELL_TESTING_TEST_RUNNER_H_
{'content_hash': 'f1e66d5bd41d249d544f9b8645834753', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 53, 'avg_line_length': 17.59375, 'alnum_prop': 0.6927175843694494, 'repo_name': 'xunmengfeng/engine', 'id': '1f787491881cb1bf21c678d133db67ff8d6bd9dd', 'size': '1042', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'sky/shell/testing/test_runner.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '2706'}, {'name': 'C', 'bytes': '303331'}, {'name': 'C++', 'bytes': '22831891'}, {'name': 'Dart', 'bytes': '1422359'}, {'name': 'Groff', 'bytes': '29030'}, {'name': 'Java', 'bytes': '769475'}, {'name': 'JavaScript', 'bytes': '27365'}, {'name': 'Makefile', 'bytes': '402'}, {'name': 'Objective-C', 'bytes': '136889'}, {'name': 'Objective-C++', 'bytes': '433481'}, {'name': 'Python', 'bytes': '2890060'}, {'name': 'Shell', 'bytes': '173354'}, {'name': 'Yacc', 'bytes': '31141'}, {'name': 'nesC', 'bytes': '18347'}]}
<?xml version="1.0" encoding="UTF-8" ?> <phpunit bootstrap="test/bootstrap.php"> <testsuites> <testsuite name="Default Testsuite"> <directory>test</directory> </testsuite> </testsuites> <filter> <whitelist> <directory>src</directory> </whitelist> </filter> </phpunit>
{'content_hash': '417f033d462fb89f09c1d987a741d8ee', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 44, 'avg_line_length': 26.153846153846153, 'alnum_prop': 0.5705882352941176, 'repo_name': 'vend/pheat', 'id': 'be257eaece2f8768253c291882b2ed80b96cfbbe', 'size': '340', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'phpunit.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '57134'}]}
var compression = require('compression'); var express = require('express'); var http = require("http"); var morgan = require('morgan'); var bodyParser = require('body-parser'); var path = require('path'); var sass = require('node-sass'); var React = require('react/addons'); var webpackRequire = require('enhanced-require')(module, { resolve: { alias: { 'grommet': path.resolve(__dirname, '../../../src/js') }, loaders: [ { test: /\.js$/, loader: 'babel', exclude: /(node_modules\/intl|node_modules\/moment|node_modules\/react)/ } ] } }); var server = express(); var TodoApp = React.createFactory(webpackRequire('../src/js/TodoApp')); var theme = sass.renderSync({ file: path.resolve(__dirname, '../../../src/scss/grommet-core/index'), includePaths: [path.resolve(__dirname, '../../../node_modules')] }); var PORT = 8050; var app = express(); app.set('views', path.resolve(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(compression()); app.use(morgan('tiny')); app.use(bodyParser.json()); app.get('/', function (req, res) { // server side rendering with react + webpack var todoAppHtml = React.renderToString(TodoApp({})); res.render('index.ejs', {appBody: todoAppHtml, styleContent: '<style>' + theme.css + '</style>'}); //for single page app uncomment following line (remember to comment the 2 lines above) //res.sendFile(path.resolve(path.join(__dirname, '/../dist/index.html'))); }); app.use('/', express.static(path.join(__dirname, '/../dist'))); var server = http.createServer(app); server.listen(PORT); console.log('Server started, listening at: http://localhost:8050...');
{'content_hash': '95a6cbd87555274913bff7969a1bc798', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 100, 'avg_line_length': 27.20967741935484, 'alnum_prop': 0.6390041493775933, 'repo_name': 'Dinesh-Ramakrishnan/grommet', 'id': 'f14a794a00bf783c5a1ae44253fb5fe3dda8a4f1', 'size': '1757', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'examples/todo-app-modular/ssr/server.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '130516'}, {'name': 'HTML', 'bytes': '3817'}, {'name': 'JavaScript', 'bytes': '541574'}]}
package com.chencoder.rpc.common; import com.chencoder.rpc.common.bean.Request; import com.chencoder.rpc.common.bean.Response; public enum MessageType { REQUEST((byte) 0), RESPONSE((byte) 1); private byte value; MessageType(byte value) { this.value = value; } public static Class getMessageTypeByExtend(byte value) { switch (value & RESPONSE_MESSAGE_TYPE) { case 0x0: return Request.class; case RESPONSE_MESSAGE_TYPE: return Response.class; default: return Request.class; } } public byte getValue() { return value; } public final static byte RESPONSE_MESSAGE_TYPE = (byte) (1 << 7); }
{'content_hash': 'ac16fdf6ef516459b0b3d39fbf434805', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 69, 'avg_line_length': 21.37142857142857, 'alnum_prop': 0.5962566844919787, 'repo_name': 'chenxh/rpc', 'id': 'c9e32d58ec98831c4a6dbad28dd3c5c9a6d1423e', 'size': '748', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rpc-common/src/main/java/com/chencoder/rpc/common/MessageType.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '116180'}]}
<?php namespace Chamilo\Libraries\Format\Table\Extension\GalleryTable; use Chamilo\Libraries\Format\Table\TableDataProvider; /** * This class represents a data provider for a gallery table Refactoring from GalleryObjectTable to support the new * Table structure * * @author Sven Vanpoucke - Hogeschool Gent */ abstract class GalleryTableDataProvider extends TableDataProvider { }
{'content_hash': '5483c8a676b0d48e1300d900e3258d85', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 115, 'avg_line_length': 27.714285714285715, 'alnum_prop': 0.8015463917525774, 'repo_name': 'cosnicsTHLU/cosnics', 'id': '588e07d0b6c33174d592cdcb15ea8202f0517a91', 'size': '388', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Chamilo/Libraries/Format/Table/Extension/GalleryTable/GalleryTableDataProvider.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '86189'}, {'name': 'C#', 'bytes': '23363'}, {'name': 'CSS', 'bytes': '1135928'}, {'name': 'CoffeeScript', 'bytes': '17503'}, {'name': 'Gherkin', 'bytes': '24033'}, {'name': 'HTML', 'bytes': '542339'}, {'name': 'JavaScript', 'bytes': '5296016'}, {'name': 'Makefile', 'bytes': '3221'}, {'name': 'PHP', 'bytes': '21903304'}, {'name': 'Ruby', 'bytes': '618'}, {'name': 'Shell', 'bytes': '6385'}, {'name': 'Smarty', 'bytes': '15750'}, {'name': 'XSLT', 'bytes': '44115'}]}
import * as React from 'react'; import { HeadingClickEventFunc, MouseEvent, Style } from '../types'; export interface HeadingProps extends Style { content?: string; onClick?: HeadingClickEventFunc; showDescSortingIcon?: boolean; } /** * * @param props */ export const Heading: React.StatelessComponent<HeadingProps> = (props: HeadingProps) => { const { content, className, showDescSortingIcon, onClick } = props; const classNames: string = ['heading', className].join(' '); const handleClick = (e: MouseEvent) => { if (onClick !== undefined) { const isSortingEnabled: boolean = showDescSortingIcon !== undefined; onClick(e, { isSortingEnabled, content }); } }; return <th scope='col' className={classNames} onClick={handleClick}>{content}</th>; }; export default Heading;
{'content_hash': '7c240fdadc5b42f17ebc9156c4bcadad', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 89, 'avg_line_length': 27.580645161290324, 'alnum_prop': 0.6619883040935672, 'repo_name': 'jbw/tyble', 'id': '57c4f03e13396de2626ceabf21226aa91ebb90e8', 'size': '855', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/tyble/presentation/heading.tsx', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1141'}, {'name': 'HTML', 'bytes': '359'}, {'name': 'JavaScript', 'bytes': '3020'}, {'name': 'TypeScript', 'bytes': '27200'}]}
package org.nextrtc.examples.videochat_with_rest; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackageClasses = AppConfig.class) public class AppConfig { }
{'content_hash': '9bb1e6fc4867f28d00dcf1bbe4d41020', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 60, 'avg_line_length': 27.0, 'alnum_prop': 0.8444444444444444, 'repo_name': 'mslosarz/nextrtc-videochat-with-rest', 'id': 'cc20a5a328d6c149eb2cdc4ea3ad819a5f195543', 'size': '270', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/nextrtc/examples/videochat_with_rest/AppConfig.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '8454'}, {'name': 'Java', 'bytes': '51061'}, {'name': 'JavaScript', 'bytes': '7413'}]}
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': '8bb5e76f68a0492847301e97db056446', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': 'd7e48a94fc015d2173d6165a24214c622b1fc5b7', 'size': '195', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Scirpoides/Scirpoides holoschoenus/ Syn. Scirpoides thunbergii/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
const app = require('./server'); const server_port = process.env.OPENSHIFT_NODEJS_PORT || process.argv[2] || 8080 const server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'; if (!module.parent) { app.listen(server_port, server_ip_address, function () { console.log( "Listening on " + server_ip_address + ", port " + server_port ) }); } module.exports = app;
{'content_hash': '48fe492814656208ea9cd043bd21ce55', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 80, 'avg_line_length': 31.916666666666668, 'alnum_prop': 0.6684073107049608, 'repo_name': 'damienomurchu/data-miner', 'id': '117827841a6323259a4b6e4f240fa1940bd54fd2', 'size': '383', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '1506'}, {'name': 'JavaScript', 'bytes': '59784'}]}
 #include <aws/rbin/model/DeleteRuleRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::RecycleBin::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; DeleteRuleRequest::DeleteRuleRequest() : m_identifierHasBeenSet(false) { } Aws::String DeleteRuleRequest::SerializePayload() const { return {}; }
{'content_hash': '2f2049b61180a59313b37b4c34290989', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 55, 'avg_line_length': 15.791666666666666, 'alnum_prop': 0.7440633245382586, 'repo_name': 'cedral/aws-sdk-cpp', 'id': '6a895d08ffcd414b5b6ba93d0195c66577f8ceae', 'size': '498', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-rbin/source/model/DeleteRuleRequest.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '294220'}, {'name': 'C++', 'bytes': '428637022'}, {'name': 'CMake', 'bytes': '862025'}, {'name': 'Dockerfile', 'bytes': '11688'}, {'name': 'HTML', 'bytes': '7904'}, {'name': 'Java', 'bytes': '352201'}, {'name': 'Python', 'bytes': '106761'}, {'name': 'Shell', 'bytes': '10891'}]}
package org.osc.core.broker.service.request; public class DeleteSslEntryRequest implements Request { private String alias; public DeleteSslEntryRequest() { } public DeleteSslEntryRequest(String alias) { this.alias = alias; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } }
{'content_hash': 'd507bad414d827a3fddd8047348c52fb', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 55, 'avg_line_length': 18.0, 'alnum_prop': 0.648989898989899, 'repo_name': 'karimull/osc-core', 'id': 'd243a5dd17946284969797a28585567c696925f7', 'size': '1172', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'osc-service-api/src/main/java/org/osc/core/broker/service/request/DeleteSslEntryRequest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '327773'}, {'name': 'Java', 'bytes': '5416933'}, {'name': 'Makefile', 'bytes': '16941'}, {'name': 'Python', 'bytes': '44416'}, {'name': 'Shell', 'bytes': '15388'}]}
<?php namespace app\models; use yii\db\ActiveRecord; use yii\helpers\Url; /** * This is the model class for table "{{%topic}}". * * @property string $id * @property string $name * @property string $icon * @property string $desc * @property integer $count * @property integer $count_best * @property integer $count_follower * @property integer $count_last_week * @property integer $count_last_month */ class Topic extends ActiveRecord { public static function tableName() { return '{{%topic}}'; } /** * @inheritdoc */ public function rules() { return [ [['desc'], 'string'], [['count', 'count_best', 'count_follower', 'count_last_week', 'count_last_month'], 'integer'], [['name'], 'string', 'max' => 128], [['icon'], 'string', 'max' => 256], [['name'], 'unique'], ]; } public function statistics() { $this->count = QuestionTopic::find()->where(['topic_id' => $this->id])->count(); $this->count_last_week = QuestionTopic::find()->where(['topic_id' => $this->id])->andWhere(['>=', 'add_time', time()-86400*7])->count(); $this->count_last_month = QuestionTopic::find()->where(['topic_id' => $this->id])->andWhere(['>=', 'add_time', time()-86400*30])->count(); return $this; } public static function getByName($name) { $model = static::findOne(['name' => $name]); if ($model === null) { $model = new static(); $model->name = $name; $model->save(false); } return $model; } public static function findByName($name) { return static::findOne(['name' => $name]); } public function getUrl() { return Url::to(['question/index', 'topic' => strtolower($this->name)]); } }
{'content_hash': '5ed3791d3179a3f95aac8207245836cc', 'timestamp': '', 'source': 'github', 'line_count': 72, 'max_line_length': 146, 'avg_line_length': 25.916666666666668, 'alnum_prop': 0.5380493033226152, 'repo_name': 'upliu/OpenAsk', 'id': 'acf4d60c396b9ab17c5197636417a0b0ec50e137', 'size': '1866', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'models/Topic.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '1030'}, {'name': 'CSS', 'bytes': '6603'}, {'name': 'JavaScript', 'bytes': '7841'}, {'name': 'PHP', 'bytes': '425667'}, {'name': 'Shell', 'bytes': '167'}]}
using Abp.Authorization.Users; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Linq; using Repairis.Authorization.Roles; namespace Repairis.Authorization.Users { public class UserStore : AbpUserStore<Role, User> { public UserStore( IUnitOfWorkManager unitOfWorkManager, IRepository<User, long> userRepository, IRepository<Role> roleRepository, IAsyncQueryableExecuter asyncQueryableExecuter, IRepository<UserRole, long> userRoleRepository, IRepository<UserLogin, long> userLoginRepository, IRepository<UserClaim, long> userClaimRepository, IRepository<UserPermissionSetting, long> userPermissionSettingRepository) : base( unitOfWorkManager, userRepository, roleRepository, asyncQueryableExecuter, userRoleRepository, userLoginRepository, userClaimRepository, userPermissionSettingRepository) { } } }
{'content_hash': 'bdb3550943be622af0584f4004a80bd7', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 86, 'avg_line_length': 34.90625, 'alnum_prop': 0.6230975828111012, 'repo_name': 'dmytrokuzmin/RepairisCore', 'id': '8641be90297281815b367c291114d2a0f8536f3c', 'size': '1117', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Repairis.Core/Authorization/Users/UserStore.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '693539'}, {'name': 'CSS', 'bytes': '14286802'}, {'name': 'HTML', 'bytes': '26205'}, {'name': 'JavaScript', 'bytes': '5922353'}, {'name': 'PowerShell', 'bytes': '468'}]}
namespace atom { class NativeWindowObserver { public: virtual ~NativeWindowObserver() {} // Called when the web page of the window has updated it's document title. virtual void OnPageTitleUpdated(bool* prevent_default, const std::string& title) {} // Called when the web page in window wants to create a popup window. virtual void WillCreatePopupWindow(const base::string16& frame_name, const GURL& target_url, const std::string& partition_id, WindowOpenDisposition disposition) {} virtual void OnFrameRendered(scoped_ptr<uint8[]> rgb, const int size) {} // Called when user is starting an navigation in web page. virtual void WillNavigate(bool* prevent_default, const GURL& url) {} // Called when the window is gonna closed. virtual void WillCloseWindow(bool* prevent_default) {} // Called when the window is closed. virtual void OnWindowClosed() {} // Called when window loses focus. virtual void OnWindowBlur() {} // Called when window gains focus. virtual void OnWindowFocus() {} // Called when window state changed. virtual void OnWindowMaximize() {} virtual void OnWindowUnmaximize() {} virtual void OnWindowMinimize() {} virtual void OnWindowRestore() {} virtual void OnWindowResize() {} virtual void OnWindowMove() {} virtual void OnWindowMoved() {} virtual void OnWindowEnterFullScreen() {} virtual void OnWindowLeaveFullScreen() {} virtual void OnWindowEnterHtmlFullScreen() {} virtual void OnWindowLeaveHtmlFullScreen() {} // Redirect devtools events. virtual void OnDevToolsFocus() {} virtual void OnDevToolsOpened() {} virtual void OnDevToolsClosed() {} // Called when renderer is hung. virtual void OnRendererUnresponsive() {} // Called when renderer recovers. virtual void OnRendererResponsive() {} // Called on Windows when App Commands arrive (WM_APPCOMMAND) virtual void OnExecuteWindowsCommand(const std::string& command_name) {} }; } // namespace atom #endif // ATOM_BROWSER_NATIVE_WINDOW_OBSERVER_H_
{'content_hash': '12c1fdeffeceb6a37557201194bdab52', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 76, 'avg_line_length': 33.765625, 'alnum_prop': 0.6876446089773253, 'repo_name': 'fffej/electron', 'id': 'db6587de1f44725543d6fcf3c2715591523a8fa2', 'size': '2514', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'atom/browser/native_window_observer.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '3671'}, {'name': 'C++', 'bytes': '1385609'}, {'name': 'CoffeeScript', 'bytes': '197124'}, {'name': 'HTML', 'bytes': '4720'}, {'name': 'JavaScript', 'bytes': '9650'}, {'name': 'Objective-C', 'bytes': '10402'}, {'name': 'Objective-C++', 'bytes': '125325'}, {'name': 'Python', 'bytes': '75275'}, {'name': 'Shell', 'bytes': '2593'}]}
<?php Class FavModel { protected $_table = "shop_fav"; public function __construct() { $this->_db = Yaf_Registry::get('_db'); } public function select($username) { $params = array( "fav_id", "user_uuid", "product_uuid", "fav_time", "comment" ); $whereis = array( "fav_id"=>$username ); $result = $this->_db->select($this->_table, $params ,$whereis ); return $result==null?false:$result; } public function selectAll($where) { //实现左连接表查询 $join = array( "[>]shop_product"=>"product_uuid" ); $params = array( "fav_id", "product_name", "money", "product_uuid", "fav_time", "comment" ); $whereis = array("user_uuid"=>$where); $result = $this->_db->select( "shop_fav" , $join, $params, $whereis ); // print_r($this->_db->error()); // print_r($result); return $result==null?false:$result; } public function insert($info) { $result = $this->_db->insert($this->_table, $info); // print_r($this->_db->error()); return $result<1?false:true; } public function update($username, $info) { $result = $this->_db->update($this->_table, $info, array( 'fav_id'=>$username )); return $result<1?false:true; } public function del($username) { $whereis = array( 'fav_id'=>$username ); $result = $this->_db->delete($this->_table, $whereis ); return $result==null?false:true; } }
{'content_hash': 'b3489142272a7d824344e24a0602d02b', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 90, 'avg_line_length': 26.98507462686567, 'alnum_prop': 0.4446902654867257, 'repo_name': 'lsqtongxin/yaf', 'id': 'aae9dcdee54aa9b7b2b37297bafde4a774515408', 'size': '1824', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'application/models/Fav.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '102'}, {'name': 'CSS', 'bytes': '379095'}, {'name': 'HTML', 'bytes': '132410'}, {'name': 'JavaScript', 'bytes': '136326'}, {'name': 'PHP', 'bytes': '485719'}, {'name': 'Smarty', 'bytes': '3657'}]}
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/display/output_configurator.h" #include <cmath> #include <cstdarg> #include <map> #include <string> #include <vector> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/message_loop/message_loop.h" #include "base/strings/stringprintf.h" #include "chromeos/display/native_display_delegate.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace { // Strings returned by TestNativeDisplayDelegate::GetActionsAndClear() to // describe various actions that were performed. const char kInitXRandR[] = "init"; const char kGrab[] = "grab"; const char kUngrab[] = "ungrab"; const char kSync[] = "sync"; const char kForceDPMS[] = "dpms"; // String returned by TestNativeDisplayDelegate::GetActionsAndClear() if no // actions were requested. const char kNoActions[] = ""; // Returns a string describing a TestNativeDisplayDelegate::SetBackgroundColor() // call. std::string GetBackgroundAction(uint32 color_argb) { return base::StringPrintf("background(0x%x)", color_argb); } // Returns a string describing a TestNativeDisplayDelegate::AddOutputMode() // call. std::string GetAddOutputModeAction(RROutput output, RRMode mode) { return base::StringPrintf("add_mode(output=%lu,mode=%lu)", output, mode); } // Returns a string describing a TestNativeDisplayDelegate::Configure() // call. std::string GetCrtcAction(RRCrtc crtc, int x, int y, RRMode mode, RROutput output) { return base::StringPrintf("crtc(crtc=%lu,x=%d,y=%d,mode=%lu,output=%lu)", crtc, x, y, mode, output); } // Returns a string describing a TestNativeDisplayDelegate::CreateFramebuffer() // call. std::string GetFramebufferAction(int width, int height, RRCrtc crtc1, RRCrtc crtc2) { return base::StringPrintf( "framebuffer(width=%d,height=%d,crtc1=%lu,crtc2=%lu)", width, height, crtc1, crtc2); } // Returns a string describing a TestNativeDisplayDelegate::ConfigureCTM() call. std::string GetCTMAction( int device_id, const OutputConfigurator::CoordinateTransformation& ctm) { return base::StringPrintf("ctm(id=%d,transform=(%f,%f,%f,%f))", device_id, ctm.x_scale, ctm.x_offset, ctm.y_scale, ctm.y_offset); } // Returns a string describing a TestNativeDisplayDelegate::SetHDCPState() call. std::string GetSetHDCPStateAction(RROutput id, ui::HDCPState state) { return base::StringPrintf("set_hdcp(id=%lu,state=%d)", id, state); } // Joins a sequence of strings describing actions (e.g. kScreenDim) such // that they can be compared against a string returned by // ActionLogger::GetActionsAndClear(). The list of actions must be // terminated by a NULL pointer. std::string JoinActions(const char* action, ...) { std::string actions; va_list arg_list; va_start(arg_list, action); while (action) { if (!actions.empty()) actions += ","; actions += action; action = va_arg(arg_list, const char*); } va_end(arg_list); return actions; } class ActionLogger { public: ActionLogger() {} void AppendAction(const std::string& action) { if (!actions_.empty()) actions_ += ","; actions_ += action; } // Returns a comma-separated string describing the actions that were // requested since the previous call to GetActionsAndClear() (i.e. // results are non-repeatable). std::string GetActionsAndClear() { std::string actions = actions_; actions_.clear(); return actions; } private: std::string actions_; DISALLOW_COPY_AND_ASSIGN(ActionLogger); }; class TestTouchscreenDelegate : public OutputConfigurator::TouchscreenDelegate { public: // Ownership of |log| remains with the caller. explicit TestTouchscreenDelegate(ActionLogger* log) : log_(log) {} virtual ~TestTouchscreenDelegate() {} const OutputConfigurator::CoordinateTransformation& GetCTM( int touch_device_id) { return ctms_[touch_device_id]; } // OutputConfigurator::TouchscreenDelegate implementation: virtual void AssociateTouchscreens( std::vector<OutputConfigurator::OutputSnapshot>* outputs) OVERRIDE {} virtual void ConfigureCTM( int touch_device_id, const OutputConfigurator::CoordinateTransformation& ctm) OVERRIDE { log_->AppendAction(GetCTMAction(touch_device_id, ctm)); ctms_[touch_device_id] = ctm; } private: ActionLogger* log_; // Not owned. // Most-recently-configured transformation matrices, keyed by touch device ID. std::map<int, OutputConfigurator::CoordinateTransformation> ctms_; DISALLOW_COPY_AND_ASSIGN(TestTouchscreenDelegate); }; class TestNativeDisplayDelegate : public NativeDisplayDelegate { public: // Ownership of |log| remains with the caller. explicit TestNativeDisplayDelegate(ActionLogger* log) : max_configurable_pixels_(0), hdcp_state_(ui::HDCP_STATE_UNDESIRED), log_(log) {} virtual ~TestNativeDisplayDelegate() {} const std::vector<OutputConfigurator::OutputSnapshot>& outputs() const { return outputs_; } void set_outputs( const std::vector<OutputConfigurator::OutputSnapshot>& outputs) { outputs_ = outputs; } void set_max_configurable_pixels(int pixels) { max_configurable_pixels_ = pixels; } void set_hdcp_state(ui::HDCPState state) { hdcp_state_ = state; } // OutputConfigurator::Delegate overrides: virtual void Initialize() OVERRIDE { log_->AppendAction(kInitXRandR); } virtual void GrabServer() OVERRIDE { log_->AppendAction(kGrab); } virtual void UngrabServer() OVERRIDE { log_->AppendAction(kUngrab); } virtual void SyncWithServer() OVERRIDE { log_->AppendAction(kSync); } virtual void SetBackgroundColor(uint32 color_argb) OVERRIDE { log_->AppendAction(GetBackgroundAction(color_argb)); } virtual void ForceDPMSOn() OVERRIDE { log_->AppendAction(kForceDPMS); } virtual std::vector<OutputConfigurator::OutputSnapshot> GetOutputs() OVERRIDE { return outputs_; } virtual void AddMode(const OutputConfigurator::OutputSnapshot& output, RRMode mode) OVERRIDE { log_->AppendAction(GetAddOutputModeAction(output.output, mode)); } virtual bool Configure(const OutputConfigurator::OutputSnapshot& output, RRMode mode, int x, int y) OVERRIDE { log_->AppendAction(GetCrtcAction(output.crtc, x, y, mode, output.output)); if (max_configurable_pixels_ == 0) return true; OutputConfigurator::OutputSnapshot* snapshot = GetOutputFromId( output.output); if (!snapshot) return false; const OutputConfigurator::ModeInfo* mode_info = OutputConfigurator::GetModeInfo(*snapshot, mode); if (!mode_info) return false; return mode_info->width * mode_info->height <= max_configurable_pixels_; } virtual void CreateFrameBuffer( int width, int height, const std::vector<OutputConfigurator::OutputSnapshot>& outputs) OVERRIDE { log_->AppendAction( GetFramebufferAction(width, height, outputs.size() >= 1 ? outputs[0].crtc : 0, outputs.size() >= 2 ? outputs[1].crtc : 0)); } virtual bool GetHDCPState(const OutputConfigurator::OutputSnapshot& output, ui::HDCPState* state) OVERRIDE { *state = hdcp_state_; return true; } virtual bool SetHDCPState(const OutputConfigurator::OutputSnapshot& output, ui::HDCPState state) OVERRIDE { log_->AppendAction(GetSetHDCPStateAction(output.output, state)); return true; } virtual void AddObserver(NativeDisplayObserver* observer) OVERRIDE {} virtual void RemoveObserver(NativeDisplayObserver* observer) OVERRIDE {} private: OutputConfigurator::OutputSnapshot* GetOutputFromId(RROutput output_id) { for (unsigned int i = 0; i < outputs_.size(); i++) { if (outputs_[i].output == output_id) return &outputs_[i]; } return NULL; } // Outputs to be returned by GetOutputs(). std::vector<OutputConfigurator::OutputSnapshot> outputs_; // |max_configurable_pixels_| represents the maximum number of pixels that // Configure will support. Tests can use this to force Configure // to fail if attempting to set a resolution that is higher than what // a device might support under a given circumstance. // A value of 0 means that no limit is enforced and Configure will // return success regardless of the resolution. int max_configurable_pixels_; // Result value of GetHDCPState(). ui::HDCPState hdcp_state_; ActionLogger* log_; // Not owned. DISALLOW_COPY_AND_ASSIGN(TestNativeDisplayDelegate); }; class TestObserver : public OutputConfigurator::Observer { public: explicit TestObserver(OutputConfigurator* configurator) : configurator_(configurator) { Reset(); configurator_->AddObserver(this); } virtual ~TestObserver() { configurator_->RemoveObserver(this); } int num_changes() const { return num_changes_; } int num_failures() const { return num_failures_; } const std::vector<OutputConfigurator::OutputSnapshot>& latest_outputs() const { return latest_outputs_; } ui::OutputState latest_failed_state() const { return latest_failed_state_; } void Reset() { num_changes_ = 0; num_failures_ = 0; latest_outputs_.clear(); latest_failed_state_ = ui::OUTPUT_STATE_INVALID; } // OutputConfigurator::Observer overrides: virtual void OnDisplayModeChanged( const std::vector<OutputConfigurator::OutputSnapshot>& outputs) OVERRIDE { num_changes_++; latest_outputs_ = outputs; } virtual void OnDisplayModeChangeFailed(ui::OutputState failed_new_state) OVERRIDE { num_failures_++; latest_failed_state_ = failed_new_state; } private: OutputConfigurator* configurator_; // Not owned. // Number of times that OnDisplayMode*() has been called. int num_changes_; int num_failures_; // Parameters most recently passed to OnDisplayMode*(). std::vector<OutputConfigurator::OutputSnapshot> latest_outputs_; ui::OutputState latest_failed_state_; DISALLOW_COPY_AND_ASSIGN(TestObserver); }; class TestStateController : public OutputConfigurator::StateController { public: TestStateController() : state_(ui::OUTPUT_STATE_DUAL_EXTENDED) {} virtual ~TestStateController() {} void set_state(ui::OutputState state) { state_ = state; } // OutputConfigurator::StateController overrides: virtual ui::OutputState GetStateForDisplayIds( const std::vector<int64>& outputs) const OVERRIDE { return state_; } virtual bool GetResolutionForDisplayId( int64 display_id, int *width, int *height) const OVERRIDE { return false; } private: ui::OutputState state_; DISALLOW_COPY_AND_ASSIGN(TestStateController); }; class TestMirroringController : public OutputConfigurator::SoftwareMirroringController { public: TestMirroringController() : software_mirroring_enabled_(false) {} virtual ~TestMirroringController() {} virtual void SetSoftwareMirroring(bool enabled) OVERRIDE { software_mirroring_enabled_ = enabled; } bool software_mirroring_enabled() const { return software_mirroring_enabled_; } private: bool software_mirroring_enabled_; DISALLOW_COPY_AND_ASSIGN(TestMirroringController); }; class OutputConfiguratorTest : public testing::Test { public: // Predefined modes that can be used by outputs. static const RRMode kSmallModeId; static const int kSmallModeWidth; static const int kSmallModeHeight; static const RRMode kBigModeId; static const int kBigModeWidth; static const int kBigModeHeight; OutputConfiguratorTest() : observer_(&configurator_), test_api_(&configurator_) { } virtual ~OutputConfiguratorTest() {} virtual void SetUp() OVERRIDE { log_.reset(new ActionLogger()); native_display_delegate_ = new TestNativeDisplayDelegate(log_.get()); configurator_.SetNativeDisplayDelegateForTesting( scoped_ptr<NativeDisplayDelegate>(native_display_delegate_)); touchscreen_delegate_ = new TestTouchscreenDelegate(log_.get()); configurator_.SetTouchscreenDelegateForTesting( scoped_ptr<OutputConfigurator::TouchscreenDelegate>( touchscreen_delegate_)); configurator_.set_state_controller(&state_controller_); configurator_.set_mirroring_controller(&mirroring_controller_); OutputConfigurator::ModeInfo small_mode_info; small_mode_info.width = kSmallModeWidth; small_mode_info.height = kSmallModeHeight; OutputConfigurator::ModeInfo big_mode_info; big_mode_info.width = kBigModeWidth; big_mode_info.height = kBigModeHeight; OutputConfigurator::OutputSnapshot* o = &outputs_[0]; o->output = 1; o->crtc = 10; o->current_mode = kSmallModeId; o->native_mode = kSmallModeId; o->type = ui::OUTPUT_TYPE_INTERNAL; o->is_aspect_preserving_scaling = true; o->mode_infos[kSmallModeId] = small_mode_info; o->has_display_id = true; o->display_id = 123; o->index = 0; o = &outputs_[1]; o->output = 2; o->crtc = 11; o->current_mode = kBigModeId; o->native_mode = kBigModeId; o->type = ui::OUTPUT_TYPE_HDMI; o->is_aspect_preserving_scaling = true; o->mode_infos[kSmallModeId] = small_mode_info; o->mode_infos[kBigModeId] = big_mode_info; o->has_display_id = true; o->display_id = 456; o->index = 1; UpdateOutputs(2, false); } protected: // Configures |native_display_delegate_| to return the first |num_outputs| // entries from // |outputs_|. If |send_events| is true, also sends screen-change and // output-change events to |configurator_| and triggers the configure // timeout if one was scheduled. void UpdateOutputs(size_t num_outputs, bool send_events) { ASSERT_LE(num_outputs, arraysize(outputs_)); std::vector<OutputConfigurator::OutputSnapshot> outputs; for (size_t i = 0; i < num_outputs; ++i) outputs.push_back(outputs_[i]); native_display_delegate_->set_outputs(outputs); if (send_events) { configurator_.OnConfigurationChanged(); test_api_.TriggerConfigureTimeout(); } } // Initializes |configurator_| with a single internal display. void InitWithSingleOutput() { UpdateOutputs(1, false); EXPECT_EQ(kNoActions, log_->GetActionsAndClear()); configurator_.Init(false); EXPECT_EQ(kNoActions, log_->GetActionsAndClear()); configurator_.ForceInitialConfigure(0); EXPECT_EQ( JoinActions( kGrab, kInitXRandR, GetFramebufferAction( kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, 0).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output) .c_str(), kForceDPMS, kUngrab, NULL), log_->GetActionsAndClear()); } base::MessageLoop message_loop_; TestStateController state_controller_; TestMirroringController mirroring_controller_; OutputConfigurator configurator_; TestObserver observer_; scoped_ptr<ActionLogger> log_; TestNativeDisplayDelegate* native_display_delegate_; // not owned TestTouchscreenDelegate* touchscreen_delegate_; // not owned OutputConfigurator::TestApi test_api_; OutputConfigurator::OutputSnapshot outputs_[2]; private: DISALLOW_COPY_AND_ASSIGN(OutputConfiguratorTest); }; const RRMode OutputConfiguratorTest::kSmallModeId = 20; const int OutputConfiguratorTest::kSmallModeWidth = 1366; const int OutputConfiguratorTest::kSmallModeHeight = 768; const RRMode OutputConfiguratorTest::kBigModeId = 21; const int OutputConfiguratorTest::kBigModeWidth = 2560; const int OutputConfiguratorTest::kBigModeHeight = 1600; } // namespace TEST_F(OutputConfiguratorTest, FindOutputModeMatchingSize) { OutputConfigurator::OutputSnapshot output; // Fields are width, height, interlaced, refresh rate. output.mode_infos[11] = OutputConfigurator::ModeInfo(1920, 1200, false, 60.0); // Different rates. output.mode_infos[12] = OutputConfigurator::ModeInfo(1920, 1080, false, 30.0); output.mode_infos[13] = OutputConfigurator::ModeInfo(1920, 1080, false, 50.0); output.mode_infos[14] = OutputConfigurator::ModeInfo(1920, 1080, false, 40.0); output.mode_infos[15] = OutputConfigurator::ModeInfo(1920, 1080, false, 0.0); // Interlaced vs non-interlaced. output.mode_infos[16] = OutputConfigurator::ModeInfo(1280, 720, true, 60.0); output.mode_infos[17] = OutputConfigurator::ModeInfo(1280, 720, false, 40.0); // Interlaced only. output.mode_infos[18] = OutputConfigurator::ModeInfo(1024, 768, true, 0.0); output.mode_infos[19] = OutputConfigurator::ModeInfo(1024, 768, true, 40.0); output.mode_infos[20] = OutputConfigurator::ModeInfo(1024, 768, true, 60.0); // Mixed. output.mode_infos[21] = OutputConfigurator::ModeInfo(1024, 600, true, 60.0); output.mode_infos[22] = OutputConfigurator::ModeInfo(1024, 600, false, 40.0); output.mode_infos[23] = OutputConfigurator::ModeInfo(1024, 600, false, 50.0); // Just one interlaced mode. output.mode_infos[24] = OutputConfigurator::ModeInfo(640, 480, true, 60.0); // Refresh rate not available. output.mode_infos[25] = OutputConfigurator::ModeInfo(320, 200, false, 0.0); EXPECT_EQ(11u, OutputConfigurator::FindOutputModeMatchingSize(output, 1920, 1200)); // Should pick highest refresh rate. EXPECT_EQ(13u, OutputConfigurator::FindOutputModeMatchingSize(output, 1920, 1080)); // Should pick non-interlaced mode. EXPECT_EQ(17u, OutputConfigurator::FindOutputModeMatchingSize(output, 1280, 720)); // Interlaced only. Should pick one with the highest refresh rate in // interlaced mode. EXPECT_EQ(20u, OutputConfigurator::FindOutputModeMatchingSize(output, 1024, 768)); // Mixed: Should pick one with the highest refresh rate in // interlaced mode. EXPECT_EQ(23u, OutputConfigurator::FindOutputModeMatchingSize(output, 1024, 600)); // Just one interlaced mode. EXPECT_EQ(24u, OutputConfigurator::FindOutputModeMatchingSize(output, 640, 480)); // Refresh rate not available. EXPECT_EQ(25u, OutputConfigurator::FindOutputModeMatchingSize(output, 320, 200)); // No mode found. EXPECT_EQ(0u, OutputConfigurator::FindOutputModeMatchingSize(output, 1440, 900)); } TEST_F(OutputConfiguratorTest, ConnectSecondOutput) { InitWithSingleOutput(); // Connect a second output and check that the configurator enters // extended mode. observer_.Reset(); state_controller_.set_state(ui::OUTPUT_STATE_DUAL_EXTENDED); UpdateOutputs(2, true); const int kDualHeight = kSmallModeHeight + OutputConfigurator::kVerticalGap + kBigModeHeight; EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kBigModeWidth, kDualHeight, outputs_[0].crtc, outputs_[1].crtc) .c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), GetCrtcAction(outputs_[1].crtc, 0, kSmallModeHeight + OutputConfigurator::kVerticalGap, kBigModeId, outputs_[1].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_FALSE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); observer_.Reset(); EXPECT_TRUE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_DUAL_MIRROR)); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction(kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, outputs_[1].crtc).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), GetCrtcAction( outputs_[1].crtc, 0, 0, kSmallModeId, outputs_[1].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_FALSE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); // Disconnect the second output. observer_.Reset(); UpdateOutputs(1, true); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, 0).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_FALSE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); // Get rid of shared modes to force software mirroring. outputs_[1].mode_infos.erase(kSmallModeId); state_controller_.set_state(ui::OUTPUT_STATE_DUAL_EXTENDED); UpdateOutputs(2, true); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kBigModeWidth, kDualHeight, outputs_[0].crtc, outputs_[1].crtc) .c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), GetCrtcAction(outputs_[1].crtc, 0, kSmallModeHeight + OutputConfigurator::kVerticalGap, kBigModeId, outputs_[1].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_FALSE(mirroring_controller_.software_mirroring_enabled()); observer_.Reset(); EXPECT_TRUE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_DUAL_MIRROR)); EXPECT_EQ(JoinActions(kGrab, kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_EQ(ui::OUTPUT_STATE_DUAL_EXTENDED, configurator_.output_state()); EXPECT_TRUE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); // Setting OUTPUT_STATE_DUAL_MIRROR should try to reconfigure. observer_.Reset(); EXPECT_TRUE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_DUAL_EXTENDED)); EXPECT_EQ(JoinActions(NULL), log_->GetActionsAndClear()); EXPECT_FALSE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); // Set back to software mirror mode. observer_.Reset(); EXPECT_TRUE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_DUAL_MIRROR)); EXPECT_EQ(JoinActions(kGrab, kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_EQ(ui::OUTPUT_STATE_DUAL_EXTENDED, configurator_.output_state()); EXPECT_TRUE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); // Disconnect the second output. observer_.Reset(); UpdateOutputs(1, true); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, 0).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_FALSE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); } TEST_F(OutputConfiguratorTest, SetDisplayPower) { InitWithSingleOutput(); state_controller_.set_state(ui::OUTPUT_STATE_DUAL_MIRROR); observer_.Reset(); UpdateOutputs(2, true); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction(kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, outputs_[1].crtc).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), GetCrtcAction( outputs_[1].crtc, 0, 0, kSmallModeId, outputs_[1].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_FALSE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); // Turning off the internal display should switch the external display to // its native mode. observer_.Reset(); configurator_.SetDisplayPower(DISPLAY_POWER_INTERNAL_OFF_EXTERNAL_ON, OutputConfigurator::kSetDisplayPowerNoFlags); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kBigModeWidth, kBigModeHeight, outputs_[0].crtc, outputs_[1].crtc) .c_str(), GetCrtcAction(outputs_[0].crtc, 0, 0, 0, outputs_[0].output).c_str(), GetCrtcAction(outputs_[1].crtc, 0, 0, kBigModeId, outputs_[1].output) .c_str(), kForceDPMS, kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_EQ(ui::OUTPUT_STATE_SINGLE, configurator_.output_state()); EXPECT_EQ(1, observer_.num_changes()); // When all displays are turned off, the framebuffer should switch back // to the mirrored size. observer_.Reset(); configurator_.SetDisplayPower(DISPLAY_POWER_ALL_OFF, OutputConfigurator::kSetDisplayPowerNoFlags); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction(kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, outputs_[1].crtc).c_str(), GetCrtcAction(outputs_[0].crtc, 0, 0, 0, outputs_[0].output).c_str(), GetCrtcAction(outputs_[1].crtc, 0, 0, 0, outputs_[1].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_EQ(ui::OUTPUT_STATE_DUAL_MIRROR, configurator_.output_state()); EXPECT_FALSE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); // Turn all displays on and check that mirroring is still used. observer_.Reset(); configurator_.SetDisplayPower(DISPLAY_POWER_ALL_ON, OutputConfigurator::kSetDisplayPowerNoFlags); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction(kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, outputs_[1].crtc).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), GetCrtcAction( outputs_[1].crtc, 0, 0, kSmallModeId, outputs_[1].output).c_str(), kForceDPMS, kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_EQ(ui::OUTPUT_STATE_DUAL_MIRROR, configurator_.output_state()); EXPECT_FALSE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); // Get rid of shared modes to force software mirroring. outputs_[1].mode_infos.erase(kSmallModeId); state_controller_.set_state(ui::OUTPUT_STATE_DUAL_MIRROR); observer_.Reset(); UpdateOutputs(2, true); const int kDualHeight = kSmallModeHeight + OutputConfigurator::kVerticalGap + kBigModeHeight; EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kBigModeWidth, kDualHeight, outputs_[0].crtc, outputs_[1].crtc) .c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), GetCrtcAction(outputs_[1].crtc, 0, kSmallModeHeight + OutputConfigurator::kVerticalGap, kBigModeId, outputs_[1].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_EQ(ui::OUTPUT_STATE_DUAL_EXTENDED, configurator_.output_state()); EXPECT_TRUE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); // Turning off the internal display should switch the external display to // its native mode. observer_.Reset(); configurator_.SetDisplayPower(DISPLAY_POWER_INTERNAL_OFF_EXTERNAL_ON, OutputConfigurator::kSetDisplayPowerNoFlags); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kBigModeWidth, kBigModeHeight, outputs_[0].crtc, outputs_[1].crtc) .c_str(), GetCrtcAction(outputs_[0].crtc, 0, 0, 0, outputs_[0].output).c_str(), GetCrtcAction(outputs_[1].crtc, 0, 0, kBigModeId, outputs_[1].output) .c_str(), kForceDPMS, kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_EQ(ui::OUTPUT_STATE_SINGLE, configurator_.output_state()); EXPECT_FALSE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); // When all displays are turned off, the framebuffer should switch back // to the extended + software mirroring. observer_.Reset(); configurator_.SetDisplayPower(DISPLAY_POWER_ALL_OFF, OutputConfigurator::kSetDisplayPowerNoFlags); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kBigModeWidth, kDualHeight, outputs_[0].crtc, outputs_[1].crtc) .c_str(), GetCrtcAction(outputs_[0].crtc, 0, 0, 0, outputs_[0].output).c_str(), GetCrtcAction(outputs_[1].crtc, 0, kSmallModeHeight + OutputConfigurator::kVerticalGap, 0, outputs_[1].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_EQ(ui::OUTPUT_STATE_DUAL_EXTENDED, configurator_.output_state()); EXPECT_TRUE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); // Turn all displays on and check that mirroring is still used. observer_.Reset(); configurator_.SetDisplayPower(DISPLAY_POWER_ALL_ON, OutputConfigurator::kSetDisplayPowerNoFlags); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kBigModeWidth, kDualHeight, outputs_[0].crtc, outputs_[1].crtc) .c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), GetCrtcAction(outputs_[1].crtc, 0, kSmallModeHeight + OutputConfigurator::kVerticalGap, kBigModeId, outputs_[1].output).c_str(), kForceDPMS, kUngrab, NULL), log_->GetActionsAndClear()); EXPECT_EQ(ui::OUTPUT_STATE_DUAL_EXTENDED, configurator_.output_state()); EXPECT_TRUE(mirroring_controller_.software_mirroring_enabled()); EXPECT_EQ(1, observer_.num_changes()); } TEST_F(OutputConfiguratorTest, SuspendAndResume) { InitWithSingleOutput(); // No preparation is needed before suspending when the display is already // on. The configurator should still reprobe on resume in case a display // was connected while suspended. configurator_.SuspendDisplays(); EXPECT_EQ(kNoActions, log_->GetActionsAndClear()); configurator_.ResumeDisplays(); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, 0).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), kForceDPMS, kUngrab, NULL), log_->GetActionsAndClear()); // Now turn the display off before suspending and check that the // configurator turns it back on and syncs with the server. configurator_.SetDisplayPower(DISPLAY_POWER_ALL_OFF, OutputConfigurator::kSetDisplayPowerNoFlags); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, 0).c_str(), GetCrtcAction(outputs_[0].crtc, 0, 0, 0, outputs_[0].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); configurator_.SuspendDisplays(); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, 0).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), kForceDPMS, kUngrab, kSync, NULL), log_->GetActionsAndClear()); configurator_.ResumeDisplays(); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, 0).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), kForceDPMS, kUngrab, NULL), log_->GetActionsAndClear()); // If a second, external display is connected, the displays shouldn't be // powered back on before suspending. state_controller_.set_state(ui::OUTPUT_STATE_DUAL_MIRROR); UpdateOutputs(2, true); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction(kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, outputs_[1].crtc).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), GetCrtcAction( outputs_[1].crtc, 0, 0, kSmallModeId, outputs_[1].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); configurator_.SetDisplayPower(DISPLAY_POWER_ALL_OFF, OutputConfigurator::kSetDisplayPowerNoFlags); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction(kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, outputs_[1].crtc).c_str(), GetCrtcAction(outputs_[0].crtc, 0, 0, 0, outputs_[0].output).c_str(), GetCrtcAction(outputs_[1].crtc, 0, 0, 0, outputs_[1].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); configurator_.SuspendDisplays(); EXPECT_EQ(JoinActions(kGrab, kUngrab, kSync, NULL), log_->GetActionsAndClear()); // If a display is disconnected while suspended, the configurator should // pick up the change. UpdateOutputs(1, false); configurator_.ResumeDisplays(); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, 0).c_str(), GetCrtcAction(outputs_[0].crtc, 0, 0, 0, outputs_[0].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); } TEST_F(OutputConfiguratorTest, Headless) { UpdateOutputs(0, false); EXPECT_EQ(kNoActions, log_->GetActionsAndClear()); configurator_.Init(false); EXPECT_EQ(kNoActions, log_->GetActionsAndClear()); configurator_.ForceInitialConfigure(0); EXPECT_EQ(JoinActions(kGrab, kInitXRandR, kForceDPMS, kUngrab, NULL), log_->GetActionsAndClear()); // Not much should happen when the display power state is changed while // no displays are connected. configurator_.SetDisplayPower(DISPLAY_POWER_ALL_OFF, OutputConfigurator::kSetDisplayPowerNoFlags); EXPECT_EQ(JoinActions(kGrab, kUngrab, NULL), log_->GetActionsAndClear()); configurator_.SetDisplayPower(DISPLAY_POWER_ALL_ON, OutputConfigurator::kSetDisplayPowerNoFlags); EXPECT_EQ(JoinActions(kGrab, kForceDPMS, kUngrab, NULL), log_->GetActionsAndClear()); // Connect an external display and check that it's configured correctly. outputs_[0] = outputs_[1]; UpdateOutputs(1, true); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction( kBigModeWidth, kBigModeHeight, outputs_[0].crtc, 0).c_str(), GetCrtcAction(outputs_[0].crtc, 0, 0, kBigModeId, outputs_[0].output) .c_str(), kUngrab, NULL), log_->GetActionsAndClear()); } TEST_F(OutputConfiguratorTest, StartWithTwoOutputs) { UpdateOutputs(2, false); EXPECT_EQ(kNoActions, log_->GetActionsAndClear()); configurator_.Init(false); EXPECT_EQ(kNoActions, log_->GetActionsAndClear()); state_controller_.set_state(ui::OUTPUT_STATE_DUAL_MIRROR); configurator_.ForceInitialConfigure(0); EXPECT_EQ( JoinActions( kGrab, kInitXRandR, GetFramebufferAction(kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, outputs_[1].crtc).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), GetCrtcAction( outputs_[1].crtc, 0, 0, kSmallModeId, outputs_[1].output).c_str(), kForceDPMS, kUngrab, NULL), log_->GetActionsAndClear()); } TEST_F(OutputConfiguratorTest, InvalidOutputStates) { UpdateOutputs(0, false); EXPECT_EQ(kNoActions, log_->GetActionsAndClear()); configurator_.Init(false); configurator_.ForceInitialConfigure(0); observer_.Reset(); EXPECT_TRUE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_HEADLESS)); EXPECT_FALSE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_SINGLE)); EXPECT_FALSE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_DUAL_MIRROR)); EXPECT_FALSE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_DUAL_EXTENDED)); EXPECT_EQ(1, observer_.num_changes()); EXPECT_EQ(3, observer_.num_failures()); UpdateOutputs(1, true); observer_.Reset(); EXPECT_FALSE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_HEADLESS)); EXPECT_TRUE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_SINGLE)); EXPECT_FALSE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_DUAL_MIRROR)); EXPECT_FALSE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_DUAL_EXTENDED)); EXPECT_EQ(1, observer_.num_changes()); EXPECT_EQ(3, observer_.num_failures()); state_controller_.set_state(ui::OUTPUT_STATE_DUAL_EXTENDED); UpdateOutputs(2, true); observer_.Reset(); EXPECT_FALSE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_HEADLESS)); EXPECT_FALSE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_SINGLE)); EXPECT_TRUE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_DUAL_MIRROR)); EXPECT_TRUE(configurator_.SetDisplayMode(ui::OUTPUT_STATE_DUAL_EXTENDED)); EXPECT_EQ(2, observer_.num_changes()); EXPECT_EQ(2, observer_.num_failures()); } TEST_F(OutputConfiguratorTest, GetOutputStateForDisplaysWithoutId) { outputs_[0].has_display_id = false; UpdateOutputs(2, false); configurator_.Init(false); state_controller_.set_state(ui::OUTPUT_STATE_DUAL_MIRROR); configurator_.ForceInitialConfigure(0); EXPECT_EQ(ui::OUTPUT_STATE_DUAL_EXTENDED, configurator_.output_state()); } TEST_F(OutputConfiguratorTest, GetOutputStateForDisplaysWithId) { outputs_[0].has_display_id = true; UpdateOutputs(2, false); configurator_.Init(false); state_controller_.set_state(ui::OUTPUT_STATE_DUAL_MIRROR); configurator_.ForceInitialConfigure(0); EXPECT_EQ(ui::OUTPUT_STATE_DUAL_MIRROR, configurator_.output_state()); } TEST_F(OutputConfiguratorTest, UpdateCachedOutputsEvenAfterFailure) { InitWithSingleOutput(); const std::vector<OutputConfigurator::OutputSnapshot>* cached = &configurator_.cached_outputs(); ASSERT_EQ(static_cast<size_t>(1), cached->size()); EXPECT_EQ(outputs_[0].current_mode, (*cached)[0].current_mode); // After connecting a second output, check that it shows up in // |cached_outputs_| even if an invalid state is requested. state_controller_.set_state(ui::OUTPUT_STATE_SINGLE); UpdateOutputs(2, true); cached = &configurator_.cached_outputs(); ASSERT_EQ(static_cast<size_t>(2), cached->size()); EXPECT_EQ(outputs_[0].current_mode, (*cached)[0].current_mode); EXPECT_EQ(outputs_[1].current_mode, (*cached)[1].current_mode); } TEST_F(OutputConfiguratorTest, PanelFitting) { // Configure the internal display to support only the big mode and the // external display to support only the small mode. outputs_[0].current_mode = kBigModeId; outputs_[0].native_mode = kBigModeId; outputs_[0].mode_infos.clear(); outputs_[0].mode_infos[kBigModeId] = OutputConfigurator::ModeInfo( kBigModeWidth, kBigModeHeight, false, 60.0); outputs_[1].current_mode = kSmallModeId; outputs_[1].native_mode = kSmallModeId; outputs_[1].mode_infos.clear(); outputs_[1].mode_infos[kSmallModeId] = OutputConfigurator::ModeInfo( kSmallModeWidth, kSmallModeHeight, false, 60.0); // The small mode should be added to the internal output when requesting // mirrored mode. UpdateOutputs(2, false); state_controller_.set_state(ui::OUTPUT_STATE_DUAL_MIRROR); configurator_.Init(true /* is_panel_fitting_enabled */); configurator_.ForceInitialConfigure(0); EXPECT_EQ(ui::OUTPUT_STATE_DUAL_MIRROR, configurator_.output_state()); EXPECT_EQ( JoinActions( kGrab, kInitXRandR, GetAddOutputModeAction(outputs_[0].output, kSmallModeId).c_str(), GetFramebufferAction(kSmallModeWidth, kSmallModeHeight, outputs_[0].crtc, outputs_[1].crtc).c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kSmallModeId, outputs_[0].output).c_str(), GetCrtcAction( outputs_[1].crtc, 0, 0, kSmallModeId, outputs_[1].output).c_str(), kForceDPMS, kUngrab, NULL), log_->GetActionsAndClear()); // Both outputs should be using the small mode. ASSERT_EQ(1, observer_.num_changes()); ASSERT_EQ(static_cast<size_t>(2), observer_.latest_outputs().size()); EXPECT_EQ(kSmallModeId, observer_.latest_outputs()[0].mirror_mode); EXPECT_EQ(kSmallModeId, observer_.latest_outputs()[0].current_mode); EXPECT_EQ(kSmallModeId, observer_.latest_outputs()[1].mirror_mode); EXPECT_EQ(kSmallModeId, observer_.latest_outputs()[1].current_mode); // Also check that the newly-added small mode is present in the internal // snapshot that was passed to the observer (http://crbug.com/289159). const OutputConfigurator::ModeInfo* info = OutputConfigurator::GetModeInfo( observer_.latest_outputs()[0], kSmallModeId); ASSERT_TRUE(info); EXPECT_EQ(kSmallModeWidth, info->width); EXPECT_EQ(kSmallModeHeight, info->height); } TEST_F(OutputConfiguratorTest, OutputProtection) { configurator_.Init(false); configurator_.ForceInitialConfigure(0); EXPECT_NE(kNoActions, log_->GetActionsAndClear()); OutputConfigurator::OutputProtectionClientId id = configurator_.RegisterOutputProtectionClient(); EXPECT_NE(0u, id); // One output. UpdateOutputs(1, true); EXPECT_NE(kNoActions, log_->GetActionsAndClear()); uint32_t link_mask = 0; uint32_t protection_mask = 0; EXPECT_TRUE(configurator_.QueryOutputProtectionStatus(id, outputs_[0].display_id, &link_mask, &protection_mask)); EXPECT_EQ(static_cast<uint32_t>(ui::OUTPUT_TYPE_INTERNAL), link_mask); EXPECT_EQ(static_cast<uint32_t>(ui::OUTPUT_PROTECTION_METHOD_NONE), protection_mask); EXPECT_EQ(kNoActions, log_->GetActionsAndClear()); // Two outputs. UpdateOutputs(2, true); EXPECT_NE(kNoActions, log_->GetActionsAndClear()); EXPECT_TRUE(configurator_.QueryOutputProtectionStatus(id, outputs_[1].display_id, &link_mask, &protection_mask)); EXPECT_EQ(static_cast<uint32_t>(ui::OUTPUT_TYPE_HDMI), link_mask); EXPECT_EQ(static_cast<uint32_t>(ui::OUTPUT_PROTECTION_METHOD_NONE), protection_mask); EXPECT_EQ(kNoActions, log_->GetActionsAndClear()); EXPECT_TRUE(configurator_.EnableOutputProtection( id, outputs_[1].display_id, ui::OUTPUT_PROTECTION_METHOD_HDCP)); EXPECT_EQ(GetSetHDCPStateAction(outputs_[1].output, ui::HDCP_STATE_DESIRED), log_->GetActionsAndClear()); // Enable protection. native_display_delegate_->set_hdcp_state(ui::HDCP_STATE_ENABLED); EXPECT_TRUE(configurator_.QueryOutputProtectionStatus(id, outputs_[1].display_id, &link_mask, &protection_mask)); EXPECT_EQ(static_cast<uint32_t>(ui::OUTPUT_TYPE_HDMI), link_mask); EXPECT_EQ(static_cast<uint32_t>(ui::OUTPUT_PROTECTION_METHOD_HDCP), protection_mask); EXPECT_EQ(kNoActions, log_->GetActionsAndClear()); // Protections should be disabled after unregister. configurator_.UnregisterOutputProtectionClient(id); EXPECT_EQ(GetSetHDCPStateAction(outputs_[1].output, ui::HDCP_STATE_UNDESIRED), log_->GetActionsAndClear()); } TEST_F(OutputConfiguratorTest, OutputProtectionTwoClients) { OutputConfigurator::OutputProtectionClientId client1 = configurator_.RegisterOutputProtectionClient(); OutputConfigurator::OutputProtectionClientId client2 = configurator_.RegisterOutputProtectionClient(); EXPECT_NE(client1, client2); configurator_.Init(false); configurator_.ForceInitialConfigure(0); UpdateOutputs(2, true); EXPECT_NE(kNoActions, log_->GetActionsAndClear()); // Clients never know state enableness for methods that they didn't request. EXPECT_TRUE(configurator_.EnableOutputProtection( client1, outputs_[1].display_id, ui::OUTPUT_PROTECTION_METHOD_HDCP)); EXPECT_EQ( GetSetHDCPStateAction(outputs_[1].output, ui::HDCP_STATE_DESIRED).c_str(), log_->GetActionsAndClear()); native_display_delegate_->set_hdcp_state(ui::HDCP_STATE_ENABLED); uint32_t link_mask = 0; uint32_t protection_mask = 0; EXPECT_TRUE(configurator_.QueryOutputProtectionStatus(client1, outputs_[1].display_id, &link_mask, &protection_mask)); EXPECT_EQ(static_cast<uint32_t>(ui::OUTPUT_TYPE_HDMI), link_mask); EXPECT_EQ(ui::OUTPUT_PROTECTION_METHOD_HDCP, protection_mask); EXPECT_TRUE(configurator_.QueryOutputProtectionStatus(client2, outputs_[1].display_id, &link_mask, &protection_mask)); EXPECT_EQ(static_cast<uint32_t>(ui::OUTPUT_TYPE_HDMI), link_mask); EXPECT_EQ(ui::OUTPUT_PROTECTION_METHOD_NONE, protection_mask); // Protections will be disabled only if no more clients request them. EXPECT_TRUE(configurator_.EnableOutputProtection( client2, outputs_[1].display_id, ui::OUTPUT_PROTECTION_METHOD_NONE)); EXPECT_EQ( GetSetHDCPStateAction(outputs_[1].output, ui::HDCP_STATE_DESIRED).c_str(), log_->GetActionsAndClear()); EXPECT_TRUE(configurator_.EnableOutputProtection( client1, outputs_[1].display_id, ui::OUTPUT_PROTECTION_METHOD_NONE)); EXPECT_EQ(GetSetHDCPStateAction(outputs_[1].output, ui::HDCP_STATE_UNDESIRED) .c_str(), log_->GetActionsAndClear()); } TEST_F(OutputConfiguratorTest, CTMForMultiScreens) { outputs_[0].touch_device_id = 1; outputs_[1].touch_device_id = 2; UpdateOutputs(2, false); configurator_.Init(false); state_controller_.set_state(ui::OUTPUT_STATE_DUAL_EXTENDED); configurator_.ForceInitialConfigure(0); const int kDualHeight = kSmallModeHeight + OutputConfigurator::kVerticalGap + kBigModeHeight; const int kDualWidth = kBigModeWidth; OutputConfigurator::CoordinateTransformation ctm1 = touchscreen_delegate_->GetCTM(1); OutputConfigurator::CoordinateTransformation ctm2 = touchscreen_delegate_->GetCTM(2); EXPECT_EQ(kSmallModeHeight - 1, round((kDualHeight - 1) * ctm1.y_scale)); EXPECT_EQ(0, round((kDualHeight - 1) * ctm1.y_offset)); EXPECT_EQ(kBigModeHeight - 1, round((kDualHeight - 1) * ctm2.y_scale)); EXPECT_EQ(kSmallModeHeight + OutputConfigurator::kVerticalGap, round((kDualHeight - 1) * ctm2.y_offset)); EXPECT_EQ(kSmallModeWidth - 1, round((kDualWidth - 1) * ctm1.x_scale)); EXPECT_EQ(0, round((kDualWidth - 1) * ctm1.x_offset)); EXPECT_EQ(kBigModeWidth - 1, round((kDualWidth - 1) * ctm2.x_scale)); EXPECT_EQ(0, round((kDualWidth - 1) * ctm2.x_offset)); } TEST_F(OutputConfiguratorTest, HandleConfigureCrtcFailure) { InitWithSingleOutput(); // kFirstMode represents the first mode in the list and // also the mode that we are requesting the output_configurator // to choose. The test will be setup so that this mode will fail // and it will have to choose the next best option. const int kFirstMode = 11; // Give the mode_info lists a few reasonable modes. for (unsigned int i = 0; i < arraysize(outputs_); i++) { outputs_[i].mode_infos.clear(); int current_mode = kFirstMode; outputs_[i].mode_infos[current_mode++] = OutputConfigurator::ModeInfo( 2560, 1600, false, 60.0); outputs_[i].mode_infos[current_mode++] = OutputConfigurator::ModeInfo( 1024, 768, false, 60.0); outputs_[i].mode_infos[current_mode++] = OutputConfigurator::ModeInfo( 1280, 720, false, 60.0); outputs_[i].mode_infos[current_mode++] = OutputConfigurator::ModeInfo( 1920, 1080, false, 60.0); outputs_[i].mode_infos[current_mode++] = OutputConfigurator::ModeInfo( 1920, 1080, false, 40.0); outputs_[i].current_mode = kFirstMode; outputs_[i].native_mode = kFirstMode; } configurator_.Init(false); // First test simply fails in OUTPUT_STATE_SINGLE mode. This is probably // unrealistic but the want to make sure any assumptions don't // creep in. native_display_delegate_->set_max_configurable_pixels( outputs_[0].mode_infos[kFirstMode + 2].width * outputs_[0].mode_infos[kFirstMode + 2].height); state_controller_.set_state(ui::OUTPUT_STATE_SINGLE); UpdateOutputs(1, true); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction(2560, 1600, outputs_[0].crtc, 0).c_str(), GetCrtcAction(outputs_[0].crtc, 0, 0, kFirstMode, outputs_[0].output) .c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kFirstMode + 3, outputs_[0].output) .c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kFirstMode + 2, outputs_[0].output) .c_str(), kUngrab, NULL), log_->GetActionsAndClear()); // This test should attempt to configure a mirror mode that will not succeed // and should end up in extended mode. native_display_delegate_->set_max_configurable_pixels( outputs_[0].mode_infos[kFirstMode + 3].width * outputs_[0].mode_infos[kFirstMode + 3].height); state_controller_.set_state(ui::OUTPUT_STATE_DUAL_MIRROR); UpdateOutputs(2, true); EXPECT_EQ( JoinActions( kGrab, GetFramebufferAction(outputs_[0].mode_infos[kFirstMode].width, outputs_[0].mode_infos[kFirstMode].height, outputs_[0].crtc, outputs_[1].crtc).c_str(), GetCrtcAction(outputs_[0].crtc, 0, 0, kFirstMode, outputs_[0].output) .c_str(), // First mode tried is expected to fail and it will // retry wil the 4th mode in the list. GetCrtcAction( outputs_[0].crtc, 0, 0, kFirstMode + 3, outputs_[0].output) .c_str(), // Then attempt to configure crtc1 with the first mode. GetCrtcAction(outputs_[1].crtc, 0, 0, kFirstMode, outputs_[1].output) .c_str(), GetCrtcAction( outputs_[1].crtc, 0, 0, kFirstMode + 3, outputs_[1].output) .c_str(), // Since it was requested to go into mirror mode // and the configured modes were different, it // should now try and setup a valid configurable // extended mode. GetFramebufferAction(outputs_[0].mode_infos[kFirstMode].width, outputs_[0].mode_infos[kFirstMode].height + outputs_[1].mode_infos[kFirstMode].height + OutputConfigurator::kVerticalGap, outputs_[0].crtc, outputs_[1].crtc).c_str(), GetCrtcAction(outputs_[0].crtc, 0, 0, kFirstMode, outputs_[0].output) .c_str(), GetCrtcAction( outputs_[0].crtc, 0, 0, kFirstMode + 3, outputs_[0].output) .c_str(), GetCrtcAction(outputs_[1].crtc, 0, outputs_[1].mode_infos[kFirstMode].height + OutputConfigurator::kVerticalGap, kFirstMode, outputs_[1].output).c_str(), GetCrtcAction(outputs_[1].crtc, 0, outputs_[1].mode_infos[kFirstMode].height + OutputConfigurator::kVerticalGap, kFirstMode + 3, outputs_[1].output).c_str(), kUngrab, NULL), log_->GetActionsAndClear()); } } // namespace chromeos
{'content_hash': '9c49fe4e3d62bcbc6a53e206da51a024', 'timestamp': '', 'source': 'github', 'line_count': 1434, 'max_line_length': 80, 'avg_line_length': 38.206415620641565, 'alnum_prop': 0.6365627509673651, 'repo_name': 'anirudhSK/chromium', 'id': '88a92bc3c24773278037a393cdf05302d227e354', 'size': '54788', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'chromeos/display/output_configurator_unittest.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '853'}, {'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '52960'}, {'name': 'Awk', 'bytes': '8660'}, {'name': 'C', 'bytes': '42502191'}, {'name': 'C#', 'bytes': '1132'}, {'name': 'C++', 'bytes': '201859263'}, {'name': 'CSS', 'bytes': '946557'}, {'name': 'DOT', 'bytes': '2984'}, {'name': 'Java', 'bytes': '5687122'}, {'name': 'JavaScript', 'bytes': '22163714'}, {'name': 'M', 'bytes': '2190'}, {'name': 'Matlab', 'bytes': '2496'}, {'name': 'Objective-C', 'bytes': '7670589'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'Perl', 'bytes': '672770'}, {'name': 'Python', 'bytes': '10873885'}, {'name': 'R', 'bytes': '262'}, {'name': 'Shell', 'bytes': '1315894'}, {'name': 'Tcl', 'bytes': '277091'}, {'name': 'TypeScript', 'bytes': '1560024'}, {'name': 'XSLT', 'bytes': '13493'}, {'name': 'nesC', 'bytes': '15206'}]}
import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Papyrus' copyright = u'2012, Éric Lemoine' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '2.4' # The full version, including alpha/beta/rc tags. release = '2.4' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Papyrusdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Papyrus.tex', u'Papyrus Documentation', u'Éric Lemoine', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'papyrus', u'Papyrus Documentation', [u'Éric Lemoine'], 1) ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} # Mocks for Read the Dics import sys from unittest.mock import MagicMock class Mock(MagicMock): @classmethod def __getattr__(cls, name): if name == '_mock_methods': return name._mock_methods else: return Mock() MOCK_MODULES = ['shapely', 'shapely.geometry', 'shapely.geometry.point', 'shapely.geometry.polygon', 'shapely.wkb', 'shapely.wkt'] sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
{'content_hash': '2047af34cd47bc348ae168765af36e80', 'timestamp': '', 'source': 'github', 'line_count': 223, 'max_line_length': 107, 'avg_line_length': 32.56053811659193, 'alnum_prop': 0.7021071477757884, 'repo_name': 'elemoine/papyrus', 'id': '44d116432bc3d502811481ef95b508ced89762a5', 'size': '7682', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/conf.py', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Makefile', 'bytes': '390'}, {'name': 'Python', 'bytes': '112745'}]}
package com.siyeh.ipp.equality; import com.intellij.psi.*; import com.intellij.psi.tree.IElementType; import com.intellij.util.IncorrectOperationException; import com.siyeh.ig.psiutils.ParenthesesUtils; import com.siyeh.ipp.base.Intention; import com.siyeh.ipp.base.PsiElementPredicate; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class ReplaceEqualityWithSafeEqualsIntention extends Intention { @NotNull public PsiElementPredicate getElementPredicate() { return new ObjectEqualityPredicate(); } public void processIntention(PsiElement element) throws IncorrectOperationException { final PsiBinaryExpression exp = (PsiBinaryExpression)element; final PsiExpression lhs = exp.getLOperand(); final PsiExpression rhs = exp.getROperand(); if (rhs == null) { return; } final PsiExpression strippedLhs = ParenthesesUtils.stripParentheses(lhs); if (strippedLhs == null) { return; } final PsiExpression strippedRhs = ParenthesesUtils.stripParentheses(rhs); if (strippedRhs == null) { return; } final String lhsText = strippedLhs.getText(); final String rhsText = strippedRhs.getText(); final PsiJavaToken operationSign = exp.getOperationSign(); final IElementType tokenType = operationSign.getTokenType(); final String signText = operationSign.getText(); @NonNls final StringBuilder buffer = new StringBuilder(lhsText); buffer.append("==null?"); buffer.append(rhsText); buffer.append(signText); buffer.append(" null:"); if (tokenType.equals(JavaTokenType.NE)) { buffer.append('!'); } if (ParenthesesUtils.getPrecedence(strippedLhs) > ParenthesesUtils.METHOD_CALL_PRECEDENCE) { buffer.append('('); buffer.append(lhsText); buffer.append(')'); } else { buffer.append(lhsText); } buffer.append(".equals("); buffer.append(rhsText); buffer.append(')'); replaceExpression(buffer.toString(), exp); } }
{'content_hash': '70d58bf39d073620fb92de03cfb1be9d', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 71, 'avg_line_length': 31.075757575757574, 'alnum_prop': 0.7084349098000975, 'repo_name': 'IllusionRom-deprecated/android_platform_tools_idea', 'id': 'd5d14f7b59ee185e370bef0085b9540927bb58b7', 'size': '2665', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'plugins/IntentionPowerPak/src/com/siyeh/ipp/equality/ReplaceEqualityWithSafeEqualsIntention.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '177802'}, {'name': 'C#', 'bytes': '390'}, {'name': 'C++', 'bytes': '78894'}, {'name': 'CSS', 'bytes': '102018'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groovy', 'bytes': '1906667'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '128322265'}, {'name': 'JavaScript', 'bytes': '123045'}, {'name': 'Objective-C', 'bytes': '22558'}, {'name': 'Perl', 'bytes': '6549'}, {'name': 'Python', 'bytes': '17760420'}, {'name': 'Ruby', 'bytes': '1213'}, {'name': 'Shell', 'bytes': '76554'}, {'name': 'TeX', 'bytes': '60798'}, {'name': 'XSLT', 'bytes': '113531'}]}
<?php namespace Gaufrette\Adapter\AzureBlobStorage; use MicrosoftAzure\Storage\Common\ServicesBuilder; /** * Basic implementation for a Blob proxy factory. * * @author Luciano Mammino <[email protected]> */ class BlobProxyFactory implements BlobProxyFactoryInterface { /** * @var string */ protected $connectionString; /** * @param string $connectionString */ public function __construct($connectionString) { $this->connectionString = $connectionString; } /** * {@inheritdoc} */ public function create() { return ServicesBuilder::getInstance()->createBlobService($this->connectionString); } }
{'content_hash': 'defa1a07e45a14e8ce7f18cb9df204e3', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 90, 'avg_line_length': 20.323529411764707, 'alnum_prop': 0.6613603473227206, 'repo_name': 'peelandsee/Gaufrette', 'id': '0db48794c7510362dc0371f7e5dc3828539e772c', 'size': '691', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/Gaufrette/Adapter/AzureBlobStorage/BlobProxyFactory.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '357189'}]}
require 'origen_link/server/pin' ################################################## # OrigenLink::Server::Sequencer Class # Instance variables: # pinmap: hash with ["pin name"] = pin object # patternpinindex: hash with ["pin name"] = # integer index into vector data # patternpinorder: Array with pin names in # the vector order # # This class processes messages targeted for # pin sequencer interface (vector pattern # execution). # # Supported messages: # pin_assign (create pin mapping) # ex: "pin_assign:tck,3,extal,23,tdo,5" # # pin_patternorder (define vector pin order) # ex: "pin_patternorder:tdo,extal,tck" # # pin_cycle (execute vector data) # ex: "pin_cycle:H11" # # pin_clear (clear all setup information) # ex: "pin_clear:" # # pin_format (setup a pin with return format) # first argument is the timeset # ex: "pin_format:1,tck,rl" # # pin_timing (define when pin events happen) # timing is stored in a timeset hash # first argument is the timeset key # ex: "pin_timing:1,tdi,0,tdo,1,tms,0 # # version (check version of app server is # running) # ex: "version:" # response ex: "P:0.2.0.pre0" ################################################## module OrigenLink module Server def self.gpio_dir=(path) @gpio_dir = path end def self.gpio_dir @gpio_dir || '/sys/class/gpio' end ################################################## # OrigenLink::Server::Sequencer Class # # This class processes messages targeted for # pin sequencer interface (vector pattern # execution). # # Supported messages: # pin_assign (create pin mapping) # ex: "pin_assign:tck,3,extal,23,tdo,5" # # pin_patternorder (define vector pin order) # ex: "pin_patternorder:tdo,extal,tck" # # pin_cycle (execute vector data) # ex: "pin_cycle:H11" # # pin_clear (clear all setup information) # ex: "pin_clear:" # # pin_format (setup a pin with return format) # first argument is the timeset # ex: "pin_format:1,tck,rl" # # pin_timing (define when pin events happen) # timing is stored in a timeset hash # first argument is the timeset key # ex: "pin_timing:1,tdi,0,tdo,1,tms,0 # # version (check version of app server is # running) # ex: "version:" # response ex: "P:0.2.0.pre0" ################################################## class Sequencer # code version of the server (populated by start_link_server) attr_accessor :version # hash holding the pinmap ('name' => pin object) attr_reader :pinmap # array of pin names in pattern order attr_reader :patternorder # hash holding programmed time set information attr_reader :cycletiming # hash holding pin pattern order ('name' => index) attr_reader :patternpinindex ################################################## # initialize method # Create empty pinmap, pattern pin index # and pattern order instance variables ################################################## def initialize @pinmap = Hash.new(-1) @patternpinindex = Hash.new(-1) @patternorder = [] @cycletiming = Hash.new(-1) @version = '' end ################################################## # processmessage method # arguments: message # message format is <group>_<command>:<args> # returns: message response # # This method splits a message into it's # command and arguments and passes this # information to the method that performs # the requested command ################################################## def processmessage(message) command = message.split(':') case command[0] when 'pin_assign' pin_assign(command[1]) when 'pin_patternorder' pin_patternorder(command[1]) when 'pin_cycle' pin_cycle(command[1]) when 'pin_clear' pin_clear when 'pin_format' pin_format(command[1]) when 'pin_timing' pin_timing(command[1]) when 'pin_timingv2' pin_timingv2(command[1]) when 'version' "P:#{@version}" else 'Error Invalid command: ' + command[0].to_s end end ################################################## # pin_assign method # arguments: <args> from the message request # see "processmessage" method # returns: "P:" or error message # # This method creates a pin instance for each # pin in the pin map and builds the pinmap # hash. Before the pinmap is created, any # information from a previous pattern run is # cleared. ################################################## def pin_assign(args) pin_clear success = true fail_message = '' argarr = args.split(',') 0.step(argarr.length - 2, 2) do |index| @pinmap[argarr[index]] = Pin.new(argarr[index + 1]) unless @pinmap[argarr[index]].gpio_valid success = false fail_message = fail_message + 'pin ' + argarr[index] + ' gpio' + argarr[index + 1] + ' is invalid' end end if success 'P:' else 'F:' + fail_message end end ######################################################## # pin_timingv2 method # arguments: <args> from the message request # Should be '1,drive,5,pin,10,pin2,|compare,0,pin3' # First integer is timeset number # # returns "P:" or error message # # This method sets up a time set. Any arbitrary # waveform can be generated # ######################################################## def pin_timingv2(args) # get the tset number argarr = args.split(',') tset_key = argarr.delete_at(0).to_i new_timeset(tset_key) args = argarr.join(',') invalid_pins = [] # process and load the timeset waves = args.split('|') waves.each do |w| argarr = w.split(',') wave_type = argarr.delete_at(0) event_data_key = wave_type + '_event_data' event_pins_key = wave_type + '_event_pins' w = argarr.join(',') events = w.split(';') events.each do |e| argarr = e.split(',') event_key = argarr.delete_at(0).to_f @cycletiming[tset_key]['events'] << event_key @cycletiming[tset_key][event_data_key][event_key] = [] unless @cycletiming[tset_key][event_data_key].key?(event_key) @cycletiming[tset_key][event_data_key][event_key] << argarr.delete_at(0) # now load the pins for this event @cycletiming[tset_key][event_pins_key][event_key] = [] unless @cycletiming[tset_key][event_pins_key].key?(event_key) @cycletiming[tset_key][event_pins_key][event_key] << [] argarr.each do |pin| if @pinmap.key?(pin) @cycletiming[tset_key][event_pins_key][event_key].last << @pinmap[pin] else invalid_pins << pin end end # of argarr.each end # of events.each end # of waves.each @cycletiming[tset_key]['events'].uniq! @cycletiming[tset_key]['events'].sort! # return result if invalid_pins.size > 0 'F:Invalid pins (not in pinmap): ' + invalid_pins.join(', ') else 'P:' end end # of def pin_timingv2 ################################################## # new_timeset(tset) # creates a new empty timeset hash # # timing format: # ['events'] = [0, 5, 10, 35] # ['drive_event_data'] = { # 0: ['data'] # 10: ['data','0'] # 35: ['0'] # } # ['drive_event_pins'] = { # 0: [[pin_obj1, pin_obj2]] # 10: [[pin1,pin2], [pin3]] # etc. # } ################################################## def new_timeset(tset) @cycletiming[tset] = {} @cycletiming[tset]['events'] = [] @cycletiming[tset]['drive_event_data'] = {} @cycletiming[tset]['drive_event_pins'] = {} @cycletiming[tset]['compare_event_data'] = {} @cycletiming[tset]['compare_event_pins'] = {} end ################################################## # pin_format method # arguments: <args> from the message request # Should be <timeset>,<pin>,rl or rh # multi-clock not currently supported # ################################################## def pin_format(args) argarr = args.split(',') tset_key = argarr.delete_at(0).to_i new_timeset(tset_key) unless @cycletiming.key?(tset_key) @cycletiming[tset_key]['events'] += [1, 3] @cycletiming[tset_key]['events'].sort! [1, 3].each do |event| @cycletiming[tset_key]['drive_event_pins'][event] = [[]] end @cycletiming[tset_key]['compare_event_data'][1] = ['data'] 0.step(argarr.length - 2, 2) do |index| drive_type = argarr[index + 1] pin_name = argarr[index] @cycletiming[tset_key]['drive_event_data'][1] = ['data'] @cycletiming[tset_key]['drive_event_pins'][1][0] << @pinmap[pin_name] @cycletiming[tset_key]['drive_event_pins'][3][0] << @pinmap[pin_name] @cycletiming[tset_key]['compare_event_pins'][1] = [[@pinmap[pin_name]]] if drive_type == 'rl' @cycletiming[tset_key]['drive_event_data'][3] = ['0'] else @cycletiming[tset_key]['drive_event_data'][3] = ['1'] end end 'P:' end ################################################## # pin_timing method # arguments: <args> from the message request # Should be '1,pin,-1,pin2,0,pin3,1' # First integer is timeset number # If argument is '', default timing is created # Default timeset number is 0, this is used # if no timeset is explicitly defined # # cycle arg: 0 1 2 # waveform : ___/***\___ # # returns "P:" or error message # # This method sets up a time set. All retrun # format pins are driven between 0 and 1 and # return between 1 and 2. Non-return pins are # acted upon during the 0, 1 or 2 time period. # ################################################## def pin_timing(args) argarr = args.split(',') tset_key = argarr.delete_at(0).to_i new_timeset(tset_key) unless @cycletiming.key?(tset_key) [0, 2, 4].each do |event| @cycletiming[tset_key]['drive_event_pins'][event] = [[]] @cycletiming[tset_key]['compare_event_pins'][event] = [[]] end # process the information received 0.step(argarr.length - 2, 2) do |index| event = argarr[index + 1].to_i # reorder event number to allow rising/falling edges event *= 2 pin_name = argarr[index] @cycletiming[tset_key]['events'] << event @cycletiming[tset_key]['drive_event_data'][event] = ['data'] @cycletiming[tset_key]['drive_event_pins'][event][0] << @pinmap[pin_name] @cycletiming[tset_key]['compare_event_data'][event] = ['data'] @cycletiming[tset_key]['compare_event_pins'][event][0] << @pinmap[pin_name] end # remove events with no associated pins @cycletiming[tset_key]['events'].uniq! @cycletiming[tset_key]['events'].sort! [0, 2, 4].each do |event| if @cycletiming[tset_key]['drive_event_pins'][event][0].size == 0 @cycletiming[tset_key]['events'] -= [event] @cycletiming[tset_key]['drive_event_data'].delete(event) @cycletiming[tset_key]['drive_event_pins'].delete(event) @cycletiming[tset_key]['compare_event_data'].delete(event) @cycletiming[tset_key]['compare_event_pins'].delete(event) end end 'P:' end ################################################## # pin_patternorder method # arguments: <args> from the message request # returns: "P:" or error message # # This method is used to define the order # for pin vector data. ################################################## def pin_patternorder(args) argarr = args.split(',') index = 0 new_timeset(0) argarr.each do |pin| @patternorder << pin @pinmap[pin].pattern_index = index # pattern index stored in pin object now @patternpinindex[pin] = index # to be removed # define default timing @cycletiming[0]['events'] << index @cycletiming[0]['drive_event_data'][index] = ['data'] @cycletiming[0]['drive_event_pins'][index] = [[@pinmap[pin]]] @cycletiming[0]['compare_event_data'][index] = ['data'] @cycletiming[0]['compare_event_pins'][index] = [[@pinmap[pin]]] index += 1 end 'P:' end ################################################## # pin_cycle method # arguments: <args> from the message request # returns: "P:" or "F:" followed by results # # This method executes one cycle of pin vector # data. The vector data is decomposed and # sequenced. Each pin object and pin data # is passed to the "process_pindata" method # for decoding and execution # ################################################## def pin_cycle(args) # set default repeats and timeset repeat_count = 1 tset = 0 if args =~ /,/ parsedargs = args.split(',') args = parsedargs.pop parsedargs.each do |arg| if arg =~ /repeat/ repeat_count = arg.sub(/repeat/, '').to_i elsif arg =~ /tset/ tset = arg.sub(/tset/, '').to_i end end end message = '' # load pattern cycle data into pin objects @pinmap.each_value { |p| p.load_pattern_data(args) } cycle_failure = false 0.upto(repeat_count - 1) do |count| # process timing events @cycletiming[tset]['events'].each do |event| # process drive events if @cycletiming[tset]['drive_event_pins'].key?(event) @cycletiming[tset]['drive_event_pins'][event].each_index do |i| @cycletiming[tset]['drive_event_pins'][event][i].each do |p| p.process_event(:drive, @cycletiming[tset]['drive_event_data'][event][i]) end end end # process compare events if @cycletiming[tset]['compare_event_pins'].key?(event) @cycletiming[tset]['compare_event_pins'][event].each_index do |i| @cycletiming[tset]['compare_event_pins'][event][i].each do |p| p.process_event(:compare, @cycletiming[tset]['compare_event_data'][event][i]) end end end end # event # build response message message += ' ' unless count == 0 @patternorder.each do |p| message += @pinmap[p].response cycle_failure = true if @pinmap[p].cycle_failure end end # count if cycle_failure rtnmsg = 'F:' + message + ' Expected:' + args else rtnmsg = 'P:' + message end rtnmsg end ################################################## # pin_clear method # # This method clears all storage objects. It # is called by the "pin_assign" method ################################################## def pin_clear @pinmap.each { |pin_name, pin| pin.destroy } @pinmap.clear @patternpinindex.clear @patternorder.delete_if { true } @cycletiming.clear 'P:' end end end end
{'content_hash': '41ca221166842e3b7c7a55ea650127ca', 'timestamp': '', 'source': 'github', 'line_count': 469, 'max_line_length': 128, 'avg_line_length': 35.76759061833689, 'alnum_prop': 0.4953204172876304, 'repo_name': 'Origen-SDK/OrigenLink', 'id': '6d8d4ef40b89ac8dbf358ea90363c5ca605b1167', 'size': '16775', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/origen_link/server/sequencer.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '21773'}, {'name': 'Ruby', 'bytes': '116468'}]}
package me.chris.RegionCheck; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.logging.Level; import net.milkbowl.vault.permission.Permission; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; public class RegionCheckMain extends JavaPlugin { @Override public void onEnable() { new Vars(this); try { firstRun(); } catch (Exception e) { e.printStackTrace(); } loadYamls(); if (!setupPermissions()) { Vars.log.log(Level.SEVERE, "[RegionCheck] No Permission found! Disabling plugin!"); getServer().getPluginManager().disablePlugin(this); return; } RegionCheckCommandHandler commandHandler = new RegionCheckCommandHandler(); getCommand("regioncheck").setExecutor(commandHandler); getCommand("rgc").setExecutor(commandHandler); Vars.log.log(Level.INFO, "[RegionCheck] Version " + Vars.version.substring(10)); Vars.log.log(Level.INFO, "[RegionCheck] Started successfully."); } @Override public void onDisable() { Vars.log.log(Level.INFO, "[RegionCheck] Stopped."); } private void firstRun() throws Exception { if (!Vars.configFile.exists()) { Vars.log.log(Level.INFO, "[RegionCheck] No config.yml file found. Attempting to make one. "); Vars.configFile.getParentFile().mkdirs(); copy(getResource("config.yml"), Vars.configFile); Vars.log.log(Level.INFO, "[RegionCheck] File Made Successfully "); } else { Vars.log.log(Level.INFO, "[RegionCheck] Config Found. Using it. "); } } private void copy(InputStream in, File file) { try { OutputStream out = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } public void loadYamls() { try { Vars.config.load(Vars.configFile); } catch (Exception e) { e.printStackTrace(); } } public void saveYamls() { Vars.exportVariables(); try { Vars.config.save(Vars.configFile); } catch (IOException e) { e.printStackTrace(); } } private Boolean setupPermissions() { RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) { Vars.perms = permissionProvider.getProvider(); } return (Vars.perms != null); } public WorldGuardPlugin getWorldGuard() { Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard"); // WorldGuard may not be loaded if (plugin == null || !(plugin instanceof WorldGuardPlugin)) { return null; // Maybe you want throw an exception instead } return (WorldGuardPlugin) plugin; } }
{'content_hash': '4f6f09e61d152d777e407253eafc9ce7', 'timestamp': '', 'source': 'github', 'line_count': 145, 'max_line_length': 158, 'avg_line_length': 22.2, 'alnum_prop': 0.6477166821994408, 'repo_name': 'hotshot2162/RegionCheck', 'id': '3d45b57281f1f58cf249a94c1b4c082a63a87e3f', 'size': '3219', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/me/chris/RegionCheck/RegionCheckMain.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '9965'}]}
/*global define:false*/ define(['grasshopperBaseView', 'pluginWrapperViewConfig', 'underscore', 'require', 'jquery'], function (GrasshopperBaseView, pluginWrapperViewConfig, _, require, $) { 'use strict'; return GrasshopperBaseView.extend({ defaultOptions : pluginWrapperViewConfig, beforeRender : beforeRender, afterRender : afterRender, addField : addField, removeField : removeField, resortMulti : _initializeSortableMulti }); function beforeRender($deferred) { _getPlugin.call(this) .done(_handleMultiple.bind(this), $deferred.resolve); } function afterRender() { _initializeSortableMulti.call(this); } function _getPlugin() { var self = this, $deferred = $.Deferred(); require(['plugins'], function(plugins) { var plugin = _.find(plugins.fields, {type : self.model.get('type')}); // Ensuring Model Data is Obj that we can get into. plugin.config.modelData = _.result(plugin.config, 'modelData'); self.model.set({ ViewModule : plugin.view, configModule : plugin.config }); $deferred.resolve(); }); return $deferred.promise(); } function addField() { _addPlugin.call(this, undefined); } function removeField(e, context) { this.collection.remove(context.field); _evaluateMultiButtons.call(this); } function _handleMultiple() { var values = this.model.get('value'), minimum = this.model.get('min'), allowMultiple = this.model.get('configModule.modelData.allowMultiple'), i = 0, self = this; if (values && !_.isUndefined(allowMultiple) && allowMultiple === false) { // If values exists and allowMultiple is false. _addPlugin.call(this, values); } else if (values && _.isArray(values) && !_.isEmpty(values)) { // If values exists and is array that is not empty. _.each(values, function (value) { _addPlugin.call(self, value); }); } else if (values && _.isArray(values) && _.isEmpty(values)) { // If value exists and is an empty array. _evaluateMultiButtons.call(this); } else if (!!values || _.isString(values)) { // if values exists. _addPlugin.call(this, values); } else if (minimum === 0) { // if values does not exist and minimum is zero. this.collection.setValuesOnParentFieldsObject(); _evaluateMultiButtons.call(this); } else { // if values does not exist and there is a minimum _evaluateMultiButtons.call(this); while(i < minimum) { _addPlugin.call(self); i++; } } } function _addPlugin(value) { var model = { value : _handleDefaultValue.call(this, value), options : this.model.get('options'), fieldId : this.model.get('_id') }; this.collection.add(model); _evaluateMultiButtons.call(this); } function _handleDefaultValue(value) { //var defaultValue = this.model.attributes.defaultValue || this.model.attributes.configModule.modelData.value, copyOfDefaultValue={}; var defaultValue = this.model.get('defaultValue') || this.model.get('configModule.modelData.value'), copyOfDefaultValue = {}; if (_.isUndefined(value)) { /* Deep copy, if object */ if (typeof(defaultValue)==='object'){ $.extend(true, copyOfDefaultValue, defaultValue); return copyOfDefaultValue; } else { return defaultValue; } } else { return value; } } function _evaluateMultiButtons() { _canShowAdditionButton.call(this); _canShowSubtractionButton.call(this); _canShowSortableMultiButton.call(this); } function _canShowAdditionButton() { this.model.set('showAdditionButton', this.collection.length < this.model.get('max')); } function _canShowSubtractionButton() { this.model.set('showSubtractionButton', this.collection.length > this.model.get('min')); } function _canShowSortableMultiButton() { this.model.set('showSortableButton', this.model.get('max') > 1 && this.collection.length > 1); } function _initializeSortableMulti() { var $sortable = this.$('#sortableMulti'+ this.model.cid); if(this.model.get('max') > 1) { $sortable .sortable( { revert : true, handle : '.sortableMultiHandle', axis : 'y', start : _fireSortStartEvent.bind(this), stop : _applyMultiSort.bind(this, $sortable) } ); } } function _fireSortStartEvent() { this.channels.views.trigger('pluginWrapperSortStart'); } function _fireSortStopEvent() { this.channels.views.trigger('pluginWrapperSortStop'); } function _applyMultiSort($sortable) { var models = [], elements = {}, $children = $sortable.children(), childLength = $children.length, self = this; $children.each(function() { var thisModelsId = $(this).children('.sortableMulti').attr('modelid'); models.push(self.collection.get(thisModelsId)); // Create an array of models in the sorted order elements[$(this).attr('sortIndex')] = this; // create an object of elements in sorted order }); _.times(childLength, function(index) { $sortable.append(elements['sort'+ index]); // Append the Elements to the parent in sorted order }); this.collection.reset(models); // reset the model's collection in sorted order _fireSortStopEvent.call(this); } });
{'content_hash': '475b47bcd08ad29bfc39eedb99afcd5c', 'timestamp': '', 'source': 'github', 'line_count': 178, 'max_line_length': 145, 'avg_line_length': 37.52247191011236, 'alnum_prop': 0.522084144332984, 'repo_name': 'grasshopper-cms/grasshopper-cms', 'id': 'c311ef5d513107589269a589bdf28b35f8b9dce1', 'size': '6679', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'plugins/admin/src/public/views/pluginWrapper/pluginWrapperView.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '5568'}, {'name': 'HTML', 'bytes': '110393'}, {'name': 'JavaScript', 'bytes': '415469'}, {'name': 'Pug', 'bytes': '3574'}]}
package com.typesafe.slick.testkit.util import scala.collection.JavaConversions import org.junit.{Before, After} import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Parameterized.Parameters @RunWith(classOf[Parameterized]) abstract class DBTest { private[this] var dbInitialized = false val tdb: JdbcTestDB lazy val db = { dbInitialized = true tdb.createDB() } println("[Using test database "+tdb+"]") @Before def beforeDBTest = tdb.cleanUpBefore() @After def afterDBTest = { if(dbInitialized) db.close() tdb.cleanUpAfter() } } abstract class DBTestObject(dbs: TestDB*) { val testClassName = { val s = getClass.getName s.substring(0, s.length-1) } @Parameters def parameters = JavaConversions.seqAsJavaList(dbs.filter(_.isEnabled).map(to => Array(to))) }
{'content_hash': 'b5bdaee5222fb1f9e9fef2dae5aac035', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 106, 'avg_line_length': 25.029411764705884, 'alnum_prop': 0.7285546415981199, 'repo_name': 'easel/slick', 'id': 'fc37732cf73389f95d95addd87781cee84ea5b50', 'size': '851', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'slick-testkit/src/main/scala/com/typesafe/slick/testkit/util/DBTest.scala', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'HTML', 'bytes': '3306'}, {'name': 'Python', 'bytes': '15753'}, {'name': 'Scala', 'bytes': '1323228'}]}
echo "###########################################" echo "# Writing nightly version in package.json #" echo "###########################################" ARG_DEFS=( ) function run { cd ../.. VERSION=$(readJsonProp "package.json" "version") NEW_VERSION="$VERSION-nightly-$TRAVIS_BUILD_NUMBER" replaceJsonProp "package.json" "version" "$NEW_VERSION" echo "-- Build version is $NEW_VERSION." } source $(dirname $0)/../utils.inc
{'content_hash': '26ff4294d6686b339899d651f75545ba', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 57, 'avg_line_length': 21.047619047619047, 'alnum_prop': 0.5361990950226244, 'repo_name': 'sahat/ionic', 'id': '5590534bfaf0fc7f1b498a6af49bf6974a585985', 'size': '443', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'scripts/travis/bump-nightly-version.sh', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '395787'}, {'name': 'JavaScript', 'bytes': '2171520'}, {'name': 'Shell', 'bytes': '12127'}]}
"""Rabbit + Pheasant puzzle. This example is the same one described in util/constraint/constraint_solver/constraint_solver.h rewritten using the SWIG generated python wrapper. Its purpose it to demonstrate how a simple example can be written in all the flavors of constraint programming interfaces. """ from ortools.constraint_solver import pywrapcp def main(): # Create the solver. solver = pywrapcp.Solver('rabbit+pheasant') # Create the variables. pheasant = solver.IntVar(0, 100, 'pheasant') rabbit = solver.IntVar(0, 100, 'rabbit') # Create the constraints. solver.Add(pheasant + rabbit == 20) solver.Add(pheasant * 2 + rabbit * 4 == 56) # Create the search phase. db = solver.Phase([rabbit, pheasant], solver.INT_VAR_DEFAULT, solver.INT_VALUE_DEFAULT) # And solve. solver.NewSearch(db) solver.NextSolution() # Display output. print pheasant print rabbit solver.EndSearch() print solver if __name__ == '__main__': main()
{'content_hash': 'e47f1d1bcbabfed9ad167fa9bfbdd568', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 76, 'avg_line_length': 23.627906976744185, 'alnum_prop': 0.6889763779527559, 'repo_name': 'abdelkimo/or-tools', 'id': '039ed71a9b1dd092d636358dab81fb3dd37936dd', 'size': '1590', 'binary': False, 'copies': '34', 'ref': 'refs/heads/master', 'path': 'examples/python/rabbit_pheasant.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '2412'}, {'name': 'C#', 'bytes': '651809'}, {'name': 'C++', 'bytes': '7485013'}, {'name': 'Java', 'bytes': '197924'}, {'name': 'Makefile', 'bytes': '165782'}, {'name': 'Protocol Buffer', 'bytes': '69287'}, {'name': 'Python', 'bytes': '688356'}, {'name': 'Shell', 'bytes': '3811'}]}
@interface UIColor (hex) + (UIColor *)colorWithHex:(long)hexColor; + (UIColor *)colorWithHex:(long)hexColor alpha:(float)opacity; + (UIColor *)colorWithIntRed:(int)red green:(int)green blue:(int)blue alpha:(float)alpha; + (UIColor *)colorWithIntRed:(int)red green:(int)green blue:(int)blue; @end
{'content_hash': '92de8008cfd43baacf8e204f70d3782e', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 89, 'avg_line_length': 37.25, 'alnum_prop': 0.738255033557047, 'repo_name': 'zhaihm/ShareManager', 'id': 'e2863b2f54e74a2919834d5f234d6d965e99aecc', 'size': '630', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'ShareManager/lib/Utils/UIColor+hex.h', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '22271'}, {'name': 'HTML', 'bytes': '9110'}, {'name': 'Objective-C', 'bytes': '1425320'}, {'name': 'Ruby', 'bytes': '2982'}]}
#ifdef CONFIG_ENABLE_EAP_FOR_SUPPLICANT #include "includes.h" #include "common.h" #include "crypto/sha256.h" #include "crypto/ms_funcs.h" #include "eap_peer/eap_i.h" #include "eap_common/eap_pwd_common.h" struct eap_pwd_data { enum { PWD_ID_Req, PWD_Commit_Req, PWD_Confirm_Req, SUCCESS_ON_FRAG_COMPLETION, SUCCESS, FAILURE } state; u8 *id_peer; size_t id_peer_len; u8 *id_server; size_t id_server_len; u8 *password; size_t password_len; int password_hash; u16 group_num; EAP_PWD_group *grp; struct wpabuf *inbuf; size_t in_frag_pos; struct wpabuf *outbuf; size_t out_frag_pos; size_t mtu; BIGNUM *k; BIGNUM *private_value; BIGNUM *server_scalar; BIGNUM *my_scalar; EC_POINT *my_element; EC_POINT *server_element; u8 msk[EAP_MSK_LEN]; u8 emsk[EAP_EMSK_LEN]; u8 session_id[1 + SHA256_MAC_LEN]; BN_CTX *bnctx; }; #ifndef CONFIG_NO_STDOUT_DEBUG static const char *eap_pwd_state_txt(int state) { switch (state) { case PWD_ID_Req: return "PWD-ID-Req"; case PWD_Commit_Req: return "PWD-Commit-Req"; case PWD_Confirm_Req: return "PWD-Confirm-Req"; case SUCCESS_ON_FRAG_COMPLETION: return "SUCCESS_ON_FRAG_COMPLETION"; case SUCCESS: return "SUCCESS"; case FAILURE: return "FAILURE"; default: return "PWD-UNK"; } } #endif /* CONFIG_NO_STDOUT_DEBUG */ static void eap_pwd_state(struct eap_pwd_data *data, int state) { wpa_printf(MSG_DEBUG, "EAP-PWD: %s -> %s", eap_pwd_state_txt(data->state), eap_pwd_state_txt(state)); data->state = state; } static void *eap_pwd_init(struct eap_sm *sm) { struct eap_pwd_data *data; const u8 *identity, *password; size_t identity_len, password_len; int fragment_size; int pwhash; password = eap_get_config_password2(sm, &password_len, &pwhash); if (password == NULL) { wpa_printf(MSG_INFO, "EAP-PWD: No password configured!"); return NULL; } identity = eap_get_config_identity(sm, &identity_len); if (identity == NULL) { wpa_printf(MSG_INFO, "EAP-PWD: No identity configured!"); return NULL; } if ((data = os_zalloc(sizeof(*data))) == NULL) { wpa_printf(MSG_INFO, "EAP-PWD: memory allocation data fail"); return NULL; } if ((data->bnctx = BN_CTX_new()) == NULL) { wpa_printf(MSG_INFO, "EAP-PWD: bn context allocation fail"); os_free(data); return NULL; } if ((data->id_peer = os_malloc(identity_len)) == NULL) { wpa_printf(MSG_INFO, "EAP-PWD: memory allocation id fail"); BN_CTX_free(data->bnctx); os_free(data); return NULL; } os_memcpy(data->id_peer, identity, identity_len); data->id_peer_len = identity_len; if ((data->password = os_malloc(password_len)) == NULL) { wpa_printf(MSG_INFO, "EAP-PWD: memory allocation psk fail"); BN_CTX_free(data->bnctx); bin_clear_free(data->id_peer, data->id_peer_len); os_free(data); return NULL; } os_memcpy(data->password, password, password_len); data->password_len = password_len; data->password_hash = pwhash; data->out_frag_pos = data->in_frag_pos = 0; data->inbuf = data->outbuf = NULL; fragment_size = eap_get_config_fragment_size(sm); if (fragment_size <= 0) { data->mtu = 1020; /* default from RFC 5931 */ } else { data->mtu = fragment_size; } data->state = PWD_ID_Req; return data; } static void eap_pwd_deinit(struct eap_sm *sm, void *priv) { struct eap_pwd_data *data = priv; BN_clear_free(data->private_value); BN_clear_free(data->server_scalar); BN_clear_free(data->my_scalar); BN_clear_free(data->k); BN_CTX_free(data->bnctx); EC_POINT_clear_free(data->my_element); EC_POINT_clear_free(data->server_element); bin_clear_free(data->id_peer, data->id_peer_len); bin_clear_free(data->id_server, data->id_server_len); bin_clear_free(data->password, data->password_len); if (data->grp) { EC_GROUP_free(data->grp->group); EC_POINT_clear_free(data->grp->pwe); BN_clear_free(data->grp->order); BN_clear_free(data->grp->prime); os_free(data->grp); } wpabuf_free(data->inbuf); wpabuf_free(data->outbuf); bin_clear_free(data, sizeof(*data)); } static u8 *eap_pwd_getkey(struct eap_sm *sm, void *priv, size_t *len) { struct eap_pwd_data *data = priv; u8 *key; if (data->state != SUCCESS) { return NULL; } key = os_malloc(EAP_MSK_LEN); if (key == NULL) { return NULL; } os_memcpy(key, data->msk, EAP_MSK_LEN); *len = EAP_MSK_LEN; return key; } static u8 *eap_pwd_get_session_id(struct eap_sm *sm, void *priv, size_t *len) { struct eap_pwd_data *data = priv; u8 *id; if (data->state != SUCCESS) { return NULL; } id = os_malloc(1 + SHA256_MAC_LEN); if (id == NULL) { return NULL; } os_memcpy(id, data->session_id, 1 + SHA256_MAC_LEN); *len = 1 + SHA256_MAC_LEN; return id; } static void eap_pwd_perform_id_exchange(struct eap_sm *sm, struct eap_pwd_data *data, struct eap_method_ret *ret, const struct wpabuf *reqData, const u8 *payload, size_t payload_len) { struct eap_pwd_id *id; const u8 *password; size_t password_len; u8 pwhashhash[16]; int res; if (data->state != PWD_ID_Req) { ret->ignore = TRUE; eap_pwd_state(data, FAILURE); return; } if (payload_len < sizeof(struct eap_pwd_id)) { ret->ignore = TRUE; eap_pwd_state(data, FAILURE); return; } id = (struct eap_pwd_id *)payload; data->group_num = be_to_host16(id->group_num); wpa_printf(MSG_DEBUG, "EAP-PWD: Server EAP-pwd-ID proposal: group=%u random=%u prf=%u prep=%u", data->group_num, id->random_function, id->prf, id->prep); if ((id->random_function != EAP_PWD_DEFAULT_RAND_FUNC) || (id->prf != EAP_PWD_DEFAULT_PRF)) { ret->ignore = TRUE; eap_pwd_state(data, FAILURE); return; } if (id->prep != EAP_PWD_PREP_NONE && id->prep != EAP_PWD_PREP_MS) { wpa_printf(MSG_DEBUG, "EAP-PWD: Unsupported password pre-processing technique (Prep=%u)", id->prep); eap_pwd_state(data, FAILURE); return; } if (id->prep == EAP_PWD_PREP_NONE && data->password_hash) { wpa_printf(MSG_DEBUG, "EAP-PWD: Unhashed password not available"); eap_pwd_state(data, FAILURE); return; } wpa_printf(MSG_DEBUG, "EAP-PWD (peer): using group %d", data->group_num); data->id_server = os_malloc(payload_len - sizeof(struct eap_pwd_id)); if (data->id_server == NULL) { wpa_printf(MSG_INFO, "EAP-PWD: memory allocation id fail"); eap_pwd_state(data, FAILURE); return; } data->id_server_len = payload_len - sizeof(struct eap_pwd_id); os_memcpy(data->id_server, id->identity, data->id_server_len); wpa_hexdump_ascii(MSG_INFO, "EAP-PWD (peer): server sent id of", data->id_server, data->id_server_len); data->grp = os_zalloc(sizeof(EAP_PWD_group)); if (data->grp == NULL) { wpa_printf(MSG_INFO, "EAP-PWD: failed to allocate memory for " "group"); eap_pwd_state(data, FAILURE); return; } if (id->prep == EAP_PWD_PREP_MS) { if (data->password_hash) { res = hash_nt_password_hash(data->password, pwhashhash); } else { u8 pwhash[16]; res = nt_password_hash(data->password, data->password_len, pwhash); if (res == 0) { res = hash_nt_password_hash(pwhash, pwhashhash); } os_memset(pwhash, 0, sizeof(pwhash)); } if (res) { eap_pwd_state(data, FAILURE); return; } password = pwhashhash; password_len = sizeof(pwhashhash); } else { password = data->password; password_len = data->password_len; } /* compute PWE */ res = compute_password_element(data->grp, data->group_num, password, password_len, data->id_server, data->id_server_len, data->id_peer, data->id_peer_len, id->token); os_memset(pwhashhash, 0, sizeof(pwhashhash)); if (res) { wpa_printf(MSG_INFO, "EAP-PWD (peer): unable to compute PWE"); eap_pwd_state(data, FAILURE); return; } wpa_printf(MSG_DEBUG, "EAP-PWD (peer): computed %d bit PWE...", BN_num_bits(data->grp->prime)); data->outbuf = wpabuf_alloc(sizeof(struct eap_pwd_id) + data->id_peer_len); if (data->outbuf == NULL) { eap_pwd_state(data, FAILURE); return; } wpabuf_put_be16(data->outbuf, data->group_num); wpabuf_put_u8(data->outbuf, EAP_PWD_DEFAULT_RAND_FUNC); wpabuf_put_u8(data->outbuf, EAP_PWD_DEFAULT_PRF); wpabuf_put_data(data->outbuf, id->token, sizeof(id->token)); wpabuf_put_u8(data->outbuf, EAP_PWD_PREP_NONE); wpabuf_put_data(data->outbuf, data->id_peer, data->id_peer_len); eap_pwd_state(data, PWD_Commit_Req); } static void eap_pwd_perform_commit_exchange(struct eap_sm *sm, struct eap_pwd_data *data, struct eap_method_ret *ret, const struct wpabuf *reqData, const u8 *payload, size_t payload_len) { EC_POINT *K = NULL, *point = NULL; BIGNUM *mask = NULL, *x = NULL, *y = NULL, *cofactor = NULL; u16 offset; u8 *ptr, *scalar = NULL, *element = NULL; size_t prime_len, order_len; if (data->state != PWD_Commit_Req) { ret->ignore = TRUE; goto fin; } prime_len = BN_num_bytes(data->grp->prime); order_len = BN_num_bytes(data->grp->order); if (payload_len != 2 * prime_len + order_len) { wpa_printf(MSG_INFO, "EAP-pwd: Unexpected Commit payload length %u (expected %u)", (unsigned int)payload_len, (unsigned int)(2 * prime_len + order_len)); goto fin; } if (((data->private_value = BN_new()) == NULL) || ((data->my_element = EC_POINT_new(data->grp->group)) == NULL) || ((cofactor = BN_new()) == NULL) || ((data->my_scalar = BN_new()) == NULL) || ((mask = BN_new()) == NULL)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): scalar allocation fail"); goto fin; } if (!EC_GROUP_get_cofactor(data->grp->group, cofactor, NULL)) { wpa_printf(MSG_INFO, "EAP-pwd (peer): unable to get cofactor " "for curve"); goto fin; } if (BN_rand_range(data->private_value, data->grp->order) != 1 || BN_rand_range(mask, data->grp->order) != 1 || BN_add(data->my_scalar, data->private_value, mask) != 1 || BN_mod(data->my_scalar, data->my_scalar, data->grp->order, data->bnctx) != 1) { wpa_printf(MSG_INFO, "EAP-pwd (peer): unable to get randomness"); goto fin; } if (!EC_POINT_mul(data->grp->group, data->my_element, NULL, data->grp->pwe, mask, data->bnctx)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): element allocation " "fail"); eap_pwd_state(data, FAILURE); goto fin; } if (!EC_POINT_invert(data->grp->group, data->my_element, data->bnctx)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): element inversion fail"); goto fin; } BN_clear_free(mask); if (((x = BN_new()) == NULL) || ((y = BN_new()) == NULL)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): point allocation fail"); goto fin; } /* process the request */ if (((data->server_scalar = BN_new()) == NULL) || ((data->k = BN_new()) == NULL) || ((K = EC_POINT_new(data->grp->group)) == NULL) || ((point = EC_POINT_new(data->grp->group)) == NULL) || ((data->server_element = EC_POINT_new(data->grp->group)) == NULL)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): peer data allocation " "fail"); goto fin; } /* element, x then y, followed by scalar */ ptr = (u8 *)payload; BN_bin2bn(ptr, BN_num_bytes(data->grp->prime), x); ptr += BN_num_bytes(data->grp->prime); BN_bin2bn(ptr, BN_num_bytes(data->grp->prime), y); ptr += BN_num_bytes(data->grp->prime); BN_bin2bn(ptr, BN_num_bytes(data->grp->order), data->server_scalar); if (!EC_POINT_set_affine_coordinates_GFp(data->grp->group, data->server_element, x, y, data->bnctx)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): setting peer element " "fail"); goto fin; } /* check to ensure server's element is not in a small sub-group */ if (BN_cmp(cofactor, BN_value_one())) { if (!EC_POINT_mul(data->grp->group, point, NULL, data->server_element, cofactor, NULL)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): cannot multiply " "server element by order!\n"); goto fin; } if (EC_POINT_is_at_infinity(data->grp->group, point)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): server element " "is at infinity!\n"); goto fin; } } /* compute the shared key, k */ if ((!EC_POINT_mul(data->grp->group, K, NULL, data->grp->pwe, data->server_scalar, data->bnctx)) || (!EC_POINT_add(data->grp->group, K, K, data->server_element, data->bnctx)) || (!EC_POINT_mul(data->grp->group, K, NULL, K, data->private_value, data->bnctx))) { wpa_printf(MSG_INFO, "EAP-PWD (peer): computing shared key " "fail"); goto fin; } /* ensure that the shared key isn't in a small sub-group */ if (BN_cmp(cofactor, BN_value_one())) { if (!EC_POINT_mul(data->grp->group, K, NULL, K, cofactor, NULL)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): cannot multiply " "shared key point by order"); goto fin; } } /* * This check is strictly speaking just for the case above where * co-factor > 1 but it was suggested that even though this is probably * never going to happen it is a simple and safe check "just to be * sure" so let's be safe. */ if (EC_POINT_is_at_infinity(data->grp->group, K)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): shared key point is at " "infinity!\n"); goto fin; } if (!EC_POINT_get_affine_coordinates_GFp(data->grp->group, K, data->k, NULL, data->bnctx)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): unable to extract " "shared secret from point"); goto fin; } /* now do the response */ if (!EC_POINT_get_affine_coordinates_GFp(data->grp->group, data->my_element, x, y, data->bnctx)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): point assignment fail"); goto fin; } if (((scalar = os_malloc(BN_num_bytes(data->grp->order))) == NULL) || ((element = os_malloc(BN_num_bytes(data->grp->prime) * 2)) == NULL)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): data allocation fail"); goto fin; } /* * bignums occupy as little memory as possible so one that is * sufficiently smaller than the prime or order might need pre-pending * with zeros. */ os_memset(scalar, 0, BN_num_bytes(data->grp->order)); os_memset(element, 0, BN_num_bytes(data->grp->prime) * 2); offset = BN_num_bytes(data->grp->order) - BN_num_bytes(data->my_scalar); BN_bn2bin(data->my_scalar, scalar + offset); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(x); BN_bn2bin(x, element + offset); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(y); BN_bn2bin(y, element + BN_num_bytes(data->grp->prime) + offset); data->outbuf = wpabuf_alloc(BN_num_bytes(data->grp->order) + 2 * BN_num_bytes(data->grp->prime)); if (data->outbuf == NULL) { goto fin; } /* we send the element as (x,y) follwed by the scalar */ wpabuf_put_data(data->outbuf, element, 2 * BN_num_bytes(data->grp->prime)); wpabuf_put_data(data->outbuf, scalar, BN_num_bytes(data->grp->order)); fin: os_free(scalar); os_free(element); BN_clear_free(x); BN_clear_free(y); BN_clear_free(cofactor); EC_POINT_clear_free(K); EC_POINT_clear_free(point); if (data->outbuf == NULL) { eap_pwd_state(data, FAILURE); } else { eap_pwd_state(data, PWD_Confirm_Req); } } static void eap_pwd_perform_confirm_exchange(struct eap_sm *sm, struct eap_pwd_data *data, struct eap_method_ret *ret, const struct wpabuf *reqData, const u8 *payload, size_t payload_len) { BIGNUM *x = NULL, *y = NULL; struct crypto_hash *hash; u32 cs; u16 grp; u8 conf[SHA256_MAC_LEN], *cruft = NULL, *ptr; int offset; if (data->state != PWD_Confirm_Req) { ret->ignore = TRUE; goto fin; } if (payload_len != SHA256_MAC_LEN) { wpa_printf(MSG_INFO, "EAP-pwd: Unexpected Confirm payload length %u (expected %u)", (unsigned int)payload_len, SHA256_MAC_LEN); goto fin; } /* * first build up the ciphersuite which is group | random_function | * prf */ grp = htons(data->group_num); ptr = (u8 *)&cs; os_memcpy(ptr, &grp, sizeof(u16)); ptr += sizeof(u16); *ptr = EAP_PWD_DEFAULT_RAND_FUNC; ptr += sizeof(u8); *ptr = EAP_PWD_DEFAULT_PRF; /* each component of the cruft will be at most as big as the prime */ if (((cruft = os_malloc(BN_num_bytes(data->grp->prime))) == NULL) || ((x = BN_new()) == NULL) || ((y = BN_new()) == NULL)) { wpa_printf(MSG_INFO, "EAP-PWD (server): confirm allocation " "fail"); goto fin; } /* * server's commit is H(k | server_element | server_scalar | * peer_element | peer_scalar | ciphersuite) */ hash = eap_pwd_h_init(); if (hash == NULL) { goto fin; } /* * zero the memory each time because this is mod prime math and some * value may start with a few zeros and the previous one did not. */ os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(data->k); BN_bn2bin(data->k, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->prime)); /* server element: x, y */ if (!EC_POINT_get_affine_coordinates_GFp(data->grp->group, data->server_element, x, y, data->bnctx)) { wpa_printf(MSG_INFO, "EAP-PWD (server): confirm point " "assignment fail"); goto fin; } os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(x); BN_bn2bin(x, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->prime)); os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(y); BN_bn2bin(y, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->prime)); /* server scalar */ os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->order) - BN_num_bytes(data->server_scalar); BN_bn2bin(data->server_scalar, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->order)); /* my element: x, y */ if (!EC_POINT_get_affine_coordinates_GFp(data->grp->group, data->my_element, x, y, data->bnctx)) { wpa_printf(MSG_INFO, "EAP-PWD (server): confirm point " "assignment fail"); goto fin; } os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(x); BN_bn2bin(x, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->prime)); os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(y); BN_bn2bin(y, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->prime)); /* my scalar */ os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->order) - BN_num_bytes(data->my_scalar); BN_bn2bin(data->my_scalar, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->order)); /* the ciphersuite */ eap_pwd_h_update(hash, (u8 *)&cs, sizeof(u32)); /* random function fin */ eap_pwd_h_final(hash, conf); ptr = (u8 *)payload; if (os_memcmp_const(conf, ptr, SHA256_MAC_LEN)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): confirm did not verify"); goto fin; } wpa_printf(MSG_DEBUG, "EAP-pwd (peer): confirm verified"); /* * compute confirm: * H(k | peer_element | peer_scalar | server_element | server_scalar | * ciphersuite) */ hash = eap_pwd_h_init(); if (hash == NULL) { goto fin; } /* k */ os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(data->k); BN_bn2bin(data->k, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->prime)); /* my element */ if (!EC_POINT_get_affine_coordinates_GFp(data->grp->group, data->my_element, x, y, data->bnctx)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): confirm point " "assignment fail"); goto fin; } os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(x); BN_bn2bin(x, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->prime)); os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(y); BN_bn2bin(y, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->prime)); /* my scalar */ os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->order) - BN_num_bytes(data->my_scalar); BN_bn2bin(data->my_scalar, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->order)); /* server element: x, y */ if (!EC_POINT_get_affine_coordinates_GFp(data->grp->group, data->server_element, x, y, data->bnctx)) { wpa_printf(MSG_INFO, "EAP-PWD (peer): confirm point " "assignment fail"); goto fin; } os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(x); BN_bn2bin(x, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->prime)); os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->prime) - BN_num_bytes(y); BN_bn2bin(y, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->prime)); /* server scalar */ os_memset(cruft, 0, BN_num_bytes(data->grp->prime)); offset = BN_num_bytes(data->grp->order) - BN_num_bytes(data->server_scalar); BN_bn2bin(data->server_scalar, cruft + offset); eap_pwd_h_update(hash, cruft, BN_num_bytes(data->grp->order)); /* the ciphersuite */ eap_pwd_h_update(hash, (u8 *)&cs, sizeof(u32)); /* all done */ eap_pwd_h_final(hash, conf); if (compute_keys(data->grp, data->bnctx, data->k, data->my_scalar, data->server_scalar, conf, ptr, &cs, data->msk, data->emsk, data->session_id) < 0) { wpa_printf(MSG_INFO, "EAP-PWD (peer): unable to compute MSK | " "EMSK"); goto fin; } data->outbuf = wpabuf_alloc(SHA256_MAC_LEN); if (data->outbuf == NULL) { goto fin; } wpabuf_put_data(data->outbuf, conf, SHA256_MAC_LEN); fin: bin_clear_free(cruft, BN_num_bytes(data->grp->prime)); BN_clear_free(x); BN_clear_free(y); if (data->outbuf == NULL) { ret->methodState = METHOD_DONE; ret->decision = DECISION_FAIL; eap_pwd_state(data, FAILURE); } else { eap_pwd_state(data, SUCCESS_ON_FRAG_COMPLETION); } } static struct wpabuf *eap_pwd_process(struct eap_sm *sm, void *priv, struct eap_method_ret *ret, const struct wpabuf *reqData) { struct eap_pwd_data *data = priv; struct wpabuf *resp = NULL; const u8 *pos, *buf; size_t len; u16 tot_len = 0; u8 lm_exch; pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_PWD, reqData, &len); if ((pos == NULL) || (len < 1)) { wpa_printf(MSG_DEBUG, "EAP-pwd: Got a frame but pos is %s and " "len is %d", pos == NULL ? "NULL" : "not NULL", (int)len); ret->ignore = TRUE; return NULL; } ret->ignore = FALSE; ret->methodState = METHOD_MAY_CONT; ret->decision = DECISION_FAIL; ret->allowNotifications = FALSE; lm_exch = *pos; pos++; /* skip over the bits and the exch */ len--; /* * we're fragmenting so send out the next fragment */ if (data->out_frag_pos) { /* * this should be an ACK */ if (len) { wpa_printf(MSG_INFO, "Bad Response! Fragmenting but " "not an ACK"); } wpa_printf(MSG_DEBUG, "EAP-pwd: Got an ACK for a fragment"); /* * check if there are going to be more fragments */ len = wpabuf_len(data->outbuf) - data->out_frag_pos; if ((len + EAP_PWD_HDR_SIZE) > data->mtu) { len = data->mtu - EAP_PWD_HDR_SIZE; EAP_PWD_SET_MORE_BIT(lm_exch); } resp = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_PWD, EAP_PWD_HDR_SIZE + len, EAP_CODE_RESPONSE, eap_get_id(reqData)); if (resp == NULL) { wpa_printf(MSG_INFO, "Unable to allocate memory for " "next fragment!"); return NULL; } wpabuf_put_u8(resp, lm_exch); buf = wpabuf_head_u8(data->outbuf); wpabuf_put_data(resp, buf + data->out_frag_pos, len); data->out_frag_pos += len; /* * this is the last fragment so get rid of the out buffer */ if (data->out_frag_pos >= wpabuf_len(data->outbuf)) { wpabuf_free(data->outbuf); data->outbuf = NULL; data->out_frag_pos = 0; } wpa_printf(MSG_DEBUG, "EAP-pwd: Send %s fragment of %d bytes", data->out_frag_pos == 0 ? "last" : "next", (int)len); if (data->state == SUCCESS_ON_FRAG_COMPLETION) { ret->methodState = METHOD_DONE; ret->decision = DECISION_UNCOND_SUCC; eap_pwd_state(data, SUCCESS); } return resp; } /* * see if this is a fragment that needs buffering * * if it's the first fragment there'll be a length field */ if (EAP_PWD_GET_LENGTH_BIT(lm_exch)) { if (len < 2) { wpa_printf(MSG_DEBUG, "EAP-pwd: Frame too short to contain Total-Length field"); ret->ignore = TRUE; return NULL; } tot_len = WPA_GET_BE16(pos); wpa_printf(MSG_DEBUG, "EAP-pwd: Incoming fragments whose " "total length = %d", tot_len); if (tot_len > 15000) { return NULL; } if (data->inbuf) { wpa_printf(MSG_DEBUG, "EAP-pwd: Unexpected new fragment start when previous fragment is still in use"); ret->ignore = TRUE; return NULL; } data->inbuf = wpabuf_alloc(tot_len); if (data->inbuf == NULL) { wpa_printf(MSG_INFO, "Out of memory to buffer " "fragments!"); return NULL; } data->in_frag_pos = 0; pos += sizeof(u16); len -= sizeof(u16); } /* * buffer and ACK the fragment */ if (EAP_PWD_GET_MORE_BIT(lm_exch)) { data->in_frag_pos += len; if (data->in_frag_pos > wpabuf_size(data->inbuf)) { wpa_printf(MSG_INFO, "EAP-pwd: Buffer overflow attack " "detected (%d vs. %d)!", (int)data->in_frag_pos, (int)wpabuf_len(data->inbuf)); wpabuf_free(data->inbuf); data->inbuf = NULL; data->in_frag_pos = 0; return NULL; } wpabuf_put_data(data->inbuf, pos, len); resp = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_PWD, EAP_PWD_HDR_SIZE, EAP_CODE_RESPONSE, eap_get_id(reqData)); if (resp != NULL) { wpabuf_put_u8(resp, (EAP_PWD_GET_EXCHANGE(lm_exch))); } wpa_printf(MSG_DEBUG, "EAP-pwd: ACKing a %d byte fragment", (int)len); return resp; } /* * we're buffering and this is the last fragment */ if (data->in_frag_pos) { wpabuf_put_data(data->inbuf, pos, len); wpa_printf(MSG_DEBUG, "EAP-pwd: Last fragment, %d bytes", (int)len); data->in_frag_pos += len; pos = wpabuf_head_u8(data->inbuf); len = data->in_frag_pos; } wpa_printf(MSG_DEBUG, "EAP-pwd: processing frame: exch %d, len %d", EAP_PWD_GET_EXCHANGE(lm_exch), (int)len); switch (EAP_PWD_GET_EXCHANGE(lm_exch)) { case EAP_PWD_OPCODE_ID_EXCH: eap_pwd_perform_id_exchange(sm, data, ret, reqData, pos, len); break; case EAP_PWD_OPCODE_COMMIT_EXCH: eap_pwd_perform_commit_exchange(sm, data, ret, reqData, pos, len); break; case EAP_PWD_OPCODE_CONFIRM_EXCH: eap_pwd_perform_confirm_exchange(sm, data, ret, reqData, pos, len); break; default: wpa_printf(MSG_INFO, "EAP-pwd: Ignoring message with unknown " "opcode %d", lm_exch); break; } /* * if we buffered the just processed input now's the time to free it */ if (data->in_frag_pos) { wpabuf_free(data->inbuf); data->inbuf = NULL; data->in_frag_pos = 0; } if (data->outbuf == NULL) { ret->methodState = METHOD_DONE; ret->decision = DECISION_FAIL; return NULL; /* generic failure */ } /* * we have output! Do we need to fragment it? */ lm_exch = EAP_PWD_GET_EXCHANGE(lm_exch); len = wpabuf_len(data->outbuf); if ((len + EAP_PWD_HDR_SIZE) > data->mtu) { resp = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_PWD, data->mtu, EAP_CODE_RESPONSE, eap_get_id(reqData)); /* * if so it's the first so include a length field */ EAP_PWD_SET_LENGTH_BIT(lm_exch); EAP_PWD_SET_MORE_BIT(lm_exch); tot_len = len; /* * keep the packet at the MTU */ len = data->mtu - EAP_PWD_HDR_SIZE - sizeof(u16); wpa_printf(MSG_DEBUG, "EAP-pwd: Fragmenting output, total " "length = %d", tot_len); } else { resp = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_PWD, EAP_PWD_HDR_SIZE + len, EAP_CODE_RESPONSE, eap_get_id(reqData)); } if (resp == NULL) { return NULL; } wpabuf_put_u8(resp, lm_exch); if (EAP_PWD_GET_LENGTH_BIT(lm_exch)) { wpabuf_put_be16(resp, tot_len); data->out_frag_pos += len; } buf = wpabuf_head_u8(data->outbuf); wpabuf_put_data(resp, buf, len); /* * if we're not fragmenting then there's no need to carry this around */ if (data->out_frag_pos == 0) { wpabuf_free(data->outbuf); data->outbuf = NULL; data->out_frag_pos = 0; if (data->state == SUCCESS_ON_FRAG_COMPLETION) { ret->methodState = METHOD_DONE; ret->decision = DECISION_UNCOND_SUCC; eap_pwd_state(data, SUCCESS); } } return resp; } static Boolean eap_pwd_key_available(struct eap_sm *sm, void *priv) { struct eap_pwd_data *data = priv; return data->state == SUCCESS; } static u8 *eap_pwd_get_emsk(struct eap_sm *sm, void *priv, size_t *len) { struct eap_pwd_data *data = priv; u8 *key; if (data->state != SUCCESS) { return NULL; } if ((key = os_malloc(EAP_EMSK_LEN)) == NULL) { return NULL; } os_memcpy(key, data->emsk, EAP_EMSK_LEN); *len = EAP_EMSK_LEN; return key; } int eap_peer_pwd_register(void) { struct eap_method *eap; int ret; eap = eap_peer_method_alloc(EAP_PEER_METHOD_INTERFACE_VERSION, EAP_VENDOR_IETF, EAP_TYPE_PWD, "PWD"); if (eap == NULL) { return -1; } eap->init = eap_pwd_init; eap->deinit = eap_pwd_deinit; eap->process = eap_pwd_process; eap->isKeyAvailable = eap_pwd_key_available; eap->getKey = eap_pwd_getkey; eap->getSessionId = eap_pwd_get_session_id; eap->get_emsk = eap_pwd_get_emsk; ret = eap_peer_method_register(eap); if (ret) { eap_peer_method_free(eap); } return ret; } #endif /* #ifndef CONFIG_DISABLE_EAP_FOR_SUPPLICANT */
{'content_hash': '5e71484fef58066251101c6f6c23d64c', 'timestamp': '', 'source': 'github', 'line_count': 938, 'max_line_length': 261, 'avg_line_length': 30.777185501066096, 'alnum_prop': 0.6489660189130209, 'repo_name': 'pillip8282/TizenRT', 'id': '1be388ac23714aead065953ae513213478e6f015', 'size': '29554', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'external/wpa_supplicant/src/eap_peer/eap_pwd.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '2045766'}, {'name': 'Batchfile', 'bytes': '42646'}, {'name': 'C', 'bytes': '75239339'}, {'name': 'C++', 'bytes': '813875'}, {'name': 'HTML', 'bytes': '2990'}, {'name': 'Java', 'bytes': '63595'}, {'name': 'Makefile', 'bytes': '822281'}, {'name': 'Perl', 'bytes': '4361'}, {'name': 'PowerShell', 'bytes': '8511'}, {'name': 'Python', 'bytes': '265804'}, {'name': 'Roff', 'bytes': '4401'}, {'name': 'Shell', 'bytes': '236136'}, {'name': 'Tcl', 'bytes': '163693'}]}
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Timeline', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('date', models.DateField()), ('keyword', models.CharField(max_length=20)), ('caption', models.TextField(blank=True)), ], options={ 'ordering': ['date'], 'verbose_name_plural': 'timeline', }, ), ]
{'content_hash': 'e2b4f129afd5c889852c155bef40fc89', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 114, 'avg_line_length': 29.24137931034483, 'alnum_prop': 0.5259433962264151, 'repo_name': 'fredwulei/fredsneverland', 'id': '3bcb46084cf10429005efeb4c0a4172b55977edc', 'size': '921', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'fredsneverland/timeline/migrations/0001_initial.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '83588'}, {'name': 'HTML', 'bytes': '27845'}, {'name': 'JavaScript', 'bytes': '271245'}, {'name': 'Python', 'bytes': '32032'}]}
// Deprecated /* istanbul ignore file */ export const getComputedClientRect = (node, contentWindow) => { const defaultRect = { height: 0, left: 0, top: 0, } if (!node) return defaultRect const rect = node.getBoundingClientRect() const { height, top, left } = rect // window.scrollY / window.scrollX cannot be modified (or easily mocked) // within JSDOM. Manually tested in the browser, and the calculations are // correct. const computedTop = top + height + contentWindow.scrollY const computedLeft = left + contentWindow.scrollX return { left: computedLeft, top: computedTop, height, } }
{'content_hash': '16fe39650fe27418cd82c6a9a8677610', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 75, 'avg_line_length': 23.77777777777778, 'alnum_prop': 0.6806853582554517, 'repo_name': 'helpscout/blue', 'id': 'cdec629693b38b65bfa00733beeb49be37301241', 'size': '642', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'src/components/Dropdown/Dropdown.MenuContainer.utils.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '47340'}, {'name': 'JavaScript', 'bytes': '1531763'}, {'name': 'Shell', 'bytes': '215'}, {'name': 'TypeScript', 'bytes': '87805'}]}
using StringType = LPWSTR; using Tests = StringMarshalingTests<StringType, TP_slen>; #define FUNCTION_NAME __FUNCTIONW__ #include "../Native/StringTestEntrypoints.inl" // Verify that we append extra null terminators to our StringBuilder native buffers. // Although this is a hidden implementation detail, it would be breaking behavior to stop doing this // so we have a test for it. In particular, this detail prevents us from optimizing marshalling StringBuilders by pinning. extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE Verify_NullTerminators_PastEnd(LPCWSTR buffer, int length) { return buffer[length+1] == W('\0'); } struct ByValStringInStructAnsi { char str[20]; }; struct ByValStringInStructUnicode { WCHAR str[20]; }; extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE MatchFuncNameAnsi(ByValStringInStructAnsi str) { return StringMarshalingTests<char*, default_callconv_strlen>::Compare(__func__, str.str); } extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE MatchFuncNameUni(ByValStringInStructUnicode str) { return StringMarshalingTests<LPWSTR, TP_slen>::Compare(__FUNCTIONW__, str.str); } extern "C" DLL_EXPORT void STDMETHODCALLTYPE ReverseByValStringAnsi(ByValStringInStructAnsi* str) { StringMarshalingTests<char*, default_callconv_strlen>::ReverseInplace(str->str); } extern "C" DLL_EXPORT void STDMETHODCALLTYPE ReverseByValStringUni(ByValStringInStructUnicode* str) { StringMarshalingTests<LPWSTR, TP_slen>::ReverseInplace(str->str); }
{'content_hash': 'cd9105e92bb5957e9afcf7c8da762e79', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 122, 'avg_line_length': 33.61363636363637, 'alnum_prop': 0.7782285327924273, 'repo_name': 'poizan42/coreclr', 'id': 'a500e598399c9e97dc9f21471cd333793d404951', 'size': '1730', 'binary': False, 'copies': '27', 'ref': 'refs/heads/master', 'path': 'tests/src/Interop/StringMarshalling/LPTSTR/LPTStrTestNative.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '939689'}, {'name': 'Awk', 'bytes': '5861'}, {'name': 'Batchfile', 'bytes': '149949'}, {'name': 'C', 'bytes': '3034023'}, {'name': 'C#', 'bytes': '134177151'}, {'name': 'C++', 'bytes': '68856945'}, {'name': 'CMake', 'bytes': '641497'}, {'name': 'Groovy', 'bytes': '202934'}, {'name': 'Makefile', 'bytes': '2736'}, {'name': 'Objective-C', 'bytes': '471678'}, {'name': 'PAWN', 'bytes': '903'}, {'name': 'Perl', 'bytes': '23640'}, {'name': 'PowerShell', 'bytes': '9319'}, {'name': 'Python', 'bytes': '242544'}, {'name': 'Roff', 'bytes': '529523'}, {'name': 'Shell', 'bytes': '223037'}, {'name': 'Smalltalk', 'bytes': '1162648'}, {'name': 'SuperCollider', 'bytes': '4752'}, {'name': 'XSLT', 'bytes': '1016'}, {'name': 'Yacc', 'bytes': '157348'}]}
@interface mycell : YBBaseViewController @end
{'content_hash': '265db8fbf5409ecc9de389949a096142', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 40, 'avg_line_length': 15.666666666666666, 'alnum_prop': 0.8085106382978723, 'repo_name': 'NerveTeam/XAnbao', 'id': '9c0ca583944cf19f36369915ee99e53976cef790', 'size': '202', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'XAnBao/XAnBao/View/Cell/My/mycell.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '932743'}, {'name': 'C++', 'bytes': '137816'}, {'name': 'HTML', 'bytes': '4556'}, {'name': 'Objective-C', 'bytes': '4195427'}, {'name': 'Objective-C++', 'bytes': '15975'}]}
<?php namespace Symfony\Component\Security\Guard\Tests\Authenticator; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator; /** * @author Jean Pasdeloup <[email protected]> */ class FormLoginAuthenticatorTest extends TestCase { private $requestWithoutSession; private $requestWithSession; private $authenticator; const LOGIN_URL = 'http://login'; const DEFAULT_SUCCESS_URL = 'http://defaultsuccess'; const CUSTOM_SUCCESS_URL = 'http://customsuccess'; public function testAuthenticationFailureWithoutSession() { $failureResponse = $this->authenticator->onAuthenticationFailure($this->requestWithoutSession, new AuthenticationException()); $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\RedirectResponse', $failureResponse); $this->assertEquals(self::LOGIN_URL, $failureResponse->getTargetUrl()); } public function testAuthenticationFailureWithSession() { $this->requestWithSession->getSession() ->expects($this->once()) ->method('set'); $failureResponse = $this->authenticator->onAuthenticationFailure($this->requestWithSession, new AuthenticationException()); $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\RedirectResponse', $failureResponse); $this->assertEquals(self::LOGIN_URL, $failureResponse->getTargetUrl()); } public function testRememberMe() { $doSupport = $this->authenticator->supportsRememberMe(); $this->assertTrue($doSupport); } public function testStartWithoutSession() { $failureResponse = $this->authenticator->start($this->requestWithoutSession, new AuthenticationException()); $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\RedirectResponse', $failureResponse); $this->assertEquals(self::LOGIN_URL, $failureResponse->getTargetUrl()); } public function testStartWithSession() { $failureResponse = $this->authenticator->start($this->requestWithSession, new AuthenticationException()); $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\RedirectResponse', $failureResponse); $this->assertEquals(self::LOGIN_URL, $failureResponse->getTargetUrl()); } protected function setUp() { $this->requestWithoutSession = new Request(array(), array(), array(), array(), array(), array()); $this->requestWithSession = new Request(array(), array(), array(), array(), array(), array()); $session = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\Session\\SessionInterface') ->disableOriginalConstructor() ->getMock(); $this->requestWithSession->setSession($session); $this->authenticator = new TestFormLoginAuthenticator(); $this->authenticator ->setLoginUrl(self::LOGIN_URL) ->setDefaultSuccessRedirectUrl(self::DEFAULT_SUCCESS_URL) ; } protected function tearDown() { $this->request = null; $this->requestWithSession = null; } } class TestFormLoginAuthenticator extends AbstractFormLoginAuthenticator { private $loginUrl; private $defaultSuccessRedirectUrl; public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey) { } /** * @param mixed $defaultSuccessRedirectUrl * * @return TestFormLoginAuthenticator */ public function setDefaultSuccessRedirectUrl($defaultSuccessRedirectUrl) { $this->defaultSuccessRedirectUrl = $defaultSuccessRedirectUrl; return $this; } /** * @param mixed $loginUrl * * @return TestFormLoginAuthenticator */ public function setLoginUrl($loginUrl) { $this->loginUrl = $loginUrl; return $this; } /** * {@inheritdoc} */ protected function getLoginUrl() { return $this->loginUrl; } /** * {@inheritdoc} */ protected function getDefaultSuccessRedirectUrl() { return $this->defaultSuccessRedirectUrl; } /** * {@inheritdoc} */ public function getCredentials(Request $request) { return 'credentials'; } /** * {@inheritdoc} */ public function getUser($credentials, UserProviderInterface $userProvider) { return $userProvider->loadUserByUsername($credentials); } /** * {@inheritdoc} */ public function checkCredentials($credentials, UserInterface $user) { return true; } }
{'content_hash': '2d5aaacf0f0f2170f3a1ea75bb81097b', 'timestamp': '', 'source': 'github', 'line_count': 167, 'max_line_length': 134, 'avg_line_length': 29.724550898203592, 'alnum_prop': 0.6770749395648671, 'repo_name': 'lepiaf/symfony', 'id': '1789b95d8c4ed0f787a9ce7ec008b10635ba8da8', 'size': '5193', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'src/Symfony/Component/Security/Guard/Tests/Authenticator/FormLoginAuthenticatorTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '332860'}, {'name': 'PHP', 'bytes': '13326142'}, {'name': 'Shell', 'bytes': '375'}]}
+++ pre = "<b>3.3.1. </b>" title = "Config Center" weight = 1 +++ ## Motivation - Centralized configuration: more and more running examples have made it hard to manage separate configurations and asynchronized configurations can cause serious problems. Concentrating them in the configuration center can make the management more effective. - Dynamic configuration: distribution after configuration modification is another important capability of configuration center. It can support dynamic switch between data sources, tables, shards and the read-write split strategy. ## Data Structure in Configuration Center Under defined name space config, configuration center stores data sources, sharding databases, sharding tables, read-write split, and properties in YAML. Modifying nodes can dynamically manage configuration. ``` config ├──authentication # Sharding-Proxy authentication configuration ├──props # Properties configuration ├──schema # Schema configuration ├ ├──sharding_db # SchemaName configuration ├ ├ ├──datasource # Datasource configuration ├ ├ ├──rule # Sharding rule configuration ├ ├──masterslave_db # SchemaName configuration ├ ├ ├──datasource # Datasource configuration ├ ├ ├──rule # Master-slave rule configuration ``` ### config/authentication ```yaml password: root username: root ``` ### config/sharding/props It corresponds to Sharding Properties in ShardingSphere configuration. ```yaml executor.size: 20 sql.show: true ``` ### config/schema/schemeName/datasource A collection of multiple database connection pools, whose properties (e.g. DBCP, C3P0, Druid and HikariCP) are configured by users themselves. ```yaml ds_0: !!org.apache.shardingsphere.orchestration.yaml.YamlDataSourceConfiguration dataSourceClassName: com.zaxxer.hikari.HikariDataSource properties: url: jdbc:mysql://127.0.0.1:3306/demo_ds_0?serverTimezone=UTC&useSSL=false password: null maxPoolSize: 50 maintenanceIntervalMilliseconds: 30000 connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 minPoolSize: 1 username: root maxLifetimeMilliseconds: 1800000 ds_1: !!org.apache.shardingsphere.orchestration.yaml.YamlDataSourceConfiguration dataSourceClassName: com.zaxxer.hikari.HikariDataSource properties: url: jdbc:mysql://127.0.0.1:3306/demo_ds_1?serverTimezone=UTC&useSSL=false password: null maxPoolSize: 50 maintenanceIntervalMilliseconds: 30000 connectionTimeoutMilliseconds: 30000 idleTimeoutMilliseconds: 60000 minPoolSize: 1 username: root maxLifetimeMilliseconds: 1800000 ``` ### config/schema/sharding_db/rule It refers to sharding configuration, including sharding + read-write split configuration. ```yaml tables: t_order: actualDataNodes: ds_$->{0..1}.t_order_$->{0..1} databaseStrategy: inline: shardingColumn: user_id algorithmExpression: ds_$->{user_id % 2} keyGenerator: column: order_id logicTable: t_order tableStrategy: inline: shardingColumn: order_id algorithmExpression: t_order_$->{order_id % 2} t_order_item: actualDataNodes: ds_$->{0..1}.t_order_item_$->{0..1} databaseStrategy: inline: shardingColumn: user_id algorithmExpression: ds_$->{user_id % 2} keyGenerator: column: order_item_id logicTable: t_order_item tableStrategy: inline: shardingColumn: order_id algorithmExpression: t_order_item_$->{order_id % 2} bindingTables: - t_order,t_order_item broadcastTables: - t_config defaultDataSourceName: ds_0 masterSlaveRules: {} ``` ### config/schema/masterslave/rule This configuration is used when read-write split is used alone. ```yaml name: ds_ms masterDataSourceName: ds_master slaveDataSourceNames: - ds_slave0 - ds_slave1 loadBalanceAlgorithmType: ROUND_ROBIN ``` ## Dynamic Effectiveness Modification, deletion and insertion of relevant configurations in the registry center will immediately take effect in the producing environment.
{'content_hash': 'b471f161fd2ffd9ed38ac5de06d1bf95', 'timestamp': '', 'source': 'github', 'line_count': 134, 'max_line_length': 259, 'avg_line_length': 32.38805970149254, 'alnum_prop': 0.6914746543778801, 'repo_name': 'leeyazhou/sharding-jdbc', 'id': '88b1369b0f778d234b19b8f7ff4073f00e094480', 'size': '4414', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/document/content/features/orchestration/config-center.en.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '266999'}, {'name': 'Batchfile', 'bytes': '3280'}, {'name': 'CSS', 'bytes': '2842'}, {'name': 'Dockerfile', 'bytes': '1485'}, {'name': 'HTML', 'bytes': '2146'}, {'name': 'Java', 'bytes': '7346718'}, {'name': 'JavaScript', 'bytes': '92884'}, {'name': 'Shell', 'bytes': '9837'}, {'name': 'TSQL', 'bytes': '68705'}, {'name': 'Vue', 'bytes': '82063'}]}
<div class="topbar topbar-dark"> <a class="topbar-logo" routerlink="/"> NiceFish-Admin </a> <a href="javascript:void(0);" class="menu-button" (click)="onToggleClick($event)"> <i class="fa fa-bars"></i> </a> <a href="javascript:void(0);" class="user-display" (click)="showTopMenu=!showTopMenu"> <span class="username">{{currentUser.username}}</span> <img src="assets/imgs/img.jpg" style="border: 0px;"> <i class="fa fa-angle-down"></i> </a> <ul class="fadeInDown topbar-menu {{showTopMenu?'topbar-menu-visible':''}}"> <li> <a href="http://damoqiongqiu.github.io" target="_blank"> <i class="topbar-icon fa fa-fw fa-user"></i> <span class="topbar-item-name">用户资料</span> </a> </li> <li> <a href="javascript:void(0);" (click)="showTopMenu=false;"> <i class="topbar-icon fa fa-fw fa-cog"></i> <span class="topbar-item-name">个人设置</span> </a> </li> <li> <a href="javascript:void(0);" (click)="showTopMenu=false;"> <i class="topbar-icon material-icons animated swing fa fa-fw fa-envelope-o"></i> <span class="topbar-item-name">消息</span> <span class="topbar-badge animated rubberBand">4</span> </a> </li> <li> <a href="javascript:void(0);" (click)="showTopMenu=false;" routerLink="/login"> <i class="topbar-icon fa fa-fw fa-power-off "></i> <span class="topbar-item-name">退出</span> <span class="topbar-badge animated rubberBand">2</span> </a> </li> </ul> </div>
{'content_hash': '8e45796221ee18c365cc53b7763b9859', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 88, 'avg_line_length': 37.78048780487805, 'alnum_prop': 0.5887669464170433, 'repo_name': 'bulabulaka/Studio', 'id': '5956a3179788bd5b9b85b48702fd6cc6f77aafd7', 'size': '1573', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/client/app/workspace/top-menu/top-menu.component.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '22660'}, {'name': 'HTML', 'bytes': '30279'}, {'name': 'SQLPL', 'bytes': '7906'}, {'name': 'TypeScript', 'bytes': '265215'}]}
package routev3 import ( "bytes" "errors" "fmt" "net" "net/mail" "net/url" "regexp" "sort" "strings" "time" "unicode/utf8" "google.golang.org/protobuf/types/known/anypb" ) // ensure the imports are used var ( _ = bytes.MinRead _ = errors.New("") _ = fmt.Print _ = utf8.UTFMax _ = (*regexp.Regexp)(nil) _ = (*strings.Reader)(nil) _ = net.IPv4len _ = time.Duration(0) _ = (*url.URL)(nil) _ = (*mail.Address)(nil) _ = anypb.Any{} _ = sort.Sort ) // Validate checks the field values on RouteConfiguration with the rules // defined in the proto definition for this message. If any rules are // violated, the first error encountered is returned, or nil if there are no violations. func (m *RouteConfiguration) Validate() error { return m.validate(false) } // ValidateAll checks the field values on RouteConfiguration with the rules // defined in the proto definition for this message. If any rules are // violated, the result is a list of violation errors wrapped in // RouteConfigurationMultiError, or nil if none found. func (m *RouteConfiguration) ValidateAll() error { return m.validate(true) } func (m *RouteConfiguration) validate(all bool) error { if m == nil { return nil } var errors []error // no validation rules for Name for idx, item := range m.GetVirtualHosts() { _, _ = idx, item if all { switch v := interface{}(item).(type) { case interface{ ValidateAll() error }: if err := v.ValidateAll(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: fmt.Sprintf("VirtualHosts[%v]", idx), reason: "embedded message failed validation", cause: err, }) } case interface{ Validate() error }: if err := v.Validate(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: fmt.Sprintf("VirtualHosts[%v]", idx), reason: "embedded message failed validation", cause: err, }) } } } else if v, ok := interface{}(item).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return RouteConfigurationValidationError{ field: fmt.Sprintf("VirtualHosts[%v]", idx), reason: "embedded message failed validation", cause: err, } } } } if all { switch v := interface{}(m.GetVhds()).(type) { case interface{ ValidateAll() error }: if err := v.ValidateAll(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: "Vhds", reason: "embedded message failed validation", cause: err, }) } case interface{ Validate() error }: if err := v.Validate(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: "Vhds", reason: "embedded message failed validation", cause: err, }) } } } else if v, ok := interface{}(m.GetVhds()).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return RouteConfigurationValidationError{ field: "Vhds", reason: "embedded message failed validation", cause: err, } } } for idx, item := range m.GetInternalOnlyHeaders() { _, _ = idx, item if !_RouteConfiguration_InternalOnlyHeaders_Pattern.MatchString(item) { err := RouteConfigurationValidationError{ field: fmt.Sprintf("InternalOnlyHeaders[%v]", idx), reason: "value does not match regex pattern \"^[^\\x00\\n\\r]*$\"", } if !all { return err } errors = append(errors, err) } } if len(m.GetResponseHeadersToAdd()) > 1000 { err := RouteConfigurationValidationError{ field: "ResponseHeadersToAdd", reason: "value must contain no more than 1000 item(s)", } if !all { return err } errors = append(errors, err) } for idx, item := range m.GetResponseHeadersToAdd() { _, _ = idx, item if all { switch v := interface{}(item).(type) { case interface{ ValidateAll() error }: if err := v.ValidateAll(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: fmt.Sprintf("ResponseHeadersToAdd[%v]", idx), reason: "embedded message failed validation", cause: err, }) } case interface{ Validate() error }: if err := v.Validate(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: fmt.Sprintf("ResponseHeadersToAdd[%v]", idx), reason: "embedded message failed validation", cause: err, }) } } } else if v, ok := interface{}(item).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return RouteConfigurationValidationError{ field: fmt.Sprintf("ResponseHeadersToAdd[%v]", idx), reason: "embedded message failed validation", cause: err, } } } } for idx, item := range m.GetResponseHeadersToRemove() { _, _ = idx, item if !_RouteConfiguration_ResponseHeadersToRemove_Pattern.MatchString(item) { err := RouteConfigurationValidationError{ field: fmt.Sprintf("ResponseHeadersToRemove[%v]", idx), reason: "value does not match regex pattern \"^[^\\x00\\n\\r]*$\"", } if !all { return err } errors = append(errors, err) } } if len(m.GetRequestHeadersToAdd()) > 1000 { err := RouteConfigurationValidationError{ field: "RequestHeadersToAdd", reason: "value must contain no more than 1000 item(s)", } if !all { return err } errors = append(errors, err) } for idx, item := range m.GetRequestHeadersToAdd() { _, _ = idx, item if all { switch v := interface{}(item).(type) { case interface{ ValidateAll() error }: if err := v.ValidateAll(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: fmt.Sprintf("RequestHeadersToAdd[%v]", idx), reason: "embedded message failed validation", cause: err, }) } case interface{ Validate() error }: if err := v.Validate(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: fmt.Sprintf("RequestHeadersToAdd[%v]", idx), reason: "embedded message failed validation", cause: err, }) } } } else if v, ok := interface{}(item).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return RouteConfigurationValidationError{ field: fmt.Sprintf("RequestHeadersToAdd[%v]", idx), reason: "embedded message failed validation", cause: err, } } } } for idx, item := range m.GetRequestHeadersToRemove() { _, _ = idx, item if !_RouteConfiguration_RequestHeadersToRemove_Pattern.MatchString(item) { err := RouteConfigurationValidationError{ field: fmt.Sprintf("RequestHeadersToRemove[%v]", idx), reason: "value does not match regex pattern \"^[^\\x00\\n\\r]*$\"", } if !all { return err } errors = append(errors, err) } } // no validation rules for MostSpecificHeaderMutationsWins if all { switch v := interface{}(m.GetValidateClusters()).(type) { case interface{ ValidateAll() error }: if err := v.ValidateAll(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: "ValidateClusters", reason: "embedded message failed validation", cause: err, }) } case interface{ Validate() error }: if err := v.Validate(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: "ValidateClusters", reason: "embedded message failed validation", cause: err, }) } } } else if v, ok := interface{}(m.GetValidateClusters()).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return RouteConfigurationValidationError{ field: "ValidateClusters", reason: "embedded message failed validation", cause: err, } } } if all { switch v := interface{}(m.GetMaxDirectResponseBodySizeBytes()).(type) { case interface{ ValidateAll() error }: if err := v.ValidateAll(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: "MaxDirectResponseBodySizeBytes", reason: "embedded message failed validation", cause: err, }) } case interface{ Validate() error }: if err := v.Validate(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: "MaxDirectResponseBodySizeBytes", reason: "embedded message failed validation", cause: err, }) } } } else if v, ok := interface{}(m.GetMaxDirectResponseBodySizeBytes()).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return RouteConfigurationValidationError{ field: "MaxDirectResponseBodySizeBytes", reason: "embedded message failed validation", cause: err, } } } for idx, item := range m.GetClusterSpecifierPlugins() { _, _ = idx, item if all { switch v := interface{}(item).(type) { case interface{ ValidateAll() error }: if err := v.ValidateAll(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: fmt.Sprintf("ClusterSpecifierPlugins[%v]", idx), reason: "embedded message failed validation", cause: err, }) } case interface{ Validate() error }: if err := v.Validate(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: fmt.Sprintf("ClusterSpecifierPlugins[%v]", idx), reason: "embedded message failed validation", cause: err, }) } } } else if v, ok := interface{}(item).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return RouteConfigurationValidationError{ field: fmt.Sprintf("ClusterSpecifierPlugins[%v]", idx), reason: "embedded message failed validation", cause: err, } } } } for idx, item := range m.GetRequestMirrorPolicies() { _, _ = idx, item if all { switch v := interface{}(item).(type) { case interface{ ValidateAll() error }: if err := v.ValidateAll(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: fmt.Sprintf("RequestMirrorPolicies[%v]", idx), reason: "embedded message failed validation", cause: err, }) } case interface{ Validate() error }: if err := v.Validate(); err != nil { errors = append(errors, RouteConfigurationValidationError{ field: fmt.Sprintf("RequestMirrorPolicies[%v]", idx), reason: "embedded message failed validation", cause: err, }) } } } else if v, ok := interface{}(item).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return RouteConfigurationValidationError{ field: fmt.Sprintf("RequestMirrorPolicies[%v]", idx), reason: "embedded message failed validation", cause: err, } } } } if len(errors) > 0 { return RouteConfigurationMultiError(errors) } return nil } // RouteConfigurationMultiError is an error wrapping multiple validation errors // returned by RouteConfiguration.ValidateAll() if the designated constraints // aren't met. type RouteConfigurationMultiError []error // Error returns a concatenation of all the error messages it wraps. func (m RouteConfigurationMultiError) Error() string { var msgs []string for _, err := range m { msgs = append(msgs, err.Error()) } return strings.Join(msgs, "; ") } // AllErrors returns a list of validation violation errors. func (m RouteConfigurationMultiError) AllErrors() []error { return m } // RouteConfigurationValidationError is the validation error returned by // RouteConfiguration.Validate if the designated constraints aren't met. type RouteConfigurationValidationError struct { field string reason string cause error key bool } // Field function returns field value. func (e RouteConfigurationValidationError) Field() string { return e.field } // Reason function returns reason value. func (e RouteConfigurationValidationError) Reason() string { return e.reason } // Cause function returns cause value. func (e RouteConfigurationValidationError) Cause() error { return e.cause } // Key function returns key value. func (e RouteConfigurationValidationError) Key() bool { return e.key } // ErrorName returns error name. func (e RouteConfigurationValidationError) ErrorName() string { return "RouteConfigurationValidationError" } // Error satisfies the builtin error interface func (e RouteConfigurationValidationError) Error() string { cause := "" if e.cause != nil { cause = fmt.Sprintf(" | caused by: %v", e.cause) } key := "" if e.key { key = "key for " } return fmt.Sprintf( "invalid %sRouteConfiguration.%s: %s%s", key, e.field, e.reason, cause) } var _ error = RouteConfigurationValidationError{} var _ interface { Field() string Reason() string Key() bool Cause() error ErrorName() string } = RouteConfigurationValidationError{} var _RouteConfiguration_InternalOnlyHeaders_Pattern = regexp.MustCompile("^[^\x00\n\r]*$") var _RouteConfiguration_ResponseHeadersToRemove_Pattern = regexp.MustCompile("^[^\x00\n\r]*$") var _RouteConfiguration_RequestHeadersToRemove_Pattern = regexp.MustCompile("^[^\x00\n\r]*$") // Validate checks the field values on ClusterSpecifierPlugin with the rules // defined in the proto definition for this message. If any rules are // violated, the first error encountered is returned, or nil if there are no violations. func (m *ClusterSpecifierPlugin) Validate() error { return m.validate(false) } // ValidateAll checks the field values on ClusterSpecifierPlugin with the rules // defined in the proto definition for this message. If any rules are // violated, the result is a list of violation errors wrapped in // ClusterSpecifierPluginMultiError, or nil if none found. func (m *ClusterSpecifierPlugin) ValidateAll() error { return m.validate(true) } func (m *ClusterSpecifierPlugin) validate(all bool) error { if m == nil { return nil } var errors []error if all { switch v := interface{}(m.GetExtension()).(type) { case interface{ ValidateAll() error }: if err := v.ValidateAll(); err != nil { errors = append(errors, ClusterSpecifierPluginValidationError{ field: "Extension", reason: "embedded message failed validation", cause: err, }) } case interface{ Validate() error }: if err := v.Validate(); err != nil { errors = append(errors, ClusterSpecifierPluginValidationError{ field: "Extension", reason: "embedded message failed validation", cause: err, }) } } } else if v, ok := interface{}(m.GetExtension()).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return ClusterSpecifierPluginValidationError{ field: "Extension", reason: "embedded message failed validation", cause: err, } } } // no validation rules for IsOptional if len(errors) > 0 { return ClusterSpecifierPluginMultiError(errors) } return nil } // ClusterSpecifierPluginMultiError is an error wrapping multiple validation // errors returned by ClusterSpecifierPlugin.ValidateAll() if the designated // constraints aren't met. type ClusterSpecifierPluginMultiError []error // Error returns a concatenation of all the error messages it wraps. func (m ClusterSpecifierPluginMultiError) Error() string { var msgs []string for _, err := range m { msgs = append(msgs, err.Error()) } return strings.Join(msgs, "; ") } // AllErrors returns a list of validation violation errors. func (m ClusterSpecifierPluginMultiError) AllErrors() []error { return m } // ClusterSpecifierPluginValidationError is the validation error returned by // ClusterSpecifierPlugin.Validate if the designated constraints aren't met. type ClusterSpecifierPluginValidationError struct { field string reason string cause error key bool } // Field function returns field value. func (e ClusterSpecifierPluginValidationError) Field() string { return e.field } // Reason function returns reason value. func (e ClusterSpecifierPluginValidationError) Reason() string { return e.reason } // Cause function returns cause value. func (e ClusterSpecifierPluginValidationError) Cause() error { return e.cause } // Key function returns key value. func (e ClusterSpecifierPluginValidationError) Key() bool { return e.key } // ErrorName returns error name. func (e ClusterSpecifierPluginValidationError) ErrorName() string { return "ClusterSpecifierPluginValidationError" } // Error satisfies the builtin error interface func (e ClusterSpecifierPluginValidationError) Error() string { cause := "" if e.cause != nil { cause = fmt.Sprintf(" | caused by: %v", e.cause) } key := "" if e.key { key = "key for " } return fmt.Sprintf( "invalid %sClusterSpecifierPlugin.%s: %s%s", key, e.field, e.reason, cause) } var _ error = ClusterSpecifierPluginValidationError{} var _ interface { Field() string Reason() string Key() bool Cause() error ErrorName() string } = ClusterSpecifierPluginValidationError{} // Validate checks the field values on Vhds with the rules defined in the proto // definition for this message. If any rules are violated, the first error // encountered is returned, or nil if there are no violations. func (m *Vhds) Validate() error { return m.validate(false) } // ValidateAll checks the field values on Vhds with the rules defined in the // proto definition for this message. If any rules are violated, the result is // a list of violation errors wrapped in VhdsMultiError, or nil if none found. func (m *Vhds) ValidateAll() error { return m.validate(true) } func (m *Vhds) validate(all bool) error { if m == nil { return nil } var errors []error if m.GetConfigSource() == nil { err := VhdsValidationError{ field: "ConfigSource", reason: "value is required", } if !all { return err } errors = append(errors, err) } if all { switch v := interface{}(m.GetConfigSource()).(type) { case interface{ ValidateAll() error }: if err := v.ValidateAll(); err != nil { errors = append(errors, VhdsValidationError{ field: "ConfigSource", reason: "embedded message failed validation", cause: err, }) } case interface{ Validate() error }: if err := v.Validate(); err != nil { errors = append(errors, VhdsValidationError{ field: "ConfigSource", reason: "embedded message failed validation", cause: err, }) } } } else if v, ok := interface{}(m.GetConfigSource()).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return VhdsValidationError{ field: "ConfigSource", reason: "embedded message failed validation", cause: err, } } } if len(errors) > 0 { return VhdsMultiError(errors) } return nil } // VhdsMultiError is an error wrapping multiple validation errors returned by // Vhds.ValidateAll() if the designated constraints aren't met. type VhdsMultiError []error // Error returns a concatenation of all the error messages it wraps. func (m VhdsMultiError) Error() string { var msgs []string for _, err := range m { msgs = append(msgs, err.Error()) } return strings.Join(msgs, "; ") } // AllErrors returns a list of validation violation errors. func (m VhdsMultiError) AllErrors() []error { return m } // VhdsValidationError is the validation error returned by Vhds.Validate if the // designated constraints aren't met. type VhdsValidationError struct { field string reason string cause error key bool } // Field function returns field value. func (e VhdsValidationError) Field() string { return e.field } // Reason function returns reason value. func (e VhdsValidationError) Reason() string { return e.reason } // Cause function returns cause value. func (e VhdsValidationError) Cause() error { return e.cause } // Key function returns key value. func (e VhdsValidationError) Key() bool { return e.key } // ErrorName returns error name. func (e VhdsValidationError) ErrorName() string { return "VhdsValidationError" } // Error satisfies the builtin error interface func (e VhdsValidationError) Error() string { cause := "" if e.cause != nil { cause = fmt.Sprintf(" | caused by: %v", e.cause) } key := "" if e.key { key = "key for " } return fmt.Sprintf( "invalid %sVhds.%s: %s%s", key, e.field, e.reason, cause) } var _ error = VhdsValidationError{} var _ interface { Field() string Reason() string Key() bool Cause() error ErrorName() string } = VhdsValidationError{}
{'content_hash': '43f16e59b9b173216ad60ab57871a7c0', 'timestamp': '', 'source': 'github', 'line_count': 743, 'max_line_length': 108, 'avg_line_length': 27.594885598923284, 'alnum_prop': 0.675510900843779, 'repo_name': 'knative-sandbox/eventing-ceph', 'id': '759d17e9a8884d0f320c10fbd7f7951ccb4edc7f', 'size': '20604', 'binary': False, 'copies': '9', 'ref': 'refs/heads/main', 'path': 'vendor/github.com/envoyproxy/go-control-plane/envoy/config/route/v3/route.pb.validate.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '58281'}, {'name': 'Shell', 'bytes': '8418'}]}
package cel import ( "context" "fmt" "sync" "testing" "time" "github.com/stretchr/testify/require" "k8s.io/api/admissionregistration/v1alpha1" k8serrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/admission/initializer" "k8s.io/apiserver/pkg/admission/plugin/cel/internal/generic" "k8s.io/apiserver/pkg/features" dynamicfake "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" clienttesting "k8s.io/client-go/testing" "k8s.io/client-go/tools/cache" "k8s.io/component-base/featuregate" "k8s.io/klog/v2" ) var ( scheme *runtime.Scheme = func() *runtime.Scheme { res := runtime.NewScheme() res.AddKnownTypeWithName(paramsGVK, &unstructured.Unstructured{}) res.AddKnownTypeWithName(schema.GroupVersionKind{ Group: paramsGVK.Group, Version: paramsGVK.Version, Kind: paramsGVK.Kind + "List", }, &unstructured.UnstructuredList{}) if err := v1alpha1.AddToScheme(res); err != nil { panic(err) } return res }() paramsGVK schema.GroupVersionKind = schema.GroupVersionKind{ Group: "example.com", Version: "v1", Kind: "ParamsConfig", } fakeRestMapper *meta.DefaultRESTMapper = func() *meta.DefaultRESTMapper { res := meta.NewDefaultRESTMapper([]schema.GroupVersion{ { Group: "", Version: "v1", }, }) res.Add(paramsGVK, meta.RESTScopeNamespace) res.Add(definitionGVK, meta.RESTScopeRoot) res.Add(bindingGVK, meta.RESTScopeRoot) return res }() definitionGVK schema.GroupVersionKind = must3(scheme.ObjectKinds(&v1alpha1.ValidatingAdmissionPolicy{}))[0] bindingGVK schema.GroupVersionKind = must3(scheme.ObjectKinds(&v1alpha1.ValidatingAdmissionPolicyBinding{}))[0] definitionsGVR schema.GroupVersionResource = must(fakeRestMapper.RESTMapping(definitionGVK.GroupKind(), definitionGVK.Version)).Resource bindingsGVR schema.GroupVersionResource = must(fakeRestMapper.RESTMapping(bindingGVK.GroupKind(), bindingGVK.Version)).Resource // Common objects denyPolicy *v1alpha1.ValidatingAdmissionPolicy = &v1alpha1.ValidatingAdmissionPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: "denypolicy.example.com", ResourceVersion: "1", }, Spec: v1alpha1.ValidatingAdmissionPolicySpec{ ParamKind: &v1alpha1.ParamKind{ APIVersion: paramsGVK.GroupVersion().String(), Kind: paramsGVK.Kind, }, FailurePolicy: ptrTo(v1alpha1.Fail), }, } fakeParams *unstructured.Unstructured = &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": paramsGVK.GroupVersion().String(), "kind": paramsGVK.Kind, "metadata": map[string]interface{}{ "name": "replicas-test.example.com", "resourceVersion": "1", }, "maxReplicas": int64(3), }, } denyBinding *v1alpha1.ValidatingAdmissionPolicyBinding = &v1alpha1.ValidatingAdmissionPolicyBinding{ ObjectMeta: metav1.ObjectMeta{ Name: "denybinding.example.com", ResourceVersion: "1", }, Spec: v1alpha1.ValidatingAdmissionPolicyBindingSpec{ PolicyName: denyPolicy.Name, ParamRef: &v1alpha1.ParamRef{ Name: fakeParams.GetName(), Namespace: fakeParams.GetNamespace(), }, }, } denyBindingWithNoParamRef *v1alpha1.ValidatingAdmissionPolicyBinding = &v1alpha1.ValidatingAdmissionPolicyBinding{ ObjectMeta: metav1.ObjectMeta{ Name: "denybinding.example.com", ResourceVersion: "1", }, Spec: v1alpha1.ValidatingAdmissionPolicyBindingSpec{ PolicyName: denyPolicy.Name, }, } ) // Interface which has fake compile and match functionality for use in tests // So that we can test the controller without pulling in any CEL functionality type fakeCompiler struct { DefaultMatch bool CompileFuncs map[string]func(*v1alpha1.ValidatingAdmissionPolicy) Validator DefinitionMatchFuncs map[string]func(*v1alpha1.ValidatingAdmissionPolicy, admission.Attributes) bool BindingMatchFuncs map[string]func(*v1alpha1.ValidatingAdmissionPolicyBinding, admission.Attributes) bool } var _ ValidatorCompiler = &fakeCompiler{} func (f *fakeCompiler) HasSynced() bool { return true } func (f *fakeCompiler) ValidateInitialization() error { return nil } // Matches says whether this policy definition matches the provided admission // resource request func (f *fakeCompiler) DefinitionMatches(a admission.Attributes, o admission.ObjectInterfaces, definition *v1alpha1.ValidatingAdmissionPolicy) (bool, schema.GroupVersionKind, error) { namespace, name := definition.Namespace, definition.Name key := namespace + "/" + name if fun, ok := f.DefinitionMatchFuncs[key]; ok { return fun(definition, a), schema.GroupVersionKind{}, nil } // Default is match everything return f.DefaultMatch, schema.GroupVersionKind{}, nil } // Matches says whether this policy definition matches the provided admission // resource request func (f *fakeCompiler) BindingMatches(a admission.Attributes, o admission.ObjectInterfaces, binding *v1alpha1.ValidatingAdmissionPolicyBinding) (bool, error) { namespace, name := binding.Namespace, binding.Name key := namespace + "/" + name if fun, ok := f.BindingMatchFuncs[key]; ok { return fun(binding, a), nil } // Default is match everything return f.DefaultMatch, nil } func (f *fakeCompiler) Compile( definition *v1alpha1.ValidatingAdmissionPolicy, ) Validator { namespace, name := definition.Namespace, definition.Name key := namespace + "/" + name if fun, ok := f.CompileFuncs[key]; ok { return fun(definition) } return nil } func (f *fakeCompiler) RegisterDefinition(definition *v1alpha1.ValidatingAdmissionPolicy, compileFunc func(*v1alpha1.ValidatingAdmissionPolicy) Validator, matchFunc func(*v1alpha1.ValidatingAdmissionPolicy, admission.Attributes) bool) { namespace, name := definition.Namespace, definition.Name key := namespace + "/" + name if compileFunc != nil { if f.CompileFuncs == nil { f.CompileFuncs = make(map[string]func(*v1alpha1.ValidatingAdmissionPolicy) Validator) } f.CompileFuncs[key] = compileFunc } if matchFunc != nil { if f.DefinitionMatchFuncs == nil { f.DefinitionMatchFuncs = make(map[string]func(*v1alpha1.ValidatingAdmissionPolicy, admission.Attributes) bool) } f.DefinitionMatchFuncs[key] = matchFunc } } func (f *fakeCompiler) RegisterBinding(binding *v1alpha1.ValidatingAdmissionPolicyBinding, matchFunc func(*v1alpha1.ValidatingAdmissionPolicyBinding, admission.Attributes) bool) { namespace, name := binding.Namespace, binding.Name key := namespace + "/" + name if matchFunc != nil { if f.BindingMatchFuncs == nil { f.BindingMatchFuncs = make(map[string]func(*v1alpha1.ValidatingAdmissionPolicyBinding, admission.Attributes) bool) } f.BindingMatchFuncs[key] = matchFunc } } func setupFakeTest(t *testing.T, comp *fakeCompiler) (plugin admission.ValidationInterface, paramTracker, policyTracker clienttesting.ObjectTracker, controller *celAdmissionController) { return setupTestCommon(t, comp) } // Starts CEL admission controller and sets up a plugin configured with it as well // as object trackers for manipulating the objects available to the system // // ParamTracker only knows the gvk `paramGVK`. If in the future we need to // support multiple types of params this function needs to be augmented // // PolicyTracker expects FakePolicyDefinition and FakePolicyBinding types func setupTestCommon(t *testing.T, compiler ValidatorCompiler) (plugin admission.ValidationInterface, paramTracker, policyTracker clienttesting.ObjectTracker, controller *celAdmissionController) { testContext, testContextCancel := context.WithCancel(context.Background()) t.Cleanup(testContextCancel) dynamicClient := dynamicfake.NewSimpleDynamicClient(scheme) fakeClient := fake.NewSimpleClientset() fakeInformerFactory := informers.NewSharedInformerFactory(fakeClient, time.Second) featureGate := featuregate.NewFeatureGate() err := featureGate.Add(map[featuregate.Feature]featuregate.FeatureSpec{ features.CELValidatingAdmission: { Default: true, PreRelease: featuregate.Alpha}}) if err != nil { // FIXME: handle error. panic("Unexpected error") } err = featureGate.SetFromMap(map[string]bool{string(features.CELValidatingAdmission): true}) if err != nil { // FIXME: handle error. panic("Unexpected error.") } handler := &celAdmissionPlugin{enabled: true} genericInitializer := initializer.New(fakeClient, dynamicClient, fakeInformerFactory, nil, featureGate, testContext.Done()) genericInitializer.Initialize(handler) handler.SetRESTMapper(fakeRestMapper) err = admission.ValidateInitialization(handler) require.NoError(t, err) require.True(t, handler.enabled) // Override compiler used by controller for tests controller = handler.evaluator.(*celAdmissionController) controller.validatorCompiler = compiler // Make sure to start the fake informers fakeInformerFactory.Start(testContext.Done()) t.Cleanup(func() { testContextCancel() // wait for informer factory to shutdown fakeInformerFactory.Shutdown() }) // Wait for admission controller to begin its object watches // This is because there is a very rare (0.05% on my machine) race doing the // initial List+Watch if an object is added after the list, but before the // watch it could be missed. // // This is only due to the fact that NewSimpleClientset above ignores // LastSyncResourceVersion on watch calls, so do it does not provide "catch up" // which may have been added since the call to list. if !cache.WaitForNamedCacheSync("initial sync", testContext.Done(), handler.evaluator.HasSynced) { t.Fatal("failed to do perform initial cache sync") } // WaitForCacheSync only tells us the list was performed. // Keep changing an object until it is observable, then remove it i := 0 dummyPolicy := &v1alpha1.ValidatingAdmissionPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: "dummypolicy.example.com", Annotations: map[string]string{ "myValue": fmt.Sprint(i), }, }, } dummyBinding := &v1alpha1.ValidatingAdmissionPolicyBinding{ ObjectMeta: metav1.ObjectMeta{ Name: "dummybinding.example.com", Annotations: map[string]string{ "myValue": fmt.Sprint(i), }, }, } require.NoError(t, fakeClient.Tracker().Create(definitionsGVR, dummyPolicy, dummyPolicy.Namespace)) require.NoError(t, fakeClient.Tracker().Create(bindingsGVR, dummyBinding, dummyBinding.Namespace)) wait.PollWithContext(testContext, 100*time.Millisecond, 300*time.Millisecond, func(ctx context.Context) (done bool, err error) { defer func() { i += 1 }() dummyPolicy.Annotations = map[string]string{ "myValue": fmt.Sprint(i), } dummyBinding.Annotations = dummyPolicy.Annotations require.NoError(t, fakeClient.Tracker().Update(definitionsGVR, dummyPolicy, dummyPolicy.Namespace)) require.NoError(t, fakeClient.Tracker().Update(bindingsGVR, dummyBinding, dummyBinding.Namespace)) if obj, err := controller.getCurrentObject(dummyPolicy); obj == nil || err != nil { return false, nil } if obj, err := controller.getCurrentObject(dummyBinding); obj == nil || err != nil { return false, nil } return true, nil }) require.NoError(t, fakeClient.Tracker().Delete(definitionsGVR, dummyPolicy.Namespace, dummyPolicy.Name)) require.NoError(t, fakeClient.Tracker().Delete(bindingsGVR, dummyBinding.Namespace, dummyBinding.Name)) return handler, dynamicClient.Tracker(), fakeClient.Tracker(), controller } // Gets the last reconciled value in the controller of an object with the same // gvk and name as the given object // // If the object is not found both the error and object will be nil. func (c *celAdmissionController) getCurrentObject(obj runtime.Object) (runtime.Object, error) { accessor, err := meta.Accessor(obj) if err != nil { return nil, err } c.mutex.RLock() defer c.mutex.RUnlock() switch obj.(type) { case *unstructured.Unstructured: paramSourceGVK := obj.GetObjectKind().GroupVersionKind() paramKind := v1alpha1.ParamKind{ APIVersion: paramSourceGVK.GroupVersion().String(), Kind: paramSourceGVK.Kind, } var paramInformer generic.Informer[*unstructured.Unstructured] if paramInfo, ok := c.paramsCRDControllers[paramKind]; ok { paramInformer = paramInfo.controller.Informer() } else { // Treat unknown CRD the same as not found return nil, nil } // Param type. Just check informer for its GVK item, err := paramInformer.Get(accessor.GetName()) if err != nil { if k8serrors.IsNotFound(err) { return nil, nil } return nil, err } return item, nil case *v1alpha1.ValidatingAdmissionPolicyBinding: nn := getNamespaceName(accessor.GetNamespace(), accessor.GetName()) info, ok := c.bindingInfos[nn] if !ok { return nil, nil } return info.lastReconciledValue, nil case *v1alpha1.ValidatingAdmissionPolicy: nn := getNamespaceName(accessor.GetNamespace(), accessor.GetName()) info, ok := c.definitionInfo[nn] if !ok { return nil, nil } return info.lastReconciledValue, nil default: panic(fmt.Errorf("unhandled object type: %T", obj)) } } // Waits for the given objects to have been the latest reconciled values of // their gvk/name in the controller func waitForReconcile(ctx context.Context, controller *celAdmissionController, objects ...runtime.Object) error { return wait.PollWithContext(ctx, 100*time.Millisecond, 1*time.Second, func(ctx context.Context) (done bool, err error) { for _, obj := range objects { objMeta, err := meta.Accessor(obj) if err != nil { return false, fmt.Errorf("error getting meta accessor for original %T object (%v): %w", obj, obj, err) } currentValue, err := controller.getCurrentObject(obj) if err != nil { return false, fmt.Errorf("error getting current object: %w", err) } else if currentValue == nil { // Object not found, but not an error. Keep waiting. klog.Infof("%v not found. keep waiting", objMeta.GetName()) return false, nil } valueMeta, err := meta.Accessor(currentValue) if err != nil { return false, fmt.Errorf("error getting meta accessor for current %T object (%v): %w", currentValue, currentValue, err) } if len(objMeta.GetResourceVersion()) == 0 { return false, fmt.Errorf("%s named %s has no resource version. please ensure your test objects have an RV", obj.GetObjectKind().GroupVersionKind().String(), objMeta.GetName()) } else if len(valueMeta.GetResourceVersion()) == 0 { return false, fmt.Errorf("%s named %s has no resource version. please ensure your test objects have an RV", currentValue.GetObjectKind().GroupVersionKind().String(), valueMeta.GetName()) } else if objMeta.GetResourceVersion() != valueMeta.GetResourceVersion() { klog.Infof("%v has RV %v. want RV %v", objMeta.GetName(), objMeta.GetResourceVersion(), objMeta.GetResourceVersion()) return false, nil } } return true, nil }) } // Waits for the admissoin controller to have no knowledge of the objects // with the given GVKs and namespace/names func waitForReconcileDeletion(ctx context.Context, controller *celAdmissionController, objects ...runtime.Object) error { return wait.PollWithContext(ctx, 200*time.Millisecond, 3*time.Hour, func(ctx context.Context) (done bool, err error) { for _, obj := range objects { currentValue, err := controller.getCurrentObject(obj) if err != nil { return false, err } if currentValue != nil { return false, nil } } return true, nil }) } func attributeRecord( old, new runtime.Object, operation admission.Operation, ) admission.Attributes { if old == nil && new == nil { panic("both `old` and `new` may not be nil") } accessor, err := meta.Accessor(new) if err != nil { panic(err) } // one of old/new may be nil, but not both example := new if example == nil { example = old } gvk := example.GetObjectKind().GroupVersionKind() if gvk.Empty() { // If gvk is not populated, try to fetch it from the scheme gvk = must3(scheme.ObjectKinds(example))[0] } mapping, err := fakeRestMapper.RESTMapping(gvk.GroupKind(), gvk.Version) if err != nil { panic(err) } return admission.NewAttributesRecord( new, old, gvk, accessor.GetNamespace(), accessor.GetName(), mapping.Resource, "", operation, nil, false, nil, ) } func ptrTo[T any](obj T) *T { return &obj } func must[T any](val T, err error) T { if err != nil { panic(err) } return val } func must3[T any, I any](val T, _ I, err error) T { if err != nil { panic(err) } return val } //////////////////////////////////////////////////////////////////////////////// // Functionality Tests //////////////////////////////////////////////////////////////////////////////// func TestBasicPolicyDefinitionFailure(t *testing.T) { testContext, testContextCancel := context.WithCancel(context.Background()) defer testContextCancel() datalock := sync.Mutex{} numCompiles := 0 compiler := &fakeCompiler{ // Match everything by default DefaultMatch: true, } compiler.RegisterDefinition(denyPolicy, func(policy *v1alpha1.ValidatingAdmissionPolicy) Validator { datalock.Lock() numCompiles += 1 datalock.Unlock() return testValidator{} }, nil) handler, paramTracker, tracker, controller := setupFakeTest(t, compiler) require.NoError(t, paramTracker.Add(fakeParams)) require.NoError(t, tracker.Create(definitionsGVR, denyPolicy, denyPolicy.Namespace)) require.NoError(t, tracker.Create(bindingsGVR, denyBinding, denyBinding.Namespace)) // Wait for controller to reconcile given objects require.NoError(t, waitForReconcile( testContext, controller, fakeParams, denyBinding, denyPolicy)) err := handler.Validate( testContext, // Object is irrelevant/unchecked for this test. Just test that // the evaluator is executed, and returns a denial attributeRecord(nil, fakeParams, admission.Create), &admission.RuntimeObjectInterfaces{}, ) require.ErrorContains(t, err, `Denied`) } type testValidator struct { } func (v testValidator) Validate(a admission.Attributes, o admission.ObjectInterfaces, params runtime.Object, matchKind schema.GroupVersionKind) ([]policyDecision, error) { // Policy always denies return []policyDecision{ { kind: deny, message: "Denied", }, }, nil } // Shows that if a definition does not match the input, it will not be used. // But with a different input it will be used. func TestDefinitionDoesntMatch(t *testing.T) { compiler := &fakeCompiler{ // Match everything by default DefaultMatch: true, } handler, paramTracker, tracker, controller := setupFakeTest(t, compiler) testContext, testContextCancel := context.WithCancel(context.Background()) defer testContextCancel() datalock := sync.Mutex{} passedParams := []*unstructured.Unstructured{} numCompiles := 0 compiler.RegisterDefinition(denyPolicy, func(vap *v1alpha1.ValidatingAdmissionPolicy) Validator { datalock.Lock() numCompiles += 1 datalock.Unlock() return testValidator{} }, func(vap *v1alpha1.ValidatingAdmissionPolicy, a admission.Attributes) bool { // Match names with even-numbered length obj := a.GetObject() accessor, err := meta.Accessor(obj) if err != nil { t.Fatal(err) return false } return len(accessor.GetName())%2 == 0 }) require.NoError(t, paramTracker.Add(fakeParams)) require.NoError(t, tracker.Create(definitionsGVR, denyPolicy, denyPolicy.Namespace)) require.NoError(t, tracker.Create(bindingsGVR, denyBinding, denyBinding.Namespace)) // Wait for controller to reconcile given objects require.NoError(t, waitForReconcile( testContext, controller, fakeParams, denyBinding, denyPolicy)) // Validate a non-matching input. // Should pass validation with no error. nonMatchingParams := &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": paramsGVK.GroupVersion().String(), "kind": paramsGVK.Kind, "metadata": map[string]interface{}{ "name": "oddlength", "resourceVersion": "1", }, }, } require.NoError(t, handler.Validate(testContext, attributeRecord( nil, nonMatchingParams, admission.Create), &admission.RuntimeObjectInterfaces{})) require.Zero(t, numCompiles) require.Empty(t, passedParams) // Validate a matching input. // Should match and be denied. matchingParams := &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": paramsGVK.GroupVersion().String(), "kind": paramsGVK.Kind, "metadata": map[string]interface{}{ "name": "evenlength", "resourceVersion": "1", }, }, } require.ErrorContains(t, handler.Validate(testContext, attributeRecord( nil, matchingParams, admission.Create), &admission.RuntimeObjectInterfaces{}), `Denied`) require.Equal(t, numCompiles, 1) } func TestReconfigureBinding(t *testing.T) { testContext, testContextCancel := context.WithCancel(context.Background()) defer testContextCancel() compiler := &fakeCompiler{ // Match everything by default DefaultMatch: true, } handler, paramTracker, tracker, controller := setupFakeTest(t, compiler) datalock := sync.Mutex{} numCompiles := 0 fakeParams2 := &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": paramsGVK.GroupVersion().String(), "kind": paramsGVK.Kind, "metadata": map[string]interface{}{ "name": "replicas-test2.example.com", "resourceVersion": "2", }, "maxReplicas": int64(35), }, } compiler.RegisterDefinition(denyPolicy, func(vap *v1alpha1.ValidatingAdmissionPolicy) Validator { datalock.Lock() numCompiles += 1 datalock.Unlock() return testValidator{} }, nil) denyBinding2 := &v1alpha1.ValidatingAdmissionPolicyBinding{ ObjectMeta: metav1.ObjectMeta{ Name: "denybinding.example.com", ResourceVersion: "2", }, Spec: v1alpha1.ValidatingAdmissionPolicyBindingSpec{ PolicyName: denyPolicy.Name, ParamRef: &v1alpha1.ParamRef{ Name: fakeParams2.GetName(), Namespace: fakeParams2.GetNamespace(), }, }, } require.NoError(t, paramTracker.Add(fakeParams)) require.NoError(t, tracker.Create(definitionsGVR, denyPolicy, denyPolicy.Namespace)) require.NoError(t, tracker.Create(bindingsGVR, denyBinding, denyBinding.Namespace)) // Wait for controller to reconcile given objects require.NoError(t, waitForReconcile( testContext, controller, fakeParams, denyBinding, denyPolicy)) err := handler.Validate( testContext, attributeRecord(nil, fakeParams, admission.Create), &admission.RuntimeObjectInterfaces{}, ) // Expect validation to fail for first time due to binding unconditionally // failing require.ErrorContains(t, err, `Denied`, "expect policy validation error") // Expect `Compile` only called once require.Equal(t, 1, numCompiles, "expect `Compile` to be called only once") // Show Evaluator was called //require.Len(t, passedParams, 1, "expect evaluator is called due to proper configuration") // Update the tracker to point at different params require.NoError(t, tracker.Update(bindingsGVR, denyBinding2, "")) // Wait for update to propagate // Wait for controller to reconcile given objects require.NoError(t, waitForReconcile(testContext, controller, denyBinding2)) err = handler.Validate( testContext, attributeRecord(nil, fakeParams, admission.Create), &admission.RuntimeObjectInterfaces{}, ) require.ErrorContains(t, err, `failed to configure binding: replicas-test2.example.com not found`) require.Equal(t, 1, numCompiles, "expect compile is not called when there is configuration error") //require.Len(t, passedParams, 1, "expect evaluator was not called when there is configuration error") // Add the missing params require.NoError(t, paramTracker.Add(fakeParams2)) // Wait for update to propagate require.NoError(t, waitForReconcile(testContext, controller, fakeParams2)) // Expect validation to now fail again. err = handler.Validate( testContext, attributeRecord(nil, fakeParams, admission.Create), &admission.RuntimeObjectInterfaces{}, ) // Expect validation to fail the third time due to validation failure require.ErrorContains(t, err, `Denied`, "expected a true policy failure, not a configuration error") //require.Equal(t, []*unstructured.Unstructured{fakeParams, fakeParams2}, passedParams, "expected call to `Validate` to cause call to evaluator") require.Equal(t, 2, numCompiles, "expect changing binding causes a recompile") } // Shows that a policy which is in effect will stop being in effect when removed func TestRemoveDefinition(t *testing.T) { testContext, testContextCancel := context.WithCancel(context.Background()) defer testContextCancel() compiler := &fakeCompiler{ // Match everything by default DefaultMatch: true, } handler, paramTracker, tracker, controller := setupFakeTest(t, compiler) datalock := sync.Mutex{} numCompiles := 0 compiler.RegisterDefinition(denyPolicy, func(vap *v1alpha1.ValidatingAdmissionPolicy) Validator { datalock.Lock() numCompiles += 1 datalock.Unlock() return testValidator{} }, nil) require.NoError(t, paramTracker.Add(fakeParams)) require.NoError(t, tracker.Create(definitionsGVR, denyPolicy, denyPolicy.Namespace)) require.NoError(t, tracker.Create(bindingsGVR, denyBinding, denyBinding.Namespace)) // Wait for controller to reconcile given objects require.NoError(t, waitForReconcile( testContext, controller, fakeParams, denyBinding, denyPolicy)) record := attributeRecord(nil, fakeParams, admission.Create) require.ErrorContains(t, handler.Validate( testContext, record, &admission.RuntimeObjectInterfaces{}, ), `Denied`) require.NoError(t, tracker.Delete(definitionsGVR, denyPolicy.Namespace, denyPolicy.Name)) require.NoError(t, waitForReconcileDeletion(testContext, controller, denyPolicy)) require.NoError(t, handler.Validate( testContext, // Object is irrelevant/unchecked for this test. Just test that // the evaluator is executed, and returns a denial record, &admission.RuntimeObjectInterfaces{}, )) } // Shows that a binding which is in effect will stop being in effect when removed func TestRemoveBinding(t *testing.T) { testContext, testContextCancel := context.WithCancel(context.Background()) defer testContextCancel() compiler := &fakeCompiler{ // Match everything by default DefaultMatch: true, } handler, paramTracker, tracker, controller := setupFakeTest(t, compiler) datalock := sync.Mutex{} numCompiles := 0 compiler.RegisterDefinition(denyPolicy, func(vap *v1alpha1.ValidatingAdmissionPolicy) Validator { datalock.Lock() numCompiles += 1 datalock.Unlock() return testValidator{} }, nil) require.NoError(t, paramTracker.Add(fakeParams)) require.NoError(t, tracker.Create(definitionsGVR, denyPolicy, denyPolicy.Namespace)) require.NoError(t, tracker.Create(bindingsGVR, denyBinding, denyBinding.Namespace)) // Wait for controller to reconcile given objects require.NoError(t, waitForReconcile( testContext, controller, fakeParams, denyBinding, denyPolicy)) record := attributeRecord(nil, fakeParams, admission.Create) require.ErrorContains(t, handler.Validate( testContext, record, &admission.RuntimeObjectInterfaces{}, ), `Denied`) //require.Equal(t, []*unstructured.Unstructured{fakeParams}, passedParams) require.NoError(t, tracker.Delete(bindingsGVR, denyBinding.Namespace, denyBinding.Name)) require.NoError(t, waitForReconcileDeletion(testContext, controller, denyBinding)) } // Shows that an error is surfaced if a paramSource specified in a binding does // not actually exist func TestInvalidParamSourceGVK(t *testing.T) { testContext, testContextCancel := context.WithCancel(context.Background()) defer testContextCancel() compiler := &fakeCompiler{ // Match everything by default DefaultMatch: true, } handler, _, tracker, controller := setupFakeTest(t, compiler) passedParams := make(chan *unstructured.Unstructured) badPolicy := *denyPolicy badPolicy.Spec.ParamKind = &v1alpha1.ParamKind{ APIVersion: paramsGVK.GroupVersion().String(), Kind: "BadParamKind", } require.NoError(t, tracker.Create(definitionsGVR, &badPolicy, badPolicy.Namespace)) require.NoError(t, tracker.Create(bindingsGVR, denyBinding, denyBinding.Namespace)) // Wait for controller to reconcile given objects require.NoError(t, waitForReconcile( testContext, controller, denyBinding, &badPolicy)) err := handler.Validate( testContext, attributeRecord(nil, fakeParams, admission.Create), &admission.RuntimeObjectInterfaces{}, ) // expect the specific error to be that the param was not found, not that CRD // is not existing require.ErrorContains(t, err, `failed to configure policy: failed to find resource referenced by paramKind: 'example.com/v1, Kind=BadParamKind'`) close(passedParams) require.Len(t, passedParams, 0) } // Shows that an error is surfaced if a param specified in a binding does not // actually exist func TestInvalidParamSourceInstanceName(t *testing.T) { testContext, testContextCancel := context.WithCancel(context.Background()) defer testContextCancel() compiler := &fakeCompiler{ // Match everything by default DefaultMatch: true, } handler, _, tracker, controller := setupFakeTest(t, compiler) datalock := sync.Mutex{} passedParams := []*unstructured.Unstructured{} numCompiles := 0 compiler.RegisterDefinition(denyPolicy, func(vap *v1alpha1.ValidatingAdmissionPolicy) Validator { datalock.Lock() numCompiles += 1 datalock.Unlock() return testValidator{} }, nil) require.NoError(t, tracker.Create(definitionsGVR, denyPolicy, denyPolicy.Namespace)) require.NoError(t, tracker.Create(bindingsGVR, denyBinding, denyBinding.Namespace)) // Wait for controller to reconcile given objects require.NoError(t, waitForReconcile( testContext, controller, denyBinding, denyPolicy)) err := handler.Validate( testContext, attributeRecord(nil, fakeParams, admission.Create), &admission.RuntimeObjectInterfaces{}, ) // expect the specific error to be that the param was not found, not that CRD // is not existing require.ErrorContains(t, err, `failed to configure binding: replicas-test.example.com not found`) require.Len(t, passedParams, 0) } // Shows that a definition with no param source works just fine, and has // nil params passed to its evaluator. // // Also shows that if binding has specified params in this instance then they // are silently ignored. func TestEmptyParamSource(t *testing.T) { testContext, testContextCancel := context.WithCancel(context.Background()) defer testContextCancel() compiler := &fakeCompiler{ // Match everything by default DefaultMatch: true, } handler, _, tracker, controller := setupFakeTest(t, compiler) datalock := sync.Mutex{} numCompiles := 0 // Push some fake noParamSourcePolicy := *denyPolicy noParamSourcePolicy.Spec.ParamKind = nil compiler.RegisterDefinition(&noParamSourcePolicy, func(vap *v1alpha1.ValidatingAdmissionPolicy) Validator { datalock.Lock() numCompiles += 1 datalock.Unlock() return testValidator{} }, nil) require.NoError(t, tracker.Create(definitionsGVR, &noParamSourcePolicy, noParamSourcePolicy.Namespace)) require.NoError(t, tracker.Create(bindingsGVR, denyBindingWithNoParamRef, denyBindingWithNoParamRef.Namespace)) // Wait for controller to reconcile given objects require.NoError(t, waitForReconcile( testContext, controller, denyBinding, denyPolicy)) err := handler.Validate( testContext, // Object is irrelevant/unchecked for this test. Just test that // the evaluator is executed, and returns a denial attributeRecord(nil, fakeParams, admission.Create), &admission.RuntimeObjectInterfaces{}, ) require.ErrorContains(t, err, `Denied`) require.Equal(t, 1, numCompiles) }
{'content_hash': 'a852d0e1eea544b5266e6da73c6b0091', 'timestamp': '', 'source': 'github', 'line_count': 1010, 'max_line_length': 236, 'avg_line_length': 31.874257425742574, 'alnum_prop': 0.7373963283943714, 'repo_name': 'ping035627/kubernetes', 'id': '75c79cc97d460113892ea8406b2ef0db3bbc8d16', 'size': '32762', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/admission_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '833'}, {'name': 'C', 'bytes': '3902'}, {'name': 'Dockerfile', 'bytes': '47376'}, {'name': 'Go', 'bytes': '63145840'}, {'name': 'HTML', 'bytes': '106'}, {'name': 'Makefile', 'bytes': '64192'}, {'name': 'PowerShell', 'bytes': '144474'}, {'name': 'Python', 'bytes': '23655'}, {'name': 'Shell', 'bytes': '1813219'}, {'name': 'sed', 'bytes': '1262'}]}
""" Django settings for Reddit Clone project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ from __future__ import absolute_import, unicode_literals import environ ROOT_DIR = environ.Path(__file__) - 3 # (/a/b/myfile.py - 3 = /) APPS_DIR = ROOT_DIR.path('reddit') env = environ.Env() # APP CONFIGURATION # ------------------------------------------------------------------------------ DJANGO_APPS = ( # Default Django apps: 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Useful template tags: # 'django.contrib.humanize', # Admin 'django.contrib.admin', ) THIRD_PARTY_APPS = ( 'crispy_forms', # Form layouts 'allauth', # registration 'allauth.account', # registration 'allauth.socialaccount', # registration ) # Apps specific for this project go here. LOCAL_APPS = ( 'reddit.users', # custom users app # Your stuff: custom apps go here ) # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS # MIDDLEWARE CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE_CLASSES = ( # Make sure djangosecure.middleware.SecurityMiddleware is listed first 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) # MIGRATIONS CONFIGURATION # ------------------------------------------------------------------------------ MIGRATION_MODULES = { 'sites': 'reddit.contrib.sites.migrations' } # DEBUG # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = env.bool("DJANGO_DEBUG", False) # FIXTURE CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS FIXTURE_DIRS = ( str(APPS_DIR.path('fixtures')), ) # EMAIL CONFIGURATION # ------------------------------------------------------------------------------ EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend') # MANAGER CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins ADMINS = ( ("""Tristan""", '[email protected]'), ) # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers MANAGERS = ADMINS # DATABASE CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { # Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ 'default': env.db("DATABASE_URL", default="postgres:///reddit"), } DATABASES['default']['ATOMIC_REQUESTS'] = True # GENERAL CONFIGURATION # ------------------------------------------------------------------------------ # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'UTC' # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code LANGUAGE_CODE = 'en-us' # See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id SITE_ID = 1 # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n USE_I18N = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n USE_L10N = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz USE_TZ = True # TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#templates TEMPLATES = [ { # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND 'BACKEND': 'django.template.backends.django.DjangoTemplates', # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs 'DIRS': [ str(APPS_DIR.path('templates')), ], 'OPTIONS': { # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug 'debug': DEBUG, # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', # Your stuff: custom template context processors go here ], }, }, ] # See: http://django-crispy-forms.readthedocs.org/en/latest/install.html#template-packs CRISPY_TEMPLATE_PACK = 'bootstrap3' # STATIC FILE CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = str(ROOT_DIR('staticfiles')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( str(APPS_DIR.path('static')), ) # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) # MEDIA CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = str(APPS_DIR('media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' # URL Configuration # ------------------------------------------------------------------------------ ROOT_URLCONF = 'config.urls' # See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application WSGI_APPLICATION = 'config.wsgi.application' # AUTHENTICATION CONFIGURATION # ------------------------------------------------------------------------------ AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) # Some really nice defaults ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' # Custom user app defaults # Select the correct user model AUTH_USER_MODEL = 'users.User' LOGIN_REDIRECT_URL = 'users:redirect' LOGIN_URL = 'account_login' # SLUGLIFIER AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify' # Location of root django.contrib.admin URL, use {% url 'admin:index' %} ADMIN_URL = r'^admin/' # Your common stuff: Below this line define 3rd party library settings
{'content_hash': 'd9171fbc695a5b43e82191a48aa05d47', 'timestamp': '', 'source': 'github', 'line_count': 227, 'max_line_length': 98, 'avg_line_length': 35.797356828193834, 'alnum_prop': 0.6062023135614079, 'repo_name': 'txl518/redditclone', 'id': 'a5828aa9a36999fd206e0b8843ab6364f9485b20', 'size': '8150', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'config/settings/common.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '1768'}, {'name': 'HTML', 'bytes': '20186'}, {'name': 'JavaScript', 'bytes': '3142'}, {'name': 'Nginx', 'bytes': '1095'}, {'name': 'Python', 'bytes': '38761'}, {'name': 'Shell', 'bytes': '4535'}]}
using audio_modem::WhispernetClient; using content::BrowserThread; namespace extensions { namespace SendFound = api::copresence_private::SendFound; namespace SendSamples = api::copresence_private::SendSamples; namespace SendInitialized = api::copresence_private::SendInitialized; namespace { base::LazyInstance<BrowserContextKeyedAPIFactory<CopresencePrivateService>> g_factory = LAZY_INSTANCE_INITIALIZER; void RunInitCallback(WhispernetClient* client, bool status) { DCHECK(client); audio_modem::SuccessCallback init_callback = client->GetInitializedCallback(); if (!init_callback.is_null()) init_callback.Run(status); } } // namespace CopresencePrivateService::CopresencePrivateService( content::BrowserContext* context) : initialized_(false) {} CopresencePrivateService::~CopresencePrivateService() {} const std::string CopresencePrivateService::RegisterWhispernetClient( WhispernetClient* client) { if (initialized_) RunInitCallback(client, true); std::string id = base::GenerateGUID(); whispernet_clients_[id] = client; return id; } void CopresencePrivateService::OnWhispernetInitialized(bool success) { if (success) initialized_ = true; DVLOG(2) << "Notifying " << whispernet_clients_.size() << " clients that initialization is complete."; for (auto client_entry : whispernet_clients_) RunInitCallback(client_entry.second, success); } WhispernetClient* CopresencePrivateService::GetWhispernetClient( const std::string& id) { WhispernetClient* client = whispernet_clients_[id]; DCHECK(client); return client; } // static BrowserContextKeyedAPIFactory<CopresencePrivateService>* CopresencePrivateService::GetFactoryInstance() { return g_factory.Pointer(); } template <> void BrowserContextKeyedAPIFactory<CopresencePrivateService> ::DeclareFactoryDependencies() { DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); } // Copresence Private functions. // CopresenceSendFoundFunction implementation: ExtensionFunction::ResponseAction CopresencePrivateSendFoundFunction::Run() { std::unique_ptr<SendFound::Params> params(SendFound::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); WhispernetClient* whispernet_client = CopresencePrivateService::GetFactoryInstance()->Get(browser_context()) ->GetWhispernetClient(params->client_id); if (whispernet_client->GetTokensCallback().is_null()) return RespondNow(NoArguments()); std::vector<audio_modem::AudioToken> tokens; for (size_t i = 0; i < params->tokens.size(); ++i) { tokens.push_back(audio_modem::AudioToken(params->tokens[i].token, params->tokens[i].audible)); } whispernet_client->GetTokensCallback().Run(tokens); return RespondNow(NoArguments()); } // CopresenceSendEncodedFunction implementation: ExtensionFunction::ResponseAction CopresencePrivateSendSamplesFunction::Run() { std::unique_ptr<SendSamples::Params> params( SendSamples::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); WhispernetClient* whispernet_client = CopresencePrivateService::GetFactoryInstance()->Get(browser_context()) ->GetWhispernetClient(params->client_id); if (whispernet_client->GetSamplesCallback().is_null()) return RespondNow(NoArguments()); scoped_refptr<media::AudioBusRefCounted> samples = media::AudioBusRefCounted::Create(1, // Mono params->samples.size() / sizeof(float)); memcpy(samples->channel(0), params->samples.data(), params->samples.size()); whispernet_client->GetSamplesCallback().Run( params->token.audible ? audio_modem::AUDIBLE : audio_modem::INAUDIBLE, params->token.token, samples); return RespondNow(NoArguments()); } // CopresenceSendInitializedFunction implementation: ExtensionFunction::ResponseAction CopresencePrivateSendInitializedFunction::Run() { std::unique_ptr<SendInitialized::Params> params( SendInitialized::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); CopresencePrivateService::GetFactoryInstance()->Get(browser_context()) ->OnWhispernetInitialized(params->success); return RespondNow(NoArguments()); } } // namespace extensions
{'content_hash': 'a0c1a670e683f8af5e39d48311ce5cca', 'timestamp': '', 'source': 'github', 'line_count': 131, 'max_line_length': 80, 'avg_line_length': 32.908396946564885, 'alnum_prop': 0.7367200185571793, 'repo_name': 'heke123/chromium-crosswalk', 'id': '4bdaf0f8301ed82d7e7a5380ba44343f89a7bc56', 'size': '4902', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'chrome/browser/extensions/api/copresence_private/copresence_private_api.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
package com.tle.web.searching.section; import com.tle.web.search.actions.StandardShareSearchQuerySection; import com.tle.web.sections.BookmarkModifier; import com.tle.web.sections.SectionInfo; import com.tle.web.sections.events.RenderContext; import com.tle.web.sections.events.js.BookmarkAndModify; import com.tle.web.sections.generic.InfoBookmark; import java.util.Map; @SuppressWarnings("nls") public class IntegrationShareSearchQuerySection extends StandardShareSearchQuerySection { private static final String SEARCHURL; static { SEARCHURL = RootSearchSection.SEARCHURL.startsWith("/") ? RootSearchSection.SEARCHURL.substring(1) : RootSearchSection.SEARCHURL; } @Override public void setupUrl(InfoBookmark bookmark, RenderContext context) { url.setValue( context, new BookmarkAndModify( bookmark, new BookmarkModifier() { @Override public void addToBookmark(SectionInfo info, Map<String, String[]> bookmarkState) { bookmarkState.put( SectionInfo.KEY_PATH, new String[] {institutionService.institutionalise(SEARCHURL)}); } }) .getHref()); url.getState(context).setEditable(false); } }
{'content_hash': '59a5acc68ace5c1ebbcedb8f6c27dbc5', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 100, 'avg_line_length': 32.90243902439025, 'alnum_prop': 0.6619718309859155, 'repo_name': 'equella/Equella', 'id': '2e235d44f8f763983d297d361b26479eb25bd2d5', 'size': '2152', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'Source/Plugins/Core/com.equella.core/src/com/tle/web/searching/section/IntegrationShareSearchQuerySection.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '402'}, {'name': 'Batchfile', 'bytes': '38432'}, {'name': 'CSS', 'bytes': '648823'}, {'name': 'Dockerfile', 'bytes': '2055'}, {'name': 'FreeMarker', 'bytes': '370046'}, {'name': 'HTML', 'bytes': '865667'}, {'name': 'Java', 'bytes': '27081020'}, {'name': 'JavaScript', 'bytes': '1673995'}, {'name': 'PHP', 'bytes': '821'}, {'name': 'PLpgSQL', 'bytes': '1363'}, {'name': 'PureScript', 'bytes': '307610'}, {'name': 'Python', 'bytes': '79871'}, {'name': 'Scala', 'bytes': '765981'}, {'name': 'Shell', 'bytes': '64170'}, {'name': 'TypeScript', 'bytes': '146564'}, {'name': 'XSLT', 'bytes': '510113'}]}
var chai = require('../node_modules/chai/chai'); var expect = chai.expect; describe('Protractor Demo App', function() { it('should have a title', function() { expect(1).to.equal(1); }); });
{'content_hash': '386c0e6d027e297ceb818865a14566ef', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 48, 'avg_line_length': 24.875, 'alnum_prop': 0.6331658291457286, 'repo_name': 'jonathanbarton/ng6-karma-mocha-webpack-starter', 'id': '3fa3bc5f696c390663eb8cb2d8b16f0deb44bfa5', 'size': '210', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'e2e/spec.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '18'}, {'name': 'HTML', 'bytes': '1952'}, {'name': 'JavaScript', 'bytes': '8531'}]}
package pprof import ( "bufio" "bytes" "fmt" "html/template" "io" "log" "net/http" "os" "runtime" "runtime/pprof" "runtime/trace" "strconv" "strings" "time" ) func init() { http.Handle("/debug/pprof/", http.HandlerFunc(Index)) http.Handle("/debug/pprof/cmdline", http.HandlerFunc(Cmdline)) http.Handle("/debug/pprof/profile", http.HandlerFunc(Profile)) http.Handle("/debug/pprof/symbol", http.HandlerFunc(Symbol)) http.Handle("/debug/pprof/trace", http.HandlerFunc(Trace)) } // Cmdline responds with the running program's // command line, with arguments separated by NUL bytes. // The package initialization registers it as /debug/pprof/cmdline. func Cmdline(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprintf(w, strings.Join(os.Args, "\x00")) } func sleep(w http.ResponseWriter, d time.Duration) { var clientGone <-chan bool if cn, ok := w.(http.CloseNotifier); ok { clientGone = cn.CloseNotify() } select { case <-time.After(d): case <-clientGone: } } // Profile responds with the pprof-formatted cpu profile. // The package initialization registers it as /debug/pprof/profile. func Profile(w http.ResponseWriter, r *http.Request) { sec, _ := strconv.ParseInt(r.FormValue("seconds"), 10, 64) if sec == 0 { sec = 30 } // Set Content Type assuming StartCPUProfile will work, // because if it does it starts writing. w.Header().Set("Content-Type", "application/octet-stream") if err := pprof.StartCPUProfile(w); err != nil { // StartCPUProfile failed, so no writes yet. // Can change header back to text content // and send error code. w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Could not enable CPU profiling: %s\n", err) return } sleep(w, time.Duration(sec)*time.Second) pprof.StopCPUProfile() } // Trace responds with the execution trace in binary form. // Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified. // The package initialization registers it as /debug/pprof/trace. func Trace(w http.ResponseWriter, r *http.Request) { sec, err := strconv.ParseFloat(r.FormValue("seconds"), 64) if sec <= 0 || err != nil { sec = 1 } // Set Content Type assuming trace.Start will work, // because if it does it starts writing. w.Header().Set("Content-Type", "application/octet-stream") if err := trace.Start(w); err != nil { // trace.Start failed, so no writes yet. // Can change header back to text content and send error code. w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Could not enable tracing: %s\n", err) return } sleep(w, time.Duration(sec*float64(time.Second))) trace.Stop() } // Symbol looks up the program counters listed in the request, // responding with a table mapping program counters to function names. // The package initialization registers it as /debug/pprof/symbol. func Symbol(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") // We have to read the whole POST body before // writing any output. Buffer the output here. var buf bytes.Buffer // We don't know how many symbols we have, but we // do have symbol information. Pprof only cares whether // this number is 0 (no symbols available) or > 0. fmt.Fprintf(&buf, "num_symbols: 1\n") var b *bufio.Reader if r.Method == "POST" { b = bufio.NewReader(r.Body) } else { b = bufio.NewReader(strings.NewReader(r.URL.RawQuery)) } for { word, err := b.ReadSlice('+') if err == nil { word = word[0 : len(word)-1] // trim + } pc, _ := strconv.ParseUint(string(word), 0, 64) if pc != 0 { f := runtime.FuncForPC(uintptr(pc)) if f != nil { fmt.Fprintf(&buf, "%#x %s\n", pc, f.Name()) } } // Wait until here to check for err; the last // symbol will have an err because it doesn't end in +. if err != nil { if err != io.EOF { fmt.Fprintf(&buf, "reading request: %v\n", err) } break } } w.Write(buf.Bytes()) } // Handler returns an HTTP handler that serves the named profile. func Handler(name string) http.Handler { return handler(name) } type handler string func (name handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") debug, _ := strconv.Atoi(r.FormValue("debug")) p := pprof.Lookup(string(name)) if p == nil { w.WriteHeader(404) fmt.Fprintf(w, "Unknown profile: %s\n", name) return } gc, _ := strconv.Atoi(r.FormValue("gc")) if name == "heap" && gc > 0 { runtime.GC() } p.WriteTo(w, debug) return } // Index responds with the pprof-formatted profile named by the request. // For example, "/debug/pprof/heap" serves the "heap" profile. // Index responds to a request for "/debug/pprof/" with an HTML page // listing the available profiles. func Index(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/debug/pprof/") { name := strings.TrimPrefix(r.URL.Path, "/debug/pprof/") if name != "" { handler(name).ServeHTTP(w, r) return } } profiles := pprof.Profiles() if err := indexTmpl.Execute(w, profiles); err != nil { log.Print(err) } } var indexTmpl = template.Must(template.New("index").Parse(`<html> <head> <title>/debug/pprof/</title> </head> <body> /debug/pprof/<br> <br> profiles:<br> <table> {{range .}} <tr><td align=right>{{.Count}}<td><a href="{{.Name}}?debug=1">{{.Name}}</a> {{end}} </table> <br> <a href="goroutine?debug=2">full goroutine stack dump</a><br> </body> </html> `))
{'content_hash': 'da1bb890f6a61b73e8f5fbc49acf8b21', 'timestamp': '', 'source': 'github', 'line_count': 203, 'max_line_length': 99, 'avg_line_length': 27.896551724137932, 'alnum_prop': 0.6794984990287833, 'repo_name': 'ganboing/go-esx', 'id': 'cb4086b963b0e433cc3bc68c9442c2be0afc3cab', 'size': '7270', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/net/http/pprof/pprof.go', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '1953066'}, {'name': 'Awk', 'bytes': '450'}, {'name': 'Batchfile', 'bytes': '7284'}, {'name': 'C', 'bytes': '183583'}, {'name': 'C++', 'bytes': '1554'}, {'name': 'CSS', 'bytes': '8'}, {'name': 'FORTRAN', 'bytes': '394'}, {'name': 'Go', 'bytes': '29677279'}, {'name': 'HTML', 'bytes': '1806597'}, {'name': 'JavaScript', 'bytes': '2550'}, {'name': 'Logos', 'bytes': '1248'}, {'name': 'Makefile', 'bytes': '748'}, {'name': 'Perl', 'bytes': '34542'}, {'name': 'Protocol Buffer', 'bytes': '1586'}, {'name': 'Python', 'bytes': '12446'}, {'name': 'Shell', 'bytes': '65444'}, {'name': 'Yacc', 'bytes': '3230'}]}
<?php declare(strict_types=1); namespace PhpParser\Node\Expr; use PhpParser\Node\Expr; class ArrayDimFetch extends Expr { /** @var Expr Variable */ public $var; /** @var null|Expr Array index / dim */ public $dim; /** * Constructs an array index fetch node. * * @param Expr $var Variable * @param null|Expr $dim Array index / dim * @param array $attributes Additional attributes */ public function __construct(Expr $var, Expr $dim = null, array $attributes = []) { parent::__construct($attributes); $this->var = $var; $this->dim = $dim; } public function getSubNodeNames() : array { return ['var', 'dim']; } public function getType() : string { return 'Expr_ArrayDimFetch'; } }
{'content_hash': '3236695dacdf2deb76fce68171f9f60f', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 86, 'avg_line_length': 24.264705882352942, 'alnum_prop': 0.5709090909090909, 'repo_name': 'leorawe/sci-base', 'id': '7c7dcecfc922061854a7c9c8e3ef9d2a1948dfa7', 'size': '825', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrayDimFetch.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '891567'}, {'name': 'Gherkin', 'bytes': '3374'}, {'name': 'HTML', 'bytes': '809692'}, {'name': 'JavaScript', 'bytes': '1514397'}, {'name': 'PHP', 'bytes': '36312357'}, {'name': 'Ruby', 'bytes': '63696'}, {'name': 'Shell', 'bytes': '59930'}]}