text:
import csnGenerator

import copy
from csnVersion import Version
from csnProject import GenericProject, ThirdPartyProject
import csnProject
from csnStandardModuleProject import StandardModuleProject
import os.path
import csnUtility
import types
import new

def _UnwrapProject(project):
    """ Unwrap a project from an input method or API project to a GenericProject. """
    if type(project) == types.FunctionType:
        project = project()
    if isinstance(project, _APIVeryGenericProject_Base):
        project = project._APIVeryGenericProject_Base__project
    return project

def _UnwrapProjectAndCustomMemberFunctions(project):
    """ Unwrap a project from an input method or API project to a GenericProject
    and return its custom member functions.
    """
    if type(project) == types.FunctionType:
        project = project()
    customMemberFunctions = None
    if isinstance(project, _APIVeryGenericProject_Base):
        customMemberFunctions = project._APIVeryGenericProject_Base__customMemberFunctions
        project = project._APIVeryGenericProject_Base__project
    return (customMemberFunctions, project)

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

class _APIVeryGenericProject_Base:
    """ Base class for the very generic project interface. """

    def __init__(self, project, apiVersion):
        """
        Constructor.
        project - The project to wrap
        apiVersion - The version of the API
        """
        # Note: As the class _APIStandardModuleProject_2_5_0 uses multiple inheritance and derives in two ways from this
        # class, it is possible that this constructor is called two times. This wouldn't hurt in its current
        # implementation. If you plan to change this constructor, make sure it won't hurt after your change, either.
        self.__project = project
        self.__apiVersion = apiVersion
        self.__customMemberFunctions = dict()

    def GetName(self):
        """ Returns the project name defined when creating the project. """
        return self.__project.name

    def AddProjects(self, projects, dependency = True, includeInSolution = True):
        """
        Connect other projects to this project. The semantics of this operations depends of the parameters "dependency" and "includeInSolution".
        projects   - List of projects to connect.
        dependency - If true, then the projects in the list "projects" are dependency of the reference project. The public
                     include folders of the projects in "projects" are added to the include paths of the reference project.
                     The reference project is linked against the libraries created by the projects in "projects".
                     If false, then none of the before-mentioned happens, but instead the projects in "projects" will
                     appear in the "Select Projects" tab of the GUI as suggestions, whenever the reference project is to
                     be compiled. The user can then decide, if he wants to compile those additional, suggested projects, too.
        includeInSolution - Determines, if the projects in "projects" will appear in the solution, so the user can easily
                            edit source files of those projects. If false, the projects will still be compiled, but won't
                            appear in the solution.
        """
        # unwrap the input projects before adding them
        unwrapped = map(_UnwrapProject, projects)
        # GenericProject.AddProjects only wants GenericProjects
        self.__project.AddProjects(unwrapped, dependency, includeInSolution)

    def GetBuildFolder(self):
        """ Returns the build folder, where the compile configuration and intermediate files of this project's compilation are stored. """
        return self.__project.GetBuildFolder()

    def AddFilesToInstall(self, filesToInstall, location = None, debugOnly = 0, releaseOnly = 0):
        """
        Registers files to be copied when doing "Install files to build folder". "debugOnly" and "releaseOnly" cannot
        be True at the same time.
        filesToInstall - A list of files to be copied
        location       - Folder to copy the files to
        debugOnly      - if True, the file is copied only to the configuration in Debug mode
        releaseOnly    - if True, the file is copied only to the configuration in Release mode
        """
        self.__project.AddFilesToInstall(filesToInstall, location, debugOnly, releaseOnly, True, True)

    def Glob(self, path):
        """
        Returns a list of files/directories matching the wildcard expression given by "path".
        path - Wildcard expression determining the result files (relativ to the project source directory)
        """
        return self.__project.Glob(path)

    def AddCustomMemberFunction(self, name, function):
        """
        Add a member function to the project object. The function will also be maintained, if the project object is
        rewrapped to another API version (then it is copied to the new wrapper, too). In the case of rewrapping the
        API version of the "self" object will always be the original one.
        Example usage: After doing "project.AddCustomMemberFunction("myCustomFunc", testFunc)" you will be able to call
        "testFunc" like this: "project.testFunc(...)"
        name     - Name of the member function (the function will be called using this name)
        function - Function to be added as member function (has to have at least one parameter: the project)
        """
        # Bind the function to this object
        function = new.instancemethod(function, self)
        # Add it to object
        self.__dict__[name] = function
        # Remember the bound function (in order to transfer it to a rewrapped project, if necessary)
        self.__customMemberFunctions[name] = function

    def GetProjects(self, recursive = False, onlyRequiredProjects = False, includeSelf = False, applyFilter = True):
        """
        Get the dependencies of this project in a sorted array (dependencies before dependents).
        recursive - If True, all (including indirectly) connected projects are returned; if False, only the directly
                    connected projects are returned.
        onlyRequiredProjects - If True, only the required projects (that the reference project depends on) are returned;
                               if False, all connected projects (including "suggestions") are returned.
        includeSelf - If True, the reference project is included in the result list, otherwise not.
        applyFilter - If True, the project filter ("Select Projects" tab in the GUI) is applied, so connections to
                      deactivated projects (and therefore also transitive connections) are removed; if False, all
                      connected projects are returned, independently of their activation state.
        """
        projects = self.__project.dependenciesManager.GetProjects(_recursive = recursive,
            _onlyRequiredProjects = onlyRequiredProjects,
            _includeSelf = includeSelf,
            _onlyPublicDependencies = False,
            _onlyNonRequiredProjects = False,
            _filter = applyFilter)
        api = FindAPI(self.__apiVersion)
        return map(api.RewrapProject, projects)

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

class _APIGenericProject_Base(_APIVeryGenericProject_Base):
    """ Base class for the generic project interface. """

    def __init__(self, project, apiVersion):
        """
        Constructor.
        project - The project to wrap
        apiVersion - The version of the API
        """
        # Note: As the sub class uses multiple inheritance and derives in two ways from this
        # class, it is possible that this constructor is called two times. This wouldn't hurt in its current
        # implementation. If you plan to change this constructor, make sure it won't hurt after your change, either.
        _APIVeryGenericProject_Base.__init__(self, project, apiVersion)
        self.__project = project
        self.__apiVersion = apiVersion

    def AddSources(self, sources, sourceGroup = "Source Files", checkExists = 1, forceAdd = 0):
        """
        Adds source files to the project that will be compiled.
        sources     - List of source files
        sourceGroup - Name of the Visual Studio project sub folder (overrides default source/header folder if non-empty)
        checkExists - Check if the files really exist before adding them (throws an exception, if they don't exist)
        forceAdd    - Force the addition of the files even if they do not exist (needs 'checkExists' to be set to false).
        """
        self.__project.AddSources(sources, False, False, sourceGroup, checkExists, forceAdd)

    def GetSources(self):
        """
        Returns a list of source files compiled by this project. Don't call this, if not absolutely necessary,
        this will substantially slow down the loading of CSnake instances.
        """
        return self.__project.GetSources()

    def SetPrecompiledHeader(self, precompiledHeader):
        """ Sets the filename of the precompiled header for the project. """
        self.__project.SetPrecompiledHeader(precompiledHeader)

    def AddIncludeFolders(self, includeFolders):
        """ Adds an include folder to the project. """
        self.__project.AddIncludeFolders(includeFolders, True, True)

    def AddProperties(self, properties):
        """
        A list of custom properties for the target that will be added using the CMake macro ADD_PROPERTY
        properties - A list of properties in the format of the macro ADD_PROPERTY
        """
        self.__project.AddProperties(properties)

    def AddDefinitions(self, listOfDefinitions, private = 0):
        """
        Adds a list of definitions to the project.
        listOfDefinitions - A list of the definitions to add to the project in the format of the CMake macro ADD_DEFINITIONS
        """
        self.__project.AddDefinitions(listOfDefinitions, private, True, True)

    def AddLibraries(self, libraries, debugOnly = 0, releaseOnly = 0):
        """
        Adds additional external libraries that this project has to link against; debugOnly and releaseOnly are not
        allowed to be True at the same time.
        debugOnly   - if True, only the debug version of the project is linked against the given libraries
        releaseOnly - if True, only the release version of the project is linked against the given libraries
        """
        self.__project.AddLibraries(libraries, True, True, debugOnly, releaseOnly)

    def AddTests(self, tests, cxxTestProject, enableWxWidgets = 0, dependencies = None, pch = ""):
        """
        Add tests to the project.
        tests - List of source files containing cxx test classes
        cxxTestProject - Project representing the CXXTEST thirdparty library
        enableWxWidgets - Enable wxWidgets in the tests.
        """
        testProject = _UnwrapProject(cxxTestProject)
        self.__project.AddTests(tests, testProject, enableWxWidgets, dependencies, pch)

    def GetTestProject(self):
        """ Returns the project that compiles all automatic tests for this project, so the user can modify its properties, if necessary. """
        testProject = self.__project.testProject
        if testProject:
            return _FindAPIGenericProjectConstructor(self.__apiVersion)(testProject, self.__apiVersion)
        else:
            raise APIError("No test present!")

    def GenerateWin32Header(self, generate = True):
        """ Determines, if a header file with import/export definitions for Windows DLLs has to be generated. """
        self.__project.SetGenerateWin32Header(generate)

    def AddCustomCommand(self, command):
        """
        Registers a function that will be executed when configuring this project.
        command - The callback function that is executed, when the reference project is configured
        """
        self.__project.AddCustomCommand(command)

    def CreateHeader(self, filename = None, variables = None, variablePrefix = None):
        """
        Creates a configuration header file in the build directory of the project, where it can be found by the
        project itself and dependent projects.
        filename - file name of the header file
        variables - map of variable names (string) to values (string) that are defined as C preprocessor defines in
                    the header file; in addition to the variables given here the source and build folders of the
                    reference project are defined
        variablePrefix - prefix for the variable names given in the parameter "variables" to avoid name conflicts; if
                         none is given then the project name (modified to be suitable as C preprocessor variable name)
                         is used as prefix
        """
        self.__project.CreateHeader(filename, variables, variablePrefix)

    def AddCMakeInsertBeforeTarget(self, callback, parameters = {}):
        """
        Registers a callback function that is called when writing the project's CMakeLists.txt and that can return
        a text as string that is included in the CMakeLists.txt before this project's target.
        callback   - callback function to be called when writing the CMakeLists.txt
        parameters - optional set of parameters to pass to the callback function (map: parameter-name -> value); in
                     addition to them the reference project is given to the callback function as first parameter, wrapped
                     with the API version with that this function was called
        """
        self.__project.AddCMakeInsertBeforeTarget(callback, self, parameters)

    def AddCMakeInsertAfterTarget(self, callback, parameters = {}):
        """
        Registers a callback function that is called when writing the project's CMakeLists.txt and that can return
        a text as string that is included in the CMakeLists.txt after this project's target.
        callback   - callback function to be called when writing the CMakeLists.txt
        parameters - optional set of parameters to pass to the callback function (map: parameter-name -> value); in
                     addition to them the reference project is given to the callback function as first parameter, wrapped
                     with the API version with that this function was called
        """
        self.__project.AddCMakeInsertAfterTarget(callback, self, parameters)

    def AddPostCMakeTasks(self, tasks):
        """
        Registers a list of functions that will be executed after executing CMake.
        tasks - A list of callback functions that will be executed after executing CMake. The first parameter of this
                function call will be the reference project (wrapped in the same API version as when calling this
                function), the second one an object that can be used to ask question to the user.
        """
        tasksWithWrappedProject=[]
        for task in tasks:
            tasksWithWrappedProject.append(lambda _, askUser : task(self, askUser))
        self.__project.AddPostCMakeTasks(tasksWithWrappedProject)

    def GetBuildResultsFolder(self, configurationName):
        """
        Returns the directory in which the resulting library/application (whatever the linking result is) will be created
        configurationName - "Debug" or "Release"
        """
        if configurationName:
            return self.__project.GetBuildResultsFolder(configurationName)
        else:
            return self.__project.GetBuildResultsFolder()

    def SetBuildResultsSubFolder(self, subfolder):
        """
        Sets a sub-folder of the global build results ("bin/bin") folder as build results folder for this project.
        """
        self.__project.installSubFolder = subfolder

class _APIGenericProject_2_5_0(_APIGenericProject_Base):
    """ Implementation of the generic project interface for version 2.5.0. """

    def __init__(self, project, apiVersion):
        """
        Constructor.
        project - The project to wrap
        apiVersion - The version of the API
        """
        _APIGenericProject_Base.__init__(self, project, apiVersion)
        self.__project = project

class _APIGenericProject_2_7_0(_APIGenericProject_2_5_0):
    """ Implementation of the generic project interface for version 2.5.0. """

    def __init__(self, project, apiVersion):
        """
        Constructor.
        project - The project to wrap
        apiVersion - The version of the API
        """
        _APIGenericProject_Base.__init__(self, project, apiVersion)
        self.__project = project

    def AddLibraryFolders(self, libraryFolders):
        """ Adds a library folder to the project """
        self.__project.AddLibraryFolders(libraryFolders, True, True)

    def AddCMakeInsertBeginning(self, callback, parameters = {}):
        """
        Registers a callback function that is called when writing the project's CMakeLists.txt and that can return
        a text as string that is included in the CMakeLists.txt relatively early (guaranteed before including
        other projects or this project itself).
        callback   - callback function to be called when writing the CMakeLists.txt
        parameters - optional set of parameters to pass to the callback function (map: parameter-name -> value); in
                     addition to them the reference project is given to the callback function as first parameter, wrapped
                     with the API version with that this function was called
        """
        self.__project.AddCMakeInsertBeginning(callback, self, parameters)

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

class _APIStandardModuleProject_Base(_APIGenericProject_Base):
    """ Base class for the standard module project interface. """

    def __init__(self, project, apiVersion):
        """
        Constructor.
        project - The project to wrap
        apiVersion - The version of the API
        """
        _APIGenericProject_Base.__init__(self, project, apiVersion)
        self.__project = project

    def AddApplications(self, modules, pch = "", applicationDependenciesList = None, holderName = None, properties = []):
        """
        Creates extra CSnake projects, each project building one application in the 'Applications' subfolder of the
        current project.
        modules - List of the subfolders within the 'Applications' subfolder that must be scanned for applications
        pch - If not "", this is the include file used to generate a precompiled header for each application
        applicationDependenciesList - List of dependencies for the applications that are not yet covered by the
                                      dependencies of the library itself
        holderName - Applications' name prefix.
        properties - A list of properties in the format of the macro ADD_PROPERTY for the application projects.
        """
        self.__project.AddApplications(modules, pch, applicationDependenciesList, holderName, properties)

    def AddLibraryModules(self, modules):
        """
        Adds source files and public include folders to the project, using a set of libmodules. It is assumed that the
        root folder of self has a subfolder called libmodules. The subfolders of libmodules should contain a subfolder
        called src (e.g. for mymodule, this would be libmodules/mymodule/src). If the src folder has a subfolder called
        'stub', it is also added to the source tree.
        modules - A list of subfolders of the libmodules folder that should be added to the project.
        """
        self.__project.AddLibraryModules(modules)

class _APIStandardModuleProject_2_5_0(_APIStandardModuleProject_Base, _APIGenericProject_2_5_0):
    """ Implementation of the standard module project interface for version 2.5.0. """

    def __init__(self, project, apiVersion):
        """
        Constructor.
        project - The project to wrap
        apiVersion - The version of the API
        """
        _APIStandardModuleProject_Base.__init__(self, project, apiVersion)
        self.__project = project

class _APIStandardModuleProject_2_7_0(_APIStandardModuleProject_Base, _APIGenericProject_2_7_0):
    """ Implementation of the standard module project interface for version 2.5.0. """

    def __init__(self, project, apiVersion):
        """
        Constructor.
        project - The project to wrap
        apiVersion - The version of the API
        """
        _APIStandardModuleProject_Base.__init__(self, project, apiVersion)
        self.__project = project

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

class _APIThirdPartyProject_Base(_APIVeryGenericProject_Base):
    """ Base class for the third party project interface. """

    def __init__(self, project, apiVersion):
        """
        Constructor.
        project - The project to wrap
        apiVersion - The version of the API
        """
        _APIVeryGenericProject_Base.__init__(self, project, apiVersion)
        self.__project = project

    def SetUseFilePath(self, path):
        """
        Sets the path to the CMake-style use-file of this third party project. The file has to be created by the
        project's "CMakeLists.txt" during configuration of the third party folders.
        """
        self.__project.SetUseFilePath(path)

    def SetConfigFilePath(self, path):
        """
        Sets the path to the CMake-style config-file of this third party project. The file has to be created by the
        project's "CMakeLists.txt" during configuration of the third party folders.
        """
        self.__project.SetConfigFilePath(path)

class _APIThirdPartyProject_2_5_0(_APIThirdPartyProject_Base):
    """ Implementation of the third party project interface for version 2.5.0. """

    def __init__(self, project, apiVersion):
        """
        Constructor.
        project - The project to wrap
        apiVersion - The version of the API
        """
        _APIThirdPartyProject_Base.__init__(self, project, apiVersion)
        self.__project = project

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

class _APICompiler_Base:
    """ Base class for the compiler interface. """

    def __init__(self, compiler):
        """
        Constructor.
        compiler - The compiler object.
        """
        self.__compiler = compiler

    def GetName(self):
        """ Returns the name of the build system (e.g. "Unix Makefiles", "Visual Studio 7 .NET 2003") in CMake style. """
        return self.__compiler.GetName()

    def TargetIsWindows(self):
        """ Returns true, if the compilation target is a Windows platform, false if not. """
        return self.__compiler.IsForPlatform(_WIN32 = True, _NOT_WIN32 = False)

    def TargetIsUnix(self):
        """ Returns true, if the compilation target is a Unix-like platform (e.g. Linux, MacOSX), false if not. """
        return self.__compiler.IsForPlatform(_WIN32 = False, _NOT_WIN32 = True)

    def TargetIsLinux(self):
        """ Returns true, if the compilation target is a Linux platform, false if not. """
        return self.__compiler.TargetIsLinux()

    def TargetIsMac(self):
        """ Returns true, if the compilation target is a Mac platform, false if not. """
        return self.__compiler.TargetIsMac()

    def TargetIs32Bits(self):
        """ Returns true, if the compilation target is a 32 Bit platform, false if not. """
        return self.__compiler.TargetIs32Bits()

    def TargetIs64Bits(self):
        """ Returns true, if the compilation target is a 64 Bit platform, false if not. """
        return self.__compiler.TargetIs64Bits()

class _APICompiler_2_5_0(_APICompiler_Base):
    """ Implementation of the compiler interface for version 2.5.0. """

    def __init__(self, compiler):
        _APICompiler_Base.__init__(self, compiler)
        self.__compiler = compiler

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

class _APIVersion_Base:
    """ Base class for the version interface. """

    def __init__(self, version):
        """
        Constructor.
        version - The string representing a version number.
        """
        self.__version = version

    def GetString(self, numDecimals):
        """
        Returns the given version number as String in the format "1.13.7-beta".
        numDecimals - Determines the minimum of numbers to be displayed behind the first dot. Non-zero numbers are
                      always displayed, independently of the parameter given.
        """
        return self.__version.GetString(numDecimals)

    def __cmp__(self, other):
        """
        Compares the version number represented by the reference object with the version number in "other" and returns
        0, if they are equal; a negative number, if "other" is greater than the reference object; a positive number,
        if the reference object is greater than "other".
        """
        return self.__version.__cmp__(other.__version)

class _APIVersion_2_5_0(_APIVersion_Base):
    """ Implementation of the version interface for version 2.5.0. """

    def __init__(self, version):
        """
        Constructor.
        version -- The string representing a version number.
        """
        _APIVersion_Base.__init__(self, version)

## Current CSnake version
_currentCSnakeVersion = Version(csnGenerator.version)

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

class _API_Base:
    """ Base class for the main API interface. """

    def __init__(self, version):
        """
        Constructor.
        version - The version of the API
        """
        self.__version = version
        self.__genericProjectConstructor = _FindAPIGenericProjectConstructor(version)
        self.__standardModuleProjectConstructor = _FindAPIStandardModuleProjectConstructor(version)
        self.__thirdPartyProjectConstructor = _FindAPIThirdPartyProjectConstructor(version)
        self.__compilerConstructor = _FindAPICompilerConstructor(version)
        self.__compiler = None
        self.__versionConstructor = _FindAPIVersionConstructor(version)

    def CreateCompiledProject(self, name, projectType, sourceRootFolder = None, categories = None, showInProjectTree = False):
        """
        Creates a compiled project.
        name - Project name
        projectType - Type of the project: Can be "executable", "library" or "dll".
        sourceRootFolder - The main folder of the library (many subsequent operations take subdirectory parameters relative
                           to this directory); if None, the location of the CSnake file calling this function is used.
        categories - Hierarchy of categories for the project tree of the "Select Projects" tab
        showInProjectTree - If True, the project will be shown in the project tree of the "Select Projects" tab (if there
                            is a connection between the selected instance and this project) and can be deselected (if the
                            selected instance doesn't depend on this project). If False, the project is always compiled, if
                            there is a connection between the selected instance and this project.
        """
        if sourceRootFolder is None:
            filename = csnProject.FindFilename(1)
            dirname = os.path.dirname(filename)
            sourceRootFolder = csnUtility.NormalizePath(dirname, _correctCase = False)
        if categories:
            showInProjectTree = True
        project = GenericProject(name, projectType, sourceRootFolder, [name] if showInProjectTree else None, _context=csnProject.globalCurrentContext)
        if categories:
            superCategory = " / ".join(categories)
            project.context.SetSuperSubCategory(superCategory, name)
        return self.__genericProjectConstructor(project, self.__version)

    def CreateStandardModuleProject(self, name, projectType, sourceRootFolder = None, categories = None, showInProjectTree = False):
        """
        Creates a compiled project (see "CreateCompiledProject") with the additional modules "AddApplications" and "AddLibraryModules".
        """
        if sourceRootFolder is None:
            filename = csnProject.FindFilename(1)
            dirname = os.path.dirname(filename)
            sourceRootFolder = csnUtility.NormalizePath(dirname, _correctCase = False)
        if categories:
            showInProjectTree = True
        project = StandardModuleProject(name, projectType, sourceRootFolder, [name] if showInProjectTree else None)
        if categories:
            superCategory = " / ".join(categories)
            project.context.SetSuperSubCategory(superCategory, name)
        return self.__standardModuleProjectConstructor(project, self.__version)

    def CreateThirdPartyProject(self, name, sourceRootFolder = None):
        """
        Creates a new third party project (project that has its source in one of the third party source folders
        and that is compiled using a custom "CMakeLists.txt" file rather than CSnake files. The CSnake project returned
        by this function can then be used to point dependent projects to the config- and use-file of this third party
        project, so other projects are able to use the libraries.
        """
        if sourceRootFolder is None:
            filename = csnProject.FindFilename(1)
            dirname = os.path.dirname(filename)
            sourceRootFolder = csnUtility.NormalizePath(dirname, _correctCase = False)
        project = ThirdPartyProject(name, csnProject.globalCurrentContext, sourceRootFolder)
        return self.__thirdPartyProjectConstructor(project, self.__version)

    def RewrapProject(self, project):
        """
        Returns a new object containing the same project, but with functions of the referenced API version
        (instead of the API version that the project was created with).
        """
        # Remove the old wrapper
        (customMemberFunctions, project) = _UnwrapProjectAndCustomMemberFunctions(project)
        # Add a new wrapper (depending on the project type)
        if isinstance(project, GenericProject):
            project = self.__genericProjectConstructor(project, self.__version)
        elif isinstance(project, StandardModuleProject):
            project = self.__standardModuleProjectConstructor(project, self.__version)
        elif isinstance(project, ThirdPartyProject):
            project = self.__thirdPartyProjectConstructor(project, self.__version)
        else:
            raise APIError("Unknown project type: %s" % str(type(project)))
        # Add the custom member functions to the new wrapper
        if not (customMemberFunctions is None):
            for name, function in customMemberFunctions.items():
                # Note: No need to bind the function to the new project wrapper - it's better to pass the object using a
                #       wrapper of the API version with which the project was created
                project.__dict__[name] = function
            project._APIVeryGenericProject_Base__customMemberFunctions = copy.copy(customMemberFunctions)
        return project

    def CreateVersion(self, version):
        """ Create a version object from a String or Array in order to safely compare version numbers. """
        return self.__versionConstructor(Version(version))

    def GetCSnakeVersion(self):
        """ Returns the version number of the CSnake version used. """
        return copy.copy(_currentCSnakeVersion)

    def GetChosenAPIVersion(self):
        """ Returns the version number of the API used. """
        return copy.copy(self.__version)

    def LoadThirdPartyModule(self, subFolder, name):
        """
        Imports the CSnake file of a third party project.
        subFolder - Where to find the CSnake file, given relative to one of the third party source folders
        name - Name of the CSnake file (without .py) to load from the folder given above
        """
        return csnProject.LoadThirdPartyModule(subFolder, name)

    def GetCompiler(self):
        """ Returns an object containing information about the build system, compiler and target platform. """
        if not self.__compiler:
            self.__compiler = self.__compilerConstructor(csnProject.globalCurrentContext.GetCompiler())
        return self.__compiler

    def GetDummyCppFilename(self):
        """ Returns the filename of an empty cpp file. """
        return csnUtility.GetDummyCppFilename()

    def FindScriptFilename(self, level = 0):
        """
        Find the filename of the source code that is (directly or indirectly) calling this function.
        level - 0: Find filename of the script calling FindScriptFilename (default),
                1: Find filename of the script calling the function that calls FindScriptFilename,
                x: Find filename of the script calling FindScriptFilename indirectly through x+1 function calls
        """
        return csnProject.FindFilename(1+level)

    def FindSourceRootFolder(self, level = 0):
        """
        Find the folder containing the CSnake file that is (directly or indirectly) calling this function.
        level - see function FindScriptFilename
        """
        return csnUtility.NormalizePath(os.path.dirname(csnProject.FindFilename(1+level)))

class _API_2_5_0(_API_Base):
    """ Implementation of the main API interface for version 2.5.0. """

    def __init__(self, version):
        """
        Constructor.
        version - The version of the API
        """
        _API_Base.__init__(self, version)

######################
# Constructor Caches #
######################
# In order to not have to search and/or instantiate the same class over and over again,
# we maintain caches

## API constructors
_apiRegister = dict()

class APIError(Exception):
    """ API version compatibility error. """
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

def FindAPI(version):
    """Find a main API.
    version - The API version to look for
    """
    if not isinstance(version, Version):
        version = Version(version)
    if not version in _apiRegister:
        if version > _currentCSnakeVersion:
            raise APIError("Your CSnake version is too old to compile this code! Demanded API version: %s - CSnake version: %s"
                % (version.GetString(), _currentCSnakeVersion.GetString()))
        elif version >= Version([2, 5, 0, "beta"]):
            _apiRegister[version] = _API_2_5_0(version)
        else:
            # there was no API before this
            raise APIError("Unknown API version: %s" % version.GetString())
    return _apiRegister[version]

## GenericProject wrapper constructors
_apiGenericProjectConstructorRegister = dict()

def _FindAPIGenericProjectConstructor(version):
    """Find an _APIGenericProject constructor.
    version - The API version to look for
    """
    if not version in _apiGenericProjectConstructorRegister:
        if version > _currentCSnakeVersion:
            raise APIError("Your CSnake version is too old to compile this code!")
        elif version >= Version([2, 7, 0, "beta"]):
            _apiGenericProjectConstructorRegister[version] = _APIGenericProject_2_7_0
        elif version >= Version([2, 5, 0, "beta"]):
            _apiGenericProjectConstructorRegister[version] = _APIGenericProject_2_5_0
        else:
            # there was no API before this
            raise APIError("Unknown API version")
    return _apiGenericProjectConstructorRegister[version]

## StandardModuleProject wrapper constructors
_apiStandardModuleProjectConstructorRegister = dict()

def _FindAPIStandardModuleProjectConstructor(version):
    """Find an _APIStandardModuleProject constructor.
    version - The API version to look for
    """
    if not version in _apiStandardModuleProjectConstructorRegister:
        if version > _currentCSnakeVersion:
            raise APIError("Your CSnake version is too old to compile this code!")
        elif version >= Version([2, 7, 0, "beta"]):
            _apiStandardModuleProjectConstructorRegister[version] = _APIStandardModuleProject_2_7_0
        elif version >= Version([2, 5, 0, "beta"]):
            _apiStandardModuleProjectConstructorRegister[version] = _APIStandardModuleProject_2_5_0
        else:
            # there was no API before this
            raise APIError("Unknown API version")
    return _apiStandardModuleProjectConstructorRegister[version]

## ThirdPartyProject wrapper constructors
_apiThirdPartyProjectConstructorRegister = dict()

def _FindAPIThirdPartyProjectConstructor(version):
    """Find an _APIThirdPartyProject constructor.
    version - The API version to look for
    """
    if not version in _apiThirdPartyProjectConstructorRegister:
        if version > _currentCSnakeVersion:
            raise APIError("Your CSnake version is too old to compile this code!")
        elif version >= Version([2, 5, 0, "beta"]):
            _apiThirdPartyProjectConstructorRegister[version] = _APIThirdPartyProject_2_5_0
        else:
            # there was no API before this
            raise APIError("Unknown API version")
    return _apiThirdPartyProjectConstructorRegister[version]

## Version class constructors
_apiVersionConstructorRegister = dict()

def _FindAPIVersionConstructor(version):
    """Find an _APIVersion constructor.
    version - The API version to look for
    """
    if not version in _apiVersionConstructorRegister:
        if version > _currentCSnakeVersion:
            raise APIError("Your CSnake version is too old to compile this code!")
        elif version >= Version([2, 5, 0, "beta"]):
            _apiVersionConstructorRegister[version] = _APIVersion_2_5_0
        else:
            # there was no API before this
            raise APIError("Unknown API version")
    return _apiVersionConstructorRegister[version]

## Compiler wrapper constructors
_apiCompilerConstructorRegister = dict()

def _FindAPICompilerConstructor(version):
    """Find an _APICompiler constructor.
    version - The API version to look for
    """
    if not version in _apiCompilerConstructorRegister:
        if version > _currentCSnakeVersion:
            raise APIError("Your CSnake version is too old to compile this code!")
        elif version >= Version([2, 5, 0, "beta"]):
            _apiCompilerConstructorRegister[version] = _APICompiler_2_5_0
        else:
            # there was no API before this
            raise APIError("Unknown API version")
    return _apiCompilerConstructorRegister[version]


text:
MIME-Version: 1.0
Server: CERN/3.0
Date: Tuesday, 07-Jan-97 15:25:03 GMT
Content-Type: text/html
Content-Length: 8689
Last-Modified: Friday, 10-Nov-95 21:22:47 GMT

<TITLE>CS395T: Multimedia Communication and Databases </TITLE>

CS395T: Multimedia Communication and Databases

Fall 1995

Instructor: <!WA0> Harrick M. Vin

<!WA1>

 Table of Contents

 <!WA2> Course Description

 <!WA3> General Information

 <!WA4> Prerequisites

 <!WA5> Synopsis

 <!WA6> Textbook(s)

 <!WA7> Course Requirements

 <!WA8> Office Hours

 <!WA9> Reading List

 <!WA10> Multimedia Conferencing

 <!WA11> Routing and Multicasting

 <!WA12> Internet Services

 <!WA13> Processor Scheduling and OS Support

 <!WA14> Multimedia Databases

<!WA15>

 Course Description

 General Information

 Course Title:   CS395T: Multimedia Communication and Databases

 Instructor:   Professor Harrick M. Vin

 Semester:   Fall 1995

 Meeting Time:   Friday 10:00 - 1:00, TAY 3.144

 Prerequisites

Graduate standing, familiarity with basic concepts in network
protocols and operating system design, and the CS395T: Multimedia
Systems course.

 Synopsis

This is an advanced course in multimedia systems. Topics to be
discussed in this course include: transport protocol design for
multimedia, routing and multicasting, mobile networking and
multimedia, operating system support for multimedia, and multimedia
databases. An emphasis will be placed on current design issues and
research topics.

 Textbook(s)

A collection of research articles will be made available by the
instructor.

 Course Requirements

Students will be required to read a number of papers in the area as
well as present and discuss them in class. Grades will be determined
based on paper presentations and class participation. Students
enrolling for a letter grade will be required to submit a paper and/or
carry out a project.

 Office Hours

Friday 2:00 - 3:00, TAY 4.115B

 By appointment:  Phone: 471-9732, E-mail: vin@cs.utexas.edu

<!WA16>

 Reading List

 Multimedia Conferencing

S. McCanne and V. Jacobson, <!WA17> ``vic: A Flexible
Framework for Packet Video'', In  Proceedings of the ACM
Multimedia'95, San Francisco, CA., November 1995

M. Handley, I. Wakeman, and J. Crowcroft, ``The Conference Control
Channel Protocol (CCCP): A Scalable Base for Building Conference
Control Applications'', In  Proceedings of ACM SIGCOMM'95,
Boston, MA., 1995

H. Gajewska, J. Kistler, M. Manasse, and D. Redell, ``Argo: A System
for Distributed Collaborations'', In  Proceedings of the ACM
Multimedia'94, San Francisco, CA., November 1994

F. Gong, ``Multipoint Audio and Video Control for Packet-based
Multimedia Conferencing'', In  Proceedings of the ACM
Multimedia'94, San Francisco, CA., November 1994

H.M. Vin, P.T. Zellweger, D.C. Swinehart, and P. Venkat Rangan,
``Multimedia Conferencing in the Etherphone Environment'',  IEEE
Computer, Vol. 24, No. 10, October 1991

 Routing and Multicasting

S. Deering and D. Cheriton, ``Multicast Routing in Datagram
Internetworks and Extended LANS'',  ACM Transactions on Computer
Systems, Vol. 8, No. 2, Pages 85-110, May 1990

T. Ballardie, P. Francis, and J. Crowcroft, ``Core Based Trees
(CBT): An Architecture for Scalable Inter-Domain Multicast Routing'',
In  Proceedings of SIGCOMM'93 , Pages 85-95, 1993

A. Thyagarajan and S. E. Deering, <!WA18>
``Hierarchical Distance Vector Multicast Routing for the MBone'',
In  Proceedings of ACM SIGCOMM'95, Boston, MA., 1995

R. Widyono, <!WA19> ``The Design and
Evaluation of Routing Algorithms for Real-time Channels'', MS
Thesis, UC Berkeley, 1994

V. Kompella, J C. Pasquale, and G C. Polyzos, <!WA20> ``Multicast Routing for Multimedia
Communication'', Technical Report, University of California
at San Diego, 1994

S. Floyd, V. Jacobson, S. McCanne, L. Zhang, and C. Liu, <!WA21> ``A Reliable Multicast Framework for Light-weight
Sessions and Application Level Framing'', In  Proceedings of
ACM SIGCOMM'95, Boston, MA., 1995

H. W. Holbrook, S. K. Singhal and D. R. Cheriton, <!WA22> ``Log-Based Receiver-Reliable Multicast for
Distributed Interactive Simulation'', In  Proceedings of the
ACM SIGCOMM'95, Boston, MA., 1995

S. Herzog, D. Estrin and S. Shenker, <!WA23>
``Sharing the Cost of Multicast Trees: An Axiomatic Analysis'', In
 Proceedings of ACM SIGCOMM'95, Boston, MA., 1995

A. Gupta, W. Howe, M. Moran, and Q. Nguyen, <!WA24> ``Resource Sharing for multi-party real-time
communication'', In  Proceedings of Infocom'95. , 1995

 Internet Services

J. D. Guyton and M. F. Schwartz, <!WA25>
``Locating Nearby Copies of Replicated Internet Servers'', In
Proceedings of ACM SIGCOMM'95,  1995

J. C. Mogul, <!WA26> ``The Case for
Persistent-Connection HTTP'', In  Proceedings of ACM
SIGCOMM'95,  1995

 Processor Scheduling and OS Support

C. Warldersburg and W. E. Weihl, <!WA27> ``Lottery Scheduling: Efficient, Flexible
Proportional Share Resource Mangement'', In  Proceedings of
Operating System Design and Implementation (OSDI), 1994

C. Warldersburg and W. E. Weihl, <!WA28> ``Stride
Scheduling: Deterministic Proportional-Share Resource
Management'', Technical Report MIT/LCS/TM-528, 1995

S.J. Golestani, ``A Self-Clocked Fair Queueing Scheme for High Speed
Applications'', In  Proceedings of INFOCOM'94, 1994

R. Govindan and D.P. Anderson, ``Scheduling and IPC Mechanisms for
Continuous Media'', In  Proceedings of the ACM Symposium on
Operating Systems Principles (SOSP), Monterey, CA., 1991

K. Jeffay, <!WA29> ``The Real-Time
Producer/Consumer Paradigm: A paradigm for the construction of
efficient, predictable real-time systems'', In  Proceedings of
the ACM/SIGAPP Symposium on Applied Computing, 1993

K. Jeffay, <!WA30>``On latency Management in
Time-Shared Operating Systems'', In  11th Workshop on Real-Time
Operating Systems and Software, Seattle, May 1994

 Multimedia Databases

W. Niblack et al., ``The QBIC Project: Querying Images by Content
Using Color, Texture, and Shape'', IBM Technical Report, February 1993

A. Cawkell, ``Picture Queries and Picture Databases'', Journal of
Information Science, Vol. 19, Pages 409-423, 1993

J.R. Bach, S. Paul, and R. Jain, ``An Interactive Image Management
System for Face Information Retrieval'', IEEE Transaction on Knowledge
and Data Engineering, Vol. 5, No. 4, Pages 619-628, August 1993.

A. Gupta, T. Weymouth, and R. Jain, ``Semantic Queries with Pictures:
VIMSYS Model'', In Proceedings of 17th International Conference on
Very Large Databases, 1991

<!WA31>

<ADDRESS>
Harrick Vin

Thu Sep 14 10:37:26 CDT 1995
</ADDRESS>

redpajama_set_name: RedPajamaGithub


text:
package com.jpaquery.util;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 可合并的Map
 *
 * @author lujijiang
 *
 * @param <K>
 * @param <V>
 */
public class _MergeMap<K, V> extends AbstractMap<K, V> {

	/**
	 * 其它引用的Map
	 */
	Set<Map<K, V>> others = Collections.synchronizedSet(new LinkedHashSet<>());
	/**
	 * 自身Map
	 */
	Map<K, V> own = Collections.synchronizedMap(new LinkedHashMap<>());

	@Override
	public Set<K> keySet() {
		Set<K> keys = new LinkedHashSet<>();
		keys.addAll(own.keySet());
		for (Map<K, V> other : others) {
			keys.addAll(other.keySet());
		}
		return keys;
	}

	@Override
	public Set<java.util.Map.Entry<K, V>> entrySet() {

		final Set<K> keys = keySet();

		return new AbstractSet<java.util.Map.Entry<K, V>>() {

			@Override
			public Iterator<java.util.Map.Entry<K, V>> iterator() {
				return new Iterator<java.util.Map.Entry<K, V>>() {

					Iterator<K> iterator = keys.iterator();

					@Override
					public boolean hasNext() {
						return iterator.hasNext();
					}

					@Override
					public java.util.Map.Entry<K, V> next() {
						return new java.util.Map.Entry<K, V>() {

							K key = iterator.next();

							@Override
							public K getKey() {
								return key;
							}

							@Override
							public V getValue() {
								return get(key);
							}

							@Override
							public V setValue(V value) {
								throw new UnsupportedOperationException();
							}
						};
					}
				};
			}

			@Override
			public int size() {
				return keys.size();
			}
		};
	}

	@Override
	public V put(K key, V value) {
		V oldValue = null;
		for (Map<K, V> other : others) {
			if (other.containsKey(key)) {
				oldValue = other.put(key, value);
			}
		}
		if (own.containsKey(key)) {
			oldValue = own.get(key);
		}
		own.put(key, value);
		return oldValue;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void putAll(Map<? extends K, ? extends V> m) {
		others.add((Map<K, V>) m);
	}

	@Override
	public boolean containsKey(Object key) {
		if (own.containsKey(key)) {
			return true;
		}
		for (Map<K, V> other : others) {
			if (other.containsKey(key)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public V get(Object key) {
		if (own.containsKey(key)) {
			return own.get(key);
		}
		for (Map<K, V> other : others) {
			if (other.containsKey(key)) {
				return other.get(key);
			}
		}
		return null;
	}

	@Override
	public V remove(Object key) {
		V value = null;
		for (Map<K, V> other : others) {
			if (other.containsKey(key)) {
				value = other.remove(key);
			}
		}
		if (own.containsKey(key)) {
			value = own.remove(key);
		}
		return value;
	}
}


text:
<?php

namespace Sonata\NewsBundle\Block;

use Sonata\AdminBundle\Admin\Pool;
use Sonata\BlockBundle\Block\BlockContextInterface;
use Sonata\CoreBundle\Model\ManagerInterface;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Response;

use Sonata\AdminBundle\Form\FormMapper;
use Sonata\CoreBundle\Validator\ErrorElement;

use Sonata\BlockBundle\Model\BlockInterface;
use Sonata\BlockBundle\Block\BaseBlockService;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 *
 * @author     Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class RecentPostsBlockService extends BaseBlockService
{
    protected $manager;

    /**
     * @param string           $name
     * @param EngineInterface  $templating
     * @param ManagerInterface $manager
     * @param Pool             $adminPool
     */
    public function __construct($name, EngineInterface $templating, ManagerInterface $manager, Pool $adminPool = null)
    {
        $this->manager = $manager;
        $this->adminPool = $adminPool;

        parent::__construct($name, $templating);
    }

    /**
     * {@inheritdoc}
     */
    public function execute(BlockContextInterface $blockContext, Response $response = null)
    {
        $criteria = array(
            'mode' => $blockContext->getSetting('mode')
        );

        $parameters = array(
            'context'    => $blockContext,
            'settings'   => $blockContext->getSettings(),
            'block'      => $blockContext->getBlock(),
            'pager'      => $this->manager->getPager($criteria, 1, $blockContext->getSetting('number')),
            'admin_pool' => $this->adminPool
        );

        if ($blockContext->getSetting('mode') === 'admin') {
            return $this->renderPrivateResponse($blockContext->getTemplate(), $parameters, $response);
        }

        return $this->renderResponse($blockContext->getTemplate(), $parameters, $response);
    }

    /**
     * {@inheritdoc}
     */
    public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
    {
        // TODO: Implement validateBlock() method.
    }

    /**
     * {@inheritdoc}
     */
    public function buildEditForm(FormMapper $formMapper, BlockInterface $block)
    {
        $formMapper->add('settings', 'sonata_type_immutable_array', array(
            'keys' => array(
                array('number', 'integer', array('required' => true)),
                array('title', 'text', array('required' => false)),
                array('mode', 'choice', array(
                    'choices' => array(
                        'public' => 'public',
                        'admin'  => 'admin'
                    )
                ))
            )
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'Recent Posts';
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultSettings(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'number'     => 5,
            'mode'       => 'public',
            'title'      => 'Recent Posts',
//            'tags'      => 'Recent Posts',
            'template'   => 'SonataNewsBundle:Block:recent_posts.html.twig'
        ));
    }
}


text:
namespace WpfApplication
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
    }
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CIMEL.Splitter")]
[assembly: AssemblyDescription("CIMEL太阳光度计数据处理软件")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("北京宇星惠通科技有限公司")]
[assembly: AssemblyProduct("CIMEL太阳光度计数据处理软件")]
[assembly: AssemblyCopyright("Copyright ©  2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("07480d26-b97b-442e-9d6d-c4b38917a190")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.17019")]
[assembly: AssemblyFileVersion("1.1.0.17019")]
[assembly: NeutralResourcesLanguageAttribute("zh-CN")]


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- Automatically generated file. DO NOT MODIFY -->

</resources>


text:
package org.killbill.billing.plugin.meter.timeline.consumer;

import java.io.IOException;

import javax.annotation.Nullable;

import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunk;
import org.killbill.billing.plugin.meter.timeline.codec.SampleCoder;

public class CSVConsumer {

    private CSVConsumer() {}

    public static String getSamplesAsCSV(final SampleCoder sampleCoder, final TimelineChunk chunk) throws IOException {
        return getSamplesAsCSV(sampleCoder, chunk, null, null);
    }

    public static String getSamplesAsCSV(final SampleCoder sampleCoder, final TimelineChunk chunk, @Nullable final DateTime startTime, @Nullable final DateTime endTime) throws IOException {
        final CSVSampleProcessor processor = new CSVSampleProcessor(startTime, endTime);
        return getSamplesAsCSV(sampleCoder, chunk, processor);
    }

    public static String getSamplesAsCSV(final SampleCoder sampleCoder, final TimelineChunk chunk, final TimeRangeSampleProcessor rangeSampleProcessor) throws IOException {
        sampleCoder.scan(chunk, rangeSampleProcessor);
        return rangeSampleProcessor.toString();
    }
}


text:
#pragma once

#include <string>
#include <vector>

#include "source/extensions/filters/network/thrift_proxy/thrift.h"

#include "test/integration/integration.h"

namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace ThriftProxy {

/**
 * DriverMode represents the modes the test driver server modes.
 */
enum class DriverMode {
  // Server returns successful responses.
  Success,

  // Server throws IDL-defined exceptions.
  IDLException,

  // Server throws application exceptions.
  Exception,
};

struct PayloadOptions {
  PayloadOptions(TransportType transport, ProtocolType protocol, DriverMode mode,
                 absl::optional<std::string> service_name, std::string method_name,
                 std::vector<std::string> method_args = {},
                 std::vector<std::pair<std::string, std::string>> headers = {})
      : transport_(transport), protocol_(protocol), mode_(mode), service_name_(service_name),
        method_name_(method_name), method_args_(method_args), headers_(headers) {}

  std::string modeName() const;
  std::string transportName() const;
  std::string protocolName() const;

  const TransportType transport_;
  const ProtocolType protocol_;
  const DriverMode mode_;
  const absl::optional<std::string> service_name_;
  const std::string method_name_;
  const std::vector<std::string> method_args_;
  const std::vector<std::pair<std::string, std::string>> headers_;
};

class BaseThriftIntegrationTest : public BaseIntegrationTest {
public:
  BaseThriftIntegrationTest()
      : BaseIntegrationTest(Network::Address::IpVersion::v4, thrift_config_) {}

  /**
   * Given PayloadOptions, generate a client request and server response and store the
   * data in the given Buffers.
   */
  void preparePayloads(const PayloadOptions& options, Buffer::Instance& request_buffer,
                       Buffer::Instance& response_buffer);

protected:
  // Tests should use a static SetUpTestSuite method to initialize this field with a suitable
  // configuration.
  static std::string thrift_config_;

private:
  void readAll(std::string file, Buffer::Instance& buffer);
};

} // namespace ThriftProxy
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package requests

import (
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
	"io"
	"reflect"
	"strconv"
)

const (
	RPC = "RPC"
	ROA = "ROA"

	HTTP  = "HTTP"
	HTTPS = "HTTPS"

	DefaultHttpPort = "80"

	GET     = "GET"
	PUT     = "PUT"
	POST    = "POST"
	DELETE  = "DELETE"
	HEAD    = "HEAD"
	OPTIONS = "OPTIONS"

	Json = "application/json"
	Xml  = "application/xml"
	Raw  = "application/octet-stream"
	Form = "application/x-www-form-urlencoded"

	Header = "Header"
	Query  = "Query"
	Body   = "Body"
	Path   = "Path"

	HeaderSeparator = "\n"
)

// interface
type AcsRequest interface {
	GetScheme() string
	GetMethod() string
	GetDomain() string
	GetPort() string
	GetRegionId() string
	GetUrl() string
	GetQueries() string
	GetHeaders() map[string]string
	GetQueryParams() map[string]string
	GetFormParams() map[string]string
	GetContent() []byte
	GetBodyReader() io.Reader
	GetStyle() string
	GetProduct() string
	GetVersion() string
	GetActionName() string
	GetAcceptFormat() string
	GetLocationServiceCode() string
	GetLocationEndpointType() string

	SetStringToSign(stringToSign string)
	GetStringToSign() string

	SetDomain(domain string)
	SetContent(content []byte)
	SetScheme(scheme string)
	BuildUrl() string
	BuildQueries() string

	addHeaderParam(key, value string)
	addQueryParam(key, value string)
	addFormParam(key, value string)
	addPathParam(key, value string)
}

// base class
type baseRequest struct {
	Scheme   string
	Method   string
	Domain   string
	Port     string
	RegionId string

	product string
	version string

	actionName string

	AcceptFormat string

	QueryParams map[string]string
	Headers     map[string]string
	FormParams  map[string]string
	Content     []byte

	locationServiceCode  string
	locationEndpointType string

	queries string

	stringToSign string
}

func (request *baseRequest) GetQueryParams() map[string]string {
	return request.QueryParams
}

func (request *baseRequest) GetFormParams() map[string]string {
	return request.FormParams
}

func (request *baseRequest) GetContent() []byte {
	return request.Content
}

func (request *baseRequest) GetVersion() string {
	return request.version
}

func (request *baseRequest) GetActionName() string {
	return request.actionName
}

func (request *baseRequest) SetContent(content []byte) {
	request.Content = content
}

func (request *baseRequest) addHeaderParam(key, value string) {
	request.Headers[key] = value
}

func (request *baseRequest) addQueryParam(key, value string) {
	request.QueryParams[key] = value
}

func (request *baseRequest) addFormParam(key, value string) {
	request.FormParams[key] = value
}

func (request *baseRequest) GetAcceptFormat() string {
	return request.AcceptFormat
}

func (request *baseRequest) GetLocationServiceCode() string {
	return request.locationServiceCode
}

func (request *baseRequest) GetLocationEndpointType() string {
	return request.locationEndpointType
}

func (request *baseRequest) GetProduct() string {
	return request.product
}

func (request *baseRequest) GetScheme() string {
	return request.Scheme
}

func (request *baseRequest) SetScheme(scheme string) {
	request.Scheme = scheme
}

func (request *baseRequest) GetMethod() string {
	return request.Method
}

func (request *baseRequest) GetDomain() string {
	return request.Domain
}

func (request *baseRequest) SetDomain(host string) {
	request.Domain = host
}

func (request *baseRequest) GetPort() string {
	return request.Port
}

func (request *baseRequest) GetRegionId() string {
	return request.RegionId
}

func (request *baseRequest) GetHeaders() map[string]string {
	return request.Headers
}

func (request *baseRequest) SetContentType(contentType string) {
	request.Headers["Content-Type"] = contentType
}

func (request *baseRequest) GetContentType() (contentType string, contains bool) {
	contentType, contains = request.Headers["Content-Type"]
	return
}

func (request *baseRequest) SetStringToSign(stringToSign string) {
	request.stringToSign = stringToSign
}

func (request *baseRequest) GetStringToSign() string {
	return request.stringToSign
}

func defaultBaseRequest() (request *baseRequest) {
	request = &baseRequest{
		Scheme:       "",
		AcceptFormat: "JSON",
		Method:       GET,
		QueryParams:  make(map[string]string),
		Headers: map[string]string{
			"x-sdk-client":      "golang/1.0.0",
			"x-sdk-invoke-type": "normal",
			"Accept-Encoding": "identity",
		},
		FormParams: make(map[string]string),
	}
	return
}

func InitParams(request AcsRequest) (err error) {
	requestValue := reflect.ValueOf(request).Elem()
	err = flatRepeatedList(requestValue, request, "", "")
	return
}

func flatRepeatedList(dataValue reflect.Value, request AcsRequest, position, prefix string) (err error) {
	dataType := dataValue.Type()
	for i := 0; i < dataType.NumField(); i++ {
		field := dataType.Field(i)
		name, containsNameTag := field.Tag.Lookup("name")
		fieldPosition := position
		if fieldPosition == "" {
			fieldPosition, _ = field.Tag.Lookup("position")
		}
		typeTag, containsTypeTag := field.Tag.Lookup("type")
		if containsNameTag {
			if !containsTypeTag {
				// simple param
				key := prefix + name
				value := dataValue.Field(i).String()
				err = addParam(request, fieldPosition, key, value)
				if err != nil {
					return
				}
			} else if typeTag == "Repeated" {
				// repeated param
				repeatedFieldValue := dataValue.Field(i)
				if repeatedFieldValue.Kind() != reflect.Slice {
					// possible value: {"[]string", "*[]struct"}, we must call Elem() in the last condition
					repeatedFieldValue = repeatedFieldValue.Elem()
				}
				if repeatedFieldValue.IsValid() && !repeatedFieldValue.IsNil() {
					for m := 0; m < repeatedFieldValue.Len(); m++ {
						elementValue := repeatedFieldValue.Index(m)
						key := prefix + name + "." + strconv.Itoa(m+1)
						if elementValue.Type().String() == "string" {
							value := elementValue.String()
							err = addParam(request, fieldPosition, key, value)
							if err != nil {
								return
							}
						} else {
							err = flatRepeatedList(elementValue, request, fieldPosition, key+".")
							if err != nil {
								return
							}
						}
					}
				}
			}
		}
	}
	return
}

func addParam(request AcsRequest, position, name, value string) (err error) {
	if len(value) > 0 {
		switch position {
		case Header:
			request.addHeaderParam(name, value)
		case Query:
			request.addQueryParam(name, value)
		case Path:
			request.addPathParam(name, value)
		case Body:
			request.addFormParam(name, value)
		default:
			errMsg := fmt.Sprintf(errors.UnsupportedParamPositionErrorMessage, position)
			err = errors.NewClientError(errors.UnsupportedParamPositionErrorCode, errMsg, nil)
		}
	}
	return
}


text:
When a workload is presented to kube-batch in the form of jobs or tasks,
kube-batch prioritizes those job/tasks, so job/task with high priority is
handled first.  In this doc, we will look into how Tasks within job are prioritized.

## Implementation

Task priority in kube-batch is done by using either of following data

1. Task's Priority given in TaskSpec(i.e. PodSpec as defined in the YAML)
2. Task's Creation time
3. Task's UID

![taskordering](../../doc/images/task_order.png)

If priority plugin in kube-batch is loaded, then priority is decided using
task's priority that will be provided in TaskSpec.
Else it checks for creationTime of tasks.  Depending on which task has been created first,
that task will be given high priority.  If creationTime is also same,
then UID is compared and then priority is decided.


text:
var mongoose = require('mongoose');
var slug = require('slug');
var hubSchema = new mongoose.Schema();
var commentSchema = new mongoose.Schema();
hubSchema.set('usePushEach', true);
commentSchema.set('usePushEach', true);

commentSchema.add({
    commentId: {type: mongoose.Schema.Types.ObjectId},
    dateAdded: { type: Date },
    dateRemoved: { type: Date },
    author: { type: String, required: true },
    authorId: { type: String, required: true },
    authorDisplayName: { type: String, required: true },
    text: { type: String, required: true }
});

commentSchema.pre('save', function (next) {
    var now = new Date();
    if (!this.dateAdded) {
        this.dateAdded= now;
    }
    next();
});

/**
 * Hub Schema - schema for the post
 */
hubSchema.add({
    courseId: {type: mongoose.Schema.Types.ObjectId, required: true},
    postId: {type: mongoose.Schema.Types.ObjectId},
    userId: {type: mongoose.Schema.Types.ObjectId, required: true},
    contentId: {type: mongoose.Schema.Types.ObjectId, required: true},
    title: {type: String, required: true},
    url: {type: String, required: true},
    type: {type: String, required: true},
    favicon: {type: String},
    hostName: {type: String},
    image: {type: String},
    embedHtml: {type: String},
    description: {type: String},
    isDeleted: {type: Boolean, required: true},
    totalVotes: {type: Number, default: 0},
    dateAdded: {type: Date},
    dateUpdated: {type: Date},
    personalUsers: [ {
        userId:{type: mongoose.Schema.Types.ObjectId}
    }],
    comments: [commentSchema],
    tags: [{type: String}],
    slug: {type: String}
});

/**
 * Set index for searching purposes
 */
hubSchema.index({ title: 'text', description: 'text', tags: 'text', url: 'text' });

hubSchema.methods.setSlug = function (s) {
    this.slug = slug(s);
};

hubSchema.pre('save', function (next) {
    var now = new Date();
    this.dateUpdated = now;
    if (!this.dateAdded) {
        this.dateAdded = now;
    }
    next();
});

hubSchema.pre('update', function (next) {
    var now = new Date();
    this.dateUpdated = now;
    next();
});

var agg = {};
agg.posts = mongoose.model('hub', hubSchema);
agg.comments = mongoose.model('hub-comment', commentSchema);
agg.posts.ensureIndexes();
// agg.posts.on('index', function(err){
//   console.log("agg.posts: " + err);
// });
module.exports = agg;


text:
package projects.Etx.nodes.nodeImplementations;

public enum NodeRoleBetEtx {
	BORDER, RELAY, SINK;
}


text: Rails.application.config.session_store :cookie_store, key: '_superhr_session'


text:
from twisted.internet.defer import returnValue
from autobahn.twisted.wamp import Application

app = Application('com.example')

@app.register()
def add2(a, b):
   print("add2() called")
   return a + b

@app.register('com.example.hello')
def hello():
   print("hello() called")
   res = yield app.session.call('com.example.add2', 2, 3)
   returnValue("Hello {}".format(res))

@app.signal('onjoined')
def onjoined():
   print("realm joined!")

if __name__ == "__main__":
   app.run("ws://localhost:8080/ws", "realm1", standalone = True)


text:
<?php

/*
 * Carto (formerly CartoDB)
 *
 * example URL: http://osm2.carto.com/viz/08aef918-94da-11e4-ad83-0e0c41326911/public_map
 *
 * possible patterns:
 * [username].carto.com/viz/[map-id]/public_map
 * [username].carto.com/viz/[map-id]/embed_map
 * [username].carto.com/viz/[map-id]/map
 * [organization].carto.com/u/[username]/viz/[map-id]/public_map
 * [organization].carto.com/u/[username]/viz/[map-id]/embed_map
 * [organization].carto.com/u/[username]/viz/[map-id]/map
 *
 * On July 8th, 2016 CartoDB changed its primary domain from cartodb.com to carto.com
 * So this shortcode still supports the cartodb.com domain for oembeds.
*/

wp_oembed_add_provider( '#https?://(?:www\.)?[^/^\.]+\.carto(db)?\.com/\S+#i', 'https://services.carto.com/oembed', true );


text:
using namespace AdapterLib;
using namespace Windows::Foundation;

namespace AdapterLib
{
    Platform::String^ DEVICE_NAME           = L"MockLampDevice";
    Platform::String^ VERSION_VALUE_NAME    = L"Version";

    Platform::String^ LAMP_STATE_CHANGED_SIGNAL_NAME    = L"LampStateChanged";
    Platform::String^ SIGNAL_PARAMETER__LAMP_ID__NAME   = L"LampID";

    Platform::String^ LAMP_ID               = L"333-333-333";
    Platform::String^ LAMP_MODEL            = "0.0.0.1";
    Platform::String^ LAMP_MANUFACTURER     = "Microsoft";

    bool LAMP_STATE_ON_OFF          = false;
    uint32 LAMP_STATE_BRIGHTNESS    = 0;
    uint32 LAMP_STATE_HUE           = 0;
    uint32 LAMP_STATE_SATURATION    = 0;
    uint32 LAMP_STATE_COLORTEMP     = 0;
}

MockLampDevice::MockLampDevice(
    Platform::String^ Name,
    MockAdapter^ ParentObject
    )
    : MockAdapterDevice(Name, ParentObject)
    , m_lampState(nullptr)
{
    SetSerialNumber(LAMP_ID);
    SetModel(LAMP_MODEL);
    SetVendor(LAMP_MANUFACTURER);
}

uint32
MockLampDevice::Initialize()
{
    uint32 status = ERROR_SUCCESS;

    status = setLampStateChangedSignal();
    if (ERROR_SUCCESS != status)
    {
        goto leave;
    }

    try
    {
        m_lampState = ref new BridgeRT::State();
        m_lampState->IsOn       = LAMP_STATE_ON_OFF;
        m_lampState->Brightness = LAMP_STATE_BRIGHTNESS;
        m_lampState->Hue        = LAMP_STATE_HUE;
        m_lampState->Saturation = LAMP_STATE_SATURATION;
        m_lampState->ColorTemp  = LAMP_STATE_COLORTEMP;
    }
    catch (Platform::OutOfMemoryException^ ex)
    {
        status = ERROR_OUTOFMEMORY;
    }

leave:

    return status;
}

uint32
MockLampDevice::setLampStateChangedSignal()
{
    uint32 status = ERROR_SUCCESS;
    Platform::Object^ object = nullptr;
    MockAdapterSignal^ lampStateChangedSignal = nullptr;

    try
    {
        lampStateChangedSignal = ref new MockAdapterSignal(LAMP_STATE_CHANGED_SIGNAL_NAME, this);

        // "LampID" signal parameter (string)
        object = PropertyValue::CreateString(LAMP_ID);
        if (object == nullptr)
        {
            status = ERROR_INVALID_HANDLE;
            goto leave;
        }

        MockAdapterValue^ lampIdSignalParameter = ref new MockAdapterValue(
            SIGNAL_PARAMETER__LAMP_ID__NAME,
            lampStateChangedSignal,
            object
            );
        lampStateChangedSignal += lampIdSignalParameter;
    }
    catch (Platform::OutOfMemoryException^ ex)
    {
        status = ERROR_OUTOFMEMORY;
        goto leave;
    }

    // Add signal to the device
    this->AddSignal(lampStateChangedSignal);

leave:

    return status;
}


text:
require File.expand_path(File.join(File.dirname(__FILE__),'..','..','..','test_helper'))

class NewRelic::Agent::StatsEngine::GCProfilerTest < Test::Unit::TestCase
  def test_init_profiler_for_rails_bench
    ::GC.stubs(:time)
    ::GC.stubs(:collections)

    assert_equal(NewRelic::Agent::StatsEngine::GCProfiler::RailsBench,
                 NewRelic::Agent::StatsEngine::GCProfiler.init.class)
  end

  def test_init_profiler_for_ruby_19
    defined = defined?(::GC::Profiler)
    if !defined
      ::GC.const_set(:Profiler, Module.new)
    end
    ::GC::Profiler.stubs(:enabled?).returns(true)
    ::GC::Profiler.stubs(:total_time).returns(0)
    ::GC.stubs(:count).returns(0)

    assert_equal(NewRelic::Agent::StatsEngine::GCProfiler::Ruby19,
                 NewRelic::Agent::StatsEngine::GCProfiler.init.class)
  ensure
    ::GC.send(:remove_const, :Profiler) unless defined
  end

  def test_init_profiler_for_rbx
    defined = defined?(::Rubinius::GC)
    if !defined
      Object.const_set(:Rubinius, Module.new)
      ::Rubinius.const_set(:GC, Module.new)
    end
    ::Rubinius::GC.stubs(:count).returns(0)
    ::Rubinius::GC.stubs(:time).returns(0)

    assert_equal(NewRelic::Agent::StatsEngine::GCProfiler::Rubinius,
                 NewRelic::Agent::StatsEngine::GCProfiler.init.class)
  ensure
    Object.send(:remove_const, :Rubinius) unless defined
  end

  def test_collect_gc_data
    GC.disable unless NewRelic::LanguageSupport.using_engine?('jruby')
    if NewRelic::LanguageSupport.using_engine?('rbx')
      agent = ::Rubinius::Agent.loopback
      agent.stubs(:get).with('system.gc.young.total_wallclock') \
        .returns([:value, 1000], [:value, 2500])
      agent.stubs(:get).with('system.gc.full.total_wallclock') \
        .returns([:value, 2000], [:value, 3500])
      agent.stubs(:get).with('system.gc.young.count') \
        .returns([:value, 1], [:value, 2])
      agent.stubs(:get).with('system.gc.full.count') \
        .returns([:value, 1], [:value, 2])
      ::Rubinius::Agent.stubs(:loopback).returns(agent)
    elsif NewRelic::LanguageSupport.using_version?('1.9')
      ::GC::Profiler.stubs(:enabled?).returns(true)
      ::GC::Profiler.stubs(:total_time).returns(1.0, 4.0)
      ::GC.stubs(:count).returns(1, 3)
      ::GC::Profiler.stubs(:clear).returns(nil)
    elsif NewRelic::LanguageSupport.using_version?('1.8.7') &&
        RUBY_DESCRIPTION =~ /Ruby Enterprise Edition/
      ::GC.stubs(:time).returns(1000000, 4000000)
      ::GC.stubs(:collections).returns(1, 3)
    else
      return true # no need to test if we're not collecting GC metrics
    end

    engine = NewRelic::Agent.instance.stats_engine
    tracer = NewRelic::Agent::TransactionSampler.new
    tracer.instance_variable_set(:@last_sample,
                                 NewRelic::TransactionSample.new)
    engine.transaction_sampler = tracer
    engine.start_transaction
    scope = engine.push_scope "scope"
    engine.pop_scope scope, 0.01
    engine.end_transaction

    gc_stats = engine.get_stats('GC/cumulative')
    assert_equal 2, gc_stats.call_count
    assert_equal 3.0, gc_stats.total_call_time
    assert_equal(3.0, tracer.last_sample.params[:custom_params][:gc_time])
  ensure
    GC.enable unless NewRelic::LanguageSupport.using_engine?('jruby')
  end
end


text:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'numberSpacing'
})

export class NumberSpacingPipe implements PipeTransform {
  transform(value: number): string {
    if (value > 0) {
      return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
    } else {
      return null;
    }
  }
}


text:
""" # *********************************************************************** #
Created on Mon Jul  1 01:31:22 2013

@author: dan segal (danSegal2@gmail.com)
""" # *********************************************************************** #
from   __future__                   import division
from   os                           import system

from   pequod.readInput             import readInput
from   pequod.getValueCombinations  import getValueCombinations
from   pequod.makeNewRunDir         import makeNewRunDir
from   pequod.makeBuckyInputs       import makeBuckyInputs
from   pequod.makeStub              import makeStub
#from   pequod.makeMap              import makeMap

class parameterSweep(object):

    # ===========================
    #  Variable USERS can change
    # ===========================

    verbose = True

    # -----------------
    #  read in red.inp
    # -----------------

    ( varList , valuesList , vectorList ) = readInput('red.inp')

    # -------------------------------------------------
    #  get every combination of values from valuesList
    # -------------------------------------------------

    ( varList , comboList , comboTypes , comboInfo ) = \
        getValueCombinations( varList ,valuesList , vectorList )

    # -----------------------------------------------------
    #  create a directory for every set defined by red.inp
    #    and fill them with their own modified bucky.inp
    # -----------------------------------------------------

    curDir = makeNewRunDir()
    makeBuckyInputs( curDir , varList , comboList )

    # ------------------------------------
    #  if verbose, print all the sublists
    # ------------------------------------

    if verbose :

        print '\n   being verbose   \n'
        for              aList in comboList :
            for        subList in     aList :
                print  subList

    # ---------------------------------------------
    #  make condor stub and submit cluster of jobs
    # ---------------------------------------------

    makeStub( curDir , len(comboList) )

    system( 'condor_submit ' + curDir + '/condorStub' )

    # ---------------------------------------------------------
    #  make an excel readable map of curDir and finish program
    # ---------------------------------------------------------

    #makeMap( curDir , varList , combinationList )

    print('\n ok done \n')