<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Microsoft Corporation
 *
 * -=- Robust Distributed System Nucleus (rDSN) -=-
 *
 * 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.
 */

/*
 * Description:
 *     Disk IO performance test
 *
 * Revision history:
 *     2016-01-05, Tianyi Wang, first version
 */

#include <cinttypes>
#include <gtest/gtest.h>
#include <dsn/service_api_cpp.h>
#include <dsn/cpp/test_utils.h>
#include <boost/lexical_cast.hpp>

void aio_testcase(uint64_t block_size, size_t concurrency, bool is_write, bool shared)
{
    std::unique_ptr<char[]> buffer(new char[block_size]);
    std::vector<dsn_handle_t> files;
    files.resize(concurrency);

    int flag;
    if (is_write)
    {
        flag = O_CREAT | O_RDWR;
        if (shared)
        {
            if (utils::filesystem::file_exists("temp"))
                utils::filesystem::remove_path("temp");
        }
        else
        {
            for (int i = 0; i < concurrency; i++)
            {
                std::stringstream ss;
                ss << "temp." << i;
                auto file = ss.str();
                if (utils::filesystem::file_exists(file))
                    utils::filesystem::remove_path(file);
            }
        }
    }
    else
    {
        flag = O_RDWR;
    }

    if (shared)
    {
        auto file_handle = dsn_file_open("temp", flag, 0666);
        EXPECT_TRUE(file_handle != nullptr);
        for (int i = 0; i < concurrency; i++)
            files[i] = file_handle;
    }
    else
    {
        for (int i = 0; i < concurrency; i++)
        {
            std::stringstream ss;
            ss << "temp." << i;
            auto file = ss.str();
            auto file_handle = dsn_file_open(file.c_str(), flag, 0666);
            EXPECT_TRUE(file_handle != nullptr);
            files[i] = file_handle;
        }
    }

    std::atomic<uint64_t> io_count(0);
    std::atomic<uint64_t> cb_flying_count(0);
    volatile bool exit = false;
    std::function<void(int)> cb;
    std::vector<uint64_t> offsets;
    offsets.resize(concurrency);

    cb = [&](int index)
    {
        if (!exit)
        {
            auto ioc = io_count++;
            uint64_t offset;
            if (!shared)
            {
                offset = offsets[index];
                offsets[index] += block_size;
            }
            else
            {
                offset = ioc * block_size;
            }

            cb_flying_count++;
            if (is_write)
            {
                file::write(files[index], buffer.get(), (int)block_size, offset,
                    LPC_AIO_TEST, nullptr, [&](::dsn::error_code code, size_t sz)
                    {
                        if (ERR_OK == code)
                            cb(index);
                        cb_flying_count--;
                    });
            }
            else
            {
                file::read(files[index], buffer.get(), (int)block_size, offset,
                    LPC_AIO_TEST, nullptr, [&](::dsn::error_code code, size_t sz)
                    {
                        if (ERR_OK == code)
                            cb(index);
                        cb_flying_count--;
                    });
            }
        }
    };

    // start
    auto tic = std::chrono::steady_clock::now();
    for (int i = 0; i < concurrency; i++)
    {
        offsets[i] = 0;
        cb(i);
    }

    // run for seconds
    std::this_thread::sleep_for(std::chrono::seconds(10));
    auto ioc = io_count.load();
    auto bytes = ioc * block_size;
    auto toc = std::chrono::steady_clock::now();

    std::cout << "is_write = " << is_write
        << ", block_size = " << block_size
        << ", shared = " << shared
        << ", concurrency = " << concurrency
        << ", iops = " << (double)ioc / (double)std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() * 1000000.0 << " #/s"
        << ", throughput = " << (double)bytes / std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() << " mB/s"
        << ", avg_latency = " << (double)std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() / (double)(ioc / concurrency) << " us"
        << std::endl;

    // safe exit
    exit = true;

    while (cb_flying_count.load() > 0)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }

    if (shared)
    {
        dsn_file_flush(files[0]);
        auto cok = dsn_file_close(files[0]);
        EXPECT_EQ(cok, ERR_OK);
    }
    else
    {
        for (auto& f : files)
        {
            dsn_file_flush(f);
            auto cok = dsn_file_close(f);
            EXPECT_EQ(cok, ERR_OK);
        }
    }
}

TEST(perf_core, aio)
{
    for (auto is_write : { true, false })
        for (auto shared : { false, true })
            for (auto blk_size_bytes : { 256, 1024, 4 * 1024 })
                for (auto concurrency : { 1, 2, 4})
                    aio_testcase(blk_size_bytes, concurrency, is_write, shared);
}
<commit_msg>fix aio perf test as the index value is referenced and changed to invalid value<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Microsoft Corporation
 *
 * -=- Robust Distributed System Nucleus (rDSN) -=-
 *
 * 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.
 */

/*
 * Description:
 *     Disk IO performance test
 *
 * Revision history:
 *     2016-01-05, Tianyi Wang, first version
 */

#include <cinttypes>
#include <gtest/gtest.h>
#include <dsn/service_api_cpp.h>
#include <dsn/cpp/test_utils.h>
#include <boost/lexical_cast.hpp>

void aio_testcase(uint64_t block_size, size_t concurrency, bool is_write, bool shared)
{
    std::unique_ptr<char[]> buffer(new char[block_size]);
    std::vector<dsn_handle_t> files;
    files.resize(concurrency);

    int flag;
    if (is_write)
    {
        flag = O_CREAT | O_RDWR;
        if (shared)
        {
            if (utils::filesystem::file_exists("temp"))
                utils::filesystem::remove_path("temp");
        }
        else
        {
            for (int i = 0; i < concurrency; i++)
            {
                std::stringstream ss;
                ss << "temp." << i;
                auto file = ss.str();
                if (utils::filesystem::file_exists(file))
                    utils::filesystem::remove_path(file);
            }
        }
    }
    else
    {
        flag = O_RDWR;
    }

    if (shared)
    {
        auto file_handle = dsn_file_open("temp", flag, 0666);
        EXPECT_TRUE(file_handle != nullptr);
        for (int i = 0; i < concurrency; i++)
            files[i] = file_handle;
    }
    else
    {
        for (int i = 0; i < concurrency; i++)
        {
            std::stringstream ss;
            ss << "temp." << i;
            auto file = ss.str();
            auto file_handle = dsn_file_open(file.c_str(), flag, 0666);
            EXPECT_TRUE(file_handle != nullptr);
            files[i] = file_handle;
        }
    }

    std::atomic<uint64_t> io_count(0);
    std::atomic<uint64_t> cb_flying_count(0);
    volatile bool exit = false;
    std::function<void(int)> cb;
    std::vector<uint64_t> offsets;
    offsets.resize(concurrency);

    cb = [&](int index)
    {
        if (!exit)
        {
            auto ioc = io_count++;
            uint64_t offset;
            if (!shared)
            {
                offset = offsets[index];
                offsets[index] += block_size;
            }
            else
            {
                offset = ioc * block_size;
            }

            cb_flying_count++;
            if (is_write)
            {
                file::write(files[index], buffer.get(), (int)block_size, offset,
                    LPC_AIO_TEST, nullptr, [idx = index, &cb, &cb_flying_count](::dsn::error_code code, size_t sz)
                    {
                        if (ERR_OK == code)
                            cb(idx);
                        cb_flying_count--;
                    });
            }
            else
            {
                file::read(files[index], buffer.get(), (int)block_size, offset,
                    LPC_AIO_TEST, nullptr, [idx = index, &cb, &cb_flying_count](::dsn::error_code code, size_t sz)
                    {
                        if (ERR_OK == code)
                            cb(idx);
                        cb_flying_count--;
                    });
            }
        }
    };

    // start
    auto tic = std::chrono::steady_clock::now();
    for (int i = 0; i < concurrency; i++)
    {
        offsets[i] = 0;
        cb(i);
    }

    // run for seconds
    std::this_thread::sleep_for(std::chrono::seconds(10));
    auto ioc = io_count.load();
    auto bytes = ioc * block_size;
    auto toc = std::chrono::steady_clock::now();

    std::cout << "is_write = " << is_write
        << ", block_size = " << block_size
        << ", shared = " << shared
        << ", concurrency = " << concurrency
        << ", iops = " << (double)ioc / (double)std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() * 1000000.0 << " #/s"
        << ", throughput = " << (double)bytes / std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() << " mB/s"
        << ", avg_latency = " << (double)std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() / (double)(ioc / concurrency) << " us"
        << std::endl;

    // safe exit
    exit = true;

    while (cb_flying_count.load() > 0)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }

    if (shared)
    {
        dsn_file_flush(files[0]);
        auto cok = dsn_file_close(files[0]);
        EXPECT_EQ(cok, ERR_OK);
    }
    else
    {
        for (auto& f : files)
        {
            dsn_file_flush(f);
            auto cok = dsn_file_close(f);
            EXPECT_EQ(cok, ERR_OK);
        }
    }
}

TEST(perf_core, aio)
{
    for (auto is_write : { true, false })
        for (auto shared : { false, true })
            for (auto blk_size_bytes : { 256, 1024, 4 * 1024 })
                for (auto concurrency : { 1, 2, 4})
                    aio_testcase(blk_size_bytes, concurrency, is_write, shared);
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016 Team Kamikakushi
 *
 * This software is provided 'as-is', without any express or implied
 * warranty.  In no event will the authors be held liable for any damages
 * arising from the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 **/

#include "net4.h"

// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1

bool loaded()
{
	return true;
}

const char *version()
{
	return "0.0.8";
}

bool isProcessRunning( const char* processName )
{
	HANDLE SnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );

	if( SnapShot == INVALID_HANDLE_VALUE )
		return false;

	PROCESSENTRY32 procEntry;
	procEntry.dwSize = sizeof( PROCESSENTRY32 );

	if( !Process32First( SnapShot, &procEntry ) )
		return false;

	do
	{
		if( strcmp( procEntry.szExeFile, processName ) == 0 )
			return true;
	}
	while( Process32Next( SnapShot, &procEntry ) );

	return false;
}

bool isValidHandle(HANDLE handle)
{
	if (handle != NULL && handle != INVALID_HANDLE_VALUE)
	{
		return true;
	}
	return false;
}

bool isValidProcessID(DWORD ProcessID)
{
	if (ProcessID != 0)
	{
		return true;
	}
	return false;
}

void WinAPI_MessageBox(const char *title, const char *message)
{
	MessageBox(0,message,title,0);
}

DWORD WinAPI_GetProcessID(const char *processName)
{
	PROCESSENTRY32 entryPoint32;
	HANDLE snapshotHandle;
	entryPoint32.dwSize = sizeof(PROCESSENTRY32);
	snapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (Process32First(snapshotHandle, &entryPoint32))
	{
		do
		{
			if(strcmp(entryPoint32.szExeFile, processName) == 0)
			{
				break;
			}
		}
		while(Process32Next(snapshotHandle, &entryPoint32));
	}
	if (isValidHandle(snapshotHandle))
	{
		CloseHandle(snapshotHandle);
		return entryPoint32.th32ProcessID;
	}
	return 0;
}

void *GetModuleBaseAddress(const char *processName, DWORD ProcessID)
{
   DWORD_PTR dwModuleBaseAddress = 0;
   HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, ProcessID);
   if (hSnapshot != INVALID_HANDLE_VALUE)
   {
      MODULEENTRY32 ModuleEntry32;
      ModuleEntry32.dwSize = sizeof(MODULEENTRY32);
      if (Module32First(hSnapshot, &ModuleEntry32))
      {
         do
         {
            if (_tcsicmp(ModuleEntry32.szModule, processName) == 0)
            {
               dwModuleBaseAddress = (DWORD_PTR)ModuleEntry32.modBaseAddr;
               break;
            }
         }
         while (Module32Next(hSnapshot, &ModuleEntry32));
      }
      CloseHandle(hSnapshot);
   }
   return (void *)dwModuleBaseAddress;
}

void *GetHWND(const char *windowName)
{
	return (void *)FindWindow(NULL, windowName);
}

HANDLE WinAPI_OpenHandle(DWORD ProcessID)
{
	HANDLE handle;
	if (isValidProcessID(ProcessID))
	{
		handle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, false, ProcessID);
		if (isValidHandle(handle))
		{
			return handle;
		}
	}
	return NULL;
}

bool WinAPI_CloseHandle(HANDLE handle)
{
	if (isValidHandle(handle))
	{
		CloseHandle(handle);
		return true;
	}
	return false;
}

bool SuspendProcess(DWORD ProcessID)
{
	if (isValidProcessID(ProcessID))
	{
		if (DebugActiveProcess(ProcessID) != 0)
		{
			DebugSetProcessKillOnExit(false);
			return true;
		}
	}
	return false;
}

bool ResumeProcess(DWORD ProcessID)
{
	if (ProcessID != 0)
	{
		bool debugPresent = false;
		HANDLE handle = WinAPI_OpenHandle(ProcessID);
		if (isValidHandle(handle))
		{
			if (CheckRemoteDebuggerPresent(handle, (PBOOL)&debugPresent) != 0 && debugPresent)
			{
				DebugActiveProcessStop(ProcessID);
				return true;
			}
		}
	}
	return false;
}

// Memory Functions

int ReadInt(HANDLE handle, DWORD address)
{
	int value;
	ReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);
	if (value == NULL)
	{
		return 0;
	}
	return value;
}

bool WriteInt(HANDLE handle, DWORD address, int value)
{
	SIZE_T bytesWritten;
	WriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);
	if (bytesWritten == sizeof(value))
	{
		return true;
	}
	return false;
}

bool ReadBool(HANDLE handle, DWORD address)
{
	bool value;
	ReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);
	if (value == NULL)
	{
		return false;
	}
	return value;
}

bool WriteBool(HANDLE handle, DWORD address, bool value)
{
	SIZE_T bytesWritten;
	WriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);
	if (bytesWritten == sizeof(value))
	{
		return true;
	}
	return false;
}

float ReadFloat(HANDLE handle, DWORD address)
{
	float value;
	ReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);
	if (value == NULL)
	{
		return 0;
	}
	return value;
}

bool WriteFloat(HANDLE handle, DWORD address, float value)
{
	SIZE_T bytesWritten;
	WriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);
	if (bytesWritten == sizeof(value))
	{
		return true;
	}
	return false;
}

void *SignatureScan(HANDLE handle, const char *signature, const char *mask, int offset)
{
	int maskLength = (int)strlen(mask);

	std::vector<unsigned char> dump;

	std::string sigstring(signature);
	std::istringstream sigstream(sigstring);
	std::vector<unsigned char> sig;
	unsigned int c;
	while (sigstream >> std::hex >> c)
	{
		sig.push_back(c);
	}

	bool canFind = true;

	MEMORY_BASIC_INFORMATION info;

	for (long currentAddress = 0; VirtualQueryEx(handle, (void *)(UINT_PTR)currentAddress, &info, sizeof(info)) == sizeof(info); currentAddress += (long)info.RegionSize) // iterate through all regions
	{
		if (info.State == MEM_COMMIT && (info.Type == MEM_MAPPED || info.Type == MEM_PRIVATE))
		{
			SIZE_T bytesRead;
			dump.resize(info.RegionSize);
			ReadProcessMemory(handle, (void *)(UINT_PTR)currentAddress, &dump[0], info.RegionSize, &bytesRead);
			dump.resize(bytesRead);

			if (bytesRead > 0) // memory is dumped
			{
				long currentOffset = 0;
				while (currentOffset < bytesRead-maskLength) // iterate through dumped region
				{
					canFind = true;
					for (int x = 0; x < maskLength-1; x++) // iterate through signature / mask at particular offset in dumped region
					{
						if (mask[x] == 'x' && dump[currentOffset+x] != sig[x])
						{
							canFind = false;
							break;
						}
					}
					if (canFind) // found signature
					{
						return (void *)(UINT_PTR)(currentAddress + currentOffset + offset - 1);
					}
					currentOffset++;
				}
			}
		}
	}
	return NULL;
}
<commit_msg>changed to MIT license<commit_after>/**
MIT License

Copyright (c) 2017 Tsuneko Shirley Kogami

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.
 **/

#include "net4.h"

// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1

bool loaded()
{
	return true;
}

const char *version()
{
	return "0.0.8";
}

bool isProcessRunning( const char* processName )
{
	HANDLE SnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );

	if( SnapShot == INVALID_HANDLE_VALUE )
		return false;

	PROCESSENTRY32 procEntry;
	procEntry.dwSize = sizeof( PROCESSENTRY32 );

	if( !Process32First( SnapShot, &procEntry ) )
		return false;

	do
	{
		if( strcmp( procEntry.szExeFile, processName ) == 0 )
			return true;
	}
	while( Process32Next( SnapShot, &procEntry ) );

	return false;
}

bool isValidHandle(HANDLE handle)
{
	if (handle != NULL && handle != INVALID_HANDLE_VALUE)
	{
		return true;
	}
	return false;
}

bool isValidProcessID(DWORD ProcessID)
{
	if (ProcessID != 0)
	{
		return true;
	}
	return false;
}

void WinAPI_MessageBox(const char *title, const char *message)
{
	MessageBox(0,message,title,0);
}

DWORD WinAPI_GetProcessID(const char *processName)
{
	PROCESSENTRY32 entryPoint32;
	HANDLE snapshotHandle;
	entryPoint32.dwSize = sizeof(PROCESSENTRY32);
	snapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (Process32First(snapshotHandle, &entryPoint32))
	{
		do
		{
			if(strcmp(entryPoint32.szExeFile, processName) == 0)
			{
				break;
			}
		}
		while(Process32Next(snapshotHandle, &entryPoint32));
	}
	if (isValidHandle(snapshotHandle))
	{
		CloseHandle(snapshotHandle);
		return entryPoint32.th32ProcessID;
	}
	return 0;
}

void *GetModuleBaseAddress(const char *processName, DWORD ProcessID)
{
   DWORD_PTR dwModuleBaseAddress = 0;
   HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, ProcessID);
   if (hSnapshot != INVALID_HANDLE_VALUE)
   {
      MODULEENTRY32 ModuleEntry32;
      ModuleEntry32.dwSize = sizeof(MODULEENTRY32);
      if (Module32First(hSnapshot, &ModuleEntry32))
      {
         do
         {
            if (_tcsicmp(ModuleEntry32.szModule, processName) == 0)
            {
               dwModuleBaseAddress = (DWORD_PTR)ModuleEntry32.modBaseAddr;
               break;
            }
         }
         while (Module32Next(hSnapshot, &ModuleEntry32));
      }
      CloseHandle(hSnapshot);
   }
   return (void *)dwModuleBaseAddress;
}

void *GetHWND(const char *windowName)
{
	return (void *)FindWindow(NULL, windowName);
}

HANDLE WinAPI_OpenHandle(DWORD ProcessID)
{
	HANDLE handle;
	if (isValidProcessID(ProcessID))
	{
		handle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, false, ProcessID);
		if (isValidHandle(handle))
		{
			return handle;
		}
	}
	return NULL;
}

bool WinAPI_CloseHandle(HANDLE handle)
{
	if (isValidHandle(handle))
	{
		CloseHandle(handle);
		return true;
	}
	return false;
}

bool SuspendProcess(DWORD ProcessID)
{
	if (isValidProcessID(ProcessID))
	{
		if (DebugActiveProcess(ProcessID) != 0)
		{
			DebugSetProcessKillOnExit(false);
			return true;
		}
	}
	return false;
}

bool ResumeProcess(DWORD ProcessID)
{
	if (ProcessID != 0)
	{
		bool debugPresent = false;
		HANDLE handle = WinAPI_OpenHandle(ProcessID);
		if (isValidHandle(handle))
		{
			if (CheckRemoteDebuggerPresent(handle, (PBOOL)&debugPresent) != 0 && debugPresent)
			{
				DebugActiveProcessStop(ProcessID);
				return true;
			}
		}
	}
	return false;
}

// Memory Functions

int ReadInt(HANDLE handle, DWORD address)
{
	int value;
	ReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);
	if (value == NULL)
	{
		return 0;
	}
	return value;
}

bool WriteInt(HANDLE handle, DWORD address, int value)
{
	SIZE_T bytesWritten;
	WriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);
	if (bytesWritten == sizeof(value))
	{
		return true;
	}
	return false;
}

bool ReadBool(HANDLE handle, DWORD address)
{
	bool value;
	ReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);
	if (value == NULL)
	{
		return false;
	}
	return value;
}

bool WriteBool(HANDLE handle, DWORD address, bool value)
{
	SIZE_T bytesWritten;
	WriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);
	if (bytesWritten == sizeof(value))
	{
		return true;
	}
	return false;
}

float ReadFloat(HANDLE handle, DWORD address)
{
	float value;
	ReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);
	if (value == NULL)
	{
		return 0;
	}
	return value;
}

bool WriteFloat(HANDLE handle, DWORD address, float value)
{
	SIZE_T bytesWritten;
	WriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);
	if (bytesWritten == sizeof(value))
	{
		return true;
	}
	return false;
}

void *SignatureScan(HANDLE handle, const char *signature, const char *mask, int offset)
{
	int maskLength = (int)strlen(mask);

	std::vector<unsigned char> dump;

	std::string sigstring(signature);
	std::istringstream sigstream(sigstring);
	std::vector<unsigned char> sig;
	unsigned int c;
	while (sigstream >> std::hex >> c)
	{
		sig.push_back(c);
	}

	bool canFind = true;

	MEMORY_BASIC_INFORMATION info;

	for (long currentAddress = 0; VirtualQueryEx(handle, (void *)(UINT_PTR)currentAddress, &info, sizeof(info)) == sizeof(info); currentAddress += (long)info.RegionSize) // iterate through all regions
	{
		if (info.State == MEM_COMMIT && (info.Type == MEM_MAPPED || info.Type == MEM_PRIVATE))
		{
			SIZE_T bytesRead;
			dump.resize(info.RegionSize);
			ReadProcessMemory(handle, (void *)(UINT_PTR)currentAddress, &dump[0], info.RegionSize, &bytesRead);
			dump.resize(bytesRead);

			if (bytesRead > 0) // memory is dumped
			{
				long currentOffset = 0;
				while (currentOffset < bytesRead-maskLength) // iterate through dumped region
				{
					canFind = true;
					for (int x = 0; x < maskLength-1; x++) // iterate through signature / mask at particular offset in dumped region
					{
						if (mask[x] == 'x' && dump[currentOffset+x] != sig[x])
						{
							canFind = false;
							break;
						}
					}
					if (canFind) // found signature
					{
						return (void *)(UINT_PTR)(currentAddress + currentOffset + offset - 1);
					}
					currentOffset++;
				}
			}
		}
	}
	return NULL;
}
<|endoftext|>


<commit_before>#ifndef _NODE_H
#define _NODE_H

#include <vector>

class Node{

    private:

        union Content{
            double idX;        //var
            double value;   //const
            int function;   //func1 ou func2
        };

        //não sei se enum e union deveriam ser globais ou declaradas dentro
        //do node. A principio, acho que não é de interesse de nenhuma outra
        //função acessar estas informação, mas pode ser que eu esteja enganado.

        Content C;
        int tipo; //recebe o índice do content

        Node *left;
        Node *right;

    public:
        Node(bool copy = false);
        ~Node();

        double eval(std::vector<double> x);
        void print_node_d();
        Node *get_copy();
};

#endif
<commit_msg>1.2.4 Fix<commit_after>//node.hpp
#ifndef _NODE_H
#define _NODE_H

#include <vector>

class Node{

    private:
        union Content{
            double idX;     //var
            double value;   //const
            int function;   //func1 ou func2
        };

        Content C;
        int tipo; //recebe o índice do content

        Node *left;
        Node *right;

    public:
        Node(bool copy = false);
        ~Node();

        double eval(double x);
        void print_node_d();
        Node *get_copy();
        int get_type();
};

#endif
<|endoftext|>


<commit_before>#ifndef _PIPE_H_
#define _PIPE_H_

#include "cmdline.hpp"

class Pipe
{
public:
	Pipe();
	virtual bool execute(vector<string> cmd, string &input) = 0;
	//virtual bool isValid() = 0;

};

#endif
<commit_msg>fixed pipe prototype<commit_after>#ifndef _PIPE_H_
#define _PIPE_H_

#include "cmdline.hpp"

class Pipe
{
public:
	Pipe();
	bool execute(vector<string> cmd, string &input);
	//virtual bool isValid() = 0;

};

#endif
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2009 by Miguel Chavez Gamboa                            *
 *   miguel@lemonpos.org                                                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include "mibitnotifier.h"

#include <QPixmap>
#include <QIcon>
#include <QString>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTimeLine>
#include <QTimer>
#include <QKeyEvent>
#include <QDebug>

MibitNotifier::MibitNotifier(QWidget *parent, const QString &file, const QPixmap &icon, const QPixmap &closeIcon, const bool &onTop)
        : QSvgWidget( parent )
{
    if (file != 0) setSVG(file);

    m_parent = parent;
    m_onTop = onTop;
    closedByUser = false;
    m_fileName = file;
    setMinimumHeight(100);
    setFixedSize(0,0); //until show we grow it
    setMaxHeight(max_H); //default sizes
    setMaxWidth(max_W);
    animRate = 500; //default animation speed (half second rate).

    img        = new QLabel();
    hLayout    = new QHBoxLayout();
    message    = new QLabel("");
    btnClose   = new QLabel(""); //only an image

    img->setPixmap(icon);
    img->setMaximumHeight(54); //the icon size is hardcoded now.
    img->setMaximumWidth(54);
    img->setAlignment(Qt::AlignLeft);
    img->setMargin(4);

    btnClose->setPixmap(closeIcon);
    btnClose->setMaximumHeight(34); //the icon size is hardcoded now.
    btnClose->setMaximumWidth(38);
    btnClose->setToolTip("Close Notification"); //what about translations?
    btnClose->setFixedSize(38,36);

    setLayout(hLayout);
    message->setWordWrap(true);
    message->setAlignment(Qt::AlignJustify|Qt::AlignVCenter);
    message->setMargin(10);

    hLayout->addWidget(img,0,Qt::AlignLeft);
    hLayout->addWidget(message,1,Qt::AlignLeft);
    hLayout->addWidget(btnClose,0,Qt::AlignRight);

    timeLine  = new QTimeLine(animRate, this);
    connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(animate(int)));
    connect(timeLine,SIGNAL(finished()), this, SLOT(onAnimationFinished()));
}

void MibitNotifier::showNotification( const QString &msg, const int &timeToLive) //timeToLive = 0 : not auto hide it.
{
    //set default msg if the sent is empty.
    if (msg.isEmpty()) setMessage(message->text()); else setMessage( msg );

    if (!m_onTop) setSVG("rotated_"+m_fileName); else setSVG(m_fileName);

    setGeometry(-1000,-1000,0,0);
    show();
    //update steps for animation, now that the window is showing.

    int maxStep; int minStep = 0;

    if ( m_onTop ) {
        maxStep = maxHeight;
        minStep = 0;
    } else {
        maxStep = m_parent->geometry().height()-maxHeight;
        minStep = m_parent->geometry().height();
    }

    timeLine->setFrameRange(minStep,maxStep);
    //make it grow
    timeLine->setDirection(QTimeLine::Forward);
    timeLine->start();
    btnClose->setFocus();

    if (timeToLive > 0 ) QTimer::singleShot(timeToLive,this,SLOT(hideDialog()));
}

void MibitNotifier::animate(const int &step)
{
    //get some sizes...
    QRect windowGeom = m_parent->geometry();
    int midPointX = (windowGeom.width()/2);
    int newX; int newW;
    QRect dRect;
    int pheight = m_parent->geometry().height();
    if (maxWidth < min_W ) newW = min_W; else newW = maxWidth;
    if ((midPointX-(newW/2)) < 0) newX = 0; else newX = midPointX - (newW/2);

    dRect.setX(newX);
    setFixedWidth(newW);

    if (m_onTop) { // Sliding from top
        dRect.setY(0);
        setGeometry(dRect);
        setFixedHeight(step);
    } else {       // Sliding from bottom
        int nh = pheight-step;
        if ( nh < min_H ) nh = min_H;
        dRect.setY(step);
        setGeometry(dRect);
        setFixedHeight(nh);

    }
}

void MibitNotifier::hideOnUserRequest()
{
    hideDialog();
    closedByUser = true;
}

void MibitNotifier::hideDialog()
{
    if ( !closedByUser ) {
        timeLine->toggleDirection();//reverse!
        timeLine->start();
    } else closedByUser = !closedByUser;
}

void MibitNotifier::onAnimationFinished()
{
    if (timeLine->direction() == QTimeLine::Backward) {
        close();
    }
}

void MibitNotifier::setOnBottom(const bool &sOnBottom)
{
    m_onTop = !sOnBottom;
}

void MibitNotifier::setSVG(const QString &file)
{
    load(file);
}

void MibitNotifier::setIcon(const QPixmap &icon)
{
     img->setPixmap(icon);
 }

void MibitNotifier::setMessage(const QString &msg)
{
    message->setText(msg);
}

void MibitNotifier::setTextColor(const QString &color)
{
    message->setStyleSheet(QString("color:%1").arg(color));
}

void MibitNotifier::mousePressEvent ( QMouseEvent * )
{
    hideOnUserRequest();
}

void MibitNotifier::keyPressEvent ( QKeyEvent * event )
{
    if ( event->key() == Qt::Key_Escape )
    {
        hideOnUserRequest();
    } //else ignore event.
}

MibitNotifier::~MibitNotifier() {}

<commit_msg>Improving animation of the notifier...<commit_after>/***************************************************************************
 *   Copyright (C) 2009 by Miguel Chavez Gamboa                            *
 *   miguel@lemonpos.org                                                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include "mibitnotifier.h"

#include <QPixmap>
#include <QIcon>
#include <QString>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTimeLine>
#include <QTimer>
#include <QKeyEvent>
#include <QDebug>

MibitNotifier::MibitNotifier(QWidget *parent, const QString &file, const QPixmap &icon, const QPixmap &closeIcon, const bool &onTop)
        : QSvgWidget( parent )
{
    if (file != 0) setSVG(file);

    m_parent = parent;
    m_onTop = onTop;
    closedByUser = false;
    m_fileName = file;
    setMinimumHeight(100);
    setFixedSize(0,0); //until show we grow it
    setMaxHeight(max_H); //default sizes
    setMaxWidth(max_W);
    animRate = 500; //default animation speed (half second rate).

    img        = new QLabel();
    hLayout    = new QHBoxLayout();
    message    = new QLabel("");
    btnClose   = new QLabel(""); //only an image

    img->setPixmap(icon);
    img->setMaximumHeight(54); //the icon size is hardcoded now.
    img->setMaximumWidth(54);
    img->setAlignment(Qt::AlignLeft);
    img->setMargin(4);

    btnClose->setPixmap(closeIcon);
    btnClose->setMaximumHeight(34); //the icon size is hardcoded now.
    btnClose->setMaximumWidth(38);
    btnClose->setToolTip("Close Notification"); //what about translations?
    btnClose->setFixedSize(38,36);

    setLayout(hLayout);
    message->setWordWrap(true);
    message->setAlignment(Qt::AlignJustify|Qt::AlignVCenter);
    message->setMargin(10);

    hLayout->addWidget(img,0,Qt::AlignLeft);
    hLayout->addWidget(message,1,Qt::AlignLeft);
    hLayout->addWidget(btnClose,0,Qt::AlignRight);

    timeLine  = new QTimeLine(animRate, this);
    connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(animate(int)));
    connect(timeLine,SIGNAL(finished()), this, SLOT(onAnimationFinished()));
}

void MibitNotifier::showNotification( const QString &msg, const int &timeToLive) //timeToLive = 0 : not auto hide it.
{
    /// Warning: if a tip is showing, if another showTip() is called, it is ignored.
    if (timeLine->state() == QTimeLine::NotRunning && size().height() <= 0) {
        //set default msg if the sent is empty.
        if (msg.isEmpty()) setMessage(message->text()); else setMessage( msg );
        //change svg skin if is not on top.
        if (!m_onTop) setSVG("rotated_"+m_fileName); else setSVG(m_fileName);
        setGeometry(-1000,-1000,0,0);
        show();
        //update steps for animation, now that the window is showing.
        int maxStep; int minStep = 0;

        if ( m_onTop ) {
            minStep = -maxHeight;
            maxStep =  0;
        } else {
            maxStep = m_parent->geometry().height()-maxHeight;
            minStep = m_parent->geometry().height();
        }
        //qDebug()<<" MaxStep:"<<maxStep<<" MinStep:"<<minStep;

        timeLine->setFrameRange(minStep,maxStep);
        //make it grow
        timeLine->setDirection(QTimeLine::Forward);
        timeLine->start();
        btnClose->setFocus();

        if (timeToLive > 0 ) QTimer::singleShot(timeToLive,this,SLOT(hideDialog()));
    } /*else qDebug()<<"notification is already showing... "<<size();*/
}

void MibitNotifier::animate(const int &step)
{
    //get some sizes...
    QRect windowGeom = m_parent->geometry();
    int midPointX = (windowGeom.width()/2);
    int newX; int newW;
    QRect dRect;
    int pheight = m_parent->geometry().height();
    if (maxWidth < min_W ) newW = min_W; else newW = maxWidth;
    if ((midPointX-(newW/2)) < 0) newX = 0; else newX = midPointX - (newW/2);

    dRect.setX(newX);
    setFixedWidth(newW);

    dRect.setY(step);
    setGeometry(dRect);
    setFixedHeight(maxHeight);

    if (m_onTop) { // Sliding from top
        if (step == -maxHeight) setFixedHeight(0);
    } else {       // Sliding from bottom
        if (step == m_parent->geometry().height()) setFixedHeight(0);
    }
}

void MibitNotifier::hideOnUserRequest()
{
    hideDialog();
    closedByUser = true;
}

void MibitNotifier::hideDialog()
{
    if ( !closedByUser ) {
        timeLine->toggleDirection();//reverse!
        timeLine->start();
    } else closedByUser = !closedByUser;
}

void MibitNotifier::onAnimationFinished()
{
    if (timeLine->direction() == QTimeLine::Backward) {
        close();
    }
}

void MibitNotifier::setOnBottom(const bool &sOnBottom)
{
    // only changes the position when the notification is not showing..
    if (timeLine->state() == QTimeLine::NotRunning && size().height() <= 0)    m_onTop = !sOnBottom;
}

void MibitNotifier::setSVG(const QString &file)
{
    load(file);
}

void MibitNotifier::setIcon(const QPixmap &icon)
{
     img->setPixmap(icon);
 }

void MibitNotifier::setMessage(const QString &msg)
{
    message->setText(msg);
}

void MibitNotifier::setTextColor(const QString &color)
{
    message->setStyleSheet(QString("color:%1").arg(color));
}

void MibitNotifier::mousePressEvent ( QMouseEvent * )
{
    hideOnUserRequest();
}

void MibitNotifier::keyPressEvent ( QKeyEvent * event )
{
    if ( event->key() == Qt::Key_Escape )
    {
        hideOnUserRequest();
    } //else ignore event.
}

MibitNotifier::~MibitNotifier() {}

<|endoftext|>


<commit_before>#include <stdlib.h>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include "omp.h"

void helpCheck(char *argv[]) {
	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl;
		exit(0);
	}
}

void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
				} else {
					filePaths->push_back(rootPath + fileBuff);
				}
			}
		}
		closedir(dir);
	}
}

void compress(std::vector<std::string> *filePaths) {
	#pragma omp parallel for schedule(dynamic)
	for (int i = 0; i < filePaths->size(); ++i) {
		std::cout << filePaths->at(i) << std::endl;
		std::string command = "XZ_OPT=-9 tar cJf test." + std::to_string(i) + ".tar.xz " + filePaths->at(i);
		system(command.c_str());
	}
}

char cwd [PATH_MAX];

int main(int argc, char *argv[]) {
	int *numFiles = new int(0);

	if (argc > 1) {
		helpCheck(argv);
	}

	getcwd(cwd, PATH_MAX);
	findAll(numFiles, cwd);
	// std::cout << *numFiles << std::endl;

	std::vector<std::string> *filePaths = new std::vector<std::string>();

	getPaths(filePaths, cwd, "");
	compress(filePaths);

	delete(numFiles);
	return 0;
}
<commit_msg>moving to unsigned long long int for more reliability for int max size<commit_after>#include <stdlib.h>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include "omp.h"

void helpCheck(char *argv[]) {
	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl;
		exit(0);
	}
}

void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
				} else {
					filePaths->push_back(rootPath + fileBuff);
				}
			}
		}
		closedir(dir);
	}
}

void compress(std::vector<std::string> *filePaths) {
	#pragma omp parallel for schedule(dynamic)
	for (unsigned long long int i = 0; i < filePaths->size(); ++i) {
		std::cout << filePaths->at(i) << std::endl;
		std::string command = "XZ_OPT=-9 tar cJf test." + std::to_string(i) + ".tar.xz " + filePaths->at(i);
		system(command.c_str());
	}
}

char cwd [PATH_MAX];

int main(int argc, char *argv[]) {
	int *numFiles = new int(0);

	if (argc > 1) {
		helpCheck(argv);
	}

	getcwd(cwd, PATH_MAX);
	findAll(numFiles, cwd);
	// std::cout << *numFiles << std::endl;

	std::vector<std::string> *filePaths = new std::vector<std::string>();

	getPaths(filePaths, cwd, "");
	compress(filePaths);

	delete(numFiles);
	return 0;
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include "omp.h"

void helpCheck(char *argv[]) {
	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl;
		exit(0);
	}
}

void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

void getPaths(std::vector<std::string> *filePaths, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str());
				} else {
					filePaths->push_back(filePath);
				}
			}
		}
		closedir(dir);
	}
}

char cwd [PATH_MAX];

int main(int argc, char *argv[]) {
	int *numFiles = new int(0);

	if (argc > 1) {
		helpCheck(argv);
	}

	getcwd(cwd, PATH_MAX);
	findAll(numFiles, cwd);

	std::vector<std::string> *filePaths = new std::vector<std::string>();

	getPaths(filePaths, cwd);

	int numThreads = omp_get_num_threads();
	std::cout << numThreads << std::endl;

	delete(numFiles);
	return 0;
}
<commit_msg>"Getting max threads not num threads"<commit_after>#include <stdlib.h>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include "omp.h"

void helpCheck(char *argv[]) {
	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl;
		exit(0);
	}
}

void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

void getPaths(std::vector<std::string> *filePaths, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str());
				} else {
					filePaths->push_back(filePath);
				}
			}
		}
		closedir(dir);
	}
}

char cwd [PATH_MAX];

int main(int argc, char *argv[]) {
	int *numFiles = new int(0);

	if (argc > 1) {
		helpCheck(argv);
	}

	getcwd(cwd, PATH_MAX);
	findAll(numFiles, cwd);

	std::vector<std::string> *filePaths = new std::vector<std::string>();

	getPaths(filePaths, cwd);

	int numThreads = omp_get_max_threads();
	std::cout << numThreads << std::endl;

	delete(numFiles);
	return 0;
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include "omp.h"

void helpCheck(char *argv[]) {
	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl;
		exit(0);
	}
}

void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

void getPaths(std::vector<std::string> *filePaths, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str());
				} else {
					filePaths->push_back(filePath);
				}
			}
		}
		closedir(dir);
	}
}

void compress(std::vector<std::string> *filePaths) {
	for (int i = 0; i < filePaths->size(); ++i) {
		std::string phrase = "echo " + std::stoi(i);
		system(phrase.c_str());
	}
}

char cwd [PATH_MAX];

int main(int argc, char *argv[]) {
	int *numFiles = new int(0);

	if (argc > 1) {
		helpCheck(argv);
	}

	getcwd(cwd, PATH_MAX);
	findAll(numFiles, cwd);

	std::vector<std::string> *filePaths = new std::vector<std::string>();

	getPaths(filePaths, cwd);
	compress(filePaths);

	delete(numFiles);
	return 0;
}
<commit_msg>using to string isntead of stoi<commit_after>#include <stdlib.h>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include "omp.h"

void helpCheck(char *argv[]) {
	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl;
		exit(0);
	}
}

void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

void getPaths(std::vector<std::string> *filePaths, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str());
				} else {
					filePaths->push_back(filePath);
				}
			}
		}
		closedir(dir);
	}
}

void compress(std::vector<std::string> *filePaths) {
	for (int i = 0; i < filePaths->size(); ++i) {
		std::string phrase = "echo " + std::to_string(i);
		system(phrase.c_str());
	}
}

char cwd [PATH_MAX];

int main(int argc, char *argv[]) {
	int *numFiles = new int(0);

	if (argc > 1) {
		helpCheck(argv);
	}

	getcwd(cwd, PATH_MAX);
	findAll(numFiles, cwd);

	std::vector<std::string> *filePaths = new std::vector<std::string>();

	getPaths(filePaths, cwd);
	compress(filePaths);

	delete(numFiles);
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <streambuf>

#include <3pp/mpc/mpc.h>

std::string readFile(char *fname)
{
    std::ifstream is(fname, std::ifstream::in);
    std::string str(
        (std::istreambuf_iterator<char>(is)),
        std::istreambuf_iterator<char>()
    );
    return str + '\n';
}

int main(int argc, char **argv)
{
    if (argc <= 1) {
        std::cout << "Usage: " << argv[0] << "file\n";
        return 1;
    }
    mpc_parser_t* Comment   = mpc_new("comment");
    mpc_parser_t* Indent   = mpc_new("indent");
    mpc_parser_t* Newline   = mpc_new("newline");
    mpc_parser_t* WhiteSpace = mpc_new("ws");
    mpc_parser_t* OptionalWhiteSpace = mpc_new("ows");
    mpc_parser_t* OptionalWhiteSpaceNewline = mpc_new("owsn");
    mpc_parser_t* Number   = mpc_new("number");
    mpc_parser_t* Operator = mpc_new("operator");
    mpc_parser_t* FactorOperator = mpc_new("factorop");
    mpc_parser_t* TermOperator = mpc_new("termop");
    mpc_parser_t* Expr     = mpc_new("expr");
    mpc_parser_t* Body     = mpc_new("body");
    mpc_parser_t* Identifier = mpc_new("identifier");
    mpc_parser_t* TypeIdent = mpc_new("typeident");
    mpc_parser_t* Import = mpc_new("import");
    mpc_parser_t* MethodRet = mpc_new("methodret");
    mpc_parser_t* MethodDef = mpc_new("methoddef");
    mpc_parser_t* ParamDef = mpc_new("paramdef");
    mpc_parser_t* String = mpc_new("string");
    mpc_parser_t* Args = mpc_new("args");
    mpc_parser_t* Lexp = mpc_new("lexp");
    mpc_parser_t* Factor = mpc_new("factor");
    mpc_parser_t* MethodCall = mpc_new("methodcall");
    mpc_parser_t* MapIndex = mpc_new("mapindex");
    mpc_parser_t* ListItem = mpc_new("listitem");
    mpc_parser_t* MapItem = mpc_new("mapitem");
    mpc_parser_t* TupleMap = mpc_new("tuplemap");
    mpc_parser_t* MapItems = mpc_new("mapitems");
    mpc_parser_t* ListItems = mpc_new("listitems");
    mpc_parser_t* List = mpc_new("list");
    mpc_parser_t* Namespacedef = mpc_new("namespacedef");
    mpc_parser_t* Primitive = mpc_new("primitive");
    mpc_parser_t* Range = mpc_new("range");
    mpc_parser_t* MatchCase = mpc_new("matchcase");
    mpc_parser_t* Match = mpc_new("match");
    mpc_parser_t* Assignment = mpc_new("assignment");
    mpc_parser_t* Stmt = mpc_new("stmt");
    mpc_parser_t* Term = mpc_new("term");
    mpc_parser_t* Const = mpc_new("const");
    mpc_parser_t* Pure = mpc_new("pure");
    mpc_parser_t* TopLevel = mpc_new("toplevel");
    mpc_parser_t* NolangPure = mpc_new("nolangpure");

    mpc_err_t* err = mpca_lang(MPCA_LANG_WHITESPACE_SENSITIVE,
        "comment    : /(#|\\/\\/)[^\\r\\n]*/"
        "           | /\\/\\*[^\\*]*(\\*[^\\/][^\\*]*)*\\*\\// ;"
        "indent     : /\\s\\s+/ ;"
        "newline    : '\\n';"
        "ws         : /[\\s]+/ ;"
        "ows        : /[\\s\\t]*/ ;"
        "owsn       : /[\\s\\t\\n]*/ ;"
        "identifier : /[A-Za-z_][A-Za-z0-9_-]*/ ;"
        "typeident  : <identifier> <ows> ':' <ows> <identifier> ;"
        "number     : /[0-9]+/ ;"
        "string     : /\"(\\\\.|[^\"])*\"/ "
        "           | /\'(\\\\.|[^\'])*\'/ ; "
        "operator   : '+' | '-' | '*' | '/' ;"
        "factorop   : '*'"
        "           | '/'"
        "           | \"div\""
        "           | \"mod\""
        "           | \"rem\";"
        "termop     : '+'"
        "           | '-';"
        "import     : \"import\" <ws> <identifier> <newline>;"
        "const      : \"const\" <ws> <assignment> <newline>;"
        "methodret  : <ows> ':' <ows> <identifier> ;"
        "methoddef  : (<pure> <ws>)? <identifier> <ows> <args>? <methodret>? <ows> \"=>\" (<newline>|<ws>) <body> ;"
        "paramdef   : <typeident>? <ows> (',' <ows> <typeident>)*; "
        "args       : '(' <paramdef>? ')'; "
        "factor     : <namespacedef>"
        "           | '(' <lexp> ')'"
        "           | <number>"
        "           | <string>"
        "           | <identifier>; "
        "term       : <factor> (<ows> <factorop> <ows> <factor>)*;"
        "lexp       : <term> (<ows> <termop> <ows> <term>)* ; "
        "expr       : <list>"
        "           | <lexp>;"
        "methodcall : '(' (<expr> (',' <ows> <expr>)*)? ')';"
        "mapindex   : '[' <expr> ']';"
        "listitem   : <expr>;"
        "mapitem    : <string> <ows> ':' <owsn> <expr> ;"
        "tuplemap   : '(' <string> <owsn> ',' <owsn> <lexp> ')';"
        "mapitems   : (<tuplemap> | <mapitem>) <owsn> (',' <owsn> (<tuplemap> | <mapitem>)) *;"
        "listitems  : <listitem> (<owsn> ',' <owsn> <listitem>) *;"
        "list       : '[' <owsn> (<mapitems> | <listitems>)? <owsn> ']' ;"
        "namespacedef : <identifier> ('.' <identifier>)* (<methodcall> | <mapindex>)?;"
        "primitive  : <identifier> | <number> | <string> ;"
        "range      : <primitive> \"..\" <primitive>?;"
        "assignment : (<typeident>|<namespacedef>) <ws> '=' <ws> <expr>;"
        "matchcase  : <comment> | (<indent> (<range> | <primitive> | '?') <ows> ':' <ows> <stmt> <newline>);"
        "match      : \"match\" <ws> <stmt> <ows> \"=>\" <newline> <matchcase>+;"
        "stmt       : <match>"
        "           | <assignment>"
        "           | <namespacedef>"
        "           | <list>"
        "           | <expr>"
        "           | <comment>;"
        "body       : ((<indent>+ <stmt>)? <newline>)* ;"
        "pure       : \"pure\" ;"
        "toplevel   : <import>"
        "           | <const>"
        "           | <comment>"
        "           | <methoddef>"
        "           | <newline>;"
        "nolangpure : /^/ <toplevel>* /$/;"
      ,
        Comment, Indent, Newline,
        WhiteSpace, OptionalWhiteSpace, OptionalWhiteSpaceNewline,
        Identifier, TypeIdent,
        Number, String,
        Operator, FactorOperator, TermOperator,
        Import, Const,
        MethodRet, MethodDef, ParamDef, Args,
        Factor, Term, Lexp,
        Expr, MethodCall,
        MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List,
        Namespacedef,
        Primitive, Range,
        Assignment, MatchCase, Match,
        Stmt,
        Body, Pure,
        TopLevel, NolangPure, NULL);

    if (err != NULL) {
        mpc_err_print(err);
        mpc_err_delete(err);
        exit(1);
    }

    mpc_result_t r;
    std::string data = readFile(argv[1]);
    if (mpc_parse(argv[1], data.c_str(), NolangPure, &r)) {
      mpc_ast_print(static_cast<mpc_ast_t*>(r.output));
      mpc_ast_delete(static_cast<mpc_ast_t*>(r.output));
    } else {
      mpc_err_print(r.error);
      mpc_err_delete(r.error);
    }

    mpc_cleanup(39,
        Comment, Indent, Newline,
        WhiteSpace, OptionalWhiteSpace, OptionalWhiteSpaceNewline,
        Identifier, TypeIdent,
        Number, String,
        Operator, FactorOperator, TermOperator,
        Import, Const,
        MethodRet, MethodDef, ParamDef, Args,
        Factor, Term, Lexp,
        Expr, MethodCall,
        MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List,
        Namespacedef,
        Primitive, Range,
        Assignment, MatchCase, Match,
        Stmt,
        Body, Pure,
        TopLevel, NolangPure);

    return 0;
}
<commit_msg>Return statement, and failure at main<commit_after>#include <iostream>
#include <fstream>
#include <streambuf>

#include <3pp/mpc/mpc.h>

std::string readFile(char *fname)
{
    std::ifstream is(fname, std::ifstream::in);
    std::string str(
        (std::istreambuf_iterator<char>(is)),
        std::istreambuf_iterator<char>()
    );
    return str + '\n';
}

int main(int argc, char **argv)
{
    if (argc <= 1) {
        std::cout << "Usage: " << argv[0] << "file\n";
        return 1;
    }
    mpc_parser_t* Comment   = mpc_new("comment");
    mpc_parser_t* Indent   = mpc_new("indent");
    mpc_parser_t* Newline   = mpc_new("newline");
    mpc_parser_t* WhiteSpace = mpc_new("ws");
    mpc_parser_t* OptionalWhiteSpace = mpc_new("ows");
    mpc_parser_t* OptionalWhiteSpaceNewline = mpc_new("owsn");
    mpc_parser_t* Number   = mpc_new("number");
    mpc_parser_t* Operator = mpc_new("operator");
    mpc_parser_t* FactorOperator = mpc_new("factorop");
    mpc_parser_t* TermOperator = mpc_new("termop");
    mpc_parser_t* Expr     = mpc_new("expr");
    mpc_parser_t* Body     = mpc_new("body");
    mpc_parser_t* Identifier = mpc_new("identifier");
    mpc_parser_t* TypeIdent = mpc_new("typeident");
    mpc_parser_t* Import = mpc_new("import");
    mpc_parser_t* MethodRet = mpc_new("methodret");
    mpc_parser_t* MethodDef = mpc_new("methoddef");
    mpc_parser_t* ParamDef = mpc_new("paramdef");
    mpc_parser_t* String = mpc_new("string");
    mpc_parser_t* Args = mpc_new("args");
    mpc_parser_t* Lexp = mpc_new("lexp");
    mpc_parser_t* Factor = mpc_new("factor");
    mpc_parser_t* MethodCall = mpc_new("methodcall");
    mpc_parser_t* MapIndex = mpc_new("mapindex");
    mpc_parser_t* ListItem = mpc_new("listitem");
    mpc_parser_t* MapItem = mpc_new("mapitem");
    mpc_parser_t* TupleMap = mpc_new("tuplemap");
    mpc_parser_t* MapItems = mpc_new("mapitems");
    mpc_parser_t* ListItems = mpc_new("listitems");
    mpc_parser_t* List = mpc_new("list");
    mpc_parser_t* Namespacedef = mpc_new("namespacedef");
    mpc_parser_t* Primitive = mpc_new("primitive");
    mpc_parser_t* Range = mpc_new("range");
    mpc_parser_t* MatchCase = mpc_new("matchcase");
    mpc_parser_t* Match = mpc_new("match");
    mpc_parser_t* Assignment = mpc_new("assignment");
    mpc_parser_t* Stmt = mpc_new("stmt");
    mpc_parser_t* Term = mpc_new("term");
    mpc_parser_t* Const = mpc_new("const");
    mpc_parser_t* Return = mpc_new("return");
    mpc_parser_t* Pure = mpc_new("pure");
    mpc_parser_t* TopLevel = mpc_new("toplevel");
    mpc_parser_t* NolangPure = mpc_new("nolangpure");

    mpc_err_t* err = mpca_lang(MPCA_LANG_WHITESPACE_SENSITIVE,
        "comment    : /(#|\\/\\/)[^\\r\\n]*/"
        "           | /\\/\\*[^\\*]*(\\*[^\\/][^\\*]*)*\\*\\// ;"
        "indent     : /\\s\\s+/ ;"
        "newline    : '\\n';"
        "ws         : /[\\s]+/ ;"
        "ows        : /[\\s\\t]*/ ;"
        "owsn       : /[\\s\\t\\n]*/ ;"
        "identifier : /[A-Za-z_][A-Za-z0-9_-]*/ ;"
        "typeident  : <identifier> <ows> ':' <ows> <identifier> ;"
        "number     : /[0-9]+/ ;"
        "string     : /\"(\\\\.|[^\"])*\"/ "
        "           | /\'(\\\\.|[^\'])*\'/ ; "
        "operator   : '+' | '-' | '*' | '/' ;"
        "factorop   : '*'"
        "           | '/'"
        "           | \"div\""
        "           | \"mod\""
        "           | \"rem\";"
        "termop     : '+'"
        "           | '-';"
        "import     : \"import\" <ws> <identifier> <newline>;"
        "const      : \"const\" <ws> <assignment> <newline>;"
        "methodret  : <ows> ':' <ows> <identifier> ;"
        "methoddef  : (<pure> <ws>)? <identifier> <ows> <args>? <methodret>? <ows> \"=>\" (<newline>|<ws>) <body> ;"
        "paramdef   : <typeident>? <ows> (',' <ows> <typeident>)*; "
        "args       : '(' <paramdef>? ')'; "
        "factor     : <namespacedef>"
        "           | '(' <lexp> ')'"
        "           | <number>"
        "           | <string>"
        "           | <identifier>; "
        "term       : <factor> (<ows> <factorop> <ows> <factor>)*;"
        "lexp       : <term> (<ows> <termop> <ows> <term>)* ; "
        "expr       : <list>"
        "           | <lexp>;"
        "methodcall : '(' (<expr> (',' <ows> <expr>)*)? ')';"
        "mapindex   : '[' <expr> ']';"
        "listitem   : <expr>;"
        "mapitem    : <string> <ows> ':' <owsn> <expr> ;"
        "tuplemap   : '(' <string> <owsn> ',' <owsn> <lexp> ')';"
        "mapitems   : (<tuplemap> | <mapitem>) <owsn> (',' <owsn> (<tuplemap> | <mapitem>)) *;"
        "listitems  : <listitem> (<owsn> ',' <owsn> <listitem>) *;"
        "list       : '[' <owsn> (<mapitems> | <listitems>)? <owsn> ']' ;"
        "namespacedef : <identifier> ('.' <identifier>)* (<methodcall> | <mapindex>)?;"
        "primitive  : <identifier> | <number> | <string> ;"
        "range      : <primitive> \"..\" <primitive>?;"
        "assignment : (<typeident>|<namespacedef>) <ws> '=' <ws> <expr>;"
        "matchcase  : <comment> | (<indent> (<range> | <primitive> | '?') <ows> ':' <ows> <stmt> <newline>);"
        "match      : \"match\" <ws> <stmt> <ows> \"=>\" <newline> <matchcase>+;"
        "stmt       : <match>"
        "           | <assignment>"
        "           | <namespacedef>"
        "           | <list>"
        "           | <expr>"
        "           | <return>"
        "           | <comment>;"
        "body       : ((<indent>+ <stmt>)? <newline>)* ;"
        "pure       : \"pure\" ;"
        "return     : \"return \" <stmt>;"
        "toplevel   : <import>"
        "           | <const>"
        "           | <comment>"
        "           | <methoddef>"
        "           | <newline>;"
        "nolangpure : /^/ <toplevel>* /$/;"
      ,
        Comment, Indent, Newline,
        WhiteSpace, OptionalWhiteSpace, OptionalWhiteSpaceNewline,
        Identifier, TypeIdent,
        Number, String,
        Operator, FactorOperator, TermOperator,
        Import, Const,
        MethodRet, MethodDef, ParamDef, Args,
        Factor, Term, Lexp,
        Expr, MethodCall,
        MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List,
        Namespacedef,
        Primitive, Range,
        Assignment, MatchCase, Match,
        Stmt,
        Body, Pure, Return,
        TopLevel, NolangPure, NULL);

    if (err != NULL) {
        mpc_err_print(err);
        mpc_err_delete(err);
        exit(1);
    }

    mpc_result_t r;
    std::string data = readFile(argv[1]);
    int res = 0;
    if (mpc_parse(argv[1], data.c_str(), NolangPure, &r)) {
      mpc_ast_print(static_cast<mpc_ast_t*>(r.output));
      mpc_ast_delete(static_cast<mpc_ast_t*>(r.output));
    } else {
        mpc_err_print(r.error);
        mpc_err_delete(r.error);
        res = 1;
    }

    mpc_cleanup(39,
        Comment, Indent, Newline,
        WhiteSpace, OptionalWhiteSpace, OptionalWhiteSpaceNewline,
        Identifier, TypeIdent,
        Number, String,
        Operator, FactorOperator, TermOperator,
        Import, Const,
        MethodRet, MethodDef, ParamDef, Args,
        Factor, Term, Lexp,
        Expr, MethodCall,
        MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List,
        Namespacedef,
        Primitive, Range,
        Assignment, MatchCase, Match,
        Stmt,
        Body, Pure, Return,
        TopLevel, NolangPure);

    return res;
}
<|endoftext|>


<commit_before>
#include <iostream>
#include <limits>
#include <vector>
#include <string>
#include <cmath>
#include <stdio.h>
#include <stdarg.h>
#include "mosek.h"

/*

TODO: Solution may not be feasible (OPTIMAL), if so, return

 */

struct Node {
    int         ID;
    double      nodeObj;
    double      lowerBound;
    double*     nodeSoln;
    bool        feasible;
    bool        intfeasible;
    bool        eliminated;
    MSKtask_t   problem;
    Node*       parent;
    std::vector< std::vector <int> > usedCuts;
    int depth;
};

static void MSKAPI printstr(void *handle, MSKCONST char str[])
{
  printf("%s",str);
}

MSKtask_t oProblem = NULL; // Original problem instance
double globalUpperBound_ = std::numeric_limits<double>::infinity();
double* bestSoln_;
int branchingRule_ = 0; // 0: most fractional, 1: index-based, 2: value-based
int cutPriority_ = 0; // 0: default, most fractional, 1: best-value
int cutRule_ = 0; // 0: default, no cut, 1: always cut, 2: deep-heuristic-cut
int cutLimit_ = 1; // max number of cuts to add, default is 1
int nodesProcessed_ = 0;
int totalNodes_ = 0;
int numVars_ = 0;
int N = 0; /* number of assets, always 1 less than numVars */
Node* root;
std::vector< Node* > nodeList_;
std::vector< Node* > allNodeList_; // Keeps pointer of all nodes for destructor
int printLevel_ = 2;

int startBB();
int createProblem(MSKtask_t* originalProblem);
int createNewNode(Node* parent, Node** newNode, int varID, double bound, int lower);
int printTxt(int level, const char* fmt, ...);
int selectNode(Node** activeNode);
int solveLP(Node* aNode);
int isIntFeasible(Node* aNode);
int branch(Node* activeNode);
int eliminateNodes();

int main(int argc, char* argv[]) {

    std::cout << "Working!" << std::endl;
    root = NULL;
    // if(argc) ....
    numVars_ = 11;
    N = numVars_ - 1;

    MSKenv_t env = NULL;
    MSKtask_t task = NULL;
    MSKrescodee r;

    /* Create the mosek environment. */
    r = MSK_makeenv(&env,NULL);
    r = MSK_maketask(env,3,N+1,&task);

    oProblem = task;

    startBB();

    return 1;
}

int startBB() {
    int status = 0;
    createProblem(&oProblem);

    root = (Node *) malloc(sizeof(Node));
    createNewNode(0, &root, -1 /*var id*/, 0 /* bound */, 0 /* lower */);

    while(true) {

        printTxt(2, "Active Nodes: %d", nodeList_.size());

        if(nodeList_.size() == 0) {
            break;
        }

        Node* activeNode;
        selectNode(&activeNode);

	if(!activeNode->eliminated) {
	  solveLP(activeNode);
	} else {
	  continue;
	}

	if( activeNode->feasible) { isIntFeasible(activeNode); }

	if( activeNode->feasible && activeNode->intfeasible) {
	  if(activeNode->nodeObj < globalUpperBound_) {
	    globalUpperBound_ = activeNode->nodeObj;
	    bestSoln_ = activeNode->nodeSoln;
	    eliminateNodes();
	    printTxt(1, "Best objective value: %f", globalUpperBound_);
	  }
	} else if(activeNode->feasible && !activeNode->intfeasible) {
	  // branch
	  if(activeNode->nodeObj <= globalUpperBound_) {
	    printTxt(3, "Upper bound: %f, current objective: %f, branching...",globalUpperBound_,activeNode->nodeObj);
	    branch(activeNode);
	  }
	} else {
	  continue;
	}

    }

    return status;
}

int branch(Node* activeNode) {
    int status = 0;

    // find most fractional
    int asset = 0;
    double mostfrac = 0;
    for(int i=0; i<N; ++i) {
      double cValue = activeNode->nodeSoln[i];
      double smallest = fmin(cValue - floor(cValue), ceil(cValue) - cValue);
      if(smallest >= mostfrac) {
	asset = i;
	mostfrac = smallest;
      }
    }

    // Call newNode twice

    // Left - Less than bound
    Node* leftNode = (Node*) malloc(sizeof(Node));
    createNewNode(activeNode /*parent*/, &leftNode, asset /*var id*/,  floor(activeNode->nodeSoln[asset])/* bound */, 0 /* lower */);
    // Right - Greater than bound
    Node* rightNode = (Node*) malloc(sizeof(Node));
    createNewNode(activeNode /*parent*/, &rightNode, asset /*var id*/, ceil(activeNode->nodeSoln[asset]) /* bound */, 1 /* lower */);

    // Add them to active list
    // Done in create

    return status;
}

int cut() {
    int status = 0;

    return status;
}

int selectNode(Node** activeNode) {
    int status = 0;
    int selected = 0;
    int max_depth = 0;
    *activeNode = nodeList_[0];
    for(unsigned int i=0; i < nodeList_.size(); i++) {
        if(nodeList_[i]->depth > max_depth) {
            selected = i;
            *activeNode = nodeList_[i];
        }
    }
    nodeList_.erase(nodeList_.begin()+selected);

    printTxt(4,"Node selected: %d (%p)", (*activeNode)->ID, *activeNode);

    return status;
}

int eliminateNodes() {
  for(unsigned int i=0; i<nodeList_.size(); i++) {
     if(nodeList_[i]->lowerBound > globalUpperBound_) {
       nodeList_[i]->eliminated = true;
     }
  }
}

int createNewNode(Node* parent, Node** newNode, int varID, double bound, int lower) {
    int status = 0;

    if(!parent) {

        for (int i = 0; i < N; ++i) { // Initialize array of used cuts
            std::vector<int> row; // Create an empty row for each asset
            //(*newNode)->usedCuts.push_back(row); // Add the row to the main vector
        }

        (*newNode)->ID = 0;
        (*newNode)->nodeObj = 0;
        (*newNode)->lowerBound = 0;
        (*newNode)->feasible = false;
        (*newNode)->intfeasible = false;
	(*newNode)->eliminated = false;
        (*newNode)->problem = oProblem;
        (*newNode)->parent = 0;
        //(*newNode)->usedCuts = usedCuts;
        (*newNode)->depth = 0;

        printTxt(3, "Root is created");

    } else {

        printTxt(3, "New node is created");

        // Add branch constraint here
        // Change problem
        MSKtask_t newProblem;
        MSK_clonetask((parent->problem), &newProblem);

	//MSK_analyzeproblem(parent->problem, MSK_STREAM_LOG);

	//MSK_analyzeproblem(newProblem, MSK_STREAM_LOG);

        if(varID!=-1) {
            MSK_chgbound (
                newProblem,         //MSKtask_t    task,
                MSK_ACC_VAR,        //MSKaccmodee  accmode,
                varID+1,            //MSKint32t    i,
                lower,              //MSKint32t    lower,
                1,                  //MSKint32t    finite,
                bound               //MSKrealt     value);
                );
        }

        std::vector< std::vector <int> > usedCuts;
        // copy usedCuts
        for (int i = 0; i < N; i++) { // Initialize array of used cuts
	  //std::vector<int> row = parent->usedCuts[i]; // Create an empty row for each asset
            //usedCuts.push_back(row); // Add the row to the main vector
        }

        (*newNode)->ID = totalNodes_;
        (*newNode)->nodeObj = 0;
        (*newNode)->lowerBound = parent->lowerBound;
        (*newNode)->feasible = false;
        (*newNode)->intfeasible = false;
	(*newNode)->eliminated = false;
        //(*newNode)->problem = &newProblem;
        (*newNode)->problem = newProblem;
	(*newNode)->parent = parent;
        //(*newNode)->usedCuts = usedCuts;
        (*newNode)->depth = parent->depth+1;

    }

    nodeList_.push_back(*newNode);
    allNodeList_.push_back(*newNode);
    totalNodes_++;

    return status;
}

int solveLP(Node* aNode) {
    int status = 0;
    MSKtask_t mtask = NULL;

    //MSK_analyzeproblem(mtask, MSK_STREAM_LOG);

    MSK_clonetask(aNode->problem, &mtask);

    //MSKvariabletypee* vartype = malloc(numVars_*sizeof(MSKvariabletypee));
    for(int i=0; i<N; ++i) {
        MSK_putvartype (mtask, i+1, MSK_VAR_TYPE_CONT);
    }
    //std::cout << "Running so far!" << std::endl;
    //MSK_linkfunctotaskstream (mtask, MSK_STREAM_LOG, NULL, printstr);
    MSK_optimize(mtask);

    MSKsolstae solsta;
    MSK_getsolsta (mtask, MSK_SOL_ITR, &solsta);

    MSKrealt primalobj;

    //if(solsta) {
        // Save it, etc..

      //}

    switch( solsta )
      {
      case MSK_SOL_STA_OPTIMAL:
      case MSK_SOL_STA_NEAR_OPTIMAL:
        {
          aNode->feasible = true;
	  MSK_getprimalobj(mtask, MSK_SOL_ITR, &primalobj);
	  aNode->nodeObj = primalobj;
	  if(primalobj > aNode->lowerBound) {
	    aNode -> lowerBound = primalobj;
	  }
	  aNode -> nodeSoln = (double*) malloc(N*sizeof(double));
	  MSK_getsolutionslice(mtask, MSK_SOL_ITR, MSK_SOL_ITEM_XX, 1, N+1, aNode->nodeSoln);

	  //for(int j=0; j<N; ++j) {
	  //  std::cout << "Variable " << j << " value: " << aNode->nodeSoln[j] << std::endl;
	  //}

	  // std::cout << primalobj << std::endl;
          printTxt(3, "Node (%d) Optimal Objective: %f", aNode->ID, aNode->nodeObj);
          break;
        }
      case MSK_SOL_STA_DUAL_INFEAS_CER:
      case MSK_SOL_STA_PRIM_INFEAS_CER:
      case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER:
      case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:
	aNode->feasible = false;
	printTxt(3,"Node (%d) infeasibility certificate found.", aNode->ID);
	break;
      default:
	aNode->feasible = false;
	break;
      }

    //MSK_solutionsummary (mtask, MSK_STREAM_LOG);

    return status;

}

int isIntFeasible(Node* aNode) {
  bool intfeasible = true;
  for(int i=0; i<N; ++i) {

    double intpart;
    if( std::modf(aNode->nodeSoln[i], &intpart) >= 1e-8) {
      intfeasible = false;
      printTxt(5,"Integer infeasibility at asset %d, value: %f",i, aNode->nodeSoln[i]);
    }
  }

  aNode->intfeasible = intfeasible;
  intfeasible ? printTxt(4,"Node %d is integer feasible",aNode->ID) : printTxt(4,"Node %d is NOT integer feasible",aNode->ID);
    return 1;
}

int printTxt(int level, const char* fmt, ...) {

    if(level<=printLevel_) {
        std::cout << level << ":";
        for(int i=0; i<level; ++i) {
            std::cout << "   ";
        }
        va_list args;
        va_start(args,fmt);
        vprintf(fmt,args);
        va_end(args);
        std::cout << std::endl;
    }
    return 1;

}

<commit_msg>Report summary is added.<commit_after>
#include <iostream>
#include <limits>
#include <vector>
#include <string>
#include <cmath>
#include <stdio.h>
#include <stdarg.h>
#include "mosek.h"

/*

TODO: Solution may not be feasible (OPTIMAL), if so, return

 */

struct Node {
    int         ID;
    double      nodeObj;
    double      lowerBound;
    double*     nodeSoln;
    bool        feasible;
    bool        intfeasible;
    bool        eliminated;
    MSKtask_t   problem;
    Node*       parent;
    std::vector< std::vector <int> > usedCuts;
    int depth;
};

static void MSKAPI printstr(void *handle, MSKCONST char str[])
{
  printf("%s",str);
}

MSKtask_t oProblem = NULL; // Original problem instance
double globalUpperBound_ = std::numeric_limits<double>::infinity();
double* bestSoln_;
int branchingRule_ = 0; // 0: most fractional, 1: index-based, 2: value-based
int cutPriority_ = 0; // 0: default, most fractional, 1: best-value
int cutRule_ = 0; // 0: default, no cut, 1: always cut, 2: deep-heuristic-cut
int cutLimit_ = 1; // max number of cuts to add, default is 1
int nodesProcessed_ = 0;
int totalNodes_ = 0;
int numVars_ = 0;
int N = 0; /* number of assets, always 1 less than numVars */
Node* root;
std::vector< Node* > nodeList_;
std::vector< Node* > allNodeList_; // Keeps pointer of all nodes for destructor
int printLevel_ = 2;

int startBB();
int createProblem(MSKtask_t* originalProblem);
int createNewNode(Node* parent, Node** newNode, int varID, double bound, int lower);
int printTxt(int level, const char* fmt, ...);
int selectNode(Node** activeNode);
int solveLP(Node* aNode);
int isIntFeasible(Node* aNode);
int branch(Node* activeNode);
int eliminateNodes();

int main(int argc, char* argv[]) {

    std::cout << "Working!" << std::endl;
    root = NULL;
    // if(argc) ....
    numVars_ = 11;
    N = numVars_ - 1;

    MSKenv_t env = NULL;
    MSKtask_t task = NULL;
    MSKrescodee r;

    /* Create the mosek environment. */
    r = MSK_makeenv(&env,NULL);
    r = MSK_maketask(env,3,N+1,&task);

    oProblem = task;

    startBB();

    return 1;
}

int startBB() {
    int status = 0;
    createProblem(&oProblem);

    root = (Node *) malloc(sizeof(Node));
    createNewNode(0, &root, -1 /*var id*/, 0 /* bound */, 0 /* lower */);

    while(true) {

        printTxt(3, "Active Nodes: %d", nodeList_.size());

        if(nodeList_.size() == 0) {
            break;
        }

        Node* activeNode;
        selectNode(&activeNode);

	if(!activeNode->eliminated) {
	  solveLP(activeNode);
	} else {
	  continue;
	}

	if( activeNode->feasible) { isIntFeasible(activeNode); }

	if( activeNode->feasible && activeNode->intfeasible) {
	  if(activeNode->nodeObj < globalUpperBound_) {
	    globalUpperBound_ = activeNode->nodeObj;
	    bestSoln_ = activeNode->nodeSoln;
	    eliminateNodes();
	    printTxt(1, "Best objective value: %f", globalUpperBound_);
	  }
	} else if(activeNode->feasible && !activeNode->intfeasible) {
	  // branch
	  if(activeNode->nodeObj <= globalUpperBound_) {
	    printTxt(3, "Upper bound: %f, current objective: %f, branching...",globalUpperBound_,activeNode->nodeObj);
	    branch(activeNode);
	  }
	} else {
	  continue;
	}

    }

    // Summary report
    printTxt(1, "========== SUMMARY ==========");
    printTxt(1, "Best objective value: %f", globalUpperBound_);
    printTxt(1, "Values: ");
    for(int i=0; i<N; i++) {
      printTxt(1, "\t%d: %f", (i+1), bestSoln_[i]);
    }
    printTxt(1,"Done...");
    return status;
}

int branch(Node* activeNode) {
    int status = 0;

    // find most fractional
    int asset = 0;
    double mostfrac = 0;
    for(int i=0; i<N; ++i) {
      double cValue = activeNode->nodeSoln[i];
      double smallest = fmin(cValue - floor(cValue), ceil(cValue) - cValue);
      if(smallest >= mostfrac) {
	asset = i;
	mostfrac = smallest;
      }
    }

    // Call newNode twice

    // Left - Less than bound
    Node* leftNode = (Node*) malloc(sizeof(Node));
    createNewNode(activeNode /*parent*/, &leftNode, asset /*var id*/,  floor(activeNode->nodeSoln[asset])/* bound */, 0 /* lower */);
    // Right - Greater than bound
    Node* rightNode = (Node*) malloc(sizeof(Node));
    createNewNode(activeNode /*parent*/, &rightNode, asset /*var id*/, ceil(activeNode->nodeSoln[asset]) /* bound */, 1 /* lower */);

    // Add them to active list
    // Done in create

    return status;
}

int cut() {
    int status = 0;

    return status;
}

int selectNode(Node** activeNode) {
    int status = 0;
    int selected = 0;
    int max_depth = 0;
    *activeNode = nodeList_[0];
    for(unsigned int i=0; i < nodeList_.size(); i++) {
        if(nodeList_[i]->depth > max_depth) {
            selected = i;
            *activeNode = nodeList_[i];
        }
    }
    nodeList_.erase(nodeList_.begin()+selected);

    printTxt(4,"Node selected: %d (%p)", (*activeNode)->ID, *activeNode);

    return status;
}

int eliminateNodes() {
  for(unsigned int i=0; i<nodeList_.size(); i++) {
     if(nodeList_[i]->lowerBound > globalUpperBound_) {
       nodeList_[i]->eliminated = true;
     }
  }
}

int createNewNode(Node* parent, Node** newNode, int varID, double bound, int lower) {
    int status = 0;

    if(!parent) {

        for (int i = 0; i < N; ++i) { // Initialize array of used cuts
            std::vector<int> row; // Create an empty row for each asset
            //(*newNode)->usedCuts.push_back(row); // Add the row to the main vector
        }

        (*newNode)->ID = 0;
        (*newNode)->nodeObj = 0;
        (*newNode)->lowerBound = 0;
        (*newNode)->feasible = false;
        (*newNode)->intfeasible = false;
	(*newNode)->eliminated = false;
        (*newNode)->problem = oProblem;
        (*newNode)->parent = 0;
        //(*newNode)->usedCuts = usedCuts;
        (*newNode)->depth = 0;

        printTxt(3, "Root is created");

    } else {

        printTxt(3, "New node is created");

        // Add branch constraint here
        // Change problem
        MSKtask_t newProblem;
        MSK_clonetask((parent->problem), &newProblem);

	//MSK_analyzeproblem(parent->problem, MSK_STREAM_LOG);

	//MSK_analyzeproblem(newProblem, MSK_STREAM_LOG);

        if(varID!=-1) {
            MSK_chgbound (
                newProblem,         //MSKtask_t    task,
                MSK_ACC_VAR,        //MSKaccmodee  accmode,
                varID+1,            //MSKint32t    i,
                lower,              //MSKint32t    lower,
                1,                  //MSKint32t    finite,
                bound               //MSKrealt     value);
                );
        }

        std::vector< std::vector <int> > usedCuts;
        // copy usedCuts
        for (int i = 0; i < N; i++) { // Initialize array of used cuts
	  //std::vector<int> row = parent->usedCuts[i]; // Create an empty row for each asset
            //usedCuts.push_back(row); // Add the row to the main vector
        }

        (*newNode)->ID = totalNodes_;
        (*newNode)->nodeObj = 0;
        (*newNode)->lowerBound = parent->lowerBound;
        (*newNode)->feasible = false;
        (*newNode)->intfeasible = false;
	(*newNode)->eliminated = false;
        //(*newNode)->problem = &newProblem;
        (*newNode)->problem = newProblem;
	(*newNode)->parent = parent;
        //(*newNode)->usedCuts = usedCuts;
        (*newNode)->depth = parent->depth+1;

    }

    nodeList_.push_back(*newNode);
    allNodeList_.push_back(*newNode);
    totalNodes_++;

    return status;
}

int solveLP(Node* aNode) {
    int status = 0;
    MSKtask_t mtask = NULL;

    //MSK_analyzeproblem(mtask, MSK_STREAM_LOG);

    MSK_clonetask(aNode->problem, &mtask);

    //MSKvariabletypee* vartype = malloc(numVars_*sizeof(MSKvariabletypee));
    for(int i=0; i<N; ++i) {
        MSK_putvartype (mtask, i+1, MSK_VAR_TYPE_CONT);
    }
    //std::cout << "Running so far!" << std::endl;
    //MSK_linkfunctotaskstream (mtask, MSK_STREAM_LOG, NULL, printstr);
    MSK_optimize(mtask);

    MSKsolstae solsta;
    MSK_getsolsta (mtask, MSK_SOL_ITR, &solsta);

    MSKrealt primalobj;

    //if(solsta) {
        // Save it, etc..

      //}

    switch( solsta )
      {
      case MSK_SOL_STA_OPTIMAL:
      case MSK_SOL_STA_NEAR_OPTIMAL:
        {
          aNode->feasible = true;
	  MSK_getprimalobj(mtask, MSK_SOL_ITR, &primalobj);
	  aNode->nodeObj = primalobj;
	  if(primalobj > aNode->lowerBound) {
	    aNode -> lowerBound = primalobj;
	  }
	  aNode -> nodeSoln = (double*) malloc(N*sizeof(double));
	  MSK_getsolutionslice(mtask, MSK_SOL_ITR, MSK_SOL_ITEM_XX, 1, N+1, aNode->nodeSoln);

	  //for(int j=0; j<N; ++j) {
	  //  std::cout << "Variable " << j << " value: " << aNode->nodeSoln[j] << std::endl;
	  //}

	  // std::cout << primalobj << std::endl;
          printTxt(3, "Node (%d) Optimal Objective: %f", aNode->ID, aNode->nodeObj);
          break;
        }
      case MSK_SOL_STA_DUAL_INFEAS_CER:
      case MSK_SOL_STA_PRIM_INFEAS_CER:
      case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER:
      case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:
	aNode->feasible = false;
	printTxt(3,"Node (%d) infeasibility certificate found.", aNode->ID);
	break;
      default:
	aNode->feasible = false;
	break;
      }

    //MSK_solutionsummary (mtask, MSK_STREAM_LOG);

    return status;

}

int isIntFeasible(Node* aNode) {
  bool intfeasible = true;
  for(int i=0; i<N; ++i) {

    double intpart;
    if( std::modf(aNode->nodeSoln[i], &intpart) >= 1e-8) {
      intfeasible = false;
      printTxt(5,"Integer infeasibility at asset %d, value: %f",i, aNode->nodeSoln[i]);
    }
  }

  aNode->intfeasible = intfeasible;
  intfeasible ? printTxt(4,"Node %d is integer feasible",aNode->ID) : printTxt(4,"Node %d is NOT integer feasible",aNode->ID);
    return 1;
}

int printTxt(int level, const char* fmt, ...) {

    if(level<=printLevel_) {
        std::cout << level << ":";
        for(int i=0; i<level; ++i) {
            std::cout << "   ";
        }
        va_list args;
        va_start(args,fmt);
        vprintf(fmt,args);
        va_end(args);
        std::cout << std::endl;
    }
    return 1;

}

<|endoftext|>


<commit_before>/*
 * =====================================================================================
 *
 *       Filename:  kmer_query.cc
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  04/27/2016 08:48:26 AM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Prashant Pandey (), ppandey@cs.stonybrook.edu
 *   Organization:  Stony Brook University
 *
 * =====================================================================================
 */
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <set>
#include <bitset>
#include <cassert>
#include <fstream>

#include <boost/thread/thread.hpp>
#include <boost/lockfree/queue.hpp>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/atomic.hpp>

#include <time.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/mman.h>

#include "clipp.h"
#include "ProgOpts.h"
#include "gqf_cpp.h"
#include "kmer.h"

/*
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description:
 * =====================================================================================
 */
int query_main(QueryOpts& opts)
{
	struct timeval start, end;
	struct timezone tzp;
	std::unordered_set<uint64_t> kmers;

	srand(time(NULL));
	spdlog::logger* console = opts.console.get();

	//Initialize the QF
	console->info("Reading kmers into the QF off the disk.");
	CQF<KeyObject> cqf(opts.squeakr_file, LOCKS_FORBIDDEN, FREAD);

	// seek to the end of the file and read the k-mer size
	std::ifstream squeakr_file(opts.squeakr_file, std::ofstream::in);
	squeakr_file.seekg(0, squeakr_file.end);
	uint64_t file_size = squeakr_file.tellg();
	uint64_t kmer_size;
	squeakr_file.seekg(file_size - sizeof(kmer_size));
	squeakr_file.read((char*)&kmer_size, sizeof(kmer_size));
	squeakr_file.close();
	console->info("kmer size: {}", kmer_size);

	if (cqf.is_exact() && kmer_size*2 != cqf.keybits()) {
		console->error("K-mer size is not correct.");
		return 1;
	}

	console->info("Parsing query file for {}-mers.", kmer_size);
	Kmer::parse_kmers(opts.queryfile.c_str(), kmer_size, kmers);
	console->info("Found {} k-mers", kmers.size());

	std::ofstream opfile(opts.output_file.c_str(), std::ofstream::out);

	console->info("Querying kmers in the QF.");
	uint64_t num_not_found = 0;
	gettimeofday(&start, &tzp);
	for (auto it = kmers.begin(); it != kmers.end(); ++it) {
		uint64_t count = cqf.query(KeyObject(*it, 0, 0));
		if (count == 0) {
			std::cout << Kmer::int_to_str(*it, kmer_size) << std::endl;
			num_not_found++;
		}
		else
			opfile << Kmer::int_to_str(*it, kmer_size) << "\t" << count << std::endl;
	}
	gettimeofday(&end, &tzp);
	opfile.close();
	print_time_elapsed("", &start, &end, console);

	console->info("Not found: {}", num_not_found);

	return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */

<commit_msg>tested query and listing.<commit_after>/*
 * =====================================================================================
 *
 *       Filename:  kmer_query.cc
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  04/27/2016 08:48:26 AM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Prashant Pandey (), ppandey@cs.stonybrook.edu
 *   Organization:  Stony Brook University
 *
 * =====================================================================================
 */
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <set>
#include <bitset>
#include <cassert>
#include <fstream>

#include <boost/thread/thread.hpp>
#include <boost/lockfree/queue.hpp>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/atomic.hpp>

#include <time.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/mman.h>

#include "clipp.h"
#include "ProgOpts.h"
#include "gqf_cpp.h"
#include "kmer.h"

/*
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description:
 * =====================================================================================
 */
int query_main(QueryOpts& opts)
{
	struct timeval start, end;
	struct timezone tzp;
	std::unordered_set<uint64_t> kmers;

	srand(time(NULL));
	spdlog::logger* console = opts.console.get();

	//Initialize the QF
	console->info("Reading kmers into the QF off the disk.");
	CQF<KeyObject> cqf(opts.squeakr_file, LOCKS_FORBIDDEN, FREAD);

	// seek to the end of the file and read the k-mer size
	std::ifstream squeakr_file(opts.squeakr_file, std::ofstream::in);
	squeakr_file.seekg(0, squeakr_file.end);
	uint64_t file_size = squeakr_file.tellg();
	uint64_t kmer_size;
	squeakr_file.seekg(file_size - sizeof(kmer_size));
	squeakr_file.read((char*)&kmer_size, sizeof(kmer_size));
	squeakr_file.close();
	console->info("kmer size: {}", kmer_size);

	if (cqf.is_exact() && kmer_size*2 != cqf.keybits()) {
		console->error("K-mer size is not correct.");
		return 1;
	}

	console->info("Parsing query file for {}-mers.", kmer_size);
	Kmer::parse_kmers(opts.queryfile.c_str(), kmer_size, kmers);
	console->info("Found {} k-mers", kmers.size());

	std::ofstream opfile(opts.output_file.c_str(), std::ofstream::out);

	console->info("Querying kmers in the QF.");
	uint64_t num_not_found = 0;
	gettimeofday(&start, &tzp);
	for (auto it = kmers.begin(); it != kmers.end(); ++it) {
		uint64_t count = cqf.query(KeyObject(*it, 0, 0));
		if (count == 0) {
			console->error(Kmer::int_to_str(*it, kmer_size));
			num_not_found++;
		}
		else
			opfile << Kmer::int_to_str(*it, kmer_size) << "\t" << count << std::endl;
	}
	gettimeofday(&end, &tzp);
	opfile.close();
	print_time_elapsed("", &start, &end, console);

	console->info("Not found: {}", num_not_found);

	return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */

<|endoftext|>