text:
#ifndef MSVC_OBJECTMODEL_H
#define MSVC_OBJECTMODEL_H

#include "project.h"
#include "xmloutput.h"

#include <proitems.h>

#include <qatomic.h>
#include <qlist.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qmap.h>
#include <qdebug.h>

QT_BEGIN_NAMESPACE

enum DotNET {
    NETUnknown = 0,
    NET2002 = 0x70,
    NET2003 = 0x71,
    NET2005 = 0x80,
    NET2008 = 0x90,
    NET2010 = 0xa0,
    NET2012 = 0xb0,
    NET2013 = 0xc0
};

/*
    This Object model is of course VERY simplyfied,
    and does not actually follow the original MSVC
    object model. However, it fulfilles the basic
    needs for qmake
*/

/*
    If a triState value is 'unset' then the
    corresponding property is not in the output,
    forcing the tool to utilize default values.
    False/True values will be in the output...
*/
enum triState {
    unset = -1,
    _False = 0,
    _True = 1
};

triState operator!(const triState &rhs);

enum addressAwarenessType {
    addrAwareDefault,
    addrAwareNoLarge,
    addrAwareLarge
};
enum asmListingOption {
    asmListingNone,
    asmListingAssemblyOnly,
    asmListingAsmMachineSrc,
    asmListingAsmMachine,
    asmListingAsmSrc
};
enum basicRuntimeCheckOption {
    runtimeBasicCheckNone = 0,
    runtimeCheckStackFrame = 1,
    runtimeCheckUninitVariables = 2,
    runtimeBasicCheckAll = runtimeCheckStackFrame | runtimeCheckUninitVariables
};
enum browseInfoOption {
    brInfoNone,
    brAllInfo,
    brNoLocalSymbols
};
enum callingConventionOption {
    callConventionDefault = -1,
    callConventionCDecl,
    callConventionFastCall,
    callConventionStdCall
};
enum charSet {
    charSetNotSet,
    charSetUnicode,
    charSetMBCS
};
enum compileAsManagedOptions {
    managedDefault           = -1, // Was: noAssembly
    managedAssembly          = 1,
    managedAssemblyPure      = 2,  // Old was: Assembly
    managedAssemblySafe      = 3,
    managedAssemblyOldSyntax = 4
};
enum CompileAsOptions{
    compileAsDefault,
    compileAsC,
    compileAsCPlusPlus
};
enum ConfigurationTypes {
    typeUnknown        = 0,
    typeApplication    = 1,
    typeDynamicLibrary = 2,
    typeStaticLibrary  = 4,
    typeGeneric        = 10
};
enum debugOption {
    debugUnknown = -1,
    debugDisabled,
    debugOldStyleInfo,
    debugLineInfoOnly,
    debugEnabled,
    debugEditAndContinue
};
enum eAppProtectionOption {
    eAppProtectUnchanged,
    eAppProtectLow,
    eAppProtectMedium,
    eAppProtectHigh
};
enum enhancedInstructionSetOption {
    archNotSet = 0,
    archSSE = 1,
    archSSE2 = 2
};
enum exceptionHandling {
    ehDefault = -1,
    ehNone    = 0,
    ehNoSEH   = 1,
    ehSEH     = 2
};
enum enumResourceLangID {
    rcUseDefault                 = 0,
    rcAfrikaans                  = 1078,
    rcAlbanian                   = 1052,
    rcArabicAlgeria              = 5121,
    rcArabicBahrain              = 15361,
    rcArabicEgypt                = 3073,
    rcArabicIraq                 = 2049,
    rcArabicJordan               = 11265,
    rcArabicKuwait               = 13313,
    rcArabicLebanon              = 12289,
    rcArabicLibya                = 4097,
    rcArabicMorocco              = 6145,
    rcArabicOman                 = 8193,
    rcArabicQatar                = 16385,
    rcArabicSaudi                = 1025,
    rcArabicSyria                = 10241,
    rcArabicTunisia              = 7169,
    rcArabicUnitedArabEmirates   = 14337,
    rcArabicYemen                = 9217,
    rcBasque                     = 1069,
    rcBulgarian                  = 1026,
    rcByelorussian               = 1059,
    rcCatalan                    = 1027,
    rcChineseHongKong            = 3076,
    rcChinesePRC                 = 2052,
    rcChineseSingapore           = 4100,
    rcChineseTaiwan              = 1028,
    rcCroatian                   = 1050,
    rcCzech                      = 1029,
    rcDanish                     = 1030,
    rcDutchBelgium               = 2067,
    rcDutchStandard              = 1043,
    rcEnglishAustralia           = 3081,
    rcEnglishBritain             = 2057,
    rcEnglishCanada              = 4105,
    RcEnglishCaribbean           = 9225,
    rcEnglishIreland             = 6153,
    rcEnglishJamaica             = 8201,
    rcEnglishNewZealand          = 5129,
    rcEnglishSouthAfrica         = 7177,
    rcEnglishUS                  = 1033,
    rcEstonian                   = 1061,
    rcFarsi                      = 1065,
    rcFinnish                    = 1035,
    rcFrenchBelgium              = 2060,
    rcFrenchCanada               = 3084,
    rcFrenchLuxembourg           = 5132,
    rcFrenchStandard             = 1036,
    rcFrenchSwitzerland          = 4108,
    rcGermanAustria              = 3079,
    rcGermanLichtenstein         = 5127,
    rcGermanLuxembourg           = 4103,
    rcGermanStandard             = 1031,
    rcGermanSwitzerland          = 2055,
    rcGreek                      = 1032,
    rcHebrew                     = 1037,
    rcHungarian                  = 1038,
    rcIcelandic                  = 1039,
    rcIndonesian                 = 1057,
    rcItalianStandard            = 1040,
    rcItalianSwitzerland         = 2064,
    rcJapanese                   = 1041,
    rcKorean                     = 1042,
    rcKoreanJohab                = 2066,
    rcLatvian                    = 1062,
    rcLithuanian                 = 1063,
    rcNorwegianBokmal            = 1044,
    rcNorwegianNynorsk           = 2068,
    rcPolish                     = 1045,
    rcPortugueseBrazilian        = 1046,
    rcPortugueseStandard         = 2070,
    rcRomanian                   = 1048,
    rcRussian                    = 1049,
    rcSerbian                    = 2074,
    rcSlovak                     = 1051,
    rcSpanishArgentina           = 11274,
    rcSpanishBolivia             = 16394,
    rcSpanishChile               = 13322,
    rcSpanishColombia            = 9226,
    rcSpanishCostaRica           = 5130,
    rcSpanishDominicanRepublic   = 7178,
    rcSpanishEcuador             = 12298,
    rcSpanishGuatemala           = 4106,
    rcSpanishMexico              = 2058,
    rcSpanishModern              = 3082,
    rcSpanishPanama              = 6154,
    rcSpanishParaguay            = 15370,
    rcSpanishPeru                = 10250,
    rcSpanishTraditional         = 1034,
    rcSpanishUruguay             = 14346,
    rcSpanishVenezuela           = 8202,
    rcSwedish                    = 1053,
    rcThai                       = 1054,
    rcTurkish                    = 1055,
    rcUkrainian                  = 1058,
    rcUrdu                       = 1056
};
enum enumSccEvent {
    eProjectInScc,
    ePreDirtyNotification
};
enum favorSizeOrSpeedOption {
    favorNone,
    favorSpeed,
    favorSize
};
enum floatingPointModel {
    floatingPointNotSet = -1,
    floatingPointPrecise,
    floatingPointStrict,
    floatingPointFast
};
enum genProxyLanguage {
    genProxyNative,
    genProxyManaged
};
enum inlineExpansionOption {
    expandDisable,
    expandOnlyInline,
    expandAnySuitable,
    expandDefault // Not useful number, but stops the output
};
enum linkIncrementalType {
    linkIncrementalDefault,
    linkIncrementalNo,
    linkIncrementalYes
};
enum linkProgressOption {
    linkProgressNotSet,
    linkProgressAll,
    linkProgressLibs
};
enum machineTypeOption {
    machineNotSet,
    machineX86,
    machineX64 = 17
};
enum midlCharOption {
    midlCharUnsigned,
    midlCharSigned,
    midlCharAscii7
};
enum midlErrorCheckOption {
    midlEnableCustom,
    midlDisableAll,
    midlEnableAll
};
enum midlStructMemberAlignOption {
    midlAlignNotSet,
    midlAlignSingleByte,
    midlAlignTwoBytes,
    midlAlignFourBytes,
    midlAlignEightBytes,
    midlAlignSixteenBytes
};
enum midlTargetEnvironment {
    midlTargetNotSet,
    midlTargetWin32,
    midlTargetWin64
};
enum midlWarningLevelOption {
    midlWarningLevel_0,
    midlWarningLevel_1,
    midlWarningLevel_2,
    midlWarningLevel_3,
    midlWarningLevel_4
};
enum optFoldingType {
    optFoldingDefault,
    optNoFolding,
    optFolding
};
enum optimizeOption {
    optimizeDisabled,
    optimizeMinSpace,
    optimizeMaxSpeed,
    optimizeFull,
    optimizeCustom,
    optimizeDefault // Not useful number, but stops the output
};
enum optRefType {
    optReferencesDefault,
    optNoReferences,
    optReferences
};
enum optWin98Type {
    optWin98Default,
    optWin98No,
    optWin98Yes
};
enum optLinkTimeCodeGenType {
    optLTCGDefault,
    optLTCGEnabled,
    optLTCGInstrument,
    optLTCGOptimize,
    optLTCGUpdate
};
enum pchOption {
    pchUnset = -1,
    pchNone,
    pchCreateUsingSpecific,
    pchGenerateAuto,
    pchUseUsingSpecific
};
enum preprocessOption {
    preprocessUnknown = -1,
    preprocessNo,
    preprocessYes,
    preprocessNoLineNumbers
};
enum ProcessorOptimizeOption {
    procOptimizeBlended,                //GB
    procOptimizePentium,                //G5
    procOptimizePentiumProAndAbove,     //G6
    procOptimizePentium4AndAbove        //G7
};
enum RegisterDeployOption {
    registerNo = 0,
    registerYes
};
enum RemoteDebuggerType {
    DbgLocal,
    DbgRemote,
    DbgRemoteTCPIP
};
enum runtimeLibraryOption {
    rtUnknown = -1,
    rtMultiThreaded,
    rtMultiThreadedDebug,
    rtMultiThreadedDLL,
    rtMultiThreadedDebugDLL,
    rtSingleThreaded,
    rtSingleThreadedDebug
};
enum structMemberAlignOption {
    alignNotSet,
    alignSingleByte,
    alignTwoBytes,
    alignFourBytes,
    alignEightBytes,
    alignSixteenBytes
};
enum subSystemOption {
    subSystemNotSet,
    subSystemConsole,
    subSystemWindows
};
enum termSvrAwarenessType {
    termSvrAwareDefault,
    termSvrAwareNo,
    termSvrAwareYes
};
enum toolSetType {
    toolSetUtility,
    toolSetMakefile,
    toolSetLinker,
    toolSetLibrarian,
    toolSetAll
};
enum TypeOfDebugger {
    DbgNativeOnly,
    DbgManagedOnly,
    DbgMixed,
    DbgAuto
};
enum useOfATL {
    useATLNotSet,
    useATLStatic,
    useATLDynamic
};
enum useOfMfc {
    useMfcStdWin,
    useMfcStatic,
    useMfcDynamic
};
enum useOfArchitecture {
    archUnknown = -1,
    archArmv4,
    archArmv5,
    archArmv4T,
    archArmv5T,
    archMips1 = 0,
    archMips2 = 1,
    archMips3 = 2,
    archMips4 = 3,
    archMips5 = 4,
    archMips16 = 5,
    archMips32 = 6,
    archMips64 = 7
};
enum warningLevelOption {
    warningLevelUnknown = -1,
    warningLevel_0,
    warningLevel_1,
    warningLevel_2,
    warningLevel_3,
    warningLevel_4
};

class VCToolBase {
protected:
    // Functions
    VCToolBase(){}
    virtual ~VCToolBase(){}
    virtual bool parseOption(const char* option) = 0;
public:
    void parseOptions(const ProStringList& options) {
        for (ProStringList::ConstIterator it=options.begin(); (it!=options.end()); it++)
            parseOption((*it).toLatin1().constData());
    }
    static QStringList fixCommandLine(const QString &input);
};

class VCConfiguration;
class VCProject;

class VCCLCompilerTool : public VCToolBase
{
public:
    // Functions
    VCCLCompilerTool();
    virtual ~VCCLCompilerTool(){}
    bool parseOption(const char* option);

    // Variables
    QStringList             AdditionalIncludeDirectories;
    QStringList             AdditionalOptions;
    QStringList             AdditionalUsingDirectories;
    QString                 AssemblerListingLocation;
    asmListingOption        AssemblerOutput;
    basicRuntimeCheckOption BasicRuntimeChecks;
    browseInfoOption        BrowseInformation;
    QString                 BrowseInformationFile;
    triState                BufferSecurityCheck;
    callingConventionOption CallingConvention;
    CompileAsOptions        CompileAs;
    compileAsManagedOptions CompileAsManaged;
    triState                CompileAsWinRT;
    triState                CompileOnly;
    debugOption             DebugInformationFormat;
    triState                DefaultCharIsUnsigned;
    triState                Detect64BitPortabilityProblems;
    triState                DisableLanguageExtensions;
    QStringList             DisableSpecificWarnings;
    enhancedInstructionSetOption  EnableEnhancedInstructionSet;
    triState                EnableFiberSafeOptimizations;
    triState                EnableFunctionLevelLinking;
    triState                EnableIntrinsicFunctions;
    exceptionHandling       ExceptionHandling;
    triState                ExpandAttributedSource;
    favorSizeOrSpeedOption  FavorSizeOrSpeed;
    floatingPointModel      FloatingPointModel;
    triState                FloatingPointExceptions;
    triState                ForceConformanceInForLoopScope;
    QStringList             ForcedIncludeFiles;
    QStringList             ForcedUsingFiles;
    preprocessOption        GeneratePreprocessedFile;
    triState                PreprocessSuppressLineNumbers;
    triState                GlobalOptimizations;
    triState                IgnoreStandardIncludePath;
    triState                ImproveFloatingPointConsistency;
    inlineExpansionOption   InlineFunctionExpansion;
    triState                KeepComments;
    triState                MinimalRebuild;
    QString                 ObjectFile;
    triState                OmitDefaultLibName;
    triState                OmitFramePointers;
    triState                OpenMP;
    optimizeOption          Optimization;
    ProcessorOptimizeOption OptimizeForProcessor;
    triState                OptimizeForWindowsApplication;
    QString                 OutputFile;
    QString                 PrecompiledHeaderFile;
    QString                 PrecompiledHeaderThrough;
    QStringList             PreprocessorDefinitions;
    QString                 ProgramDataBaseFileName;
    runtimeLibraryOption    RuntimeLibrary;
    triState                RuntimeTypeInfo;
    triState                ShowIncludes;
    triState                SmallerTypeCheck;
    triState                StringPooling;
    structMemberAlignOption StructMemberAlignment;
    triState                SuppressStartupBanner;
    triState                TreatWChar_tAsBuiltInType;
    triState                TurnOffAssemblyGeneration;
    triState                UndefineAllPreprocessorDefinitions;
    QStringList             UndefinePreprocessorDefinitions;
    pchOption               UsePrecompiledHeader;
    triState                UseUnicodeForAssemblerListing;
    QStringList             TreatSpecificWarningsAsErrors;
    triState                WarnAsError;
    warningLevelOption      WarningLevel;
    triState                WholeProgramOptimization;
    useOfArchitecture       CompileForArchitecture;
    triState                InterworkCalls;

    // VS2010
    triState                EnablePREfast;
    triState                DisplayFullPaths;
    triState                MultiProcessorCompilation;
    QString                 MultiProcessorCompilationProcessorCount;
    triState                GenerateXMLDocumentationFiles;
    QString                 XMLDocumentationFileName;
    QString                 ErrorReporting;
    triState                CreateHotpatchableImage;
    QString                 PreprocessOutputPath;

    VCConfiguration*        config;

private:
    bool parseRuntimeCheckOption(char c, int *rtc);
};

class VCLinkerTool : public VCToolBase
{
public:
    // Functions
    VCLinkerTool();
    virtual ~VCLinkerTool(){}
    bool parseOption(const char* option);

    // Variables
    QStringList             AdditionalDependencies;
    QStringList             AdditionalLibraryDirectories;
    QStringList             AdditionalOptions;
    QStringList             AddModuleNamesToAssembly;
    QString                 BaseAddress;
    triState                DataExecutionPrevention;
    QStringList             DelayLoadDLLs;
    optFoldingType          EnableCOMDATFolding;
    QString                 EntryPointSymbol;
    QStringList             ForceSymbolReferences;
    QString                 FunctionOrder;
    triState                GenerateDebugInformation;
    triState                GenerateMapFile;
    qlonglong               HeapCommitSize;
    qlonglong               HeapReserveSize;
    triState                IgnoreAllDefaultLibraries;
    QStringList             IgnoreDefaultLibraryNames;
    triState                IgnoreEmbeddedIDL;
    triState                IgnoreImportLibrary;
    triState                ImageHasSafeExceptionHandlers;
    QString                 ImportLibrary;
    addressAwarenessType    LargeAddressAware;
    triState                LinkDLL;
    linkIncrementalType     LinkIncremental;
    optLinkTimeCodeGenType  LinkTimeCodeGeneration;
    QString                 LinkToManagedResourceFile;
    triState                MapExports;
    QString                 MapFileName;
    triState                MapLines;
    QString                 MergedIDLBaseFileName;
    QString                 MergeSections;          // Should be list?
    QString                 MidlCommandFile;
    QString                 ModuleDefinitionFile;   // Should be list?
    optWin98Type            OptimizeForWindows98;
    optRefType              OptimizeReferences;
    QString                 OutputFile;
    QString                 ProgramDatabaseFile;
    triState                RandomizedBaseAddress;
    triState                RegisterOutput;
    triState                ResourceOnlyDLL;
    triState                SetChecksum;
    linkProgressOption      ShowProgress;
    qlonglong               StackCommitSize;
    qlonglong               StackReserveSize;
    QString                 StripPrivateSymbols;    // Should be list?
    subSystemOption         SubSystem;
    triState                SupportUnloadOfDelayLoadedDLL;
    triState                SuppressStartupBanner;
    triState                SwapRunFromCD;
    triState                SwapRunFromNet;
    machineTypeOption       TargetMachine;
    termSvrAwarenessType    TerminalServerAware;
    triState                TreatWarningsAsErrors;
    triState                TurnOffAssemblyGeneration;
    QString                 TypeLibraryFile;
    qlonglong               TypeLibraryResourceID;
    QString                 Version;

    // VS2010
    triState                GenerateManifest;
    QStringList             AdditionalManifestDependencies;
    QString                 ManifestFile;
    triState                EnableUAC;
    QString                 UACExecutionLevel;
    triState                UACUIAccess;
    qlonglong               SectionAlignment;
    triState                PreventDllBinding;
    triState                AllowIsolation;
    triState                AssemblyDebug;
    QStringList             AssemblyLinkResource;
    QString                 CLRImageType;
    QString                 CLRSupportLastError;
    QString                 CLRThreadAttribute;
    triState                CLRUnmanagedCodeCheck;
    triState                DelaySign;
    QString                 KeyContainer;
    QString                 KeyFile;
    QString                 LinkErrorReporting;

    // VS2012
    triState                GenerateWindowsMetadata;
    QString                 WindowsMetadataFile;

    VCConfiguration*        config;
};

class VCManifestTool : public VCToolBase
{
public:
    VCManifestTool();
    ~VCManifestTool();
    bool parseOption(const char* option);

    triState                EmbedManifest;
};

class VCMIDLTool : public VCToolBase
{
public:
    // Functions
    VCMIDLTool();
    virtual ~VCMIDLTool(){}
    bool parseOption(const char* option);

    // Variables
    QStringList             AdditionalIncludeDirectories;
    QStringList             AdditionalOptions;
    QStringList             CPreprocessOptions;
    midlCharOption          DefaultCharType;
    QString                 DLLDataFileName;    // Should be list?
    midlErrorCheckOption    EnableErrorChecks;
    triState                ErrorCheckAllocations;
    triState                ErrorCheckBounds;
    triState                ErrorCheckEnumRange;
    triState                ErrorCheckRefPointers;
    triState                ErrorCheckStubData;
    QStringList             FullIncludePath;
    triState                GenerateStublessProxies;
    triState                GenerateTypeLibrary;
    QString                 HeaderFileName;
    triState                IgnoreStandardIncludePath;
    QString                 InterfaceIdentifierFileName;
    triState                MkTypLibCompatible;
    QString                 OutputDirectory;
    QStringList             PreprocessorDefinitions;
    QString                 ProxyFileName;
    QString                 RedirectOutputAndErrors;
    midlStructMemberAlignOption StructMemberAlignment;
    triState                SuppressStartupBanner;
    midlTargetEnvironment   TargetEnvironment;
    QString                 TypeLibraryName;
    QStringList             UndefinePreprocessorDefinitions;
    triState                ValidateParameters;
    triState                WarnAsError;
    midlWarningLevelOption  WarningLevel;

    // VS 2010
    triState                ApplicationConfigurationMode;
    QString                 GenerateClientFiles;
    QString                 ClientStubFile;
    QString                 TypeLibFormat;
    triState                ValidateAllParameters;
    triState                SuppressCompilerWarnings;
    QString                 GenerateServerFiles;
    QString                 ServerStubFile;
    qlonglong               LocaleID;

    VCConfiguration*        config;
};

class VCLibrarianTool : public VCToolBase
{
public:
    // Functions
    VCLibrarianTool();
    virtual ~VCLibrarianTool(){}
    bool parseOption(const char*){ return false; }

    // Variables
    QStringList             AdditionalDependencies;
    QStringList             AdditionalLibraryDirectories;
    QStringList             AdditionalOptions;
    QStringList             ExportNamedFunctions;
    QStringList             ForceSymbolReferences;
    triState                IgnoreAllDefaultLibraries;
    QStringList             IgnoreDefaultLibraryNames;
    QString                 ModuleDefinitionFile;
    QString                 OutputFile;
    triState                SuppressStartupBanner;
};

class VCCustomBuildTool : public VCToolBase
{
public:
    // Functions
    VCCustomBuildTool();
    virtual ~VCCustomBuildTool(){}
    bool parseOption(const char*){ return false; }

    // Variables
    QStringList             AdditionalDependencies;
    QStringList             CommandLine;
    QString                 Description;
    QStringList             Outputs;
    QString                 ToolName;
    QString                 ToolPath;

    VCConfiguration*        config;
};

class VCResourceCompilerTool : public VCToolBase
{
public:
    // Functions
    VCResourceCompilerTool();
    virtual ~VCResourceCompilerTool(){}
    bool parseOption(const char*){ return false; }

    // Variables
    QStringList             AdditionalIncludeDirectories;
    QStringList             AdditionalOptions;
    enumResourceLangID      Culture;
    QStringList             FullIncludePath;
    triState                IgnoreStandardIncludePath;
    QStringList             PreprocessorDefinitions;
    QString                 ResourceOutputFileName;
    linkProgressOption      ShowProgress;
    QString                 ToolPath;
    triState                SuppressStartupBanner;
};

class VCDeploymentTool
{
public:
    // Functions
    VCDeploymentTool();
    virtual ~VCDeploymentTool() {}

    // Variables
    QString                 DeploymentTag;
    QString                 RemoteDirectory;
    RegisterDeployOption    RegisterOutput;
    QString                 AdditionalFiles;
};

class VCEventTool : public VCToolBase
{
protected:
    // Functions
    VCEventTool(const QString &eventName);
    virtual ~VCEventTool(){}
    bool parseOption(const char*){ return false; }

public:
    // Variables
    QStringList             CommandLine;
    QString                 Description;
    triState                ExcludedFromBuild;
    QString                 EventName;
    QString                 ToolName;
    QString                 ToolPath;
};

class VCPostBuildEventTool : public VCEventTool
{
public:
    VCPostBuildEventTool();
    ~VCPostBuildEventTool(){}
};

class VCPreBuildEventTool : public VCEventTool
{
public:
    VCPreBuildEventTool();
    ~VCPreBuildEventTool(){}
};

class VCPreLinkEventTool : public VCEventTool
{
public:
    VCPreLinkEventTool();
    ~VCPreLinkEventTool(){}
};

class VCWinDeployQtTool : public VCToolBase
{
public:
    VCWinDeployQtTool() {}
    ~VCWinDeployQtTool() {}

protected:
    bool parseOption(const char *) { return false; }

public:
    // Variables
    QString                 Record;
    QString                 CommandLine;
    bool                    ExcludedFromBuild;

    VCConfiguration *       config;
};

class VCConfiguration
{
public:
    // Functions
    VCConfiguration();
    ~VCConfiguration(){}

    bool                    suppressUnknownOptionWarnings;
    DotNET                  CompilerVersion;
    bool                    WinRT, WinPhone, WinPhone80;

    // Variables
    triState                ATLMinimizesCRunTimeLibraryUsage;
    triState                BuildBrowserInformation;
    charSet                 CharacterSet;
    ConfigurationTypes      ConfigurationType;
    QString                 DeleteExtensionsOnClean;
    QString                 ImportLibrary;
    QString                 IntermediateDirectory;
    QString                 Name;   // "ConfigurationName|PlatformName"
    QString                 ConfigurationName;
    QString                 OutputDirectory;
    QString                 PrimaryOutput;
    QString                 PrimaryOutputExtension;
    QString                 ProgramDatabase;
    QString                 PlatformToolSet;
    triState                RegisterOutput;
    useOfATL                UseOfATL;
    useOfMfc                UseOfMfc;
    triState                WholeProgramOptimization;

    // XML sub-parts
    VCCLCompilerTool        compiler;
    VCLinkerTool            linker;
    VCLibrarianTool         librarian;
    VCManifestTool          manifestTool;
    VCCustomBuildTool       custom;
    VCMIDLTool              idl;
    VCPostBuildEventTool    postBuild;
    VCPreBuildEventTool     preBuild;
    VCDeploymentTool        deployment;
    VCPreLinkEventTool      preLink;
    VCResourceCompilerTool  resource;
    VCWinDeployQtTool       windeployqt;
};

struct VCFilterFile
{
    VCFilterFile()
    { excludeFromBuild = false; }
    VCFilterFile(const QString &filename, bool exclude = false )
    { file = filename; excludeFromBuild = exclude; }
    VCFilterFile(const QString &filename, const QString &additional, bool exclude = false )
    { file = filename; excludeFromBuild = exclude; additionalFile = additional; }
    bool operator==(const VCFilterFile &other){
        return file == other.file
               && additionalFile == other.additionalFile
               && excludeFromBuild == other.excludeFromBuild;
    }

    bool                    excludeFromBuild;
    QString                 file;
    QString                 additionalFile; // For tools like MOC
};

#ifndef QT_NO_DEBUG_OUTPUT
inline QDebug operator<<(QDebug dbg, const VCFilterFile &p)
{
    dbg.nospace() << "VCFilterFile(file(" << p.file
                  << ") additionalFile(" << p.additionalFile
                  << ") excludeFromBuild(" << p.excludeFromBuild << "))" << endl;
    return dbg.space();
}
#endif

class VcprojGenerator;
class VCFilter
{
public:
    // Functions
    VCFilter();
    ~VCFilter(){}

    void addFile(const QString& filename);
    void addFile(const VCFilterFile& fileInfo);
    void addFiles(const QStringList& fileList);
    void addFiles(const ProStringList& fileList);
    bool addExtraCompiler(const VCFilterFile &info);
    void modifyPCHstage(QString str);
    VCFilterFile findFile(const QString &filePath, bool *found) const;

    // Variables
    QString                 Name;
    QString                 Filter;
    QString                 Guid;
    triState                ParseFiles;
    VcprojGenerator*        Project;
    VCConfiguration*        Config;
    QList<VCFilterFile>     Files;

    bool                    useCustomBuildTool;
    VCCustomBuildTool       CustomBuildTool;

    bool                    useCompilerTool;
    VCCLCompilerTool        CompilerTool;
};

typedef QList<VCFilter> VCFilterList;
class VCProjectSingleConfig
{
public:
    enum FilterTypes {
        None,
        Source,
        Header,
        Generated,
        LexYacc,
        Translation,
        Resources,
        Extras
    };
    // Functions
    VCProjectSingleConfig(){}
    ~VCProjectSingleConfig(){}

    // Variables
    QString                 Name;
    QString                 Version;
    QString                 ProjectGUID;
    QString                 Keyword;
    QString                 SccProjectName;
    QString                 SccLocalPath;
    QString                 PlatformName;
    QString                 SdkVersion;

    // XML sub-parts
    VCConfiguration         Configuration;
    VCFilter                RootFiles;
    VCFilter                SourceFiles;
    VCFilter                HeaderFiles;
    VCFilter                GeneratedFiles;
    VCFilter                LexYaccFiles;
    VCFilter                TranslationFiles;
    VCFilter                FormFiles;
    VCFilter                ResourceFiles;
    VCFilter                DeploymentFiles;
    VCFilterList            ExtraCompilersFiles;

    bool                    flat_files;

    const VCFilter &filterByName(const QString &name) const;
    const VCFilter &filterForExtraCompiler(const QString &compilerName) const;
};

// Tree & Flat view of files --------------------------------------------------
class VCFilter;
class Node
{
public:
    virtual ~Node() { }
    void addElement(const VCFilterFile &file) {
        addElement(file.file, file);
    }
    virtual void addElement(const QString &filepath, const VCFilterFile &allInfo) = 0;
    virtual void removeElements()= 0;
    virtual void generateXML(XmlOutput &xml, const QString &tagName, VCProject &tool, const QString &filter) = 0;
    virtual bool hasElements() = 0;
};

class TreeNode : public Node
{
    typedef QMap<QString, TreeNode*> ChildrenMap;
    VCFilterFile info;
    ChildrenMap children;

public:
    virtual ~TreeNode() { removeElements(); }

    int pathIndex(const QString &filepath) {
        int Windex = filepath.indexOf("\\");
        int Uindex = filepath.indexOf("/");
        if (Windex != -1 && Uindex != -1)
            return qMin(Windex, Uindex);
        else if (Windex != -1)
            return Windex;
        return Uindex;
    }

    void addElement(const QString &filepath, const VCFilterFile &allInfo){
        QString newNodeName(filepath);

        int index = pathIndex(filepath);
        if (index != -1)
            newNodeName = filepath.left(index);

        TreeNode *n = children.value(newNodeName);
        if (!n) {
            n = new TreeNode;
            n->info = allInfo;
            children.insert(newNodeName, n);
        }
        if (index != -1)
            n->addElement(filepath.mid(index+1), allInfo);
    }

    void removeElements() {
        ChildrenMap::ConstIterator it = children.constBegin();
        ChildrenMap::ConstIterator end = children.constEnd();
        for( ; it != end; it++) {
            (*it)->removeElements();
            delete it.value();
        }
        children.clear();
    }

    void generateXML(XmlOutput &xml, const QString &tagName, VCProject &tool, const QString &filter);
    bool hasElements() {
        return children.size() != 0;
    }
};

class FlatNode : public Node
{
    typedef QMap<QString, VCFilterFile> ChildrenMapFlat;
    ChildrenMapFlat children;

public:
    virtual ~FlatNode() { removeElements(); }

    int pathIndex(const QString &filepath) {
        int Windex = filepath.lastIndexOf("\\");
        int Uindex = filepath.lastIndexOf("/");
        if (Windex != -1 && Uindex != -1)
            return qMax(Windex, Uindex);
        else if (Windex != -1)
            return Windex;
        return Uindex;
    }

    void addElement(const QString &filepath, const VCFilterFile &allInfo){
        QString newKey(filepath);

        int index = pathIndex(filepath);
        if (index != -1)
            newKey = filepath.mid(index+1);

        // Key designed to sort files with same
        // name in different paths correctly
        children.insert(newKey + "\0" + allInfo.file, allInfo);
    }

    void removeElements() {
        children.clear();
    }

    void generateXML(XmlOutput &xml, const QString &tagName, VCProject &proj, const QString &filter);
    bool hasElements() {
        return children.size() != 0;
    }
};
// ----------------------------------------------------------------------------

class VCProject
{
public:
    // Variables
    QString                 Name;
    QString                 Version;
    QString                 ProjectGUID;
    QString                 Keyword;
    QString                 SccProjectName;
    QString                 SccLocalPath;
    QString                 PlatformName;
    QString                 SdkVersion;

    // Single projects
    QList<VCProjectSingleConfig>  SingleProjects;

    // List of all extracompilers
    QStringList             ExtraCompilers;
};

class VCProjectWriter
{
public:
    virtual ~VCProjectWriter() {}

    virtual void write(XmlOutput &, VCProjectSingleConfig &);
    virtual void write(XmlOutput &, VCProject &);

    virtual void write(XmlOutput &, const VCCLCompilerTool &);
    virtual void write(XmlOutput &, const VCLinkerTool &);
    virtual void write(XmlOutput &, const VCManifestTool &);
    virtual void write(XmlOutput &, const VCMIDLTool &);
    virtual void write(XmlOutput &, const VCCustomBuildTool &);
    virtual void write(XmlOutput &, const VCLibrarianTool &);
    virtual void write(XmlOutput &, const VCResourceCompilerTool &);
    virtual void write(XmlOutput &, const VCEventTool &);
    virtual void write(XmlOutput &, const VCDeploymentTool &);
    virtual void write(XmlOutput &, const VCWinDeployQtTool &);
    virtual void write(XmlOutput &, const VCConfiguration &);
    virtual void write(XmlOutput &, VCFilter &);

private:
    static void outputFilter(VCProject &project, XmlOutput &xml, const QString &filtername);
    static void outputFileConfigs(VCProject &project, XmlOutput &xml, const VCFilterFile &info, const QString &filtername);
    static void outputFileConfig(VCFilter &filter, XmlOutput &xml, const QString &filename);

    friend class TreeNode;
    friend class FlatNode;
};

QT_END_NAMESPACE

#endif // MSVC_OBJECTMODEL_H


text:
package com.solaiemes.main;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.impl.client.DefaultHttpClient;

import com.solaiemes.constant.Constants;
import com.solaiemes.httpsclient.DefaultHttpsClient;
import com.solaiemes.provisioning.UserProvisioning;
import com.solaiemes.services.EcoSeviceHandler;

public class Main extends Thread{

	/////////////////////////////////////////PAY ATTENTON !!////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////
	//BEFORE START, YOU NEED TO EDIT SERVICE_ECO_USERNAME,API_KEY AND API_ID IN JAVA Constants CLASS
	////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////

	private static final Log log = LogFactory.getLog(Main.class);
	public static boolean end=false;
	public static EcoSeviceHandler echo=null;
	public static DefaultHttpClient client = DefaultHttpsClient.getNewHttpClient();

	public Main(){
		try {
			end=true;
			start();
		} catch (Exception e) {
			log.error("Echo Sevices can't run ",e);
		}
	}

	@Override
	public void run(){

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		end=false;

		if(echo==null){
			echo=new EcoSeviceHandler();
		}

		try {
			sleep(4000);
		} catch (InterruptedException e1) {		}

		System.out.println("\n**********************************");
		System.out.println("FINISH SERVICES AFTER WRITE 'EXIT'");
		System.out.println("**********************************\n");

		while(!end){
			try {

				String str=br.readLine();
				if(str!=null && str.equalsIgnoreCase("exit")){
					end=true;
				}
				else{
					System.out.println("\n*****************************************************");
					System.out.println("Unknow option "+str+". FINISH SERVICES AFTER WRITE 'EXIT'");
					System.out.println("*****************************************************\n");
				}

			} catch (Exception e) {
				System.out.println("\n**********************************");
				System.out.println("FINISH SERVICES AFTER WRITE 'EXIT'");
				System.out.println("**********************************\n");
			}
		}

		try {
			UserProvisioning.unregister(Constants.SERVICE_ECO_USERNAME,Constants.API_ID);
		} catch (Exception e) {
			log.error("Echo Sevices can't run ",e);
		}finally{
			getHttsClient().getConnectionManager().shutdown();
		}

	}

	public synchronized static DefaultHttpClient getHttsClient(){
		return client;
	}

	public static void main (String arg[]){
		log.info("Running application");
		new Main();
	}
}

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';
import { reduxForm, Field } from 'redux-form';
import { connect } from 'react-redux';
import * as actions from '../../actions';
//import { signinUser } from '../../actions';

class Signin extends Component{
    handleFormSubmit({ email, password }) {
        console.log(email, password);
        // TODO: Something to log user in
        this.props.signinUser({ email, password});
    }

    renderAlert() {
        if(this.props.errorMessage) {
            return (

                    Oops!{this.props.errorMessage}

            );
        }
    }

    render() {
        const { handleSubmit,  fields = { email, password }} = this.props;

        return (
            <form onSubmit={ handleSubmit(this.handleFormSubmit.bind(this)) }>
                <fieldset className="form-group">
                    Email:
                    <Field name="email" component="input" className="form-control" type="text"/>
                </fieldset>
                <fieldset className="form-group">
                    Password:
                    <Field name="password" component="input" className="form-control" type="text"/>
                </fieldset>
                {this.renderAlert()}
                <button className="btn btn-primary" action="submit">Sign in</button>
            </form>
        );
    }
}

function mapStateToProps(state) {
    return { errorMessage: state.auth.error };
}

Signin = reduxForm({
    form: 'signin',
    fields: [ 'email', 'password' ]
})(Signin);

export default Signin = connect(mapStateToProps, actions)(Signin);


text:
module Crypto.Gpgme.Crypto (

      encrypt
    , encryptSign
    , encryptFd
    , encryptSignFd
    , encrypt'
    , encryptSign'
    , decrypt
    , decryptFd
    , decryptVerifyFd
    , decrypt'
    , decryptVerify
    , decryptVerify'
    , verify
    , verify'
    , verifyDetached
    , verifyDetached'
    , verifyPlain
    , verifyPlain'
    , sign

) where

import System.Posix.Types (Fd(Fd))
import Bindings.Gpgme
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8
import Control.Monad (liftM)
import Control.Monad.Trans.Except (ExceptT(ExceptT), runExceptT, mapExceptT)
import Foreign
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
import GHC.Ptr

import Crypto.Gpgme.Ctx
import Crypto.Gpgme.Internal
import Crypto.Gpgme.Key
import Crypto.Gpgme.Types

locale :: String
locale = "C"

-- | Convenience wrapper around 'withCtx' and 'withKey' to
--   encrypt a single plaintext for a single recipient with
--   its homedirectory.
encrypt' :: String -> Fpr -> Plain -> IO (Either String Encrypted)
encrypt' = encryptIntern' encrypt

-- | Convenience wrapper around 'withCtx' and 'withKey' to
--   encrypt and sign a single plaintext for a single recipient
--   with its homedirectory.
encryptSign' :: String -> Fpr -> Plain -> IO (Either String Encrypted)
encryptSign' = encryptIntern' encryptSign

orElse :: Monad m => m (Maybe a) -> e -> ExceptT e m a
orElse action err = ExceptT $ maybe (Left err) return `liftM` action

bimapExceptT :: Functor m => (x -> y) -> (a -> b) -> ExceptT x m a -> ExceptT y m b
bimapExceptT f g = mapExceptT (fmap h)
  where
    h (Left  e) = Left  (f e)
    h (Right a) = Right (g a)

encryptIntern' :: (Ctx -> [Key] -> Flag -> Plain
                        -> IO (Either [InvalidKey] Encrypted)
                    ) -> String -> Fpr -> Plain -> IO (Either String Encrypted)
encryptIntern' encrFun gpgDir recFpr plain =
    withCtx gpgDir locale OpenPGP $ \ctx -> runExceptT $
        do pubKey <- getKey ctx recFpr NoSecret `orElse` ("no such key: " ++ show recFpr)
           bimapExceptT show id $ ExceptT $ encrFun ctx [pubKey] NoFlag plain

-- | encrypt for a list of recipients
encrypt :: Ctx -> [Key] -> Flag -> Plain -> IO (Either [InvalidKey] Encrypted)
encrypt = encryptIntern c'gpgme_op_encrypt

-- | encrypt and sign for a list of recipients
encryptSign :: Ctx -> [Key] -> Flag -> Plain -> IO (Either [InvalidKey] Encrypted)
encryptSign = encryptIntern c'gpgme_op_encrypt_sign

encryptIntern :: (C'gpgme_ctx_t
                    -> GHC.Ptr.Ptr C'gpgme_key_t
                    -> C'gpgme_encrypt_flags_t
                    -> C'gpgme_data_t
                    -> C'gpgme_data_t
                    -> IO C'gpgme_error_t
                  )
                  -> Ctx
                  -> [Key]
                  -> Flag
                  -> Plain
                  -> IO (Either [InvalidKey] Encrypted)
encryptIntern enc_op (Ctx {_ctx=ctxPtr}) recPtrs flag plain = do
    -- init buffer with plaintext
    plainBufPtr <- malloc
    BS.useAsCString plain $ \bs -> do
        let copyData = 1 -- gpgme shall copy data, as bytestring will free it
        let plainlen = fromIntegral (BS.length plain)
        ret <- c'gpgme_data_new_from_mem plainBufPtr bs plainlen copyData
        checkError "data_new_from_mem" ret
    plainBuf <- peek plainBufPtr

    -- init buffer for result
    resultBufPtr <- newDataBuffer
    resultBuf <- peek resultBufPtr

    ctx <- peek ctxPtr

    -- encrypt
    withKeyPtrArray recPtrs $ \recArray ->
        checkError "op_encrypt" =<< enc_op ctx recArray (fromFlag flag)
                                        plainBuf resultBuf
    free plainBufPtr

    -- check whether all keys could be used for encryption
    encResPtr <- c'gpgme_op_encrypt_result ctx
    encRes <- peek encResPtr
    let recPtr = c'_gpgme_op_encrypt_result'invalid_recipients encRes

    let res = if recPtr /= nullPtr
                then Left (collectFprs recPtr)
                else Right (collectResult resultBuf)

    free resultBufPtr

    return res

-- | Encrypt plaintext
encryptFd :: Ctx -> [Key] -> Flag -> Fd -> Fd -> IO (Either [InvalidKey] ())
encryptFd = encryptFdIntern c'gpgme_op_encrypt

-- | Encrypt and sign plaintext
encryptSignFd :: Ctx -> [Key] -> Flag -> Fd -> Fd -> IO (Either [InvalidKey] ())
encryptSignFd = encryptFdIntern c'gpgme_op_encrypt_sign

encryptFdIntern :: (C'gpgme_ctx_t
                 -> GHC.Ptr.Ptr C'gpgme_key_t
                 -> C'gpgme_encrypt_flags_t
                 -> C'gpgme_data_t
                 -> C'gpgme_data_t
                 -> IO C'gpgme_error_t
               )
               -> Ctx
               -> [Key]
               -> Flag
               -> Fd  -- ^ Plaintext data
               -> Fd  -- ^ Ciphertext data
               -> IO (Either [InvalidKey] ())
encryptFdIntern enc_op (Ctx {_ctx=ctxPtr}) recPtrs flag (Fd plainCInt) (Fd cipherCInt) = do
  -- Initialize plaintext buffer
  plainBufPtr <- malloc
  _ <- c'gpgme_data_new_from_fd plainBufPtr plainCInt
  plainBuf <- peek plainBufPtr

  -- Initialize ciphertext buffer
  cipherBufPtr <- malloc
  _ <- c'gpgme_data_new_from_fd cipherBufPtr cipherCInt
  cipherBuf <- peek cipherBufPtr

  ctx <- peek ctxPtr

  -- encrypt
  withKeyPtrArray recPtrs $ \recArray ->
      checkError "op_encrypt" =<< enc_op ctx recArray (fromFlag flag)
                                      plainBuf cipherBuf
  free plainBufPtr

  -- check whether all keys could be used for encryption
  encResPtr <- c'gpgme_op_encrypt_result ctx
  encRes <- peek encResPtr
  let recPtr = c'_gpgme_op_encrypt_result'invalid_recipients encRes

  let res = if recPtr /= nullPtr
              then Left (collectFprs recPtr)
              else Right (())

  free cipherBufPtr

  return res

-- | Build a null-terminated array of pointers from a list of 'Key's
withKeyPtrArray :: [Key] -> (Ptr C'gpgme_key_t -> IO a) -> IO a
withKeyPtrArray [] f   = f nullPtr
withKeyPtrArray keys f = do
    arr <- newArray0 nullPtr =<< mapM (peek . unsafeForeignPtrToPtr . unKey) keys
    f arr

-- | Convenience wrapper around 'withCtx' and 'withKey' to
--   decrypt a single ciphertext with its homedirectory.
decrypt' :: String -> Encrypted -> IO (Either DecryptError Plain)
decrypt' = decryptInternal' decrypt

-- | Convenience wrapper around 'withCtx' and 'withKey' to
--   decrypt and verify a single ciphertext with its homedirectory.
decryptVerify' :: String -> Encrypted -> IO (Either DecryptError Plain)
decryptVerify' = decryptInternal' decryptVerify

decryptInternal' :: (Ctx -> Encrypted -> IO (Either DecryptError Plain))
                  -> String
                  -> Encrypted
                  -> IO (Either DecryptError Plain)
decryptInternal' decrFun gpgDir cipher =
    withCtx gpgDir locale OpenPGP $ \ctx ->
        decrFun ctx cipher

-- | Decrypts a ciphertext
decrypt :: Ctx -> Encrypted -> IO (Either DecryptError Plain)
decrypt = decryptIntern c'gpgme_op_decrypt

-- | Decrypts and verifies a ciphertext
decryptVerify :: Ctx -> Encrypted -> IO (Either DecryptError Plain)
decryptVerify = decryptIntern c'gpgme_op_decrypt_verify

decryptIntern :: (C'gpgme_ctx_t
                    -> C'gpgme_data_t
                    -> C'gpgme_data_t
                    -> IO C'gpgme_error_t
                  )
                  -> Ctx
                  -> Encrypted
                  -> IO (Either DecryptError Plain)
decryptIntern dec_op (Ctx {_ctx=ctxPtr}) cipher = do
    -- init buffer with cipher
    cipherBufPtr <- malloc
    BS.useAsCString cipher $ \bs -> do
        let copyData = 1 -- gpgme shall copy data, as bytestring will free it
        let cipherlen = fromIntegral (BS.length cipher)
        ret <- c'gpgme_data_new_from_mem cipherBufPtr bs cipherlen copyData
        checkError "data_new_from_mem" ret
    cipherBuf <- peek cipherBufPtr

    -- init buffer for result
    resultBufPtr <- newDataBuffer
    resultBuf <- peek resultBufPtr

    ctx <- peek ctxPtr

    -- decrypt
    errcode <- dec_op ctx cipherBuf resultBuf

    let res = if errcode /= noError
                then Left  (toDecryptError errcode)
                else Right (collectResult resultBuf)

    free cipherBufPtr
    free resultBufPtr

    return res

-- | Decrypt a ciphertext
decryptFd :: Ctx -> Fd -> Fd -> IO (Either DecryptError ())
decryptFd = decryptFdIntern c'gpgme_op_decrypt

-- | Decrypt and verify ciphertext
decryptVerifyFd :: Ctx -> Fd -> Fd -> IO (Either DecryptError ())
decryptVerifyFd = decryptFdIntern c'gpgme_op_decrypt_verify

decryptFdIntern :: (C'gpgme_ctx_t
                    -> C'gpgme_data_t
                    -> C'gpgme_data_t
                    -> IO C'gpgme_error_t
                  )
                  -> Ctx
                  -> Fd
                  -> Fd
                  -> IO (Either DecryptError ())
decryptFdIntern dec_op (Ctx {_ctx=ctxPtr}) (Fd cipherCInt) (Fd plainCInt)= do
  -- Initialize ciphertext buffer
  cipherBufPtr <- malloc
  _ <- c'gpgme_data_new_from_fd cipherBufPtr cipherCInt
  cipherBuf <- peek cipherBufPtr

  -- Initialize plaintext buffer
  plainBufPtr <- malloc
  _ <- c'gpgme_data_new_from_fd plainBufPtr plainCInt
  plainBuf <- peek plainBufPtr

  ctx <- peek ctxPtr

  -- decrypt
  errcode <- dec_op ctx cipherBuf plainBuf

  let res = if errcode /= noError
              then Left  (toDecryptError errcode)
              else Right (())

  free cipherBufPtr
  free plainBufPtr

  return res

-- | Sign plaintext for a list of signers
sign :: Ctx      -- ^ Context to sign
     -> [Key]    -- ^ Keys to used for signing. An empty list will use context's default key.
     -> SignMode -- ^ Signing mode
     -> Plain    -- ^ Plain text to sign
     -> IO (Either [InvalidKey] Plain)
sign = signIntern c'gpgme_op_sign

signIntern :: (    C'gpgme_ctx_t
                -> C'gpgme_data_t
                -> C'gpgme_data_t
                -> C'gpgme_sig_mode_t
                -> IO C'gpgme_error_t
              ) -- ^ c'gpgme_op_sign type signature
              -> Ctx
              -> [Key]
              -> SignMode
              -> Plain
              -> IO (Either [InvalidKey] Encrypted)
signIntern sign_op (Ctx {_ctx=ctxPtr}) signPtrs mode plain = do
    -- init buffer with plaintext
    plainBufPtr <- malloc
    BS.useAsCString plain $ \bs -> do
        let copyData = 1 -- gpgme shall copy data, as bytestring will free it
        let plainlen = fromIntegral (BS.length plain)
        ret <- c'gpgme_data_new_from_mem plainBufPtr bs plainlen copyData
        checkError "data_new_from_mem" ret
    plainBuf <- peek plainBufPtr

    -- init buffer for result
    resultBufPtr <- newDataBuffer
    resultBuf <- peek resultBufPtr

    ctx <- peek ctxPtr

    -- add signing keys
    _ <- mapM ( \kForPtr -> withForeignPtr (unKey kForPtr)
           (\kPtr -> do
             k <- peek kPtr
             c'gpgme_signers_add ctx k
           )
         ) signPtrs

    -- sign
    let modeCode = case mode of
                     Normal -> c'GPGME_SIG_MODE_NORMAL
                     Detach -> c'GPGME_SIG_MODE_DETACH
                     Clear  -> c'GPGME_SIG_MODE_CLEAR

    checkError "op_sign" =<< sign_op ctx plainBuf resultBuf modeCode
    free plainBufPtr

    -- check whether all keys could be used for signingi
    signResPtr <- c'gpgme_op_sign_result ctx
    signRes <- peek signResPtr
    let recPtr = c'_gpgme_op_sign_result'invalid_signers signRes

    let res = if recPtr /= nullPtr
                then Left (collectFprs recPtr)
                else Right (collectResult resultBuf)

    free resultBufPtr

    return res

-- | Verify a payload with a detached signature
verifyDetached :: Ctx           -- ^ GPG context
               -> Signature     -- ^ Detached signature
               -> BS.ByteString -- ^ Signed text
               -> IO (Either GpgmeError VerificationResult)
verifyDetached ctx sig dat = do
    res <- verifyInternal go ctx sig dat
    return $ fmap fst res
    where
        go ctx' sig' dat' = do
            errcode <- c'gpgme_op_verify ctx' sig' dat' 0
            return (errcode, ())

-- | Convenience wrapper around 'withCtx' to
--   verify a single detached signature with its homedirectory.
verifyDetached' :: String        -- ^ GPG context home directory
                -> Signature     -- ^ Detached signature
                -> BS.ByteString -- ^ Signed text
                -> IO (Either GpgmeError VerificationResult)
verifyDetached' gpgDir sig dat =
    withCtx gpgDir locale OpenPGP $ \ctx ->
        verifyDetached ctx sig dat

{-# DEPRECATED verifyPlain "Use verify" #-}
verifyPlain :: Ctx -> Signature -> BS.ByteString -> IO (Either GpgmeError (VerificationResult, BS.ByteString))
verifyPlain c s _ = verify c s
{-# DEPRECATED verifyPlain' "Use verify'" #-}
verifyPlain' :: String -> Signature -> BS.ByteString -> IO (Either GpgmeError (VerificationResult, BS.ByteString))
verifyPlain' str sig _ = verify' str sig

-- | Verify a payload with a plain signature
verify :: Ctx -> Signature -> IO (Either GpgmeError (VerificationResult, BS.ByteString))
verify c s = verifyInternal go c s (C8.pack "")
    where
        go ctx sig _ = do
            -- init buffer for result
            resultBufPtr <- newDataBuffer
            resultBuf <- peek resultBufPtr

            errcode <- c'gpgme_op_verify ctx sig 0 resultBuf

            let res = if errcode /= noError
                        then mempty
                        else collectResult resultBuf

            free resultBufPtr

            return (errcode, res)

-- | Convenience wrapper around 'withCtx' to
--   verify a single plain signature with its homedirectory.
verify' :: String -> Signature -> IO (Either GpgmeError (VerificationResult, BS.ByteString))
verify' gpgDir sig =
    withCtx gpgDir locale OpenPGP $ \ctx ->
        verify ctx sig

verifyInternal :: (    C'gpgme_ctx_t
                    -> C'gpgme_data_t
                    -> C'gpgme_data_t
                    -> IO (C'gpgme_error_t, a)
                  )
                  -> Ctx
                  -> Signature
                  -> BS.ByteString
                  -> IO (Either GpgmeError (VerificationResult, a))
verifyInternal ver_op (Ctx {_ctx=ctxPtr}) sig dat = do
    -- init buffer with signature
    sigBufPtr <- malloc
    BS.useAsCString sig $ \bs -> do
        let copyData = 1 -- gpgme shall copy data, as bytestring will free it
        let siglen = fromIntegral (BS.length sig)
        ret <- c'gpgme_data_new_from_mem sigBufPtr bs siglen copyData
        checkError "data_new_from_mem" ret
    sigBuf <- peek sigBufPtr

    -- init buffer with data
    datBufPtr <- malloc
    BS.useAsCString dat $ \bs -> do
        let copyData = 1 -- gpgme shall copy data, as bytestring will free it
        let datlen = fromIntegral (BS.length dat)
        ret <- c'gpgme_data_new_from_mem datBufPtr bs datlen copyData
        checkError "data_new_from_mem" ret
    datBuf <- peek datBufPtr

    ctx <- peek ctxPtr

    -- verify
    (errcode, res) <- ver_op ctx sigBuf datBuf

    sigs <- collectSignatures' ctx
    let res' = if errcode /= noError
                then Left  (GpgmeError errcode)
                else Right (sigs, res)

    free sigBufPtr
    free datBufPtr

    return res'

newDataBuffer :: IO (Ptr C'gpgme_data_t)
newDataBuffer = do
    resultBufPtr <- malloc
    checkError "data_new" =<< c'gpgme_data_new resultBufPtr
    return resultBufPtr


text:
title: Telerik.Web.UI.PivotGrid.Core.Fields.FieldInfoData
page_title: Telerik.Web.UI.PivotGrid.Core.Fields.FieldInfoData
description: Telerik.Web.UI.PivotGrid.Core.Fields.FieldInfoData
---

# Telerik.Web.UI.PivotGrid.Core.Fields.FieldInfoData

Provides information about properties/fields of items that are used by a Telerik.Web.UI.PivotGrid.Core.Fields.IFieldDescriptionProvider .

## Inheritance Hierarchy

* System.Object
* Telerik.Web.UI.PivotGrid.Core.Fields.FieldInfoData

## Properties

###  RootFieldInfo `ContainerNode`

## Methods

###  GetFieldDescriptionByMember

#### Returns

`Telerik.Web.UI.PivotGrid.Core.Fields.IPivotFieldInfo`


text:
<?php

/**
 * attribute type int
 *
 * @category	Ultimate
 * @package		Ultimate_ModuleCreator
 * @author 		Marius Strajeru <marius.strajeru@gmail.com>
 */
class Ultimate_ModuleCreator_Model_Attribute_Type_Int extends Ultimate_ModuleCreator_Model_Attribute_Type_Abstract{
	/**
	 * sql colum ddl type
	 * @var string
	 */
	protected $_typeDdl 	= 'TYPE_INTEGER';
	/**
	 * sql colum ddl size
	 * @var string
	 */
	protected $_sizeDdl 	= 'null';
	/**
	 * get the sql column
	 * @access public
	 * @return string
	 * @author Marius Strajeru <marius.strajeru@gmail.com>
	 */
	public function getSqlColumn(){
		return '`'.$this->getAttribute()->getCode().'` int(10) '.$this->getNullSql().' default \'0\',';
	}
}


text:
A grunt.js task to run your jasmine feature suite using jasmine-node.

## Getting Started
Install this grunt plugin next to your project's grunt.js gruntfile with: `npm install grunt-jasmine-node`

Then add this line to your project's `grunt.js` grunt file:

```javascript
grunt.initConfig({
  jasmine_node: {
    js: {
      extensions: 'js',
      specNameMatcher: "./spec",
      projectRoot: ".",
      requirejs: false,
      forceExit: true,
      jUnit: {
        report: false,
        savePath : "./build/reports/jasmine/",
        useDotNotation: true,
        consolidate: true
      }
    }
  }
});

grunt.loadNpmTasks('grunt-jasmine-node');

grunt.registerTask('default', 'jasmine_node');
```

## Bugs

Help us squash them by submitting an issue that describes how you encountered it; please be as specific as possible including operating system, node, grunt, and grunt-jasmine-node versions.

## Release History

see [GitHub Repository](/s9tpepper/grunt-jasmine-node).

## License
Copyright (c) 2012 "s9tpepper" Omar Gonzalez & contributors.
Licensed under the MIT license.


text:
require([
    'app/FilterDateTime',

    'dojo/dom-construct',
    'dojo/query'
], function (
    WidgetUnderTest,

    domConstruct,
    query
) {
    describe('app/FilterDateTime', function () {
        var widget;
        var destroy = function (widget) {
            widget.destroyRecursive();
            widget = null;
        };

        beforeEach(function () {
            widget = new WidgetUnderTest(null, domConstruct.create('div', null, document.body));
        });

        afterEach(function () {
            if (widget) {
                destroy(widget);
            }
        });

        describe('Sanity', function () {
            it('should create a FilterDateTime', function () {
                expect(widget).toEqual(jasmine.any(WidgetUnderTest));
            });
        });
        describe('Gather values', function () {
            it('gathers custom ranges', function () {
                widget.fromDateNode.value = '2015-01-01';
                widget.toDateNode.value = '2015-02-11';

                widget._gatherData();
                var actual = widget.get('data');
                expect(actual).toEqual({
                    date: {
                        fromDate: '2015-01-01',
                        toDate: '2015-02-11'
                    }
                });
            });
            it('gathers days of the week', function () {
                query('[value=2]')[0].checked = true;
                query('[value=7]')[0].checked = true;

                widget._gatherData();
                var actual = widget.get('data');
                expect(actual).toEqual({
                    date: {
                        specificDays: ['2', '7']
                    }
                });
            });
            it('gathers nothing with days are not selected', function () {
                widget._gatherData();
                var actual = widget.get('data');
                expect(actual).toEqual({
                    date: {}
                });
            });
            it('gathers time of day', function () {
                widget.fromTimeNode.value = '00:00';
                widget.toTimeNode.value = '01:23';

                widget._gatherData();
                var actual = widget.get('data');
                expect(actual).toEqual({
                    date: {
                        fromTime: '00:00',
                        toTime: '01:23'
                    }
                });
            });
            it('gathers everything from all!', function () {
                widget.fromDateNode.value = '2015-01-01';
                widget.toDateNode.value = '2015-02-11';
                widget.fromTimeNode.value = '00:00';
                widget.toTimeNode.value = '01:23';

                query('[value=2]')[0].checked = true;
                query('[value=7]')[0].checked = true;

                widget._gatherData();
                var actual = widget.get('data');
                expect(actual).toEqual({
                    date: {
                        fromDate: '2015-01-01',
                        toDate: '2015-02-11',
                        fromTime: '00:00',
                        toTime: '01:23',
                        specificDays: ['2', '7']
                    }
                });
            });
        });
    });
});


text:
import pytest
from django.urls import reverse
from guardian.shortcuts import assign_perm

from metaci.fixtures.factories import RebuildFactory

@pytest.mark.django_db
class TestBuildViews:
    def test_build_list(self, client, superuser, data):
        client.force_login(superuser)
        url = reverse("home")
        response = client.get(url, {"repo": data["repo"].name})

        assert response.status_code == 200

    def test_build_detail__permission_denied(self, client, user, data):
        client.force_login(user)
        url = reverse("build_detail", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 403

    def test_build_detail(self, client, superuser, data):
        client.force_login(superuser)
        url = reverse("build_detail", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 200

    def test_build_detail__stacktrace_present(self, client, superuser, data):
        client.force_login(superuser)
        data["build"].status = "error"
        data["build"].traceback = "This is the stacktrace."
        data["build"].save()

        url = reverse("build_detail", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 200
        assert response.templates[0].name == "build/detail.html"
        assert "Stacktrace" in str(response.content)

    def test_build_detail__build_error_no_stacktrace(self, client, user, data):
        assign_perm("plan.view_builds", user, data["planrepo"])
        client.force_login(user)
        data["build"].status = "error"
        data["build"].traceback = "This is the stacktrace."
        data["build"].save()

        url = reverse("build_detail", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 200
        assert response.templates[0].name == "build/detail.html"
        # non-superusers shouldn't see a stacktrace
        assert "Stacktrace" not in str(response.content)

    def test_build_detail_flows(self, client, superuser, data):
        client.force_login(superuser)
        url = reverse("build_detail_flows", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 200

    def test_build_detail_tests(self, client, superuser, data):
        client.force_login(superuser)
        url = reverse("build_detail_tests", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 200

    def test_build_detail_rebuilds(self, client, superuser, data):
        client.force_login(superuser)
        url = reverse("build_detail_rebuilds", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 200

    def test_build_detail_org(self, client, superuser, data):
        client.force_login(superuser)
        url = reverse("build_detail_org", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 200

    def test_build_detail_org__rebuild(self, client, superuser, data):
        rebuild = RebuildFactory(build=data["build"])
        client.force_login(superuser)
        url = reverse(
            "build_detail_org",
            kwargs={"build_id": data["build"].id, "rebuild_id": rebuild.id},
        )
        response = client.get(url)

        assert response.status_code == 200

    def test_build_detail_org__permission_denied(self, client, user, data):
        # This permission is checked for in build_detail_base()
        assign_perm("plan.view_builds", user, data["planrepo"])
        client.force_login(user)
        url = reverse("build_detail_org", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 403

    def test_build_detail_qa(self, client, superuser, data):
        client.force_login(superuser)
        url = reverse("build_detail_qa", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 200

    def test_build_detail_qa__post(self, client, superuser, data):
        client.force_login(superuser)
        url = reverse("build_detail_qa", kwargs={"build_id": data["build"].id})
        response = client.post(url)

        assert response.status_code == 200

    def test_build_detail_qa__permission_denied(self, client, user, data):
        # This permission is checked for in build_detail_base()
        assign_perm("plan.view_builds", user, data["planrepo"])
        client.force_login(user)
        url = reverse("build_detail_qa", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 403

    def test_build_rebuild(self, client, superuser, data):
        client.force_login(superuser)
        url = reverse("build_rebuild", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 302

    def test_build_rebuild__permission_denied(self, client, user, data):
        client.force_login(user)
        url = reverse("build_rebuild", kwargs={"build_id": data["build"].id})
        response = client.get(url)

        assert response.status_code == 403

    def test_build_search(self, client, superuser, data):
        client.force_login(superuser)
        url = reverse("build_search")
        response = client.get(url, {"q": data["build"]})

        assert response.status_code == 200


text:
package com.ctrip.framework.apollo.internals;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctrip.framework.apollo.Apollo;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.ctrip.framework.apollo.util.http.HttpRequest;
import com.ctrip.framework.apollo.util.http.HttpResponse;
import com.ctrip.framework.apollo.util.http.HttpUtil;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.escape.Escaper;
import com.google.common.net.UrlEscapers;
import com.google.common.util.concurrent.RateLimiter;

/**
 * @author Jason Song(song_s@ctrip.com)
 */
public class RemoteConfigRepository extends AbstractConfigRepository {
  private static final Logger logger = LoggerFactory.getLogger(RemoteConfigRepository.class);
  private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
  private static final Joiner.MapJoiner MAP_JOINER = Joiner.on("&").withKeyValueSeparator("=");
  private ConfigServiceLocator m_serviceLocator;
  private HttpUtil m_httpUtil;
  private ConfigUtil m_configUtil;
  private RemoteConfigLongPollService remoteConfigLongPollService;
  private volatile AtomicReference<ApolloConfig> m_configCache;
  private final String m_namespace;
  private final static ScheduledExecutorService m_executorService;
  private AtomicReference<ServiceDTO> m_longPollServiceDto;
  private RateLimiter m_loadConfigRateLimiter;
  private static final Escaper pathEscaper = UrlEscapers.urlPathSegmentEscaper();
  private static final Escaper queryParamEscaper = UrlEscapers.urlFormParameterEscaper();

  static {
    m_executorService = Executors.newScheduledThreadPool(1,
        ApolloThreadFactory.create("RemoteConfigRepository", true));
  }

  /**
   * Constructor.
   *
   * @param namespace the namespace
   */
  public RemoteConfigRepository(String namespace) {
    m_namespace = namespace;
    m_configCache = new AtomicReference<>();
    m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
    m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
    m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
    remoteConfigLongPollService = ApolloInjector.getInstance(RemoteConfigLongPollService.class);
    m_longPollServiceDto = new AtomicReference<>();
    m_loadConfigRateLimiter = RateLimiter.create(m_configUtil.getLoadConfigQPS());
    this.trySync();
    this.schedulePeriodicRefresh();
    this.scheduleLongPollingRefresh();
  }

  @Override
  public Properties getConfig() {
    if (m_configCache.get() == null) {
      this.sync();
    }
    return transformApolloConfigToProperties(m_configCache.get());
  }

  @Override
  public void setUpstreamRepository(ConfigRepository upstreamConfigRepository) {
    //remote config doesn't need upstream
  }

  private void schedulePeriodicRefresh() {
    logger.debug("Schedule periodic refresh with interval: {} {}",
        m_configUtil.getRefreshInterval(), m_configUtil.getRefreshIntervalTimeUnit());
    m_executorService.scheduleAtFixedRate(
        new Runnable() {
          @Override
          public void run() {
            Tracer.logEvent("Apollo.ConfigService", String.format("periodicRefresh: %s", m_namespace));
            logger.debug("refresh config for namespace: {}", m_namespace);
            trySync();
            Tracer.logEvent("Apollo.Client.Version", Apollo.VERSION);
          }
        }, m_configUtil.getRefreshInterval(), m_configUtil.getRefreshInterval(),
        m_configUtil.getRefreshIntervalTimeUnit());
  }

  @Override
  protected synchronized void sync() {
    Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncRemoteConfig");

    try {
      ApolloConfig previous = m_configCache.get();
      ApolloConfig current = loadApolloConfig();

      //reference equals means HTTP 304
      if (previous != current) {
        logger.debug("Remote Config refreshed!");
        m_configCache.set(current);
        this.fireRepositoryChange(m_namespace, this.getConfig());
      }

      if (current != null) {
        Tracer.logEvent(String.format("Apollo.Client.Configs.%s", current.getNamespaceName()),
            current.getReleaseKey());
      }

      transaction.setStatus(Transaction.SUCCESS);
    } catch (Throwable ex) {
      transaction.setStatus(ex);
      throw ex;
    } finally {
      transaction.complete();
    }
  }

  private Properties transformApolloConfigToProperties(ApolloConfig apolloConfig) {
    Properties result = new Properties();
    result.putAll(apolloConfig.getConfigurations());
    return result;
  }

  private ApolloConfig loadApolloConfig() {
    if (!m_loadConfigRateLimiter.tryAcquire(5, TimeUnit.SECONDS)) {
      //wait at most 5 seconds
      try {
        TimeUnit.SECONDS.sleep(5);
      } catch (InterruptedException e) {
      }
    }
    String appId = m_configUtil.getAppId();
    String cluster = m_configUtil.getCluster();
    String dataCenter = m_configUtil.getDataCenter();
    Tracer.logEvent("Apollo.Client.ConfigMeta", STRING_JOINER.join(appId, cluster, m_namespace));
    int maxRetries = 2;
    Throwable exception = null;

    List<ServiceDTO> configServices = getConfigServices();
    for (int i = 0; i < maxRetries; i++) {
      List<ServiceDTO> randomConfigServices = Lists.newLinkedList(configServices);
      Collections.shuffle(randomConfigServices);
      //Access the server which notifies the client first
      if (m_longPollServiceDto.get() != null) {
        randomConfigServices.add(0, m_longPollServiceDto.getAndSet(null));
      }

      for (ServiceDTO configService : randomConfigServices) {
        String url =
            assembleQueryConfigUrl(configService.getHomepageUrl(), appId, cluster, m_namespace,
                dataCenter, m_configCache.get());

        logger.debug("Loading config from {}", url);
        HttpRequest request = new HttpRequest(url);

        Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "queryConfig");
        transaction.addData("Url", url);
        try {

          HttpResponse<ApolloConfig> response = m_httpUtil.doGet(request, ApolloConfig.class);

          transaction.addData("StatusCode", response.getStatusCode());
          transaction.setStatus(Transaction.SUCCESS);

          if (response.getStatusCode() == 304) {
            logger.debug("Config server responds with 304 HTTP status code.");
            return m_configCache.get();
          }

          ApolloConfig result = response.getBody();

          logger.debug("Loaded config for {}: {}", m_namespace, result);

          return result;
        } catch (ApolloConfigStatusCodeException ex) {
          ApolloConfigStatusCodeException statusCodeException = ex;
          //config not found
          if (ex.getStatusCode() == 404) {
            String message = String.format(
                "Could not find config for namespace - appId: %s, cluster: %s, namespace: %s, " +
                    "please check whether the configs are released in Apollo!",
                appId, cluster, m_namespace);
            statusCodeException = new ApolloConfigStatusCodeException(ex.getStatusCode(),
                message);
          }
          Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(statusCodeException));
          transaction.setStatus(statusCodeException);
          exception = statusCodeException;
        } catch (Throwable ex) {
          Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
          transaction.setStatus(ex);
          exception = ex;
        } finally {
          transaction.complete();
        }

      }

      try {
        m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(m_configUtil.getOnErrorRetryInterval());
      } catch (InterruptedException ex) {
        //ignore
      }
    }
    String message = String.format(
        "Load Apollo Config failed - appId: %s, cluster: %s, namespace: %s",
        appId, cluster, m_namespace);
    throw new ApolloConfigException(message, exception);
  }

  String assembleQueryConfigUrl(String uri, String appId, String cluster, String namespace,
                                String dataCenter, ApolloConfig previousConfig) {

    String path = "configs/%s/%s/%s";
    List<String> pathParams =
        Lists.newArrayList(pathEscaper.escape(appId), pathEscaper.escape(cluster),
            pathEscaper.escape(namespace));
    Map<String, String> queryParams = Maps.newHashMap();

    if (previousConfig != null) {
      queryParams.put("releaseKey", queryParamEscaper.escape(previousConfig.getReleaseKey()));
    }

    if (!Strings.isNullOrEmpty(dataCenter)) {
      queryParams.put("dataCenter", queryParamEscaper.escape(dataCenter));
    }

    String localIp = m_configUtil.getLocalIp();
    if (!Strings.isNullOrEmpty(localIp)) {
      queryParams.put("ip", queryParamEscaper.escape(localIp));
    }

    String pathExpanded = String.format(path, pathParams.toArray());

    if (!queryParams.isEmpty()) {
      pathExpanded += "?" + MAP_JOINER.join(queryParams);
    }
    if (!uri.endsWith("/")) {
      uri += "/";
    }
    return uri + pathExpanded;
  }

  private void scheduleLongPollingRefresh() {
    remoteConfigLongPollService.submit(m_namespace, this);
  }

  public void onLongPollNotified(ServiceDTO longPollNotifiedServiceDto) {
    m_longPollServiceDto.set(longPollNotifiedServiceDto);
    m_executorService.submit(new Runnable() {
      @Override
      public void run() {
        trySync();
      }
    });
  }

  private List<ServiceDTO> getConfigServices() {
    List<ServiceDTO> services = m_serviceLocator.getConfigServices();
    if (services.size() == 0) {
      throw new ApolloConfigException("No available config service");
    }

    return services;
  }
}


text:
NS_ASSUME_NONNULL_BEGIN

typedef void (^ABI44_0_0EXUpdatesAppLauncherCompletionBlock)(NSError * _Nullable error, BOOL success);

@protocol ABI44_0_0EXUpdatesAppLauncher

@property (nullable, nonatomic, strong, readonly) ABI44_0_0EXUpdatesUpdate *launchedUpdate;
@property (nullable, nonatomic, strong, readonly) NSURL *launchAssetUrl;
@property (nullable, nonatomic, strong, readonly) NSDictionary *assetFilesMap;
@property (nonatomic, assign, readonly) BOOL isUsingEmbeddedAssets;

@end

NS_ASSUME_NONNULL_END


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Streetview API: Simple example</title>

      <input type="button" onclick="toggleOverlay()" value="Toggle Tile Layer"/>


text:
//
//  DatePickerViewController.m
//  TODOList
//
//  Created by SMC-MAC on 17/3/14.
//  Copyright © 2017年 heyou. All rights reserved.
//

#import "DatePickerViewController.h"

@interface DatePickerViewController ()
- (IBAction)onValueChanged:(UIDatePicker *)sender;

@property (nonatomic, strong) NSDate* selDate;
@property (nonatomic, strong) NSDate* minDate;
@property (nonatomic, strong) NSDate* maxDate;

@end

@implementation DatePickerViewController

- (void)setSelectedDate:(NSDate*)selectedDate {
    [self setSelectedDate:selectedDate minDate:nil maxDate:nil];
}

- (void)setSelectedDate:(NSDate*)selectedDate minDate:(NSDate* _Nullable)minDate maxDate:(NSDate* _Nullable)maxDate {
    self.selDate   = selectedDate;
    self.minDate   = minDate;
    self.maxDate   = maxDate;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (self.selDate) {
        self.datePicker.date = self.selDate;
    }
    self.datePicker.minimumDate = self.minDate;
    self.datePicker.maximumDate = self.maxDate;

    self.datePicker.datePickerMode = self.pickerMode;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)onValueChanged:(UIDatePicker *)sender {
    if (self.onSelectDate) {
        self.onSelectDate(sender.date);
    }
}
@end


text:
![Imgur](https://i.imgur.com/so3NXVC.png)

Snowball Exam Tips
======

What did we learn?

* 3 Different types:

  * `Snowball` - pure storage. Comes in different sizes starting at 50 TB in the US; 80 TB outside the US
  * `Snowball Edge` -  storage + compute functionality-- mini AWS data center. lambda functions can be run locally
  * `Snowmobile` - 45 foot container arriving by truck.
      * Offers a 100 Petabytes of storage
      * Can come with security guards
      * Currently only available in the continental United States
      * Price available upon application

* Understand what Import/Export is; Snowball can
  * Import to S3
  * Export from S3

##

**[Previous Lab/Lecture](snowball.md) | [AWS (Root)](../readme.adoc) | [Next Lab/Lecture](../s3/s3-static-website.md)**


text:
using System;
using System.Threading.Tasks;
using BuiltToRoam;

namespace RealEstateInspector.Core
{
    public interface ISyncService
    {
        event EventHandler<DualParameterEventArgs<double, string>> Progress;
        Task Synchronise(bool waitForCompletion);
        Task ForceUpload();
        Task Cancel();
    }
}


text:
/*
*   (A)---------------(B)-------------(E)---------------(F)
*    |                 |               |                 |
*    |                 |               |                 |
*    |                 |               |                 |
*   (C)---------------(D)-------------(G)                |
*                      |                                 |
*                      -----------------------------------
*
*	7 Vertex
*	9 Edges
*
*/

class No {
    /**
     * @type {Number}
     */
    static MAX_VERTEX;
    /**
     * @type {Number}
     */
    static MAX_EDGES;

    static constructor() {
        this.setMaxVertex(7);
    }

    /**
     * @param {Number} n Max Vertex
     *
     * @description When setting the maximum vertex, the maximum edges are automatically calculated
     */
    static setMaxVertex(n) {
        this.MAX_VERTEX = n;
        this.MAX_EDGES = (n * (n - 1));
    }

    /**
     * @type {Array<No>}
     */
    noNeighbors;

    /**
     * @param {Number|String} id
     */
    constructor(id) {
        this.id = id;
        this.numberNeighbors = 0;
        this.visited = false;
        this.noNeighbors = [];
    }

    /**
     * @param {No} vertexCurrent
     * @param {No} vertexNeighbor
     */
    static linkVertex(vertexCurrent, vertexNeighbor) {
        // Adds the new neighbor to the list of neighbors
        vertexCurrent.noNeighbors.push(vertexNeighbor);
        vertexCurrent.numberNeighbors++;

        vertexNeighbor.noNeighbors.push(vertexCurrent);
        vertexNeighbor.numberNeighbors++;
    }
}

class GraphSearch {

    /**
     * In-Depth Search - DFS - Depth First Search
     * Cycles through all neighbors that were first connected to the vertex
     *
     * @param {No} vertexOrigin
     * @param {No} vertexDestiny
     * @param {Number} visited Position visited
     *
     * @returns {number} -1 Not found destiny or depth position value
     */
    inDepthSearch(vertexOrigin, vertexDestiny, visited) {
        vertexOrigin.visited = true;

        // If it is the desired destination, it will return
        if (vertexOrigin.id === vertexDestiny.id) return visited;

        let aux = 0;

        // While there is neighbor
        while (vertexOrigin.noNeighbors[aux]) {
            if (vertexOrigin.noNeighbors[aux].visited === false) {
                // Recursively calls passing a new neighbor as a start, that is, it will go through all its neighbors, and so on, successively
                const result = this.inDepthSearch(vertexOrigin.noNeighbors[aux], vertexDestiny, visited + 1);

                // If the result is different from -1, then the target value was found
                if (result !== -1) return result;

            }

            // Next of list
            aux++;
        }

        // Vertex not found
        return -1;
    }

    /**
     *
     * @param {No} vertexOrigin
     * @param {No} vertexDestiny
     *
     * @returns {number} -1 Not found destiny or depth position value
     */
    widthSearch(vertexOrigin, vertexDestiny) {
        let startQueue = 0;
        let lengthQueue = 1;

        /**
         * @type {Array<No>} Vertex queue be compared
         */
        let queue = new Array(No.MAX_VERTEX);
        queue[startQueue] = vertexOrigin;

        while (startQueue < lengthQueue) {
            // If it is the desired destination, it will return
            if (queue[startQueue].id === vertexDestiny.id) return startQueue;

            /*
            * For all neighbors of the vertex that is about to 'exit' the queue:
            * Mark everyone as visited, so as not to put them in the queue again, and then put them in the queue, and increase the size of the queue.
            */
            for (let i = 0; i < queue[startQueue].numberNeighbors; i++) {
                const vertexCurrent = queue[startQueue];
                if (!vertexCurrent.noNeighbors[i].visited) {
                    vertexCurrent.noNeighbors[i].visited = true;
                    queue[lengthQueue] = vertexCurrent.noNeighbors[i];
                    lengthQueue++;
                }
            }

            // Increments 1 at the beginning of the queue, as if it excluded the first one who entered the queue (FIFO - First In First Out)
            startQueue++;
        }

        return -1;
    }
}

function main() {
    // Graph - set of independent vertices
    let A = new No('A');
    let B = new No('B');
    let C = new No('C');
    let D = new No('D');
    let E = new No('E');
    let F = new No('F');
    let G = new No('G');

    // Connects all vertex according to the GRAPH shown in the introduction
    No.linkVertex(A, B);
    No.linkVertex(A, C);
    No.linkVertex(B, D);
    No.linkVertex(B, E);
    No.linkVertex(C, D);
    No.linkVertex(D, F);
    No.linkVertex(D, G);
    No.linkVertex(E, F);
    No.linkVertex(E, G);

    const graphSearch = new GraphSearch();

    let distance = graphSearch.inDepthSearch(A, G, 0);
    if (distance !== -1)
        console.log(`DFS - Distance: ${distance}`);
    else
        console.log("DFS - Not found.");

    // Clears all visits
    A.visited = false;
    B.visited = false;
    C.visited = false;
    D.visited = false;
    E.visited = false;
    F.visited = false;
    G.visited = false;

    distance = graphSearch.widthSearch(A, G);
    if (distance !== -1)
        console.log(`BFS - Distance: ${distance}`);
    else
        console.log("BFS - Not found.");
}

main();


text:
/*home View-Model*/
var home = (function (window, $, ko, app, undefined) {

	'use strict';

	/**
	 * view{} is initialized to be the main object literal of home view.
	 *
	*/
	var view = {

		observables : {
			initial : {
				content : {
					h1 : {text : 'SPA Prototyping Boilerplate for KnockoutJS / Index'},
					p : {text : 'This is a KnockoutJS boilerplate code for Prototyping a Single-Page Application.'},
					a : {text : 'Go Home'}
				}
			},
			content : {
				h1 : {text : ''},
				p : {text : ''},
				a : {text : ''}
			}
		},

		el : {
			wrapper : document.getElementById('js-vm-index')
		},

		/**
		 * applyBinding() binds view-model for the specific view.
		 *
		*/
		applyBinding : function () {
			app.applyBinding('index', view, view.el.wrapper);
		},

		/**
	   * init can be used to init other view-models which is not initialized.
		*/
		init : function () {
			view.applyBinding();
		}

	};

	/**
	 * DOMContentLoaded waits until the whole content loaded.
	 *
	*/
	window.addEventListener("DOMContentLoaded", function() {
		view.init();
  }, false);

	return {
		view : view
	}

})(window, jQuery, ko, app);


text:
#ifndef ROBO_H
#define ROBO_H

#include "tipoEstruturas.hpp"
#include "roteiro.hpp"
#include <cstring>
#include <bitset>
#include <cmath>

#define MASSA_ROBO 0.89
#define RAIO_DA_RODA 1.6
#define RAIO_DISTANCIA 5
#define DIST_ENTRE_RODAS 7
#define TAM_ROBO 8 //tamanho do lado do robo em cm

enum INDEX_ATRIBUTOS {
	CHUTE_GIRANDO_HORARIO,
	CHUTE_GIRANDO_ANTI_HORARIO,
	CHUTANDO,

	/* Adicionar os novos atributos antes de BITSET_SIZE */
	BITSET_SIZE
};

class Robo {
    estadoRobo estadoAtualRobo; /**< Todas as informacoes atuais sobre o robo. */
    estadoRobo estadoPrevRobo; /**< Todas as informacoes sobre as posicoes futuras do robo. */
    estadoRobo estadoObjRobo; /**< Informações sobre o objetivo do robo. */

    ROTEIROS tipoJogador; // identificao de qual roteiro esta sendo seguido pelo robo no momento.

    friend class Comportamento;
    friend class Roteiro;

    public:
				std::bitset<BITSET_SIZE> atributos; /**< bitset sinalizando se os atributos do robo */

        /*************************** CONSTRUTOR *************************/
        // inicializa todas as componentes do robo com zero e define o roteiro atual do robo como "INDEFINIDO".
        Robo();
        /****************************************************************/

        /***************************** GETTERS **************************/

        /************************ POSICAO ATUAL ROBO ********************/
        // Retorna as coordenadas do robo.
        posXY getPosicaoAtualRobo ();

        // Retorna as componentes de movimentacao do robo.
        vetorSentido getVetorSentidoAtualRobo ();

        // Retorna o angulo do robo.
        float getAnguloAtualRobo ();

        // Retorna a velocidade do robo.
        velocidadeRobo getVelocidadeAtualRobo ();
        /****************************************************************/

        /********************* POSICAO PREVISTA ROBO ********************/
        // Retorna as coordenadas previstas do robo.
        posXY getPosicaoPrevRobo ();

        // Retorna as componentes de movimentacao previstas do robo.
        vetorSentido getVetorSentidoPrevRobo ();

        // Retorna o angulo previsto do robo.
        float getAnguloPrevRobo ();

        // Retorna a velocidade prevista do robo.
        velocidadeRobo getVelocidadePrevRobo ();
        /****************************************************************/

        /************************ OBJETIVO DO ROBO **********************/
        // Retorna a velocidade esperada quando chegar no objetivo.
        velocidadeRobo getVelocidadeAtualObj ();

        // Retorna a posicao do objetivo do  robo.
        posXY getPosicaoObj ();

        // Retorna o angulo esperado do robo quando chegar no objetivo.
        float getAnguloObj ();
        /****************************************************************/

				/*********************** FUNCAO ROTEIRO *************************/
        /* Define o identificador de roteiro do robo */
        ROTEIROS getRoteiro();
				/****************************************************************/

				/*********************** CALCULO DISTANCIAS *************************/
				/* retorna a distancia entre o Objetivo e o Robo (posObj - posRobo)*/
				posXY getDistObjRobo();
				void getDistObjRobo(posXY& dist);

				/* retorna a distancia euclidiana entre o Objetivo e o Robo */
				double getDistEuclianaObjRobo();

				// Checa se o robo está com a bola logo a frente.
				bool isRoboComBola(const posXY posicao, int raio);

				// Checa se a bola está no intervalo y do robô.
				bool Robo::isBolaNoIntervaloYRobo(const posXY posicao);
				/****************************************************************/

        /***************************** SETTERS **************************/

        /************************ POSICAO ATUAL ROBO ********************/
        // Define a posicao XY do robo.
        void setPosicaoAtualRobo (const posXY posicao);
        void setPosicaoAtualRobo (const float x, const float y);

        // Define o vetor de sentido de deslocamento do robo.
        void setVetorSentidoAtualRobo(const vetorSentido vetor);
        void setVetorSentidoAtualRobo(const float vetorX, const float vetorY);

        // Define o angulo atual do robo.
        void setAnguloAtualRobo (const float angulo);

        // Define a velocidade de cada roda do robo.
        void setVelocidadeAtualRobo (const velocidadeRobo velocidade);
        void setVelocidadeAtualRobo (const unsigned char velRodaEsq, const unsigned char velRodaDir);
        /****************************************************************/

        /********************* POSICAO PREVISTA ROBO ********************/
        // Define as coordenadas previstas do robo.
        void setPosicaoPrevRobo (const posXY posicao);
        void setPosicaoPrevRobo (const float x, const float y);

        // Define as componentes de movimentacao previstas do robo.
        void setVetorSentidoPrevRobo (const vetorSentido vetor);
        void setVetorSentidoPrevRobo(const float x, const float y);

        // Define o angulo previsto do robo.
        void setAnguloPrevRobo (const float angulo);

        // Define a velocidade prevista do robo.
        void setVelocidadePrevRobo (const velocidadeRobo velocidade);
        void setVelocidadePrevRobo (const unsigned char velRodaEsq, const unsigned char velRodaDir);
        /****************************************************************/

        /************************ OBJETIVO DO ROBO **********************/
        // Define a posicao objetivo do robo.
        void setPosicaoObj (const posXY posicao);
        void setPosicaoObj (const float x, const float y);

        // Define o angulo de chegada do robo no objetivo.
        void setAnguloObj (const float angulo);

        // Define a velocidade de chegada do robo no objetivo.
        void setVelocidadeObj(const velocidadeRobo velocidade);
        void setVelocidadeObj (const unsigned char velRodaEsq, const unsigned char velRodaDir);
        /****************************************************************/

        /*********************** FUNCAO ROTEIRO *************************/
        /* Define o identificador de roteiro do robo */
        void setRoteiro(ROTEIROS r);
				/****************************************************************/

				/*********************** ESTADOS DO ROBO *************************/
				/* define o estado atual como sendo o estado previsto (faz a copia das variaveis de estadoPrevRobo para estadoAtualRobo) */
				void setEstadoAtualComoEstadoPrev();

				/* define o estado atual como sendo o estado no objetivo (faz a copia das variaveis de estadoObjRobo para estadoAtualRobo) */
				void setEstadoAtualComoEstadoObj();

				/* definie o estado previsto como sendo o estado atual (faz a copia das variaveis de estadoAtualRobo para estadoPrevRobo) */
				void setEstadoPrevComoEstadoAtual();

				/* define o estado previsto como sendo o estado no objetivo (faz a copia das variaveis de estadoAtualRobo para estadoPrevRobo) */
				void setEstadoPrevComoEstadoObj();
				/****************************************************************/

        /* Corre o roteiro determinado por tipo_jogador */
        void run();
};

#endif /* ROBO_H */


text:
<!DOCTYPE html>
<html lang="en">

{% include head.html %}

<body id="page-top">
  {% include nav.html %}
  <header class="header-nav"></header>
  {{ content }}
  {% include contact.html %}
  {% include scripts.html %}
</body>

</html>


text:
DPPL
====
Discriminative Probabilistic Prototype Learning (DPPL).
Implements the Discriminative Probabilistic Prototype Learning framework of Bonilla and and Robles-Kelly (ICML, 2012).

Author:
-----
Edwin V. Bonilla
Last update: April 17th, 2013

Main Contents
-----------
1. learn_dppl.m: Learns the DPPL model.
2. predict_dppl.m:  Makes predictions on new data-points for the DPPL model.
3. test_dppl.m: A toy example demonstrating the use of the DPPL package

References
-----------
[1] Edwin V. Bonilla,  and Antonio Robles-Kelly.
Discriminative Probabilistic Prototype Learning.
International Conference on Machine Learning (ICML), 2012.


text:
'''Reads the Webkit Version.xcconfig file looking for MAJOR_VERSION and
MINOR_VERSION, emitting them into a webkit_version.h header file as
WEBKIT_MAJOR_VERSION and WEBKIT_MINOR_VERSION macros.
'''

import os
import re
import sys

def ReadVersionFile(fname):
  '''Reads the Webkit Version.xcconfig file looking for MAJOR_VERSION and
     MINOR_VERSION.  This function doesn't attempt to support the full syntax
     of xcconfig files.'''
  re_major = re.compile('MAJOR_VERSION\s*=\s*(\d+).*')
  re_minor = re.compile('MINOR_VERSION\s*=\s*(\d+).*')
  major = -1
  minor = -1
  f = open(fname, 'rb')
  line = "not empty"
  while line and not (major >= 0 and minor >= 0):
    line = f.readline()
    if major == -1:
      match = re_major.match(line)
      if match:
        major = int(match.group(1))
        continue
    if minor == -1:
      match = re_minor.match(line)
      if match:
        minor = int(match.group(1))
        continue
  assert(major >= 0 and minor >= 0)
  return (major, minor)

def EmitVersionHeader(version_file, output_dir):
  '''Given webkit's version file, emit a header file that we can use from
  within webkit_glue.cc.
  '''
  (major, minor) = ReadVersionFile(version_file)
  fname = os.path.join(output_dir, "webkit_version.h")
  f = open(fname, 'wb')
  template = """// webkit_version.h
// generated from %s

#define WEBKIT_VERSION_MAJOR %d
#define WEBKIT_VERSION_MINOR %d
""" % (version_file, major, minor)
  f.write(template)
  f.close()

def main():
  EmitVersionHeader(sys.argv[1], sys.argv[2])

if __name__ == "__main__":
  main()


text:
InteractiveElement::InteractiveElement(){

}

void InteractiveElement::_draw(){
    mybox.set(width, height, 100);
    mybox.drawFaces();

}
void InteractiveElement::_drawForPicking(){
    mybox.drawFaces();
}

void InteractiveElement::onTap(MultiTouchEvent& e){
    rotateTo(ofRandom(0,360), ofRandom(0,360), ofRandom(0,360), 500);
}