text:
//---------------------------------------------------------------------------
#include "ZenLib/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "ZenLib/Conf_Internal.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#ifdef ZENLIB_USEWX
    #include <wx/file.h>
    #include <wx/filename.h>
    #include <wx/utils.h>
#else //ZENLIB_USEWX
    #ifdef ZENLIB_STANDARD
        #ifdef WINDOWS
        #else
            #include <cstdio>
        #endif
        #include <sys/stat.h>
        #if !defined(WINDOWS)
            #include <unistd.h>
        #endif //!defined(WINDOWS)
        #include <fstream>
        using namespace std;
        #ifndef S_ISDIR
            #define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR)
        #endif
        #ifndef S_ISREG
            #define S_ISREG(mode) (((mode)&S_IFMT) == S_IFREG)
        #endif
    #elif defined WINDOWS
        #undef __TEXT
        #include <windows.h>
    #endif
#endif //ZENLIB_USEWX
#include "ZenLib/File.h"
#include "ZenLib/OS_Utils.h"
#include <map>
//---------------------------------------------------------------------------

namespace ZenLib
{

//---------------------------------------------------------------------------
// Debug
#ifdef ZENLIB_DEBUG
    #include <stdio.h>
    #include <windows.h>
    namespace ZenLib_File_Debug
    {
        FILE* F;
        std::string Debug;
        SYSTEMTIME st_In;

        void Debug_Open(bool Out)
        {
            F=fopen("C:\\Temp\\ZenLib_Debug.txt", "a+t");
            Debug.clear();
            SYSTEMTIME st;
            GetLocalTime( &st );

            char Duration[100];
            if (Out)
            {
                FILETIME ft_In;
                if (SystemTimeToFileTime(&st_In, &ft_In))
                {
                    FILETIME ft_Out;
                    if (SystemTimeToFileTime(&st, &ft_Out))
                    {
                        ULARGE_INTEGER UI_In;
                        UI_In.HighPart=ft_In.dwHighDateTime;
                        UI_In.LowPart=ft_In.dwLowDateTime;

                        ULARGE_INTEGER UI_Out;
                        UI_Out.HighPart=ft_Out.dwHighDateTime;
                        UI_Out.LowPart=ft_Out.dwLowDateTime;

                        ULARGE_INTEGER UI_Diff;
                        UI_Diff.QuadPart=UI_Out.QuadPart-UI_In.QuadPart;

                        FILETIME ft_Diff;
                        ft_Diff.dwHighDateTime=UI_Diff.HighPart;
                        ft_Diff.dwLowDateTime=UI_Diff.LowPart;

                        SYSTEMTIME st_Diff;
                        if (FileTimeToSystemTime(&ft_Diff, &st_Diff))
                        {
                            sprintf(Duration, "%02hd:%02hd:%02hd.%03hd", st_Diff.wHour, st_Diff.wMinute, st_Diff.wSecond, st_Diff.wMilliseconds);
                        }
                        else
                            strcpy(Duration, "            ");
                    }
                    else
                        strcpy(Duration, "            ");

                }
                else
                    strcpy(Duration, "            ");
            }
            else
            {
                st_In=st;
                strcpy(Duration, "            ");
            }

            fprintf(F,"                                       %02hd:%02hd:%02hd.%03hd %s", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, Duration);
        }

        void Debug_Close()
        {
            Debug += "\r\n";
            fwrite(Debug.c_str(), Debug.size(), 1, F); \
            fclose(F);
        }
    }
    using namespace ZenLib_File_Debug;

    #define ZENLIB_DEBUG1(_NAME,_TOAPPEND) \
        Debug_Open(false); \
        Debug+=", ";Debug+=_NAME; \
        _TOAPPEND; \
        Debug_Close();

    #define ZENLIB_DEBUG2(_NAME,_TOAPPEND) \
        Debug_Open(true); \
        Debug+=", ";Debug+=_NAME; \
        _TOAPPEND; \
        Debug_Close();
#else // ZENLIB_DEBUG
    #define ZENLIB_DEBUG1(_NAME,_TOAPPEND)
    #define ZENLIB_DEBUG2(_NAME,_TOAPPEND)
#endif // ZENLIB_DEBUG

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File::File()
{
    #ifdef ZENLIB_USEWX
        File_Handle=NULL;
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            File_Handle=NULL;
        #elif defined WINDOWS
            File_Handle=INVALID_HANDLE_VALUE;
        #endif
    #endif //ZENLIB_USEWX
    Position=(int64u)-1;
    Size=(int64u)-1;
}

File::File(Ztring File_Name, access_t Access)
{
    #ifdef ZENLIB_USEWX
        File_Handle=NULL;
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            File_Handle=NULL;
        #elif defined WINDOWS
            File_Handle=INVALID_HANDLE_VALUE;
        #endif
    #endif //ZENLIB_USEWX
    Position=(int64u)-1;
    Size=(int64u)-1;
    Open(File_Name, Access);
}

//---------------------------------------------------------------------------
File::~File()
{
    Close();
}

//***************************************************************************
// Open/Close
//***************************************************************************

//---------------------------------------------------------------------------
bool File::Open (const tstring &File_Name_, access_t Access)
{
    Close();

    ZENLIB_DEBUG1(      "File Open",
                        Debug+=", File_Name="; Debug +=Ztring(File_Name_).To_UTF8();)

    File_Name=File_Name_;

    #ifdef ZENLIB_USEWX
        File_Handle=(void*)new wxFile();
        if (((wxFile*)File_Handle)->Open(File_Name.c_str(), (wxFile::OpenMode)Access)==0)
        {
            //Sometime the file is locked for few milliseconds, we try again later
            wxMilliSleep(1000);
            if (((wxFile*)File_Handle)->Open(File_Name.c_str(), (wxFile::OpenMode)Access)==0)
                //File is not openable
                return false;
        }
        return true;
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            /*
            int access;
            switch (Access)
            {
                case Access_Read         : access=O_BINARY|O_RDONLY          ; break;
                case Access_Write        : access=O_BINARY|O_WRONLY|O_CREAT|O_TRUNC  ; break;
                case Access_Read_Write   : access=O_BINARY|O_RDWR  |O_CREAT  ; break;
                case Access_Write_Append : access=O_BINARY|O_WRONLY|O_CREAT|O_APPEND ; break;
                default                  : access=0                          ; break;
            }
            #ifdef UNICODE
                File_Handle=open(File_Name.To_Local().c_str(), access);
            #else
                File_Handle=open(File_Name.c_str(), access);
            #endif //UNICODE
            return File_Handle!=-1;
            */
            ios_base::openmode mode;
            switch (Access)
            {
                case Access_Read         : mode=ios_base::binary|ios_base::in; break;
                case Access_Write        : mode=ios_base::binary|ios_base::in|ios_base::out; break;
                case Access_Read_Write   : mode=ios_base::binary|ios_base::in|ios_base::out; break;
                case Access_Write_Append : if (!Exists(File_Name))
                                                mode=ios_base::binary|ios_base::out;
                                           else
                                                mode=ios_base::binary|ios_base::out|ios_base::app;
                                           break;
                default                  : ;
            }
            #ifdef UNICODE
                File_Handle=new fstream(File_Name.To_Local().c_str(), mode);
            #else
                File_Handle=new fstream(File_Name.c_str(), mode);
            #endif //UNICODE
            if (!((fstream*)File_Handle)->is_open())
            {
                delete (fstream*)File_Handle; File_Handle=NULL;
                return false;
            }
            return true;
        #elif defined WINDOWS
            DWORD dwDesiredAccess, dwShareMode, dwCreationDisposition;
            switch (Access)
            {
                case Access_Read         : dwDesiredAccess=FILE_READ_DATA; dwShareMode=FILE_SHARE_READ|FILE_SHARE_WRITE; dwCreationDisposition=OPEN_EXISTING;   break;
                case Access_Write        : dwDesiredAccess=GENERIC_WRITE;   dwShareMode=0;                                 dwCreationDisposition=OPEN_ALWAYS;   break;
                case Access_Read_Write   : dwDesiredAccess=FILE_READ_DATA|GENERIC_WRITE;   dwShareMode=0; dwCreationDisposition=OPEN_ALWAYS;                    break;
                case Access_Write_Append : dwDesiredAccess = FILE_APPEND_DATA; dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; dwCreationDisposition = OPEN_ALWAYS; break;
                default                  : dwDesiredAccess=0;               dwShareMode=0;                                 dwCreationDisposition=0;             break;
            }

            #ifdef UNICODE
                File_Handle=CreateFileW(File_Name.c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);
            #else
                File_Handle=CreateFile(File_Name.c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);
            #endif //UNICODE
            #if 0 //Disabled
            if (File_Handle==INVALID_HANDLE_VALUE)
            {
                //Sometimes the file is locked for few milliseconds, we try again later
                DWORD dw = GetLastError();
                if (dw!=ERROR_FILE_NOT_FOUND)
                {
                    /*
                    char lpMsgBuf[1000];
                    FormatMessageA(
                    FORMAT_MESSAGE_FROM_SYSTEM,
                    NULL,
                    dw,
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                    lpMsgBuf,
                    1000, NULL );
                    */
                    Sleep(1000);
                    #ifdef UNICODE
                        File_Handle=CreateFileW(File_Name.c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);
                    #else
                        File_Handle=CreateFile(File_Name.c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);
                    #endif //UNICODE
                }
            }
            #endif //0
            if (File_Handle==INVALID_HANDLE_VALUE)
            {
                ZENLIB_DEBUG2(      "File Open",
                                    Debug+=", returns 0";)

                //File is not openable
                return false;
            }

            ZENLIB_DEBUG2(      "File Open",
                                Debug+=", returns 1";)

            return true;
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
bool File::Create (const Ztring &File_Name_, bool OverWrite)
{
    Close();

    ZENLIB_DEBUG1(      "File Create",
                        Debug+=", File_Name="; Debug +=Ztring(File_Name_).To_UTF8();)

    File_Name=File_Name_;

    #ifdef ZENLIB_USEWX
        File_Handle=(void*)new wxFile();
        if (((wxFile*)File_Handle)->Create(File_Name.c_str(), OverWrite)==0)
        {
            //Sometime the file is locked for few milliseconds, we try again later
            wxMilliSleep(3000);
            if (((wxFile*)File_Handle)->Create(File_Name.c_str(), OverWrite)==0)
                //File is not openable
                return false;
        }
        return true;
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            /*
            int access;
            switch (OverWrite)
            {
                case false        : access=O_BINARY|O_CREAT|O_WRONLY|O_EXCL ; break;
                default           : access=O_BINARY|O_CREAT|O_WRONLY|O_TRUNC; break;
            }
            #ifdef UNICODE
                File_Handle=open(File_Name.To_Local().c_str(), access);
            #else
                File_Handle=open(File_Name.c_str(), access);
            #endif //UNICODE
            return  File_Handle!=-1;
            */
            /*ios_base::openmode mode;

            switch (OverWrite)
            {
                //case false         : mode=          ; break;
                default                  : mode=0                            ; break;
            }*/
            ios_base::openmode access;

            if (!OverWrite && Exists(File_Name))
                return false;

            access=ios_base::binary|ios_base::in|ios_base::out|ios_base::trunc;

            #ifdef UNICODE
                File_Handle=new fstream(File_Name.To_Local().c_str(), access);
            #else
                File_Handle=new fstream(File_Name.c_str(), access);
            #endif //UNICODE
            return ((fstream*)File_Handle)->is_open();
        #elif defined WINDOWS
            DWORD dwDesiredAccess, dwShareMode, dwCreationDisposition;
            if (OverWrite) {
                dwDesiredAccess=GENERIC_WRITE;
                dwCreationDisposition=CREATE_ALWAYS;
            } else {
                dwDesiredAccess=GENERIC_WRITE;
                dwCreationDisposition=CREATE_NEW;
            }
            dwShareMode=0;

            #ifdef UNICODE
                File_Handle=CreateFileW(File_Name.c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);
            #else
                File_Handle=CreateFile(File_Name.c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);
            #endif //UNICODE
            #if 0 //Disabled
            if (File_Handle==INVALID_HANDLE_VALUE)
            {
                //Sometime the file is locked for few milliseconds, we try again later
                Sleep(3000);
                #ifdef UNICODE
                    File_Handle=CreateFileW(File_Name.c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);
                #else
                    File_Handle=CreateFile(File_Name.c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);
                #endif //UNICODE
            }
            #endif //0
            if (File_Handle==INVALID_HANDLE_VALUE)
            {
                ZENLIB_DEBUG2(      "File Create",
                                    Debug+=", returns 0";)

                //File is not openable
                return false;
            }

            ZENLIB_DEBUG2(      "File Create",
                                Debug+=", returns 1";)

            return true;
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
void File::Close ()
{
    #ifdef ZENLIB_DEBUG
        bool isOpen=false;
        #ifdef ZENLIB_USEWX
            if (File_Handle!=NULL)
        #else //ZENLIB_USEWX
            #ifdef ZENLIB_STANDARD
                if (File_Handle!=NULL)
            #elif defined WINDOWS
                if (File_Handle!=INVALID_HANDLE_VALUE)
            #endif
        #endif //ZENLIB_USEWX
            {
                ZENLIB_DEBUG1(      "File Close",
                                    Debug+=", File_Name="; Debug+=Ztring(File_Name).To_UTF8();)
                isOpen=true;
            }
    #endif

    #ifdef ZENLIB_USEWX
        delete (wxFile*)File_Handle; File_Handle=NULL;
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            //close(File_Handle); File_Handle=-1;
            delete (fstream*)File_Handle; File_Handle=NULL;
        #elif defined WINDOWS
            CloseHandle(File_Handle); File_Handle=INVALID_HANDLE_VALUE;
        #endif
    #endif //ZENLIB_USEWX
    Position=(int64u)-1;
    Size=(int64u)-1;

    #ifdef ZENLIB_DEBUG
        if (isOpen)
        {
            ZENLIB_DEBUG2(      "File Close",
                                )
        }
    #endif
}

//***************************************************************************
// Read/Write
//***************************************************************************

//---------------------------------------------------------------------------
size_t File::Read (int8u* Buffer, size_t Buffer_Size_Max)
{
    ZENLIB_DEBUG1(      "File Read",
                        Debug+=", File_Name="; Debug+=Ztring(File_Name).To_UTF8(); Debug+=", MaxSize="; Debug +=Ztring::ToZtring(Buffer_Size_Max).To_UTF8())

    #ifdef ZENLIB_USEWX
        if (File_Handle==NULL)
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            if (File_Handle==NULL)
        #elif defined WINDOWS
            if (File_Handle==INVALID_HANDLE_VALUE)
        #endif
    #endif //ZENLIB_USEWX
        return 0;

    #ifdef ZENLIB_USEWX
        size_t ByteRead=((wxFile*)File_Handle)->Read(Buffer, Buffer_Size_Max);
        Position+=ByteRead;
        return ByteRead;
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            //return read((int)File_Handle, Buffer, Buffer_Size_Max);
            if (Position==(int64u)-1)
                Position_Get();
            if (Size==(int64u)-1)
                Size_Get();
            if (Position!=(int64u)-1 && Position+Buffer_Size_Max>Size)
                Buffer_Size_Max=(size_t)(Size-Position); //We don't want to enable eofbit (impossible to seek after)
            ((fstream*)File_Handle)->read((char*)Buffer, Buffer_Size_Max);
            size_t ByteRead=((fstream*)File_Handle)->gcount();
            Position+=ByteRead;
            return ByteRead;
        #elif defined WINDOWS
            DWORD Buffer_Size;
            if (ReadFile(File_Handle, Buffer, (DWORD)Buffer_Size_Max, &Buffer_Size, NULL))
            {
                Position+=Buffer_Size;

                ZENLIB_DEBUG2(      "File Read",
                                    Debug+=", new position ";Debug+=Ztring::ToZtring(Position).To_UTF8();;Debug+=", returns ";Debug+=Ztring::ToZtring((int64u)Buffer_Size).To_UTF8();)

                return Buffer_Size;
            }
            else
            {
                ZENLIB_DEBUG2(      "File Read",
                                    Debug+=", returns 0";)
                return 0;
            }
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
size_t File::Write (const int8u* Buffer, size_t Buffer_Size)
{
    #ifdef ZENLIB_USEWX
        if (File_Handle==NULL)
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            if (File_Handle==NULL)
        #elif defined WINDOWS
            if (File_Handle==INVALID_HANDLE_VALUE)
        #endif
    #endif //ZENLIB_USEWX
        return 0;

    #ifdef ZENLIB_USEWX
        return ((wxFile*)File_Handle)->Write(Buffer, Buffer_Size);
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            //return write(File_Handle, Buffer, Buffer_Size);
            ((fstream*)File_Handle)->write((char*)Buffer, Buffer_Size);
            if (((fstream*)File_Handle)->bad())
            {
                Position=(int64u)-1;
                return 0;
            }
            else
            {
                if (Position!=(int64u)-1)
                    Position+=Buffer_Size;
                return Buffer_Size;
            }
        #elif defined WINDOWS
            DWORD Buffer_Size_Written;
            if (WriteFile(File_Handle, Buffer, (DWORD)Buffer_Size, &Buffer_Size_Written, NULL))
            {
                if (Position!=(int64u)-1)
                    Position+=Buffer_Size_Written;
                return Buffer_Size_Written;
            }
            else
            {
                Position=(int64u)-1;
                return 0;
            }
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
bool File::Truncate (int64u Offset)
{
    if (File_Handle==NULL)
        return false;

    #ifdef ZENLIB_USEWX
        return false; //Not supported
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            #if defined(WINDOWS)
                return false; //Not supported
            #else //defined(WINDOWS)
                //Need to close the file, use truncate, reopen it
                if (Offset==(int64u)-1)
                    Offset=Position_Get();
                Ztring File_Name_Sav=File_Name;
                Close();
                truncate(File_Name_Sav.To_Local().c_str(), Offset);
                if (!Open(File_Name_Sav, Access_Read_Write))
                    return false;
                GoTo(0, FromEnd);
                return true;
            #endif //!defined(WINDOWS)
        #elif defined WINDOWS
            if(Offset!=(int64u)-1 && Offset!=Position_Get())
                if (!GoTo(Offset))
                    return false;
            SetEndOfFile(File_Handle);
            return true;
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
size_t File::Write (const Ztring &ToWrite)
{
    std::string AnsiString=ToWrite.To_UTF8();
    return Write((const int8u*)AnsiString.c_str(), AnsiString.size());
}

//***************************************************************************
// Moving
//***************************************************************************

//---------------------------------------------------------------------------
bool File::GoTo (int64s Position_ToMove, move_t MoveMethod)
{
    ZENLIB_DEBUG1(      "File GoTo",
                        Debug+=", File_Name="; Debug+=Ztring(File_Name).To_UTF8(); Debug+="File GoTo: "; Debug +=Ztring(File_Name).To_UTF8(); Debug+=", MoveMethod="; Debug +=Ztring::ToZtring(MoveMethod).To_UTF8(); Debug+=", MaxSize="; Debug +=Ztring::ToZtring(Position_ToMove).To_UTF8())

    #ifdef ZENLIB_USEWX
        if (File_Handle==NULL)
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            if (File_Handle==NULL)
        #elif defined WINDOWS
            if (File_Handle==INVALID_HANDLE_VALUE)
        #endif
    #endif //ZENLIB_USEWX
        return false;

    Position=(int64u)-1; //Disabling memory
    #ifdef ZENLIB_USEWX
        return ((wxFile*)File_Handle)->Seek(Position, (wxSeekMode)MoveMethod)!=wxInvalidOffset; //move_t and wxSeekMode are same
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            /*
            int fromwhere;
            switch (MoveMethod)
            {
                case FromBegin : fromwhere=SEEK_SET; break;
                case FromCurrent : fromwhere=SEEK_CUR; break;
                case FromEnd : fromwhere=SEEK_END; break;
                default : fromwhere=SEEK_CUR; break;
            }
            return lseek(File_Handle, Position, fromwhere)!=-1;
            */
            ios_base::seekdir dir;
            switch (MoveMethod)
            {
                case FromBegin   : dir=ios_base::beg; break;
                case FromCurrent : dir=ios_base::cur; break;
                case FromEnd     : dir=ios_base::end; break;
                default          : dir=ios_base::beg;
            }
            ((fstream*)File_Handle)->seekg((streamoff)Position_ToMove, dir);
            return !((fstream*)File_Handle)->fail();
        #elif defined WINDOWS
            LARGE_INTEGER GoTo;
            GoTo.QuadPart=Position_ToMove;
            BOOL i=SetFilePointerEx(File_Handle, GoTo, NULL, MoveMethod);

            #ifdef ZENLIB_DEBUG
                LARGE_INTEGER Temp; Temp.QuadPart=0;
                SetFilePointerEx(File_Handle, Temp, &Temp, FILE_CURRENT);
                ZENLIB_DEBUG2(      "File GoTo",
                                    Debug+=", new position ";Debug+=Ztring::ToZtring(Temp.QuadPart).To_UTF8();Debug+=", returns ";Debug+=i?'1':'0';)
            #endif //ZENLIB_DEBUG

            return i?true:false;
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
int64u File::Position_Get ()
{
    if (Position!=(int64u)-1)
        return Position;

    ZENLIB_DEBUG1(      "File Position_Get",
                        Debug+=", File_Name="; Debug+=Ztring(File_Name).To_UTF8())

    #ifdef ZENLIB_USEWX
        if (File_Handle==NULL)
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            if (File_Handle==NULL)
        #elif defined WINDOWS
            if (File_Handle==INVALID_HANDLE_VALUE)
        #endif
    #endif //ZENLIB_USEWX
        return (int64u)-1;

    #ifdef ZENLIB_USEWX
        return (int64u)-1;
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            Position=((fstream*)File_Handle)->tellg();
            return Position;
        #elif defined WINDOWS
            LARGE_INTEGER GoTo; GoTo.QuadPart=0;
            GoTo.LowPart=SetFilePointer(File_Handle, GoTo.LowPart, &GoTo.HighPart, FILE_CURRENT);
            Position=GoTo.QuadPart;

            ZENLIB_DEBUG2(      "File GoTo",
                                Debug+=", new position ";Debug+=Ztring::ToZtring(GoTo.QuadPart).To_UTF8();Debug+=", returns 1";)

            return Position;
        #endif
    #endif //ZENLIB_USEWX
}

//***************************************************************************
// Attributes
//***************************************************************************

//---------------------------------------------------------------------------
int64u File::Size_Get()
{
    #ifdef ZENLIB_USEWX
        if (File_Handle==NULL)
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            if (File_Handle==NULL)
        #elif defined WINDOWS
            if (File_Handle==INVALID_HANDLE_VALUE)
        #endif
    #endif //ZENLIB_USEWX
        return 0;

    #ifdef ZENLIB_USEWX
        return ((wxFile*)File_Handle)->Length();
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            /*
            int CurrentPos=lseek(File_Handle, 0, SEEK_CUR);
            int64u File_Size;
            File_Size=lseek(File_Handle, 0, SEEK_END);
            lseek(File_Handle, CurrentPos, SEEK_SET);
            */
            fstream::pos_type CurrentPos=((fstream*)File_Handle)->tellg();
            if (CurrentPos!=(fstream::pos_type)-1)
            {
                ((fstream*)File_Handle)->seekg(0, ios_base::end);
                Size=((fstream*)File_Handle)->tellg();
                ((fstream*)File_Handle)->seekg(CurrentPos);
            }
            else
                Size=(int64u)-1;
        #elif defined WINDOWS
                LARGE_INTEGER x = {0};
                BOOL bRet = ::GetFileSizeEx(File_Handle, &x);
                if (bRet == FALSE)
                    return (int64u)-1;
                Size=x.QuadPart;
        #endif
        return Size;
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
Ztring File::Created_Get()
{
    #ifdef ZENLIB_USEWX
        if (File_Handle==NULL)
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            if (File_Handle==NULL)
        #elif defined WINDOWS
            if (File_Handle==INVALID_HANDLE_VALUE)
        #endif
    #endif //ZENLIB_USEWX
        return Ztring();

    #ifdef ZENLIB_USEWX
        return __T(""); //Not implemented
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            return __T(""); //Not implemented
        #elif defined WINDOWS
            FILETIME TimeFT;
            if (GetFileTime(File_Handle, &TimeFT, NULL, NULL))
            {
                int64u Time64=0x100000000ULL*TimeFT.dwHighDateTime+TimeFT.dwLowDateTime;
                Ztring Time; Time.Date_From_Milliseconds_1601(Time64/10000);
                return Time;
            }
            else
                return __T(""); //There was a problem
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
Ztring File::Created_Local_Get()
{
    #ifdef ZENLIB_USEWX
        if (File_Handle==NULL)
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            if (File_Handle==NULL)
        #elif defined WINDOWS
            if (File_Handle==INVALID_HANDLE_VALUE)
        #endif
    #endif //ZENLIB_USEWX
        return Ztring();

    #ifdef ZENLIB_USEWX
        return __T(""); //Not implemented
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            return __T(""); //Not implemented
        #elif defined WINDOWS
            FILETIME TimeFT;
            if (GetFileTime(File_Handle, &TimeFT, NULL, NULL))
            {
                int64u Time64=0x100000000ULL*TimeFT.dwHighDateTime+TimeFT.dwLowDateTime;
                TIME_ZONE_INFORMATION Info;
                DWORD Result=GetTimeZoneInformation(&Info);
                if (Result!=TIME_ZONE_ID_INVALID)
                {
                    Time64-=((int64s)Info.Bias)*60*1000*1000*10;
                    if (Result==TIME_ZONE_ID_DAYLIGHT)
                        Time64-=((int64s)Info.DaylightBias)*60*1000*1000*10;
                    else
                        Time64-=((int64s)Info.StandardBias)*60*1000*1000*10;
                }
                Ztring Time; Time.Date_From_Milliseconds_1601(Time64/10000);
                Time.FindAndReplace(__T("UTC "), __T(""));
                return Time;
            }
            else
                return __T(""); //There was a problem
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
Ztring File::Modified_Get()
{
    #ifdef ZENLIB_USEWX
        if (File_Handle==NULL)
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            if (File_Handle==NULL)
        #elif defined WINDOWS
            if (File_Handle==INVALID_HANDLE_VALUE)
        #endif
    #endif //ZENLIB_USEWX
        return Ztring();

    #ifdef ZENLIB_USEWX
        return __T(""); //Not implemented
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            struct stat Stat;
            int Result=stat(File_Name.To_Local().c_str(), &Stat);
            if (Result<0)
                return __T(""); //Error
            Ztring Time; Time.Date_From_Seconds_1970((int64s)Stat.st_mtime);
            return Time;
        #elif defined WINDOWS
            FILETIME TimeFT;
            if (GetFileTime(File_Handle, NULL, NULL, &TimeFT))
            {
                int64u Time64=0x100000000ULL*TimeFT.dwHighDateTime+TimeFT.dwLowDateTime;
                Ztring Time; Time.Date_From_Milliseconds_1601(Time64/10000);
                return Time;
            }
            else
                return __T(""); //There was a problem
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
Ztring File::Modified_Local_Get()
{
    #ifdef ZENLIB_USEWX
        if (File_Handle==NULL)
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            if (File_Handle==NULL)
        #elif defined WINDOWS
            if (File_Handle==INVALID_HANDLE_VALUE)
        #endif
    #endif //ZENLIB_USEWX
        return Ztring();

    #ifdef ZENLIB_USEWX
        return __T(""); //Not implemented
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            struct stat Stat;
            int Result=stat(File_Name.To_Local().c_str(), &Stat);
            if (Result<0)
                return __T(""); //Error
            Ztring Time; Time.Date_From_Seconds_1970_Local(Stat.st_mtime);
            return Time;
        #elif defined WINDOWS
            FILETIME TimeFT;
            if (GetFileTime(File_Handle, NULL, NULL, &TimeFT))
            {
                int64u Time64=0x100000000ULL*TimeFT.dwHighDateTime+TimeFT.dwLowDateTime; //100-ns
                TIME_ZONE_INFORMATION Info;
                DWORD Result=GetTimeZoneInformation(&Info);
                if (Result!=TIME_ZONE_ID_INVALID)
                {
                    Time64-=((int64s)Info.Bias)*60*1000*1000*10;
                    if (Result==TIME_ZONE_ID_DAYLIGHT)
                        Time64-=((int64s)Info.DaylightBias)*60*1000*1000*10;
                    else
                        Time64-=((int64s)Info.StandardBias)*60*1000*1000*10;
                }
                Ztring Time; Time.Date_From_Milliseconds_1601(Time64/10000);
                Time.FindAndReplace(__T("UTC "), __T(""));
                return Time;
            }
            else
                return __T(""); //There was a problem
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
bool File::Opened_Get()
{
    #ifdef ZENLIB_USEWX
        return File_Handle!=NULL;
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            //return File_Handle!=-1;
            return File_Handle!=NULL && ((fstream*)File_Handle)->is_open();
        #elif defined WINDOWS
            return File_Handle!=INVALID_HANDLE_VALUE;
        #endif
    #endif //ZENLIB_USEWX
}

//***************************************************************************
// Helpers
//***************************************************************************

//---------------------------------------------------------------------------
int64u File::Size_Get(const Ztring &File_Name)
{
    File F(File_Name);
    return F.Size_Get();
}

//---------------------------------------------------------------------------
Ztring File::Created_Get(const Ztring &File_Name)
{
    File F(File_Name);
    return F.Created_Get();
}

//---------------------------------------------------------------------------
Ztring File::Modified_Get(const Ztring &File_Name)
{
    File F(File_Name);
    return F.Modified_Get();
}

//---------------------------------------------------------------------------
bool File::Exists(const Ztring &File_Name)
{
    ZENLIB_DEBUG1(      "File Exists",
                        Debug+=", File_Name="; Debug+=Ztring(File_Name).To_UTF8())

    #ifdef ZENLIB_USEWX
        wxFileName FN(File_Name.c_str());
        return FN.FileExists();
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            #if defined WINDOWS
                if (File_Name.find(__T('*'))!=std::string::npos || (File_Name.find(__T("\\\\?\\"))!=0 && File_Name.find(__T('?'))!=std::string::npos) || (File_Name.find(__T("\\\\?\\"))==0 && File_Name.find(__T('?'), 4)!=std::string::npos))
                    return false;
            #endif //defined WINDOWS
            struct stat buffer;
            int         status;
            #ifdef UNICODE
                status=stat(File_Name.To_Local().c_str(), &buffer);
            #else
                status=stat(File_Name.c_str(), &buffer);
            #endif //UNICODE
            return status==0 && S_ISREG(buffer.st_mode);
        #elif defined WINDOWS
            if (File_Name.find(__T('*'))!=std::string::npos || (File_Name.find(__T("\\\\?\\"))!=0 && File_Name.find(__T('?'))!=std::string::npos) || (File_Name.find(__T("\\\\?\\"))==0 && File_Name.find(__T('?'), 4)!=std::string::npos))
                return false;
            #ifdef UNICODE
                DWORD FileAttributes=GetFileAttributesW(File_Name.c_str());
            #else
                DWORD FileAttributes=GetFileAttributes(File_Name.c_str());
            #endif //UNICODE

            ZENLIB_DEBUG2(      "File Exists",
                                Debug+=", File_Name="; Debug+=Ztring::ToZtring(((FileAttributes!=INVALID_FILE_ATTRIBUTES) && !(FileAttributes&FILE_ATTRIBUTE_DIRECTORY))?1:0).To_UTF8())

            return ((FileAttributes!=INVALID_FILE_ATTRIBUTES) && !(FileAttributes&FILE_ATTRIBUTE_DIRECTORY));
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
bool File::Copy(const Ztring &Source, const Ztring &Destination, bool OverWrite)
{
    #ifdef ZENLIB_USEWX
        return wxCopyFile(Source.c_str(), Destination.c_str(), OverWrite);
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            return false;
        #elif defined WINDOWS
            #ifdef UNICODE
                return CopyFileW(Source.c_str(), Destination.c_str(), !OverWrite)!=0;
            #else
                return CopyFile(Source.c_str(), Destination.c_str(), !OverWrite)!=0;
            #endif //UNICODE
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
bool File::Move(const Ztring &Source, const Ztring &Destination, bool OverWrite)
{
    if (OverWrite && Exists(Source))
        Delete(Destination);
    #ifdef ZENLIB_USEWX
        if (OverWrite && Exists(Destination))
            wxRemoveFile(Destination.c_str());
        return wxRenameFile(Source.c_str(), Destination.c_str());
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            return !std::rename(Source.To_Local().c_str(), Destination.To_Local().c_str());
        #elif defined WINDOWS
            #ifdef UNICODE
                return MoveFileW(Source.c_str(), Destination.c_str())!=0;
            #else
                return MoveFile(Source.c_str(), Destination.c_str())!=0;
            #endif //UNICODE
        #endif
    #endif //ZENLIB_USEWX
}

//---------------------------------------------------------------------------
bool File::Delete(const Ztring &File_Name)
{
    #ifdef ZENLIB_USEWX
        return wxRemoveFile(File_Name.c_str());
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            #ifdef UNICODE
                return unlink(File_Name.To_Local().c_str())==0;
            #else
                return unlink(File_Name.c_str())==0;
            #endif //UNICODE
        #elif defined WINDOWS
            #ifdef UNICODE
                return DeleteFileW(File_Name.c_str())!=0;
            #else
                return DeleteFile(File_Name.c_str())!=0;
            #endif //UNICODE
        #endif
    #endif //ZENLIB_USEWX
}

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

} //namespace


text:
express-ifttt
=============

An IFTTT WordPress XML-RPC proxy middleware for express

Usage
-----

```js
var express = require('express');
var ifttt = require('express-ifttt');
var app = express();

app.post('/xmlrpc.php', ifttt, function (req, res) {
  console.log(req.body);
  /* req.body should look something like the object below.
  {
    username: 'username',
    password: 'password',
    title: 'article title',
    description: 'article content',
    categories: [ 'category1', 'category2' ],
    mt_keywords: [ 'keyword1', 'keyword2' ],
    post_status: 'publish'
  }
  */
  res.send(200);
});

// Note: This web server should be accessible from port 80
app.listen(3000);
```

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<TrackResponse>
  <Response>
    <ResponseStatusCode>3</ResponseStatusCode>
    <ResponseStatusDescription>Failure</ResponseStatusDescription>
    <Error>
      <ErrorCode>10002</ErrorCode>
    </Error>
  </Response>
</TrackResponse>


text:
<?php

namespace Ens\CvBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class EnsCvBundle extends Bundle
{
}


text:
class SpellCheckMarker {
 public:
  // A predicate to test spellcheck marker validity.
  class IsValidPredicate {
   public:
    typedef SpellCheckMarker argument_type;
    explicit IsValidPredicate(size_t text_length) : text_length_(text_length) {}
    bool operator()(const SpellCheckMarker& marker) const {
      return marker.offset < text_length_;
    }
   private:
    size_t text_length_;
  };

  // IPC requires a default constructor.
  SpellCheckMarker() : hash(0xFFFFFFFF), offset(UINT32_MAX) {}

  SpellCheckMarker(uint32_t hash, uint32_t offset)
      : hash(hash), offset(offset) {}

  uint32_t hash;
  // Note: we use uint32_t instead of size_t because this struct is sent over
  // IPC which could span 32 & 64 bit processes. This is fine since the offset
  // shouldn't exceed UINT32_MAX even on 64 bit builds.
  uint32_t offset;
};

#endif  // CHROME_COMMON_SPELLCHECK_MARKER_H_


text:
module TestRmailMbox

  #
  # Main fixtures test
  #

  def test_fixtures
    TestHelper::Output.puts_test_log("RMail fixtures")

    messages = read_mailbox(TestHelper::Fixtures.rmail_mbox)
    length = TestHelper::Fixtures.rmail_length

    # test total amount
    assert_equal(length, messages.length)

    # test messages individually
    # assertions are called in the same order as the messages appear in the mailbox
    assert_minimal_message(messages.shift)
    assert_charset_madness(messages.shift)
    assert_quoted_message(messages.shift)
    assert_html_message(messages.shift)
    assert_multipart_message(messages.shift)
  end

  #
  # Minimal message (not much to do here)
  #

  def assert_minimal_message(message)
    content_type = 'text/plain'
    charset      = 'us-ascii'

    assert !message.multipart?
    assert message.plaintext?
    assert !message.has_attachments?

    assert_equal(content_type, message.header.content_type)
    assert_equal(content_type, message.header.content_type_naive)
    assert_equal(charset, message.header.charset)
    assert_nil(message.header.content_disposition)
    assert_nil(message.header.content_disposition_naive)
  end

  #
  # Multiple content-type fields (example for folded header field)
  #

  def assert_charset_madness(message)
    content_type = 'plain'
    charset      = 'iso-8859-1'

    assert_equal(content_type, message.header.content_type)
    assert_equal(charset, message.header.charset)

    content_types = message.header.all_fields_with_params('content-type')
    assert_equal(2, content_types.length)

    m_content_type = content_types.last[:value].downcase
    m_charset      = content_types.last[:params]['charset'].downcase

    # old methods will only return first charset field specified
    assert_not_equal(m_content_type, message.header.content_type_naive)
    assert_not_equal(m_charset, message.header.charset_naive)

    # new methods should always return last field
    assert_equal(m_content_type, message.header.content_type)
    assert_equal(m_charset, message.header.charset)
  end

  #
  # Quoted-Printable Message
  #

  def assert_quoted_message(message)
    transfer_encoding = 'quoted-printable'
    special_chars     = "äöüß"

    assert_equal(transfer_encoding, message.header['content-transfer-encoding'])
    assert_not_nil message.header.unquoted_subject.index(special_chars)
    assert_not_nil message.header.unquoted_address("from").first.index(special_chars)
    assert_not_nil message.unquoted_body.index(special_chars)
  end

  #
  # HTML message with multiple content-type fields
  #

  def assert_html_message(message)
    content_type = 'html'
    charset      = 'windows-1252'

    assert_equal(content_type, message.header.content_type)
    assert_equal(charset, message.header.charset)
  end

  #
  # Multipart message with JPEG attachment
  #

  def assert_multipart_message(message)
    count       = 1
    disposition = "attachment"
    filename    = "attachment.jpg"
    type        = "image/jpeg"

    assert message.multipart?
    assert message.has_attachments?

    attachment = message.part(1)
    assert attachment.attachment?

    assert_equal(disposition, attachment.header.content_disposition)
    assert_equal(disposition, attachment.header.content_disposition_naive)
    assert_equal(filename, attachment.header.unquoted_filename)
    assert_equal(type, attachment.header.content_type)
    assert_equal(type, attachment.header.content_type_naive)

    attachments = message.attachments(false)
    assert_equal(count, attachments.length)

    attachment = attachments.shift
    assert_equal(disposition, attachment[:disposition])
    assert_equal(filename, attachment[:filename])
    assert_equal(type, attachment[:type])
  end

  private

  #
  # Parse fixtures with TMail and RMail
  #

  def read_mailbox(name)
    messages = []
    # tmail crashes on charset madness
    assert_raises(TMail::SyntaxError) {
      parse_mailbox_with_tmail(name) { |m| messages << m }
    }

    messages = []
    # rmail parser should not crash
    assert_nothing_raised {
      parse_mailbox_with_rmail(name) { |m| messages << m }
    }

    messages
  end

  def parse_mailbox_with_rmail(mailbox_file)
    File.open(mailbox_file) { |mailbox|
      RMail::Mailbox.parse_mbox(mailbox).each { |msg_string|
        yield RMail::Parser.read(msg_string)
      }
    }
  end

  def parse_mailbox_with_tmail(mailbox_file)
    mailbox = TMail::UNIXMbox.new(mailbox_file, nil, true)
    mailbox.each_port { |port|
      yield TMail::Mail.new(port)
    }
  end

end

class TestRmailExtensions < Test::Unit::TestCase

  include TestRmailMbox

  #
  # Add an attachment to new message
  #

  def test_add_attachment
    TestHelper::Output.puts_test_log("RMail add attachment")

    text_parts = [ "Test Message Part 1", "Test Message Part 2" ]

    message = RMail::Message.new
    message.body = text_parts[0]
    assert !message.multipart?
    assert !message.has_attachments?

    message.add_part(text_parts[1])
    assert message.multipart?
    assert !message.has_attachments?
    assert_equal(0,message.attachments.length)

    message.add_attachment("", "")
    assert message.multipart?
    assert message.has_attachments?
  end

  #
  # Get attachment from message
  #

  def test_get_attachment
    TestHelper::Output.puts_test_log("RMail get attachment")

    count    = 1
    filename = "test.txt"
    content  = "test"

    message = RMail::Message.new

    message.add_attachment(filename, content)
    assert_equal(count, message.attachments.length)

    # do not get actual file data
    attachment = message.attachments.shift
    assert_equal(filename, attachment[:filename])
    assert_equal("", attachment[:content])

    # also get file data
    attachment = message.attachments(false).shift
    assert_equal(content, attachment[:content])
  end

  #
  # Message responds to custom methods
  #

  def test_respond_to
    TestHelper::Output.puts_test_log("RMail respond_to")

    native_methods     = [ :subject, :from, :to, :cc, :bcc ]
    custom_methods     = [ :charset, :content_type, :content_disposition, :filename ]
    unquoted_methods   = RMail::Header::UNQUOTED_METHODS
    unsupported_method = :unquoted_blah

    message = RMail::Message.new

    native_methods.each do |method_id|
      assert(message.header.respond_to?(method_id))
    end

    custom_methods.each do |method_id|
      assert(message.header.respond_to?(method_id))
    end

    unquoted_methods.each do |method_id|
      method_id = "unquoted_#{method_id.to_s}".to_sym
      assert(message.header.respond_to?(method_id))
    end

    # this method is not supported
    assert(!message.header.respond_to?(unsupported_method))
    assert_raises(NoMethodError) { message.header.send(unsupported_method) }
  end

  #
  # Custom "unquoted_*" methods work as expected
  #

  def test_custom_methods
    TestHelper::Output.puts_test_log("RMail custom methods")

    message = RMail::Message.new
    assert_nil(message.header.unquoted_subject)
    assert_nil(message.header.unquoted_filename)
    assert_equal([], message.header.unquoted_address("from"))
    assert_nil(message.header.unquoted_field("subject"))
  end

end


text:
module Tempora
  module Logging
    module Logger
      extend ActiveSupport::Concern

      module ClassMethods
        def is_logger?
          true
        end

        # @return [Array] with found loggable associations
        def tempora_assoc
          self.reflections.values.select{ |r| r.klass.is_loggable? }
        end

      end

      # Creates a new log entry for self and the given loggable
      # @param loggable item to log
      # @param opts {}
      def log(loggable, opts={})
        return false unless loggable.is_loggable?
        logs.create loggable: loggable, event: "#{loggable.class}::#{opts[:event]}"
      end

      def ratings
        Tempora.redis.hgetall Tempora::KeyMapper.logger_key self
      end

      def similarity_with logger
        Tempora::Recommender::Core.similarity self, logger
      end

      def predict loggable
        Tempora::Recommender::Core.prediction self, loggable
      end

      def is_logger?
        true
      end

      # Is self associated with loggable?
      # @param loggable
      # @return [Boolean]
      def assoc_with? obj
        obj.is_loggable? && is_tempora_assoc?(obj).present?
      end

      # @param limit [Integer]
      # @return [Array] List with recommended items
      def recommendation_list limit = 10
        Tempora::Recommender::Core.recommendation_list self, limit
      end

      # @param loggable_class your loggable model
      # @return [Array] associated items
      def association_list loggable_class
        if loggable_class.is_loggable?
          assoc = self.send(self.class.tempora_assoc.detect{
            |a| a.klass == loggable_class
          }.plural_name)
        end
      end
    end
  end
end


text:
// Copyright(c) 2007 Andreas Gullberg Larsen
// https://github.com/anjdreas/UnitsNet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using UnitsNet.Units;

namespace UnitsNet
{
    /// <summary>
    ///     A class for representing position in two dimensions.
    /// </summary>
    public struct Length2d : IEquatable<Length2d>
    {
        /// <summary>
        ///     Returns a point represented in meters.
        /// </summary>
        public readonly Vector2 Meters;

        /// <summary>
        ///     Creates an instance based on X and Y in implicitly defined SI units.
        /// </summary>
        public Length2d(double xMeters, double yMeters)
        {
            Meters = new Vector2(xMeters, yMeters);
        }

        public Length2d(Length x, Length y) : this(x.Meters, y.Meters)
        {
        }

        #region Static

        public static Length GetDistance(Length2d a, Length2d b)
        {
            Vector2 d = (a - b).Meters;
            return Length.FromMeters(Math.Sqrt(d.X*d.X + d.Y*d.Y));
        }

        #endregion

        #region Public properties

        public Length Length
        {
            get
            {
                double x = Meters.X;
                double y = Meters.Y;
                return Length.FromMeters(Math.Sqrt(x*x + y*y));
            }
        }

        public Length X => Length.FromMeters(Meters.X);

        public Length Y => Length.FromMeters(Meters.Y);

        public Vector2 Miles => new Vector2(X.Miles, Y.Miles);

        public Vector2 Yards => new Vector2(X.Yards, Y.Yards);

        public Vector2 Feet => new Vector2(X.Feet, Y.Feet);

        public Vector2 Inches => new Vector2(X.Inches, Y.Inches);

        public Vector2 Kilometers => new Vector2(X.Kilometers, Y.Kilometers);

        public Vector2 Decimeters => new Vector2(X.Decimeters, Y.Decimeters);

        /// <summary>
        ///     Returns a point represented in centimeters.
        /// </summary>
        public Vector2 Centimeters => new Vector2(Meters.X*1E2, Meters.Y*1E2);

        /// <summary>
        ///     Returns a point represented in millimeters.
        /// </summary>
        public Vector2 Millimeters => new Vector2(Meters.X*1E3, Meters.Y*1E3);

        public Vector2 Micrometers => new Vector2(X.Micrometers, Y.Micrometers);

        public Vector2 Nanometers => new Vector2(X.Nanometers, Y.Nanometers);

        #endregion

        #region Static methods

        public static Length2d Zero => new Length2d();

        public static Length2d FromMeters(double xMeters, double yMeters)
        {
            return new Length2d(xMeters, yMeters);
        }

        public static Length2d FromCentimeters(double xCentimeters, double yCentimeters)
        {
            return new Length2d(xCentimeters*1E-2, yCentimeters*1E-2);
        }

        public static Length2d FromMillimeters(double xMillimeters, double yMillimeters)
        {
            return new Length2d(xMillimeters*1E-3, yMillimeters*1E-3);
        }

        #endregion

        #region Arithmetic operators

        public static Length2d operator -(Length2d right)
        {
            return FromMeters(-right.X.Meters, -right.Y.Meters);
        }

        public static Length2d operator +(Length2d left, Length2d right)
        {
            double x = left.X.Meters + right.X.Meters;
            double y = left.Y.Meters + right.Y.Meters;
            return FromMeters(x, y);
        }

        public static Length2d operator -(Length2d left, Length2d right)
        {
            double x = left.X.Meters - right.X.Meters;
            double y = left.Y.Meters - right.Y.Meters;
            return FromMeters(x, y);
        }

        public static Length2d operator *(double left, Length2d right)
        {
            double x = left*right.X.Meters;
            double y = left*right.Y.Meters;
            return FromMeters(x, y);
        }

        public static Length2d operator *(Length2d left, double right)
        {
            double x = left.X.Meters*right;
            double y = left.Y.Meters*right;
            return FromMeters(x, y);
        }

        public static Length2d operator *(Length2d left, Length2d right)
        {
            double x = left.X.Meters*right.X.Meters;
            double y = left.Y.Meters*right.Y.Meters;
            return FromMeters(x, y);
        }

        public static Length2d operator /(Length2d left, double right)
        {
            double x = left.X.Meters/right;
            double y = left.Y.Meters/right;
            return FromMeters(x, y);
        }

        public static Vector2 operator /(Length2d left, Length2d right)
        {
            double x = left.X.Meters/right.X.Meters;
            double y = left.Y.Meters/right.Y.Meters;
            return new Vector2(x, y);
        }

        #endregion

        #region Public methods

        public override string ToString()
        {
            return
                $"({X.Meters:0.##}, {Y.Meters:0.##}) {UnitSystem.GetCached().GetDefaultAbbreviation(LengthUnit.Meter)}";
        }

        public Length DistanceTo(Length2d other)
        {
            double dx = X.Meters - other.X.Meters;
            double dy = Y.Meters - other.Y.Meters;
            double distance = Math.Sqrt(dx*dx + dy*dy);

            return Length.FromMeters(distance);
        }

        #endregion

        #region Equality

        private static IEqualityComparer<Length2d> MetersComparer { get; } = new MetersEqualityComparer();

        public bool Equals(Length2d other)
        {
            return MetersComparer.Equals(this, other);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            return obj is Length2d && Equals((Length2d) obj);
        }

        public override int GetHashCode()
        {
            return Meters.GetHashCode();
        }

        public static bool operator !=(Length2d left, Length2d right)
        {
            return left.Meters != right.Meters;
        }

        public static bool operator ==(Length2d left, Length2d right)
        {
            return left.Meters == right.Meters;
        }

        private sealed class MetersEqualityComparer : IEqualityComparer<Length2d>
        {
            public bool Equals(Length2d x, Length2d y)
            {
                return x.Meters.Equals(y.Meters);
            }

            public int GetHashCode(Length2d obj)
            {
                return obj.Meters.GetHashCode();
            }
        }

        #endregion
    }
}


text:
        <title>Fleet Submission Form</title>

Submit your fleet here

<form action="/submitter" method="POST" id="inputform">

Player Name:<input type="text" name="player" width="40">

Tournament name:<input type="text" name="tourney" width="40">

Attendees:<input type="text" name="attendees" width="40">

Placing:<input type="text" name="place" width="40">

Fleet:
</form>

<textarea name="fleet" cols="40" rows="20" form="inputform" onfocus="clearContents(this);">
This app currently supports text lists exported from:

    Fab's
    Warlords
    Armada Fleet Designer (Android)
</textarea>

<input form="inputform" type="submit">


text:
<?php

namespace Hmaus\Branda\ApiDescription;

use Hmaus\DrafterPhp\DrafterInterface;
use Hmaus\Spas\Parser\ParsedRequest;
use Hmaus\Spas\Parser\Parser;

class ApiBlueprint implements DescriptionReader
{
    /**
     * @var DrafterInterface
     */
    private $drafter;

    /**
     * @var Parser
     */
    private $requestProvider;

    public function __construct(DrafterInterface $drafter, Parser $requestProvider)
    {
        $this->drafter = $drafter;
        $this->requestProvider = $requestProvider;
    }

    /**
     * @param string $description Absolute path to api description
     * @return ParsedRequest[]
     */
    public function parse($description)
    {
        $rawParseResult = $this->drafter
            ->input($description)
            ->format('json')
            ->type('refract')
            ->run();

        return $this->requestProvider->parse(
            json_decode($rawParseResult, true)
        );
    }
}


text:
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using LockCheck;

namespace Test.NetCore
{
    class Program
    {
        private static int Main(string[] args)
        {
            try
            {
                if (!Debugger.IsAttached)
                {
                    if (args.Length == 0)
                    {
                        Console.Error.WriteLine("Usage: {0} FILE [FILE ...]",
                            typeof(Program).Assembly.GetName().Name);
                        return 1;
                    }

                    if (args[0] == "-self")
                    {
                        SelfTest();
                    }
                    else
                    {
                        DumpLockInfo(args);
                    }
                }
                else
                {
                    SelfTest();
                }
            }
            catch (Win32Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                return ex.ErrorCode;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return ex.HResult;
            }
            return 0;
        }

        private static void DumpLockInfo(string[] paths)
        {
            var infos = LockManager.GetLockingProcessInfos(paths, LockManagerFeatures.UseLowLevelApi);
            if (!infos.Any())
            {
                Console.WriteLine("No locking processes found.");
                return;
            }

            bool first = true;
            foreach (var p in infos)
            {
                if (!first)
                {
                    Console.WriteLine("----------------------------------------------------");
                }

                Console.WriteLine("Process ID        : {0}", p.ProcessId);
                Console.WriteLine("Process Start Time: {0}", p.StartTime.ToString("F"));
                Console.WriteLine("Process File Path : {0}", p.ExecutableFullPath);
                Console.WriteLine("Process User Name : {0}", p.Owner);
                Console.WriteLine("Executable  Name  : {0}", p.ExecutableName);
                Console.WriteLine("Application Name  : {0}", p.ApplicationName);
                Console.WriteLine("Session ID        : {0}", p.SessionId);
                first = false;
            }
        }

        public static void SelfTest()
        {
            string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".test");

            try
            {
                using (var file = File.Open(tempFile, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    DumpLockInfo(new[] { tempFile });
                }
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
    }
}


text:
package org.javacc.plugin.gradle.javacc.compiler;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.gradle.api.file.FileTree;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.TaskCollection;
import org.gradle.api.tasks.compile.JavaCompile;

public class JavaccCompilerInputOutputConfiguration implements CompilerInputOutputConfiguration {
    private final File inputDirectory;
    private final File outputDirectory;
    private final FileTree source;
    private final Set<JavaCompile> javaCompileTasks;

    public JavaccCompilerInputOutputConfiguration(File inputDirectory, File outputDirectory, FileTree source, TaskCollection<JavaCompile> javaCompileTasks) {
        this.inputDirectory = inputDirectory;
        this.outputDirectory = outputDirectory;
        this.source = source;
        this.javaCompileTasks = new HashSet<JavaCompile>();

        if (!CollectionUtils.isEmpty(javaCompileTasks)) {
            this.javaCompileTasks.addAll(javaCompileTasks);
        }
    }

    @Override
    public File getOutputDirectory() {
        return outputDirectory;
    }

    @Override
    public File getInputDirectory() {
        return inputDirectory;
    }

    @Override
    public File getTempOutputDirectory() {
        return new File(getOutputDirectory(), "tmp");
    }

    @Override
    public FileTree getSource() {
        return source;
    }

    @Override
    public FileTree getCompleteSourceTree() {
        FileTree javaccTaskSourceTree = getSource();
        FileTree javaTasksSourceTree = getJavaSourceTree();
        FileTree completeSourceTree;

        if (javaTasksSourceTree == null) {
            completeSourceTree = javaccTaskSourceTree;
        } else {
            completeSourceTree = javaccTaskSourceTree.plus(javaTasksSourceTree);
        }

        return excludeOutputDirectory(completeSourceTree);
    }

    @Override
    public FileTree getJavaSourceTree() {
        FileTree javaSourceTree = null;

        for (JavaCompile task : javaCompileTasks) {
            if (javaSourceTree == null) {
                javaSourceTree = task.getSource();
            } else {
                javaSourceTree = javaSourceTree.plus(task.getSource());
            }
        }

        return excludeOutputDirectory(javaSourceTree);
    }

    private FileTree excludeOutputDirectory(FileTree sourceTree) {
        if (sourceTree == null) {
            return null;
        }

        Spec<File> outputDirectoryFilter = new Spec<File>() {

            @Override
            public boolean isSatisfiedBy(File file) {
                return file.getAbsolutePath().contains(getOutputDirectory().getAbsolutePath());
            }
        };

        FileTree fileTree = sourceTree.minus(sourceTree.filter(outputDirectoryFilter)).getAsFileTree();
        return fileTree;
    }
}


text:
package com.datatorrent.contrib.redis;

import java.util.Map;

import com.datatorrent.lib.util.KeyValPair;

/**
 * This is the an implementation of a Redis input operator It takes in keys to
 * fetch and emits Values stored as Maps in Redis i.e. when value datatype in
 * Redis is HashMap
 *
 * @displayName Redis Input Operator for Map
 * @category Store
 * @tags input operator, key value
 * @since 3.1.0
 *
 */

public class RedisMapAsValueInputOperator extends AbstractRedisInputOperator<KeyValPair<String, Map<String, String>>>
{
  @Override
  public void processTuples()
  {
    for (String key : keys) {
      if (store.getType(key).equals("hash")) {
        Map<String, String> mapValue = store.getMap(key);
        outputPort.emit(new KeyValPair<String, Map<String, String>>(key, mapValue));
      }
    }
    keys.clear();
  }

  @Override
  public KeyValPair<String, Map<String, String>> convertToTuple(Map<Object, Object> o)
  {
    // Do nothing for the override, Emit already handled in processTuples
    return null;
  }
}


text:
Remove-SCDatabaseOperations -Path "$PWD\Sitecore 8.2 rev. 170614_single.scwdp.zip"
Remove-SCDatabaseOperations -Path "$PWD\Web Forms for Marketers 8.2 rev. 170518_single.scwdp.zip"


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Fl. Alpes marit. 2:222. 1896

#### Original name
null

### Remarks
null


text:
package com.thinkgem.jeesite.modules.sys.dao.gbj;

import java.util.List;

import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.modules.sys.entity.gbj.GbjUserRewardComments;

/**
 * 悬赏信息评论DAO接口
 *
 * @author snnu
 * @version 2017-12-21
 */
@MyBatisDao
public interface GbjUserRewardCommentsDao extends CrudDao<GbjUserRewardComments> {
	// 根据reward_id查询卖标评论信息
	public List<GbjUserRewardComments> getCommentsList(String reward_Id);

	public List<GbjUserRewardComments> findDomainArticleRewardCommentsList(String id);

	public List<GbjUserRewardComments> findDomainArticleRewardReplyCommentsList(String id);

	public int updateCount(GbjUserRewardComments gbjUserRewardComments);

}


text:
package org.devocative.ares.cmd;

import org.devocative.ares.vo.TabularVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class ConsoleResultProcessing {
	private static final Logger logger = LoggerFactory.getLogger(ConsoleResultProcessing.class);

	private int ignoreStartingLines = 0;

	private int ignoreLinesAfterHeader = 0;

	private List<String> columns = new ArrayList<>();

	private List<List<String>> rows = new ArrayList<>();

	private String text;

	private Integer size;

	// ---------------

	private List<String> possibleColumns = new ArrayList<>();

	private String splitBy;

	// ---------------

	private List<Integer> indexOfColumns = new ArrayList<>();

	// ------------------------------

	public ConsoleResultProcessing(String text) {
		this.text = text;
	}

	// ------------------------------

	public ConsoleResultProcessing setIgnoreStartingLines(int ignoreStartingLines) {
		this.ignoreStartingLines = ignoreStartingLines;
		return this;
	}

	public ConsoleResultProcessing setIgnoreLinesAfterHeader(int ignoreLinesAfterHeader) {
		this.ignoreLinesAfterHeader = ignoreLinesAfterHeader;
		return this;
	}

	public ConsoleResultProcessing setPossibleColumns(String... columns) {
		copyArrToCollection(columns, this.possibleColumns, false);
		return this;
	}

	public ConsoleResultProcessing setSplitBy(String splitBy) {
		this.splitBy = splitBy;
		return this;
	}

	public ConsoleResultProcessing setSize(Integer size) {
		this.size = size;
		return this;
	}

	public List<String> getColumns() {
		return columns;
	}

	public List<List<String>> getRows() {
		return rows;
	}

	// ---------------

	public ConsoleResultProcessing prepend(String txt) {
		text = txt + text;
		return this;
	}

	public ConsoleResultProcessing append(String txt) {
		text = text + txt;
		return this;
	}

	public TabularVO build() {
		return build(null);
	}

	public TabularVO build(Map<String, String> filter) {
		text = text.replaceAll("[\r]", "");
		if (text.length() > 0) {
			String[] split = text.split("[\n]");

			List<String> lines = new ArrayList<>();
			copyArrToCollection(split, lines, false);

			for (int i = 0; i < ignoreStartingLines; i++) {
				lines.remove(0);
			}

			for (int i = 0; i < ignoreLinesAfterHeader; i++) {
				lines.remove(1);
			}

			String header = lines.remove(0);

			if (!possibleColumns.isEmpty()) {
				findByColumnNames(header);
				fillRowsByIndex(lines);
			} else if (splitBy != null) {
				fillBySplit(header, lines);
			} else {
				throw new RuntimeException("Auto-find is not implemented!");
			}

			logger.debug("Final Columns: {}", columns);
			logger.debug("Rows: {}", rows);

			return new TabularVO<>(columns, rows, filter).setSize(size);
		} else {
			return new TabularVO<>(Collections.singletonList("No Shell Result!"), Collections.emptyList(), null);
		}
	}

	// ------------------------------

	private void findByColumnNames(String header) {
		indexOfColumns.add(0);

		for (String column : possibleColumns) {
			int idx = 0;
			while (idx > -1) {
				idx = header.indexOf(column, idx);
				if (idx > -1) {
					if (!indexOfColumns.contains(idx)) {
						indexOfColumns.add(idx);
					}

					idx += column.length();
				}
			}
		}

		Collections.sort(indexOfColumns);

		String firstCol = header.substring(indexOfColumns.get(0), indexOfColumns.get(1));
		if (firstCol.trim().isEmpty()) {
			indexOfColumns.remove(1);
		}
		logger.debug("Found Index of Columns: {}", indexOfColumns);

		findPartsByIndex(header, columns);
	}

	private void fillRowsByIndex(List<String> lines) {
		for (String line : lines) {
			List<String> cells = new ArrayList<>();

			findPartsByIndex(line, cells);

			rows.add(cells);
		}
	}

	private void findPartsByIndex(String line, List<String> cells) {
		for (int i = 0; i < indexOfColumns.size(); i++) {
			int start = indexOfColumns.get(i);
			int end;
			if ((i + 1) < indexOfColumns.size()) {
				end = indexOfColumns.get(i + 1);
			} else {
				end = line.length();
			}

			String cell = line.substring(start, end).trim();
			cells.add(cell);
		}
	}

	private void fillBySplit(String header, List<String> lines) {
		String[] headerParts = header.split(splitBy);
		copyArrToCollection(headerParts, columns, true);

		for (String line : lines) {
			String[] lineParts = line.split(splitBy);
			List<String> cells = new ArrayList<>();
			copyArrToCollection(lineParts, cells, true);

			if (lineParts.length < headerParts.length) {
				int diff = headerParts.length - lineParts.length;
				for (int i = 0; i < diff; i++) {
					cells.add("");
				}
			}

			rows.add(cells);
		}
	}

	private void copyArrToCollection(String[] arr, Collection<String> col, boolean ignoreEmptyCell) {
		for (String cell : arr) {
			cell = cell.trim();
			if (ignoreEmptyCell || cell.length() > 0) {
				col.add(cell);
			}
		}
	}
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
   xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">
  <!-- Serve /api/ content through the guice context listener -->
  <filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/api/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>
        com.google.tripmeout.frontend.FrontendGuiceServletContextListener
    </listener-class>
  </listener>

  <!-- Filter all requests that don't have a known static content extension.
       This is pretty gross, but I don't have a better solution. -->
  <filter>
    <filter-name>nonStaticExtensionDefaulter</filter-name>
    <filter-class>com.google.tripmeout.ui.NonStaticExtensionDefaulter</filter-class>
    <!-- A comma seperated list of extensions to not filter. -->
    <init-param>
      <param-name>extensions</param-name>
      <param-value>js,jpg,png,css,json</param-value>
    </init-param>
    <!-- A regex of prefixes to ignore (don't serve the default content for). This
         allows us to skip the default content for auth. -->
    <init-param>
        <param-name>ignore-prefix-regex</param-name>
        <param-value>/_ah/.*</param-value>
    </init-param>
    <!-- The default content to serve for all requests that do not use one of the
         specified extensions. -->
    <init-param>
      <param-name>default-content</param-name>
      <param-value>/index.html</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>nonStaticExtensionDefaulter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>


text:
<?php
if ( ! defined( 'ABSPATH' ) ) {
	die( '-1' );
}

require_once( 'class-vc-grids-common.php' );
$masonryMediaGridParams = VcGridsCommon::getMasonryMediaCommonAtts();

return array(
	'name' => __( 'Masonry Media Grid', 'js_composer' ),
	'base' => 'vc_masonry_media_grid',
	'icon' => 'vc_icon-vc-masonry-media-grid',
	'category' => __( 'Content', 'js_composer' ),
	'description' => __( 'Masonry media grid from Media Library', 'js_composer' ),
	'params' => $masonryMediaGridParams,
);


text:
<?php
$errors_v = validation_errors('
', '
');
if (!empty($errors_v)) {
    echo '
'.$errors_v.'
';
}
if(!empty($success))
{
     echo '
'.$success.'
';
}
if(!empty($rows) && is_array($rows))
{
    $hidden = array('idpid'=>$idp_id);
    $attrs = array('id'=>'arpexlusions');
    echo form_open(current_url(),$attrs,$hidden);
    echo form_fieldset();
    foreach($rows as $r)
    {
       echo '

'.$r.'

';

    }
    echo form_fieldset_close();
    $btns = array(
        '<button type="reset" name="reset" value="reset" class="button alert">
                  '.lang('rr_reset').'</button>',
        '<button type="submit" name="modify" value="submit" class="button">
                  '.lang('rr_save').'</button>'
    );
    echo '
';

    echo revealBtnsRow($btns);
    echo  '
';
    echo form_close();
}
else
{
   echo '
'.lang('nospfoundtoexcl').'
';

}


text:
@implementation eLongCountlyEventShow

- (void)sendEventCount:(NSInteger)count {
    [super sendEvent:@"show" count:count];
}

- (id) init{
    if (self = [super init]) {
        self.channelId = [Countly sharedInstance].channelId;
        self.appt = [Countly sharedInstance].appt;
        self.status = @([Countly sharedInstance].status);
    }
    return self;
}

@end


text:
import unittest
import simple_script as ss

class SimpleTest(unittest.TestCase):

	def testAdd(self):
		self.assertTrue(ss.add(1, 1) == 2)
		self.assertTrue(ss.add(2, 2) == 4)

	def testSubtract(self):
		self.assertTrue(ss.subtract(2, 1) == 1)

	def testMultiply(self):
		self.assertTrue(ss.multiply(2, 3) == 6)

	# Commented out to test coverage
	# def testDivide(self):
	# 	self.assertTrue(ss.divide(4, 2) == 2)

if __name__ == '__main__':
	unittest.main()


text:
module LSQS
  class Message
    attr_reader :body, :id, :md5
    attr_accessor :visibility_timeout

    def initialize(options = {})
      @body = options['MessageBody'] || ''
      @id   = options.fetch('Id') { SecureRandom.uuid }
      @md5  = options.fetch('MD5') { Digest::MD5.hexdigest(body) }
    end

    def attributes
      {
        "MessageBody" => body,
        "Id"          => id,
        "MD5"         => md5,
      }
    end

    ##
    # Check if a message's visibility has timed out.
    #
    # @return [TrueClass|FalseClass]
    #
    def expired?
      visibility_timeout.nil? || visibility_timeout < Time.now
    end

    ##
    # Sets the time when the message should expire.
    #
    # @param [Fixnum] seconds
    #
    # @return [Time]
    #
    def expire_in(seconds)
      @visibility_timeout = Time.now + seconds
    end

    ##
    # Resets the visibility time of the message.
    #
    # @return [NilClass]
    #
    def expire
      @visibility_timeout = nil
    end
  end # Message
end # LSQS


text:
namespace Bempp
{

namespace {

double min3(double x, double y, double z)
{
    return std::min(x, std::min(y, z));
}

double max3(double x, double y, double z)
{
    return std::max(x, std::max(y, z));
}

bool isNew(const arma::Col<double>& intersection,
           const std::vector<arma::Col<double> >& intersections)
{
    const double EPSILON = 1e-10;
    for (size_t i = 0; i < intersections.size(); ++i)
        if (fabs(intersections[i](0) - intersection(0)) < EPSILON &&
                fabs(intersections[i](1) - intersection(1)) < EPSILON &&
                fabs(intersections[i](2) - intersection(2)) < EPSILON)
            return false;
    return true;
}

} // namespace

bool Grid::isBarycentricRepresentationOf(const Grid& other) const {
    if (!other.hasBarycentricGrid())
        return false;
    else
        return (this==other.barycentricGrid().get());
}

void Grid::getBoundingBox(arma::Col<double>& lowerBound,
                          arma::Col<double>& upperBound) const
{
    // In this simple implementation we assume that all elements are flat.
    if (m_lowerBound.n_rows == dimWorld() &&
            m_upperBound.n_rows == dimWorld()) {
        lowerBound = m_lowerBound;
        upperBound = m_upperBound;
        return;
    }

    std::auto_ptr<GridView> view = leafView();

    arma::Mat<double> vertices;
    arma::Mat<int> elementCorners; // unused
    arma::Mat<char> auxData; // unused
    view->getRawElementData(vertices, elementCorners, auxData);

    m_lowerBound = lowerBound = arma::min(vertices, 1); // 1 -> min. value in each row
    m_upperBound = upperBound = arma::max(vertices, 1); // 1 -> max. value in each row
}

std::vector<bool> areInside(const Grid& grid, const arma::Mat<double>& points)
{
    if (grid.dim() != 2 || grid.dimWorld() != 3)
        throw NotImplementedError("areInside(): currently implemented only for"
                                  "2D grids embedded in 3D spaces");

    std::auto_ptr<GridView> view = grid.leafView();
    std::auto_ptr<EntityIterator<0> > it = view->entityIterator<0>();

    std::vector<arma::Mat<double> > triangles;
    triangles.reserve(view->entityCount(0));

    {
        arma::Mat<double> triangle(grid.dimWorld(), 3);
        arma::Mat<double> corners;
        while (!it->finished()) {
            const Entity<0>& element = it->entity();
            element.geometry().getCorners(corners);
            if (corners.n_cols == 3) // triangle
                triangles.push_back(corners);
            else if (corners.n_cols == 4) { // quadrilateral, split into 2 triangles
                // NOTE: this won't work for concave quads,
                triangle.col(0) = corners.col(0);
                triangle.col(1) = corners.col(1);
                triangle.col(2) = corners.col(2);
                triangles.push_back(triangle);
                triangle.col(0) = corners.col(2);
                triangle.col(1) = corners.col(3);
                triangle.col(2) = corners.col(0);
                triangles.push_back(triangle);
            } else
                throw std::runtime_error("areInside(): unknown element type");
            it->next();
        }
    }

    const size_t triangleCount = triangles.size();
    arma::Row<double> xMins(triangleCount);
    arma::Row<double> xMaxs(triangleCount);
    arma::Row<double> yMins(triangleCount);
    arma::Row<double> yMaxs(triangleCount);
    arma::Row<double> zMins(triangleCount);
    arma::Row<double> zMaxs(triangleCount);
    for (size_t i = 0; i < triangleCount; ++i) {
        const arma::Mat<double>& triangle = triangles[i];
        xMins(i) = min3(triangle(0, 0), triangle(0, 1), triangle(0, 2));
        xMaxs(i) = max3(triangle(0, 0), triangle(0, 1), triangle(0, 2));
        yMins(i) = min3(triangle(1, 0), triangle(1, 1), triangle(1, 2));
        yMaxs(i) = max3(triangle(1, 0), triangle(1, 1), triangle(1, 2));
        zMins(i) = min3(triangle(2, 0), triangle(2, 1), triangle(2, 2));
        zMaxs(i) = max3(triangle(2, 0), triangle(2, 1), triangle(2, 2));
    }

    const double gridXMin = arma::min(xMins);
    const double gridXMax = arma::max(xMaxs);
    const double gridYMin = arma::min(yMins);
    const double gridYMax = arma::max(yMaxs);
    const double gridZMin = arma::min(zMins);
    const double gridZMax = arma::max(zMaxs);

    const size_t pointCount = points.n_cols;
    std::vector<bool> result(pointCount, false);
    std::vector<arma::Col<double> > intersections;
    arma::Col<double> intersection(3);
    for (size_t pt = 0; pt < pointCount; ++pt) {
        if (points(0, pt) < gridXMin || points(0, pt) > gridXMax ||
                points(1, pt) < gridYMin || points(1, pt) > gridYMax ||
                points(2, pt) < gridZMin || points(2, pt) > gridZMax)
            continue; // point outside grid's bounding box
        intersections.clear();
        for (size_t tri = 0; tri < triangleCount; ++tri)
            if (points(0, pt) >= xMins(tri) && points(0, pt) <= xMaxs(tri) &&
                    points(1, pt) >= yMins(tri) && points(1, pt) <= yMaxs(tri))
                if (zRayIntersectsTriangle(points.colptr(pt),
                                           triangles[tri].colptr(0),
                                           triangles[tri].colptr(1),
                                           triangles[tri].colptr(2),
                                           intersection.colptr(0)) > 0.)
                    if (isNew(intersection, intersections))
                        intersections.push_back(intersection);
        result[pt] = intersections.size();
    }
    return result;
}

std::vector<bool> areInside(const Grid& grid, const arma::Mat<float>& points)
{
    arma::Mat<double> pointsDouble(points.n_rows, points.n_cols);
    for (int c = 0; c < points.n_cols; ++c)
        for (int r = 0; r < points.n_rows; ++r)
            pointsDouble(r, c) = points(r, c);
    return areInside(grid, pointsDouble);
}

} // namespace Bempp


text:
<?php

use Dflydev\FigCookies\Cookies;

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'bootstrap.php';

$app = new Slim\App(array(
    'displayErrorDetails' => DEVELOP,
    'routerCacheFile' => ROOTDIR . DS . 'tmp' . DS . 'router.'.$version.'.cache'
));

$container = $app->getContainer();

$container['config'] = $config;
$container['I18N']   = $I18N;

$app->add(function ($request, $response, $next) {
    $path = $request->getUri()->getPath();

    if (!in_array($path, array('login', 'config'))) {
        $cookies = Cookies::fromRequest($request);

        if ($cookies->has('token')) {
            $session = new ORM\Session;
            $session->filterByToken($cookies->get('token')->getValue())
                    ->filterRaw('until >= {1}', time())
                    ->findOne();
            if (!$session->getUser()) {
                return $response->withStatus(401);
            }
        } else {
            return $response->withStatus(401);
        }
    }

    return $next($request, $response);
});

foreach (glob(__DIR__ . DS . 'routes' . DS . '*.php') as $file) {
	require_once $file;
}

$app->run();


text:
from hypothesis.utils.conventions import not_set

def accept(f):
    def test_next_notification_after_last_notification(self, subscription=not_set):
        return f(self=self, subscription=subscription)
    return test_next_notification_after_last_notification


text:
'use strict';

var Client = require('../lib/client');
var expect = require('chai').expect;
var sinon = require('sinon');
var noop = function() {};
var dummyTransport = {
  subscribe: noop,
  publish: noop
};

describe('Uva client', function() {
  describe('call', function() {
    it('should throw an error if no parameters were passed', function() {
      var client = new Client(dummyTransport, {
        name: 'foo'
      });

      expect(function() {
        client.call();
      }).to.throw(TypeError, 'call requires a methodName');
    });

    it('should not throw an error if the third parameter is not a function', function() {
      var client = new Client(dummyTransport, {
        name: 'foo'
      });

      expect(function() {
        client.call('foo', null, 4234);
      }).not.to.throw(Error);
    });

    it('should not throw an exception if the second parameter is a callback function', function() {
      var client = new Client(dummyTransport, {
        name: 'foo'
      });

      expect(function() {
        client.call('foo', noop);
      }).not.to.throw(Error);
    });

    it('should not throw an exception if the third parameter is a callback function', function() {
      var client = new Client(dummyTransport, {
        name: 'foo'
      });

      expect(function() {
        client.call('foo', {
          a: 34
        }, noop);
      }).not.to.throw(Error);
    });

    it('should not throw an exception if no callback function passed', function() {
      var client = new Client(dummyTransport, {
        name: 'foo'
      });

      expect(function() {
        client.call('foo', {
          a: 34
        });
      }).not.to.throw(Error);
    });
  });

  describe('register', function() {
    it('should register one method', function() {
      var client = new Client(dummyTransport, {
        name: 'foo'
      });

      client.register('foo1');
      expect(client.methods.foo1).to.be.a('function');
    });

    it('should register several methods', function() {
      var client = new Client(dummyTransport, {
        name: 'foo'
      });

      client.register(['foo2', 'foo3']);
      expect(client.methods.foo2).to.be.a('function');
      expect(client.methods.foo3).to.be.a('function');
    });
  });
});


text:
var logger = require('./index').defaultLogger;

// Set the path for the files (used by the file logger)
var options = {filePath: __dirname };
logger.setup(options);

// Log a few things with different levels
logger.debug('hello world');
logger.info('just for your information');
logger.warn('bridge freezes before the road');
logger.error('something bad just happend');

console.log("\r\n\r\nTest is done.");
console.log("There should be a file (named with today's date) with these log entries too");


text:
package org.kuali.rice.krad.service;

import org.kuali.rice.krad.bo.Attachment;
import org.kuali.rice.krad.bo.Note;
import org.kuali.rice.krad.bo.PersistableBusinessObject;

import java.io.IOException;
import java.io.InputStream;

/**
 * Defines the methods common to all AttachmentService implementations
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public interface AttachmentService {
    /**
     * Stores the given fileContents and returns referring Attachment object which acts as a momento to the archived object.
     *
     * @param parent - the document to which the attachment belongs
     * @param uploadedFileName - the name of the uploaded file
     * @param mimeType - the uploaded file's mime type
     * @param  fileSize - the size of the uploaded file in bytes
     * @param  fileContents - an input stream used to read the file's contents
     * @param attachmentType -the attachment type code
     *
     * @return Attachment - the attachment, having been written to the file system
     * @throws IOException
     */
    public Attachment createAttachment(PersistableBusinessObject parent, String uploadedFileName, String mimeType, int fileSize, InputStream fileContents, String attachmentType) throws IOException;

    /**
     * Retrieves a given Attachments contents from the corresponding Attachment object
     *
     * @param attachment - the attachment whose contents are to be retrieved
     *
     * @return OutputStream
     * @throws IOException
     */
    public InputStream retrieveAttachmentContents(Attachment attachment) throws IOException;

    /**
     * Deletes a given DocumentAttachment contents from the corresponding Attachment object
     *
     * @param attachment - the attachment whose contents are to be deleted
     */
    public void deleteAttachmentContents(Attachment attachment);

    /**
     *
     * Moves attachments on notes from the pending directory to the real one
     * @param note the Note from which to move attachments.  If this Note does not
     * have an attachment then this method does nothing.
     *
     * @throws IllegalArgumentException if the given Note is null
     * @throws IllegalArgumentException if the Note does not have a valid object id
     */
    public void moveAttachmentWherePending(Note note);

    /**
     * Deletes pending attachments that were last modified before the given time.  Java does not have easy access to a file's creation
     * time, so we use modification time instead.
     *
     * @param modificationTime the number of milliseconds since "the epoch" (i.e.January 1, 1970, 00:00:00 GMT).  java.util.Date and java.util.Calendar's
     *  methods return time in this format.  If a pending attachment was modified before this time, then it will be deleted (unless an error occurs)
     */
    public void deletePendingAttachmentsModifiedBefore(long modificationTime);

    public Attachment getAttachmentByNoteId(Long noteId);
}


text:
package com.qinyadan.monitor.network.util;

import java.net.InetSocketAddress;

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

import com.qinyadan.monitor.network.MonitorSocketException;
import com.qinyadan.monitor.network.client.MonitorClient;
import com.qinyadan.monitor.network.client.MonitorClientFactory;

public final class ClientFactoryUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(ClientFactoryUtils.class);

	public static MonitorClient createPinpointClient(String host, int port, MonitorClientFactory clientFactory) {
		InetSocketAddress connectAddress = new InetSocketAddress(host, port);
		return createPinpointClient(connectAddress, clientFactory);
	}

	public static MonitorClient createPinpointClient(InetSocketAddress connectAddress,
			MonitorClientFactory clientFactory) {
		MonitorClient monitorClient = null;
		for (int i = 0; i < 3; i++) {
			try {
				monitorClient = clientFactory.connect(connectAddress);
				LOGGER.info("tcp connect success. remote:{}", connectAddress);
				return monitorClient;
			} catch (MonitorSocketException e) {
				LOGGER.warn("tcp connect fail. remote:{} try reconnect, retryCount:{}", connectAddress, i);
			}
		}
		LOGGER.warn("change background tcp connect mode remote:{} ", connectAddress);
		return monitorClient;
	}

}


text:
<?php

/**
 * Quote payments collection
 *
 * @category    Mage
 * @package     Mage_Sales
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Sales_Model_Mysql4_Quote_Payment_Collection extends Mage_Sales_Model_Resource_Quote_Payment_Collection
{
}


text:
require 'vcr'

VCR.config do |c|
  c.stub_with :fakeweb
  c.cassette_library_dir     = 'features/cassettes'
  c.default_cassette_options = { :record => :new_episodes }
end

VCR.cucumber_tags do |t|
  t.tag  '@tumblr_movingtompls'
end

FakeWeb.allow_net_connect = false


text:
from decimal import Decimal

# TODO open this to translation/expansion?
TRUE_VALUES = ('true', 'on', 'yes', '1')

class EnvDict(dict):
    """
    A dictionary that starts from a system environment dictionary and casts
    dictionary values from source strings.
    """

    def __init__(self, *args, **kwargs):
        """
        Pull in the default environment variables, then update using a provided
        file, then update with the first
        """
        self.cast_funcs = {
            int: int,
            str: str,
            float: float,
            bool: lambda x: x.lower() in TRUE_VALUES,
            list: lambda x: list(x.split(',')),
            dict: lambda x: dict([y.split('=') for y in x.split(',')]),
            'decimal': lambda x: Decimal(x),
        }
        self.cast_funcs.update(kwargs.pop('casts', {}))
        self.schema = kwargs.pop('schema', {})
        super(EnvDict, self).__init__(*args, **kwargs)
        for key, cast in self.schema.items():
            self[key] = self.cast_funcs.get(cast, str)(self[key])

    def get(self, key, default=None, **kwargs):
        """
        The default value should never be cast
        """
        cast = kwargs.pop('cast', None)

        if not key in self:
            return default
        val = self[key]

        if cast is not None:
            return self.cast_funcs.get(cast, str)(val)
        return val

    def pop(self, key, default=None, **kwargs):
        """
        The default value should never be cast
        """
        cast = kwargs.pop('cast', None)

        if not key in self:
            return default
        val = self[key]

        if cast is not None:
            return self.cast_funcs.pop(cast, str)(val)
        return val

    def recast(self, schema=None):
        """
        Should recast the dictionary based on a schema
        """
        if schema:
            self.schema = schema
        for key, cast in self.schema.items():
            self[key] = self.cast_funcs.get(cast, str)(self[key])
        return self