<commit_before>#include <cstdio>
#include <stdlib.h>
#include <string.h>
#if defined(__NODE_V0_11_OR_12__) || defined(__NODE_GE_V4__)
#include <fcntl.h>
#endif

//#ifdef __POSIX__
#include <unistd.h>
/*#else
#include <process.h>
#endif*/

#include <nan.h>

using v8::Array;
using v8::FunctionTemplate;
using v8::Handle;
using v8::Integer;
using v8::Local;
using v8::Object;
using v8::String;

static int clear_cloexec (int desc)
{
    int flags = fcntl (desc, F_GETFD, 0);
    if (flags <  0)
        return flags; //return if reading failed

    flags &= ~FD_CLOEXEC; //clear FD_CLOEXEC bit
    return fcntl (desc, F_SETFD, flags);
}

static int do_exec(char *argv[])
{
        clear_cloexec(0); //stdin
        clear_cloexec(1); //stdout
        clear_cloexec(2); //stderr
        return execvp(argv[0], argv);
}

NAN_METHOD(kexec) {
    Nan::HandleScope scope;

    /*
     * Steve Blott: 17 Jan, 2014
     *              Temporary comment by way of explanation...
     *              To be deleted.
     *
     * With a single argument:
     *   - pass it to execvp as "sh -c 'args[0]'"
     *   - this is the existing usage
     *
     * With exactly two arguments:
     *   - the first is the command name
     *   - the second is an array of arguments
     *     ...as in process.child_process.spawn()
     *
     * This approach is not great, but it allows the established usage to
     * coexist with direct execvp-usage, and avoids making any changes to the
     * established API.
     */

    if ( 1 == info.Length() && info[0]->IsString() )
    {
        String::Utf8Value str(info[0]);
        char* argv[] = { const_cast<char *>("/bin/sh"), const_cast<char *>("-c"), *str, NULL};

        int err = do_exec(argv);

        info.GetReturnValue().Set(Nan::New<Integer>(err));
    }

    if ( 2 == info.Length() && info[0]->IsString() && info[1]->IsArray() )
    {
        String::Utf8Value str(info[0]);

        // Substantially copied from:
        // https://github.com/joyent/node/blob/2944e03/src/node_child_process.cc#L92-104
        Local<Array> argv_handle = Local<Array>::Cast(info[1]);
        int argc = argv_handle->Length();

        int argv_length = argc + 1 + 1;
        char **argv = new char*[argv_length];

        argv[0] = *str;
        argv[argv_length-1] = NULL;
        for (int i = 0; i < argc; i++) {
            String::Utf8Value arg(argv_handle->Get(Nan::New<Integer>(i))->ToString());
            argv[i+1] = strdup(*arg);
        }

        int err = do_exec(argv);

        // Failed...!
        // FIXME: It might be better to raise an exception here.
        for (int i = 0; i < argc; i++)
            free(argv[i+1]);
        delete [] argv;

        info.GetReturnValue().Set(Nan::New<Integer>(err));
    }

    return Nan::ThrowTypeError("kexec: invalid arguments");
}

#define EXPORT(name, symbol) exports->Set( \
  Nan::New<String>(name).ToLocalChecked(), \
  Nan::New<FunctionTemplate>(symbol)->GetFunction() \
)

void init (Handle<Object> exports) {
    EXPORT("kexec", kexec);
}

NODE_MODULE(kexec, init);
<commit_msg>Remove unnecessary handle scope<commit_after>#include <cstdio>
#include <stdlib.h>
#include <string.h>
#if defined(__NODE_V0_11_OR_12__) || defined(__NODE_GE_V4__)
#include <fcntl.h>
#endif

//#ifdef __POSIX__
#include <unistd.h>
/*#else
#include <process.h>
#endif*/

#include <nan.h>

using v8::Array;
using v8::FunctionTemplate;
using v8::Handle;
using v8::Integer;
using v8::Local;
using v8::Object;
using v8::String;

static int clear_cloexec (int desc)
{
    int flags = fcntl (desc, F_GETFD, 0);
    if (flags <  0)
        return flags; //return if reading failed

    flags &= ~FD_CLOEXEC; //clear FD_CLOEXEC bit
    return fcntl (desc, F_SETFD, flags);
}

static int do_exec(char *argv[])
{
        clear_cloexec(0); //stdin
        clear_cloexec(1); //stdout
        clear_cloexec(2); //stderr
        return execvp(argv[0], argv);
}

NAN_METHOD(kexec) {
    /*
     * Steve Blott: 17 Jan, 2014
     *              Temporary comment by way of explanation...
     *              To be deleted.
     *
     * With a single argument:
     *   - pass it to execvp as "sh -c 'args[0]'"
     *   - this is the existing usage
     *
     * With exactly two arguments:
     *   - the first is the command name
     *   - the second is an array of arguments
     *     ...as in process.child_process.spawn()
     *
     * This approach is not great, but it allows the established usage to
     * coexist with direct execvp-usage, and avoids making any changes to the
     * established API.
     */

    if ( 1 == info.Length() && info[0]->IsString() )
    {
        String::Utf8Value str(info[0]);
        char* argv[] = { const_cast<char *>("/bin/sh"), const_cast<char *>("-c"), *str, NULL};

        int err = do_exec(argv);

        info.GetReturnValue().Set(Nan::New<Integer>(err));
    }

    if ( 2 == info.Length() && info[0]->IsString() && info[1]->IsArray() )
    {
        String::Utf8Value str(info[0]);

        // Substantially copied from:
        // https://github.com/joyent/node/blob/2944e03/src/node_child_process.cc#L92-104
        Local<Array> argv_handle = Local<Array>::Cast(info[1]);
        int argc = argv_handle->Length();

        int argv_length = argc + 1 + 1;
        char **argv = new char*[argv_length];

        argv[0] = *str;
        argv[argv_length-1] = NULL;
        for (int i = 0; i < argc; i++) {
            String::Utf8Value arg(argv_handle->Get(Nan::New<Integer>(i))->ToString());
            argv[i+1] = strdup(*arg);
        }

        int err = do_exec(argv);

        // Failed...!
        // FIXME: It might be better to raise an exception here.
        for (int i = 0; i < argc; i++)
            free(argv[i+1]);
        delete [] argv;

        info.GetReturnValue().Set(Nan::New<Integer>(err));
    }

    return Nan::ThrowTypeError("kexec: invalid arguments");
}

#define EXPORT(name, symbol) exports->Set( \
  Nan::New<String>(name).ToLocalChecked(), \
  Nan::New<FunctionTemplate>(symbol)->GetFunction() \
)

void init (Handle<Object> exports) {
    EXPORT("kexec", kexec);
}

NODE_MODULE(kexec, init);
<|endoftext|>


<commit_before>//stl list
//载入头文件
#include <iostream>
#include <list>

using namespace std;

typedef struct {
	char name[21];
	int id;
}  note ;

int main(int argc, char const *argv[])
{
	//建立
	list<int> L0;       // 空链表
	list<int> L1(9);   // 建一个含一个元素的链表
	list<int> L2(5,1); // 建一个多个个元素的链表
	list<int> L3(L2);  // 复制L2的元素，重新建立一个链表
	list<int> L4(L0.begin(), L0.end());//建一个含L0一个区域的链表

	//其他元素类型的链表

	list<double> Ld;
	list<note> Lu;

	//链表操作
	//一个链表
	list<int> l;
	//在链表头部插入元素
	l.push_front(1);
	//尾部
	l.push_back(2);

	return 0;
}<commit_msg>update list<commit_after>//stl list
//载入头文件
#include <iostream>
#include <list>

using namespace std;

typedef struct {
	char name[21];
	int id;
}  note ;

int main(int argc, char const *argv[])
{
	//建立
	list<int> L0;       // 空链表
	list<int> L1(9);   // 建一个含一个元素的链表
	list<int> L2(5,1); // 建一个多个个元素的链表
	list<int> L3(L2);  // 复制L2的元素，重新建立一个链表
	list<int> L4(L0.begin(), L0.end());//建一个含L0一个区域的链表

	//其他元素类型的链表

	list<double> Ld;
	list<note> Lu;

	//链表操作
	//一个链表
	list<int> l;
	//在链表头部插入元素
	l.push_front(1);
	//尾部
	l.push_back(2);

	//返回第一个元素的引用
	int n= l.front()    // = 1
    //返回最后一元素的引用
	n = l.back()     // = 2
	//返回第一个元素的迭代器(iterator)
	list<int>::iterator it = l.begin();    // *it = 1
    //返回最后一个元素的下一位置的指针(list为空时end()=begin())
    it = l.end();

	return 0;
}<|endoftext|>


<commit_before>/*
 * main.cpp
 * Copyright (c) 2015 Markus Himmel. All rights reserved.
 * Distributed under the terms of the MIT license.
 */

#include <algorithm>
#include <iostream>

#include <String.h>
#include <Directory.h>

#include "BookmarksTree.h"
#include "BookmarksFormat.h"

int helpMessage(int code, BookmarksOutput* a, BookmarksInput* b)
{
	delete a;
	delete b;
	std::cout	<< "Converts browser bookmarks between a selection of formats."
				<< std::endl << std::endl
				<< "Usage: bookmarkconverter -f [format] [inputpath]"
				<< " [outputpath]" << std::endl
				<< "       bookmarkconverter --webpositive-import -f [format]"
				<< " [outputpath]" << std::endl
				<< "       bookmarkconverter --qupzilla-import -f [format]"
				<< " [outputpath]" << std::endl
				<< "       bookmarkconverter --help" << std::endl
				<< std::endl
				<< "       format            "
				<< "The destination format (HTML, CHROME, WEBPOSITIVE)"
				<< std::endl;
	return code;
}

int main(int argc, char* argv[])
{
	BookmarksOutput* output = NULL;
	BookmarksInput* input = NULL;
	int curarg = 0, curpath = 0;;
	BString paths[2];

	while (curarg + 1 < argc) {
		curarg++;
		BString current(argv[curarg]);
		if (current == "-h" || current == "--help")
			return helpMessage(0, output, input);
		else if (current == "-f" || current == "--format") {
			if (curarg == argc - 1)
				return helpMessage(1, output, input);
			else {
				curarg++;
				BString format(argv[curarg]);
				if (format.ICompare("html") == 0)
					output = new HTMLOutput();
				else if (format.ICompare("chrome") == 0)
					output = new ChromeOutput();
				else if (format.ICompare("webpositive") == 0)
					output = new BeOutput();
				else if (format.ICompare("qupzilla") == 0)
					output = new QupZillaOutput();
				else
					return helpMessage(2, output, input);
			}
		} else if (current == "--webpositive-import") {
			input = new BeInput();
			paths[0] = "";
			curpath = std::max(curpath, 1);
		} else if (current == "--qupzilla-import") {
			input = new QupZillaInput();
			paths[0] = "";
			curpath = std::max(curpath, 1);
		} else if (curpath >= 2)
			return helpMessage(5, output, input);
		else
			paths[curpath++] = argv[curarg];

	}

	if (input == NULL) {
		BDirectory test(paths[0].String());
		input = (test.InitCheck() == B_OK) ?
			new BeInput() : new QupZillaInput();
	}

	if (output == NULL)
		return helpMessage(4, output, input);

	BookmarksEntry* read = input->Input(paths[0].String());
	if (read != NULL)
		output->Output(read, paths[1].String());
	else
		std::cerr << "There was an error reading the input" << std::endl;

	delete input;
	delete output;
	return 0;
}

<commit_msg>Add missing output format in the help message<commit_after>/*
 * main.cpp
 * Copyright (c) 2015 Markus Himmel. All rights reserved.
 * Distributed under the terms of the MIT license.
 */

#include <algorithm>
#include <iostream>

#include <String.h>
#include <Directory.h>

#include "BookmarksTree.h"
#include "BookmarksFormat.h"

int helpMessage(int code, BookmarksOutput* a, BookmarksInput* b)
{
	delete a;
	delete b;
	std::cout	<< "Converts browser bookmarks between a selection of formats."
				<< std::endl << std::endl
				<< "Usage: bookmarkconverter -f [format] [inputpath]"
				<< " [outputpath]" << std::endl
				<< "       bookmarkconverter --webpositive-import -f [format]"
				<< " [outputpath]" << std::endl
				<< "       bookmarkconverter --qupzilla-import -f [format]"
				<< " [outputpath]" << std::endl
				<< "       bookmarkconverter --help" << std::endl
				<< std::endl
				<< "       format            "
				<< "The destination format (HTML, CHROME, WEBPOSITIVE, "
				<< "QUPZILLA)" << std::endl;
	return code;
}

int main(int argc, char* argv[])
{
	BookmarksOutput* output = NULL;
	BookmarksInput* input = NULL;
	int curarg = 0, curpath = 0;;
	BString paths[2];

	while (curarg + 1 < argc) {
		curarg++;
		BString current(argv[curarg]);
		if (current == "-h" || current == "--help")
			return helpMessage(0, output, input);
		else if (current == "-f" || current == "--format") {
			if (curarg == argc - 1)
				return helpMessage(1, output, input);
			else {
				curarg++;
				BString format(argv[curarg]);
				if (format.ICompare("html") == 0)
					output = new HTMLOutput();
				else if (format.ICompare("chrome") == 0)
					output = new ChromeOutput();
				else if (format.ICompare("webpositive") == 0)
					output = new BeOutput();
				else if (format.ICompare("qupzilla") == 0)
					output = new QupZillaOutput();
				else
					return helpMessage(2, output, input);
			}
		} else if (current == "--webpositive-import") {
			input = new BeInput();
			paths[0] = "";
			curpath = std::max(curpath, 1);
		} else if (current == "--qupzilla-import") {
			input = new QupZillaInput();
			paths[0] = "";
			curpath = std::max(curpath, 1);
		} else if (curpath >= 2)
			return helpMessage(5, output, input);
		else
			paths[curpath++] = argv[curarg];

	}

	if (input == NULL) {
		BDirectory test(paths[0].String());
		input = (test.InitCheck() == B_OK) ?
			new BeInput() : new QupZillaInput();
	}

	if (output == NULL)
		return helpMessage(4, output, input);

	BookmarksEntry* read = input->Input(paths[0].String());
	if (read != NULL)
		output->Output(read, paths[1].String());
	else
		std::cerr << "There was an error reading the input" << std::endl;

	delete input;
	delete output;
	return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <cstddef>
#include <time.h>

#include "StackAllocator.h"

/*
void test_primitives(Allocator &allocator){
	std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl;

	allocator.Allocate(sizeof(int), alignof(int));			// 4  -> 4
	allocator.Allocate(sizeof(bool), alignof(bool));		// 1  -> 5
															// 3  -> 8
	allocator.Allocate(sizeof(int), alignof(int));			// 4  -> 12
															// 4  -> 16
	allocator.Allocate(sizeof(double), alignof(double));	// 8  -> 24
	allocator.Allocate(sizeof(char), alignof(char));		// 1  -> 25
															// 3  -> 28
	allocator.Allocate(sizeof(int), alignof(int));			// 4  -> 32

	allocator.Reset();
	std::cout << std::endl;

}

void test_primitives_unaligned(Allocator &allocator){
	std::cout << "\tTEST_PRIMITIVES_TYPES_UNALIGNED" << std::endl;

	allocator.Allocate(sizeof(int));		// 4  -> 4
	allocator.Allocate(sizeof(bool));		// 1  -> 5
											// 0  -> 5
	allocator.Allocate(sizeof(int));		// 4  -> 9
	allocator.Allocate(sizeof(double));		// 8  -> 17
	allocator.Allocate(sizeof(char));		// 1  -> 18
											// 0  -> 18
	allocator.Allocate(sizeof(int));		// 4  -> 22

	allocator.Reset();
	std::cout << std::endl;
}

void test_structs(Allocator &allocator){
	std::cout << "\tTEST_CUSTOM_TYPES" << std::endl;

	allocator.Allocate(sizeof(bar), alignof(bar));			// 16  -> 16
	allocator.Allocate(sizeof(foo), alignof(foo));			// 16  -> 32
	allocator.Allocate(sizeof(baz), alignof(baz));			// 4   -> 36
	allocator.Allocate(sizeof(bool), alignof(bool));		// 1   -> 37
															// 3   -> 40
	allocator.Allocate(sizeof(foo3), alignof(foo3));		// 8   -> 48
	allocator.Reset();
	std::cout << std::endl;
}

void test_structs_unaligned(Allocator &allocator){
	std::cout << "\tTEST_CUSTOM_TYPES_UNALIGNED" << std::endl;

	allocator.Allocate(sizeof(bar), 0);			// 16  -> 16
	allocator.Allocate(sizeof(foo), 0);			// 16  -> 32
	allocator.Allocate(sizeof(baz), 0);			// 4   -> 36
	allocator.Allocate(sizeof(bool), 0);		// 1   -> 37
												// 0   -> 37
	allocator.Allocate(sizeof(foo3), 0);		// 8   -> 45
	allocator.Reset();
	std::cout << std::endl;
}

void test_linear_allocator(){
	std::cout << "TEST_LINEAR_ALLOCATOR" << std::endl;

	LinearAllocator linearAllocator(100);
	test_primitives(linearAllocator);
	test_structs(linearAllocator);

	test_primitives_unaligned(linearAllocator);
	test_structs_unaligned(linearAllocator);
}

void test_stack_allocator_primitives(StackAllocator &stackAllocator){
	std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl;

	stackAllocator.Allocate(sizeof(bool), alignof(bool));		// 1  -> 1
																// 3  -> 4
	stackAllocator.Allocate(sizeof(baz), alignof(baz));			// 4  -> 8
	stackAllocator.Allocate(sizeof(int), alignof(int));			// 4  -> 12

	std::cout << std::endl;
	stackAllocator.Free(nullptr, sizeof(int));					// 4  -> 8
	stackAllocator.Free(nullptr, sizeof(baz));					// 8  -> 4(3) -> 1
																// 7  -> 8
	stackAllocator.Allocate(sizeof(double), alignof(double));	// 8  -> 16

	stackAllocator.Reset();
}

void test_stack_allocator(){
	std::cout << "TEST_STACK_ALLOCATOR" << std::endl;

	StackAllocator stackAllocator(100);
	//test_primitives(stackAllocator);
	//test_structs(stackAllocator);

	//test_primitives_unaligned(stackAllocator);
	//test_structs_unaligned(stackAllocator);
	test_stack_allocator_primitives(stackAllocator);
}
*/

struct foo {
    char *p;     /* 8 bytes */
    char c;      /* 1 byte */
};

struct bar {
	int a;		// 4
	bool b;		// 1 -> 5
				// 3 -> 8
	int c;		// 4 -> 12
	bool d;		// 1 -> 13
	bool e;		// 1 -> 14
				// 2 -> 16
};

struct bar2 {
	int a;	// 4
	int c;	// 4 -> 8
	bool b;	// 1 -> 9
	bool d;
	bool e;
			// 3 -> 12
};

struct foo3 {
	int i;      /* 4 byte */
    char c;     /* 1 bytes */
    bool b;		/* 1 bytes */
    			// 2 bytes
};

struct foo2 {
	char c;      /* 1 byte */
    char *p;     /* 8 bytes */
};

struct baz {
    short s;     /* 2 bytes */
    char c;      /* 1 byte */
};

void setTimer(timespec& timer){
  clock_gettime(CLOCK_REALTIME, &timer);
}

timespec diff(timespec &start, timespec &end) {
    timespec temp;
    if ((end.tv_nsec-start.tv_nsec)<0) {
        temp.tv_sec = end.tv_sec-start.tv_sec-1;
        temp.tv_nsec = 1e9+end.tv_nsec-start.tv_nsec;
    } else {
        temp.tv_sec = end.tv_sec-start.tv_sec;
        temp.tv_nsec = end.tv_nsec-start.tv_nsec;
    }
    return temp;
}

void print_benchmark_stats(const timespec& elapsed_time, const int& memory_used, const int&memory_wasted, const int max_operations){
	double time_sec = (double) elapsed_time.tv_sec;
  	double time_nsec = (double) elapsed_time.tv_nsec;
  	double time_msec = (time_sec * 1000) + (time_nsec / 1000000);

	std::cout << std::endl;
	std::cout << "\tSTATS:" << std::endl;
	std::cout << "\t\tOperations:    \t" << max_operations  << std::endl;
	std::cout << "\t\tTime elapsed:  \t" << time_msec << " ms" << std::endl;
	std::cout << "\t\tOp per sec:    \t" << (max_operations / 1e3) / time_msec << " mops/ms" << std::endl;
	std::cout << "\t\tTimer per op:  \t" << time_msec/(max_operations / 1e3) << " ms/mops" << std::endl;

	//std::cout << "\t\tMemory used:   \t" << memory_used  << " bytes" << std::endl;
	//std::cout << "\t\tMemory wasted: \t" << memory_wasted  << " bytes\t" << ((float) memory_wasted / memory_used) * 100 << " %" << std::endl;
	std::cout << std::endl;
}

void benchmark_stack(long MAX_OPERATIONS = 1e4){
	timespec start, end;

	std::cout << "BENCHMARK STACK ALLOCATOR: START" << std::endl;

	setTimer(start);

	StackAllocator stackAllocator(1e10);

	int operations = 0;
	while(operations < MAX_OPERATIONS){
		stackAllocator.Allocate(sizeof(int), alignof(int));			// 4  -> 4
		stackAllocator.Allocate(sizeof(bool), alignof(bool));		// 1  -> 5
																	// 3  -> 8
		stackAllocator.Allocate(sizeof(foo), alignof(foo));			// 16 -> 24
		++operations;
	}
	setTimer(end);
	const timespec elapsed_time = diff(start, end);
	const std::size_t memory_used = 0;
	const std::size_t  memory_wasted = 0;
	stackAllocator.Reset();
	print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
	std::cout << "BENCHMARK STACK ALLOCATOR: END" << std::endl;
}

void benchmark_malloc(long MAX_OPERATIONS = 1e4){
	timespec start, end;

	std::cout << "BENCHMARK MALLOC ALLOCATOR: START" << std::endl;

	setTimer(start);

	int operations = 0;
	srand (1);
	while(operations < MAX_OPERATIONS){
		malloc(sizeof(int));
		malloc(sizeof(bool));
		malloc(sizeof(foo));
		++operations;
	}

	setTimer(end);
	const timespec elapsed_time = diff(start, end);
	const std::size_t memory_used = 0;
	const std::size_t  memory_wasted = 0;

	print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
	std::cout << "BENCHMARK MALLOC ALLOCATOR: END" << std::endl;
}
/* TODO
	1-  Deinterface
	2- benchmark free (3pointers)
	3- move to utils file?
*/
int main(){
	//benchmark_stack(1e7);
	benchmark_malloc(1e7);
	return 1;
}

<commit_msg>Added benchmark to measure time performance executing free operations.<commit_after>#include <iostream>
#include <cstddef>
#include <time.h>

#include "StackAllocator.h"

/*
void test_primitives(Allocator &allocator){
	std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl;

	allocator.Allocate(sizeof(int), alignof(int));			// 4  -> 4
	allocator.Allocate(sizeof(bool), alignof(bool));		// 1  -> 5
															// 3  -> 8
	allocator.Allocate(sizeof(int), alignof(int));			// 4  -> 12
															// 4  -> 16
	allocator.Allocate(sizeof(double), alignof(double));	// 8  -> 24
	allocator.Allocate(sizeof(char), alignof(char));		// 1  -> 25
															// 3  -> 28
	allocator.Allocate(sizeof(int), alignof(int));			// 4  -> 32

	allocator.Reset();
	std::cout << std::endl;

}

void test_primitives_unaligned(Allocator &allocator){
	std::cout << "\tTEST_PRIMITIVES_TYPES_UNALIGNED" << std::endl;

	allocator.Allocate(sizeof(int));		// 4  -> 4
	allocator.Allocate(sizeof(bool));		// 1  -> 5
											// 0  -> 5
	allocator.Allocate(sizeof(int));		// 4  -> 9
	allocator.Allocate(sizeof(double));		// 8  -> 17
	allocator.Allocate(sizeof(char));		// 1  -> 18
											// 0  -> 18
	allocator.Allocate(sizeof(int));		// 4  -> 22

	allocator.Reset();
	std::cout << std::endl;
}

void test_structs(Allocator &allocator){
	std::cout << "\tTEST_CUSTOM_TYPES" << std::endl;

	allocator.Allocate(sizeof(bar), alignof(bar));			// 16  -> 16
	allocator.Allocate(sizeof(foo), alignof(foo));			// 16  -> 32
	allocator.Allocate(sizeof(baz), alignof(baz));			// 4   -> 36
	allocator.Allocate(sizeof(bool), alignof(bool));		// 1   -> 37
															// 3   -> 40
	allocator.Allocate(sizeof(foo3), alignof(foo3));		// 8   -> 48
	allocator.Reset();
	std::cout << std::endl;
}

void test_structs_unaligned(Allocator &allocator){
	std::cout << "\tTEST_CUSTOM_TYPES_UNALIGNED" << std::endl;

	allocator.Allocate(sizeof(bar), 0);			// 16  -> 16
	allocator.Allocate(sizeof(foo), 0);			// 16  -> 32
	allocator.Allocate(sizeof(baz), 0);			// 4   -> 36
	allocator.Allocate(sizeof(bool), 0);		// 1   -> 37
												// 0   -> 37
	allocator.Allocate(sizeof(foo3), 0);		// 8   -> 45
	allocator.Reset();
	std::cout << std::endl;
}

void test_linear_allocator(){
	std::cout << "TEST_LINEAR_ALLOCATOR" << std::endl;

	LinearAllocator linearAllocator(100);
	test_primitives(linearAllocator);
	test_structs(linearAllocator);

	test_primitives_unaligned(linearAllocator);
	test_structs_unaligned(linearAllocator);
}

void test_stack_allocator_primitives(StackAllocator &stackAllocator){
	std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl;

	stackAllocator.Allocate(sizeof(bool), alignof(bool));		// 1  -> 1
																// 3  -> 4
	stackAllocator.Allocate(sizeof(baz), alignof(baz));			// 4  -> 8
	stackAllocator.Allocate(sizeof(int), alignof(int));			// 4  -> 12

	std::cout << std::endl;
	stackAllocator.Free(nullptr, sizeof(int));					// 4  -> 8
	stackAllocator.Free(nullptr, sizeof(baz));					// 8  -> 4(3) -> 1
																// 7  -> 8
	stackAllocator.Allocate(sizeof(double), alignof(double));	// 8  -> 16

	stackAllocator.Reset();
}

void test_stack_allocator(){
	std::cout << "TEST_STACK_ALLOCATOR" << std::endl;

	StackAllocator stackAllocator(100);
	//test_primitives(stackAllocator);
	//test_structs(stackAllocator);

	//test_primitives_unaligned(stackAllocator);
	//test_structs_unaligned(stackAllocator);
	test_stack_allocator_primitives(stackAllocator);
}
*/

struct foo {
    char *p;     /* 8 bytes */
    char c;      /* 1 byte */
};

struct bar {
	int a;		// 4
	bool b;		// 1 -> 5
				// 3 -> 8
	int c;		// 4 -> 12
	bool d;		// 1 -> 13
	bool e;		// 1 -> 14
				// 2 -> 16
};

struct bar2 {
	int a;	// 4
	int c;	// 4 -> 8
	bool b;	// 1 -> 9
	bool d;
	bool e;
			// 3 -> 12
};

struct foo3 {
	int i;      /* 4 byte */
    char c;     /* 1 bytes */
    bool b;		/* 1 bytes */
    			// 2 bytes
};

struct foo2 {
	char c;      /* 1 byte */
    char *p;     /* 8 bytes */
};

struct baz {
    short s;     /* 2 bytes */
    char c;      /* 1 byte */
};

void setTimer(timespec& timer){
  clock_gettime(CLOCK_REALTIME, &timer);
}

timespec diff(timespec &start, timespec &end) {
    timespec temp;
    if ((end.tv_nsec-start.tv_nsec)<0) {
        temp.tv_sec = end.tv_sec-start.tv_sec-1;
        temp.tv_nsec = 1e9+end.tv_nsec-start.tv_nsec;
    } else {
        temp.tv_sec = end.tv_sec-start.tv_sec;
        temp.tv_nsec = end.tv_nsec-start.tv_nsec;
    }
    return temp;
}

void print_benchmark_stats(const timespec& elapsed_time, const int& memory_used, const int&memory_wasted, const int max_operations){
	double time_sec = (double) elapsed_time.tv_sec;
  	double time_nsec = (double) elapsed_time.tv_nsec;
  	double time_msec = (time_sec * 1000) + (time_nsec / 1000000);

	std::cout << std::endl;
	std::cout << "\tSTATS:" << std::endl;
	std::cout << "\t\tOperations:    \t" << max_operations  << std::endl;
	std::cout << "\t\tTime elapsed:  \t" << time_msec << " ms" << std::endl;
	std::cout << "\t\tOp per sec:    \t" << (max_operations / 1e3) / time_msec << " mops/ms" << std::endl;
	std::cout << "\t\tTimer per op:  \t" << time_msec/(max_operations / 1e3) << " ms/mops" << std::endl;

	//std::cout << "\t\tMemory used:   \t" << memory_used  << " bytes" << std::endl;
	//std::cout << "\t\tMemory wasted: \t" << memory_wasted  << " bytes\t" << ((float) memory_wasted / memory_used) * 100 << " %" << std::endl;
	std::cout << std::endl;
}

void benchmark_stack_allocate(long MAX_OPERATIONS = 1e4){
	timespec start, end;

	std::cout << "BENCHMARK STACK A: START" << std::endl;

	setTimer(start);

	StackAllocator stackAllocator(1e10);

	int operations = 0;
	while(operations < MAX_OPERATIONS){
		stackAllocator.Allocate(sizeof(int), alignof(int));			// 4  -> 4
		stackAllocator.Allocate(sizeof(bool), alignof(bool));		// 1  -> 5
																	// 3  -> 8
		stackAllocator.Allocate(sizeof(foo), alignof(foo));			// 16 -> 24
		++operations;
	}
	setTimer(end);
	const timespec elapsed_time = diff(start, end);
	const std::size_t memory_used = 0;
	const std::size_t  memory_wasted = 0;
	stackAllocator.Reset();
	print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
	std::cout << "BENCHMARK STACK A: END" << std::endl;
}

void benchmark_stack_allocate_free(long MAX_OPERATIONS = 1e4){
	timespec start, end;

	std::cout << "BENCHMARK STACK A/F: START" << std::endl;

	setTimer(start);

	StackAllocator stackAllocator(1e10);

	int operations = 0;
	bool allocate = true;
	while(operations < MAX_OPERATIONS){
		if (allocate) {
			stackAllocator.Allocate(sizeof(int), alignof(int));			// 4  -> 4
			stackAllocator.Allocate(sizeof(bool), alignof(bool));		// 1  -> 5
																		// 3  -> 8
			stackAllocator.Allocate(sizeof(foo), alignof(foo));			// 16 -> 24
			allocate = false;
		}else {
			stackAllocator.Free(nullptr, sizeof(foo));
			stackAllocator.Free(nullptr, sizeof(bool));
			stackAllocator.Free(nullptr, sizeof(int));
			allocate = true;
		}
		++operations;
	}
	setTimer(end);
	const timespec elapsed_time = diff(start, end);
	const std::size_t memory_used = 0;
	const std::size_t  memory_wasted = 0;
	stackAllocator.Reset();
	print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
	std::cout << "BENCHMARK STACK A/F: END" << std::endl;
}

void benchmark_malloc_allocate(long MAX_OPERATIONS = 1e4){
	timespec start, end;

	std::cout << "BENCHMARK MALLOC A: START" << std::endl;

	setTimer(start);

	int operations = 0;
	srand (1);
	while(operations < MAX_OPERATIONS){
		malloc(sizeof(int));
		malloc(sizeof(bool));
		malloc(sizeof(foo));
		++operations;
	}

	setTimer(end);
	const timespec elapsed_time = diff(start, end);
	const std::size_t memory_used = 0;
	const std::size_t  memory_wasted = 0;

	print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
	std::cout << "BENCHMARK MALLOC A: END" << std::endl;
}

void benchmark_malloc_allocate_free(long MAX_OPERATIONS = 1e4){
	timespec start, end;

	std::cout << "BENCHMARK MALLOC A/F: START" << std::endl;

	setTimer(start);

	int operations = 0;
	bool allocate = true;
	int * i;
	bool * b;
	foo * f;
	while(operations < MAX_OPERATIONS){
		if (allocate){
			i = (int*) malloc(sizeof(int));
			b = (bool*) malloc(sizeof(bool));
			f = (foo*) malloc(sizeof(foo));
			allocate = false;
		}else {
			free(f);
			free(b);
			free(i);
			allocate = true;
		}

		++operations;
	}

	setTimer(end);
	const timespec elapsed_time = diff(start, end);
	const std::size_t memory_used = 0;
	const std::size_t  memory_wasted = 0;

	print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
	std::cout << "BENCHMARK MALLOC A/F: END" << std::endl;
}

/* TODO
	1-  Deinterface
	2- Stack/Linear ->Calculate padding (Aligned allocators interface?)
	2- benchmark free (3pointers)
	3- read values (check speed)
	4- move to utils file?
*/
int main(){
	benchmark_stack_allocate_free(1e8);
	benchmark_malloc_allocate_free(1e8);
	return 1;
}

<|endoftext|>


<commit_before>/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   main.cpp                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: kchetty <marvin@42.fr>                     +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2016/11/28 08:34:50 by kchetty           #+#    #+#             */
/*   Updated: 2016/12/09 10:01:59 by kchetty          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "gomoku.h"

void draw_screen(int dim, t_global *g)
{

	int x,y;
	int win_y, win_x;
	int tmp = 9;

	getmaxyx(stdscr, win_y, win_x);
	mvwprintw(g->the_board, 2, 2,  "teh x: %d AND WIN_Y: %d\n ", win_x  ,win_y);
	for(y = 0; y < dim; y++)
	{
		for(x = 0; x < dim; x++)
		{
			if (x == 0)
				mvwprintw(g->the_board, tmp, ((win_x / 2) - (77 / 2)), " ---");
			else
				wprintw(g->the_board, " ---");
		}
		wprintw(g->the_board, "\n");
		tmp++;
		for(x = 0; x < dim; x++)
		{
			if (x == 0)
				mvwprintw(g->the_board, tmp, ((win_x / 2) - (77 / 2)), "|   ");
			else
				wprintw(g->the_board, "|   ");
		}
		tmp++;
		if(x == dim)
			wprintw(g->the_board, "|\n");
		else
			wprintw(g->the_board, "\n");
	}
	for(x = 0; x < dim; x++)
	{
		if (x == 0)
			mvwprintw(g->the_board, tmp , ((win_x / 2) - (77 / 2)), " ---");
		else
			wprintw(g->the_board, " ---");
	}
	wprintw(g->the_board, "\n");
	wrefresh(g->the_board);
}

void	redraw_stuff(t_global *g)
{
	int y = 0, x = 0;
	int win_y, win_x;
	getmaxyx(g->the_board, win_y, win_x);
	start_color();
	win_y -= win_y;
	wmove(g->the_board, y*2+10, x*4 + ((win_x / 2) - (77 / 2)) + 2);
	for (y = 0; y < 19; y++)
	{
		for (x = 0; x < 19; x++)
		{
			if (g->board->get(x, y) == 0)
			{
				init_color(COLOR_RED, 700,0, 700);
				init_pair(1, COLOR_RED, COLOR_BLACK);
				wattron(g->the_board, COLOR_PAIR(1));
				mvwprintw(g->the_board, y*2+10,x*4+ ((win_x / 2) - (77 / 2)) + 2, "X");
				wattroff(g->the_board, COLOR_PAIR(1));
			}
			else if (g->board->get(x, y) == 1)
			{
				init_color(COLOR_CYAN, 700, 100, 0);
				init_pair(6, COLOR_CYAN, COLOR_BLACK);
				wattron(g->the_board, COLOR_PAIR(6));
				mvwprintw(g->the_board, y*2+10, x*4+ ((win_x / 2) - (77 / 2)) + 2, "O");
				wattroff(g->the_board ,COLOR_PAIR(6));
			}
		}
	}
	wrefresh(g->the_board);
}

int  keyhook(int dim, int player, t_global *g)
{
	int win_y, win_x;
	getmaxyx(g->the_board, win_y, win_x);
	win_y -= win_y;
	mvwprintw(g->the_board, dim * 2 + 17, ((win_x - 24) / 2), "Make you move: Player %c ",player==0 ? 'X' : 'O');
	wmove(g->the_board, g->y*2+10, g->x*4 + ((win_x / 2) - (77 / 2)) + 2);
	wrefresh(g->the_board);
	noecho();
	switch(wgetch(g->the_board))
	{
		case KEY_UP:
			if(g->y > 0)
				g->y--;
			return(-2);
		case KEY_LEFT:
			if(g->x > 0)
				g->x--;
			return(-2);
		case KEY_RIGHT:
			if(g->x < dim-1)
				g->x++;
			return(-2);
		case KEY_DOWN:
			if(g->y < dim-1)
				g->y++;
			return(-2);
		case '\n':
			echo();
			wrefresh(g->the_board);
			start_color();
			if (player == 0)
			{
				if (g->board->set_x(g->x, g->y))
				{
					//init_color(COLOR_RED, 700,0, 100);
					init_pair(1, COLOR_RED, COLOR_BLACK);
					wattron(g->the_board, COLOR_PAIR(1));
					mvwprintw(g->the_board, g->y*2+10,g->x*4+ ((win_x / 2) - (77 / 2)) + 2, "X");
					wattroff(g->the_board, COLOR_PAIR(1));
					return (1);
				}
				else
					return (-3);
			}
			else
			{
				if (g->board->set_o(g->x, g->y))
				{
					//init_color(COLOR_CYAN, 700, 100, 0);
					init_pair(6, COLOR_CYAN, COLOR_BLACK);
					wattron(g->the_board, COLOR_PAIR(6));
					mvwprintw(g->the_board, g->y*2+10,g->x*4+ ((win_x / 2) - (77 / 2)) + 2, "O");
					wattroff(g->the_board ,COLOR_PAIR(6));
					return (1);
				}
				else
					return (-3);
			}
			break;
		case 'q':
			return(-1);
		default:
			return(-2);
			break;
	}
	wmove(g->the_board, g->y*2+10,g->x*4+((win_x - 80) / 2) + 2);
	wrefresh(g->the_board);
	return(0);
}

void draw_borders(WINDOW *screen)
{
	int x, y, i;
	getmaxyx(screen, y, x);

	// 4 corners
	mvwprintw(screen, 0, 0, "+");
	mvwprintw(screen, y - 1, 0, "+");
	mvwprintw(screen, 0, x - 1, "+");
	mvwprintw(screen, y - 1, x - 1, "+");

	// sides
	for (i = 1; i < (y - 1); i++)
	{
		mvwprintw(screen, i, 0, "|");
		mvwprintw(screen, i, x - 1, "|");
	}

	// top and bottom
	for (i = 1; i < (x - 1); i++)
	{
		mvwprintw(screen, 0, i, "-");
		mvwprintw(screen, y - 1, i, "-");
	}

	wrefresh(screen);
}

void	create_menu()
{
	int max_x, max_y;

	getmaxyx(stdscr, max_y, max_x);
	WINDOW *menu = newwin(max_y, max_x, 0, 0);

	start_color();
	draw_borders(menu);
	mvwprintw(menu, 2, ((max_x - 80) / 2) + 2,  "    GGGGGGGGGGGGG                                                          kkkkkkkk\n"
			" GGG::::::::::::G                                                          k::::::k\n"
		   "GG:::::::::::::::G                                                          k::::::k\n"
		  "G:::::GGGGGGGG::::G                                                          k::::::k\n"
	     "G:::::G      GGGGGG   ooooooooooo      mmmmmmm    mmmmmmm      ooooooooooo   k:::::k    kkkkkkkuuuuuu    uuuuuu\n"
		 "G:::::G               oo:::::::::::oo  mm:::::::m  m:::::::mm  oo:::::::::::oo  k:::::k   k:::::k u::::u    u::::u\n"
	     "G:::::G              o:::::::::::::::om::::::::::mm::::::::::mo:::::::::::::::o k:::::k  k:::::k  u::::u    u::::u\n"
		 "G:::::G    GGGGGGGGGGo:::::ooooo:::::om::::::::::::::::::::::mo:::::ooooo:::::o k:::::k k:::::k   u::::u    u::::u\n"
	   	 "G:::::G    G::::::::Go::::o     o::::om:::::mmm::::::mmm:::::mo::::o     o::::o k::::::k:::::k    u::::u    u::::u\n"
		 "G:::::G    GGGGG::::Go::::o     o::::om::::m   m::::m   m::::mo::::o     o::::o k:::::::::::k     u::::u    u::::u\n"
		 "G:::::G        G::::Go::::o     o::::om::::m   m::::m   m::::mo::::o     o::::o k:::::::::::k     u::::u    u::::u\n"
		 " G:::::G       G::::Go::::o     o::::om::::m   m::::m   m::::mo::::o     o::::o k::::::k:::::k    u:::::uuuu:::::u\n"
		   "G:::::GGGGGGGG::::Go:::::ooooo:::::om::::m   m::::m   m::::mo:::::ooooo:::::ok::::::k k:::::k   u:::::::::::::::uu\n"
			"GG:::::::::::::::Go:::::::::::::::om::::m   m::::m   m::::mo:::::::::::::::ok::::::k  k:::::k   u:::::::::::::::u\n"
			 "GGG::::::GGG:::G oo:::::::::::oo m::::m   m::::m   m::::m oo:::::::::::oo k::::::k   k:::::k   uu::::::::uu:::u\n"
			   "GGGGGG   GGGG   ooooooooooo   mmmmmm   mmmmmm   mmmmmm   ooooooooooo   kkkkkkkk    kkkkkkk    uuuuuuuu  uuuu\n");
	while (1)
		wrefresh(menu);
}

void	init(t_global *g)
{
	g->x = 0;
	g->y = 0;
	g->board = new board_class();

	initscr();
	noecho();
	cbreak();
}

int main()
{
	t_global g;

	int dim,rtn,player = 0;
	int parent_x = 0, parent_y = 0, new_x, new_y;

	init(&g);

	//create_menu();
	//get our maximun window dimensions
	getmaxyx(stdscr, parent_y, parent_x);

	g.header = newwin(((parent_y / 4)), parent_x, 0, 0);
	g.the_board = newwin(parent_y - (parent_y / 4) + 1, parent_x, (parent_y / 4) - 1, 0);

	wclear(g.the_board);
	draw_borders(g.header);
	draw_borders(g.the_board);

	keypad(g.the_board,TRUE);
	dim = 19;

	draw_screen(dim, &g);
	while (1)
	{
		getmaxyx(stdscr, new_y, new_x);
		if (new_y != parent_y || new_x != parent_x)
		{
			parent_x = new_x;
			parent_y = new_y;
			wresize(g.header, ((new_y / 4)), new_x);
			mvwin(g.header, 0, 0);
			wresize(g.the_board, new_y - (new_y / 4) + 1, new_x);
			mvwin(g.the_board, (new_y / 4) - 1, 0);
			wclear(stdscr);
			wclear(g.the_board);
			wclear(g.header);
			//draw_borders(g.the_board);
			draw_borders(g.header);
			draw_screen(dim, &g);
			redraw_stuff(&g);
		}
		if((rtn=keyhook(dim,player, &g))==-1)
			break;
		if(rtn == 1) {
			if (g.board->check_win(player))
				break ;
			player=!player;
		}
		if (rtn == -3)
		{
			move(dim * 2 + 4, 0);
			printw("Invalid Move");
		}
	}
	delwin(g.the_board);
	delwin(g.header);
	endwin();

	printf("HAHAHAHAHA SOMEONE WON");
	return (0);
}
<commit_msg>resizing works<commit_after>/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   main.cpp                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: kchetty <marvin@42.fr>                     +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2016/11/28 08:34:50 by kchetty           #+#    #+#             */
/*   Updated: 2016/12/09 10:37:08 by kchetty          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "gomoku.h"

void draw_screen(int dim, t_global *g)
{

	int x,y;
	int win_y, win_x;
	int tmp;

	getmaxyx(g->the_board, win_y, win_x);
	tmp = ((win_y / 2) - (38 / 2));
	mvwprintw(g->the_board, 2, 2,  "teh x: %d AND WIN_Y: %d\n ", win_x  ,win_y);
	for(y = 0; y < dim; y++)
	{
		for(x = 0; x < dim; x++)
		{
			if (x == 0)
				mvwprintw(g->the_board, tmp, ((win_x / 2) - (77 / 2)), " ---");
			else
				wprintw(g->the_board, " ---");
		}
		wprintw(g->the_board, "\n");
		tmp++;
		for(x = 0; x < dim; x++)
		{
			if (x == 0)
				mvwprintw(g->the_board, tmp, ((win_x / 2) - (77 / 2)), "|   ");
			else
				wprintw(g->the_board, "|   ");
		}
		tmp++;
		if(x == dim)
			wprintw(g->the_board, "|\n");
		else
			wprintw(g->the_board, "\n");
	}
	for(x = 0; x < dim; x++)
	{
		if (x == 0)
			mvwprintw(g->the_board, tmp , ((win_x / 2) - (77 / 2)), " ---");
		else
			wprintw(g->the_board, " ---");
	}
	wprintw(g->the_board, "\n");
	wrefresh(g->the_board);
}

void	redraw_stuff(t_global *g)
{
	int y = 0, x = 0;
	int win_y, win_x;
	getmaxyx(g->the_board, win_y, win_x);
	start_color();
	win_y -= win_y;
	wmove(g->the_board, y*2+((win_y / 2) - (38 / 2)) + 1, x*4 + ((win_x / 2) - (77 / 2)) + 2);
	for (y = 0; y < 19; y++)
	{
		for (x = 0; x < 19; x++)
		{
			if (g->board->get(x, y) == 0)
			{
				init_color(COLOR_RED, 700,0, 700);
				init_pair(1, COLOR_RED, COLOR_BLACK);
				wattron(g->the_board, COLOR_PAIR(1));
				mvwprintw(g->the_board, y * 2 + ((win_y / 2) - (38 / 2)) + 1, x * 4 + ((win_x / 2) - (77 / 2)) + 2, "X");
				wattroff(g->the_board, COLOR_PAIR(1));
			}
			else if (g->board->get(x, y) == 1)
			{
				init_color(COLOR_CYAN, 700, 100, 0);
				init_pair(6, COLOR_CYAN, COLOR_BLACK);
				wattron(g->the_board, COLOR_PAIR(6));
				mvwprintw(g->the_board, y*2+ ((win_y / 2) - (38 / 2)) + 1, x*4+ ((win_x / 2) - (77 / 2)) + 2, "O");
				wattroff(g->the_board ,COLOR_PAIR(6));
			}
		}
	}
	wrefresh(g->the_board);
}

int  keyhook(int dim, int player, t_global *g)
{
	int win_y, win_x;
	getmaxyx(g->the_board, win_y, win_x);
	//win_y -= win_y;
	mvwprintw(g->the_board, win_y, ((win_x / 2) - (23 / 2)), "Make you move: Player %c ",player==0 ? 'X' : 'O');
	wmove(g->the_board, g->y*2+((win_y / 2) - (38 / 2)) + 1, g->x*4 + ((win_x / 2) - (77 / 2)) + 2);
	wrefresh(g->the_board);
	noecho();
	switch(wgetch(g->the_board))
	{
		case KEY_UP:
			if(g->y > 0)
				g->y--;
			return(-2);
		case KEY_LEFT:
			if(g->x > 0)
				g->x--;
			return(-2);
		case KEY_RIGHT:
			if(g->x < dim-1)
				g->x++;
			return(-2);
		case KEY_DOWN:
			if(g->y < dim-1)
				g->y++;
			return(-2);
		case '\n':
			echo();
			wrefresh(g->the_board);
			start_color();
			if (player == 0)
			{
				if (g->board->set_x(g->x, g->y))
				{
					//init_color(COLOR_RED, 700,0, 100);
					init_pair(1, COLOR_RED, COLOR_BLACK);
					wattron(g->the_board, COLOR_PAIR(1));
					mvwprintw(g->the_board, g->y*2+((win_y / 2) - (38 / 2)) + 1,g->x*4+ ((win_x / 2) - (77 / 2)) + 2, "X");
					wattroff(g->the_board, COLOR_PAIR(1));
					return (1);
				}
				else
					return (-3);
			}
			else
			{
				if (g->board->set_o(g->x, g->y))
				{
					//init_color(COLOR_CYAN, 700, 100, 0);
					init_pair(6, COLOR_CYAN, COLOR_BLACK);
					wattron(g->the_board, COLOR_PAIR(6));
					mvwprintw(g->the_board, g->y*2+((win_y / 2) - (38 / 2)) + 1,g->x*4+ ((win_x / 2) - (77 / 2)) + 2, "O");
					wattroff(g->the_board ,COLOR_PAIR(6));
					return (1);
				}
				else
					return (-3);
			}
			break;
		case 'q':
			return(-1);
		default:
			return(-2);
			break;
	}
	wmove(g->the_board, g->y*2+((win_y / 2) - (38 / 2)) + 1, g->x*4+((win_x - 80) / 2) + 2);
	wrefresh(g->the_board);
	return(0);
}

void draw_borders(WINDOW *screen)
{
	int x, y, i;
	getmaxyx(screen, y, x);

	// 4 corners
	mvwprintw(screen, 0, 0, "+");
	mvwprintw(screen, y - 1, 0, "+");
	mvwprintw(screen, 0, x - 1, "+");
	mvwprintw(screen, y - 1, x - 1, "+");

	// sides
	for (i = 1; i < (y - 1); i++)
	{
		mvwprintw(screen, i, 0, "|");
		mvwprintw(screen, i, x - 1, "|");
	}

	// top and bottom
	for (i = 1; i < (x - 1); i++)
	{
		mvwprintw(screen, 0, i, "-");
		mvwprintw(screen, y - 1, i, "-");
	}

	wrefresh(screen);
}

void	create_menu()
{
	int max_x, max_y;

	getmaxyx(stdscr, max_y, max_x);
	WINDOW *menu = newwin(max_y, max_x, 0, 0);

	start_color();
	draw_borders(menu);
	mvwprintw(menu, 2, ((max_x - 80) / 2) + 2,  "    GGGGGGGGGGGGG                                                          kkkkkkkk\n"
			" GGG::::::::::::G                                                          k::::::k\n"
		   "GG:::::::::::::::G                                                          k::::::k\n"
		  "G:::::GGGGGGGG::::G                                                          k::::::k\n"
	     "G:::::G      GGGGGG   ooooooooooo      mmmmmmm    mmmmmmm      ooooooooooo   k:::::k    kkkkkkkuuuuuu    uuuuuu\n"
		 "G:::::G               oo:::::::::::oo  mm:::::::m  m:::::::mm  oo:::::::::::oo  k:::::k   k:::::k u::::u    u::::u\n"
	     "G:::::G              o:::::::::::::::om::::::::::mm::::::::::mo:::::::::::::::o k:::::k  k:::::k  u::::u    u::::u\n"
		 "G:::::G    GGGGGGGGGGo:::::ooooo:::::om::::::::::::::::::::::mo:::::ooooo:::::o k:::::k k:::::k   u::::u    u::::u\n"
	   	 "G:::::G    G::::::::Go::::o     o::::om:::::mmm::::::mmm:::::mo::::o     o::::o k::::::k:::::k    u::::u    u::::u\n"
		 "G:::::G    GGGGG::::Go::::o     o::::om::::m   m::::m   m::::mo::::o     o::::o k:::::::::::k     u::::u    u::::u\n"
		 "G:::::G        G::::Go::::o     o::::om::::m   m::::m   m::::mo::::o     o::::o k:::::::::::k     u::::u    u::::u\n"
		 " G:::::G       G::::Go::::o     o::::om::::m   m::::m   m::::mo::::o     o::::o k::::::k:::::k    u:::::uuuu:::::u\n"
		   "G:::::GGGGGGGG::::Go:::::ooooo:::::om::::m   m::::m   m::::mo:::::ooooo:::::ok::::::k k:::::k   u:::::::::::::::uu\n"
			"GG:::::::::::::::Go:::::::::::::::om::::m   m::::m   m::::mo:::::::::::::::ok::::::k  k:::::k   u:::::::::::::::u\n"
			 "GGG::::::GGG:::G oo:::::::::::oo m::::m   m::::m   m::::m oo:::::::::::oo k::::::k   k:::::k   uu::::::::uu:::u\n"
			   "GGGGGG   GGGG   ooooooooooo   mmmmmm   mmmmmm   mmmmmm   ooooooooooo   kkkkkkkk    kkkkkkk    uuuuuuuu  uuuu\n");
	while (1)
		wrefresh(menu);
}

void	init(t_global *g)
{
	g->x = 0;
	g->y = 0;
	g->board = new board_class();

	initscr();
	noecho();
	cbreak();
}

int main()
{
	t_global g;

	int dim,rtn,player = 0;
	int parent_x = 0, parent_y = 0, new_x, new_y;

	init(&g);

	//create_menu();
	//get our maximun window dimensions
	getmaxyx(stdscr, parent_y, parent_x);

	g.header = newwin(((parent_y / 4)), parent_x, 0, 0);
	g.the_board = newwin(parent_y - (parent_y / 4) + 1, parent_x, (parent_y / 4) - 1, 0);

	wclear(g.the_board);
	draw_borders(g.header);
	draw_borders(g.the_board);

	keypad(g.the_board,TRUE);
	dim = 19;

	draw_screen(dim, &g);
	while (1)
	{
		getmaxyx(stdscr, new_y, new_x);
		if (new_y != parent_y || new_x != parent_x)
		{
			parent_x = new_x;
			parent_y = new_y;
			wresize(g.header, ((new_y / 4)), new_x);
			mvwin(g.header, 0, 0);
			wresize(g.the_board, new_y - (new_y / 4) + 1, new_x);
			mvwin(g.the_board, (new_y / 4) - 1, 0);
			wclear(stdscr);
			wclear(g.the_board);
			wclear(g.header);
			draw_borders(g.the_board);
			draw_borders(g.header);
			draw_screen(dim, &g);
			redraw_stuff(&g);
		}
		if((rtn=keyhook(dim,player, &g))==-1)
			break;
		if(rtn == 1) {
			if (g.board->check_win(player))
				break ;
			player=!player;
		}
		if (rtn == -3)
		{
			move(dim * 2 + 4, 0);
			printw("Invalid Move");
		}
	}
	delwin(g.the_board);
	delwin(g.header);
	endwin();

	printf("HAHAHAHAHA SOMEONE WON");
	return (0);
}
<|endoftext|>


<commit_before>/**
 * @file Cosa/Driver/NEXA.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2013, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include "Cosa/Driver/NEXA.hh"
#include "Cosa/RTC.hh"
#include "Cosa/Watchdog.hh"

IOStream& operator<<(IOStream& outs, NEXA::code_t code)
{
  outs << PSTR("house = ") << code.house
       << PSTR(", group = ") << code.group
       << PSTR(", device = ") << code.device
       << PSTR(", on/off = ") << code.onoff;
  return (outs);
}

void
NEXA::Receiver::on_interrupt(uint16_t arg)
{
  // Check start condition
  if (m_start == 0L) {
    if (is_clear()) return;
    m_start = RTC::micros();
    m_ix = 0;
    return;
  }

  // Calculate the pulse width (both low and high) and check against threshold
  uint32_t stop = RTC::micros();
  uint32_t us = (stop - m_start);
  m_start = stop;
  if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) goto exception;
  m_sample[m_ix & IX_MASK] = us;
  m_ix += 1;

  // Decode every four pulses to a bit
  if ((m_ix & IX_MASK) == 0) {
    int8_t bit = decode_bit();
    if (bit < 0) goto exception;
    m_code = (m_code << 1) | bit;
  }
  if (m_ix != IX_MAX) return;

  // And when all samples have been read push an event
  Event::push(Event::RECEIVE_COMPLETED_TYPE, this);

 exception:
  m_start = 0L;
}

int8_t
NEXA::Receiver::decode_bit()
{
  uint8_t bit;
  // The pedantic version checks even the first pulse. This could be removed
  bit = ((m_sample[0] < BIT_THRESHOLD) << 1) | (m_sample[1] < BIT_THRESHOLD);
  if (bit < 2) return (-1);
  // The second pulse has the actual transmitted bit
  bit = ((m_sample[2] < BIT_THRESHOLD) << 1) | (m_sample[3] < BIT_THRESHOLD);
  if (bit < 2) return (-1);
  // And map back to a bit (2 => 0, 3 => 1)
  return (bit > 2);
}

void
NEXA::Receiver::attach(Listener& device)
{
  device.m_next = m_first;
  m_first = &device;
}

void
NEXA::Receiver::detach(Listener& device)
{
  if (m_first != 0) {
    if (m_first == &device) {
      m_first = device.m_next;
    }
    else {
      Listener* d;
      for (d = m_first; (d->m_next != 0) && (d->m_next != &device); d = d->m_next);
      if (d->m_next == 0) return;
      d->m_next = device.m_next;
    }
  }
  device.m_next = 0;
}

void
NEXA::Receiver::dispatch()
{
  code_t cmd = m_code;
  for (Listener* device = m_first; device != 0; device = device->m_next)
    if (cmd == device->m_unit) {
      device->on_change(cmd.onoff);
      if (!cmd.group) return;
    }
}

void
NEXA::Receiver::recv(code_t& cmd)
{
  uint32_t start, stop;
  int32_t bits = 0L;
  uint16_t us;
  uint16_t ix;
  do {
    // Wait for the start condition
    while (is_low());
    stop = RTC::micros();

    // Collect the samples; high followed by low pulse
    ix = 0;
    while (ix < IX_MAX) {
      // Capture length of high period
      start = stop;
      while (is_high());
      stop = RTC::micros();
      us = stop - start;
      if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) break;
      m_sample[ix & IX_MASK] = us;
      ix += 1;
      // Capture length of low period
      start = stop;
      while (is_low());
      stop = RTC::micros();
      us = stop - start;
      if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) break;
      m_sample[ix & IX_MASK] = us;
      ix += 1;
      // Decode every four samples to a code bit
      if ((ix & IX_MASK) == 0) {
	int8_t bit = decode_bit();
	if (bit < 0) break;
	bits = (bits << 1) | bit;
      }
    }
  } while (ix != IX_MAX);
  m_code = bits;
  cmd = bits;
}

void
NEXA::Transmitter::send_code(code_t cmd, int8_t onoff, uint8_t mode)
{
  // Send the code four times with a pause between each
  for (uint8_t i = 0; i < SEND_CODE_MAX; i++) {
    const uint8_t BITS_MAX = 32;
    const uint8_t ONOFF_POS = 27;
    int32_t bits = cmd.as_long;
    // Send start pulse with extended delay, code bits and stop pulse
    send_pulse(0);
    DELAY(START);
    for (uint8_t j = 0; j < BITS_MAX; j++) {
      // Check for dim level (-1..-15)
      if ((j == ONOFF_POS) && (onoff < 0)) {
	send_pulse(0);
	send_pulse(0);
      }
      else send_bit(bits < 0);
      bits <<= 1;
    }
    // Check for dim level transmission; level encoded as -1..-15
    if (onoff < 0) {
      int8_t level = (-onoff) << 4;
      for (uint8_t j = 0; j < 4; j++) {
	send_bit(level < 0);
	level <<= 1;
      }
    }
    send_pulse(0);
    // Wait for the transmission of the code
    uint32_t start = RTC::millis();
    while ((RTC::millis() - start) < PAUSE) Power::sleep(mode);
  }
}
<commit_msg>Fixed missing null assignment after detach().<commit_after>/**
 * @file Cosa/Driver/NEXA.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2013, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include "Cosa/Driver/NEXA.hh"
#include "Cosa/RTC.hh"
#include "Cosa/Watchdog.hh"

IOStream& operator<<(IOStream& outs, NEXA::code_t code)
{
  outs << PSTR("house = ") << code.house
       << PSTR(", group = ") << code.group
       << PSTR(", device = ") << code.device
       << PSTR(", on/off = ") << code.onoff;
  return (outs);
}

void
NEXA::Receiver::on_interrupt(uint16_t arg)
{
  // Check start condition
  if (m_start == 0L) {
    if (is_clear()) return;
    m_start = RTC::micros();
    m_ix = 0;
    return;
  }

  // Calculate the pulse width (both low and high) and check against threshold
  uint32_t stop = RTC::micros();
  uint32_t us = (stop - m_start);
  m_start = stop;
  if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) goto exception;
  m_sample[m_ix & IX_MASK] = us;
  m_ix += 1;

  // Decode every four pulses to a bit
  if ((m_ix & IX_MASK) == 0) {
    int8_t bit = decode_bit();
    if (bit < 0) goto exception;
    m_code = (m_code << 1) | bit;
  }
  if (m_ix != IX_MAX) return;

  // And when all samples have been read push an event
  Event::push(Event::RECEIVE_COMPLETED_TYPE, this);

 exception:
  m_start = 0L;
}

int8_t
NEXA::Receiver::decode_bit()
{
  uint8_t bit;
  // The pedantic version checks even the first pulse. This could be removed
  bit = ((m_sample[0] < BIT_THRESHOLD) << 1) | (m_sample[1] < BIT_THRESHOLD);
  if (bit < 2) return (-1);
  // The second pulse has the actual transmitted bit
  bit = ((m_sample[2] < BIT_THRESHOLD) << 1) | (m_sample[3] < BIT_THRESHOLD);
  if (bit < 2) return (-1);
  // And map back to a bit (2 => 0, 3 => 1)
  return (bit > 2);
}

void
NEXA::Receiver::attach(Listener& device)
{
  device.m_next = m_first;
  m_first = &device;
}

void
NEXA::Receiver::detach(Listener& device)
{
  if (m_first != 0) {
    if (m_first == &device) {
      m_first = device.m_next;
    }
    else {
      Listener* d;
      for (d = m_first; (d->m_next != 0) && (d->m_next != &device); d = d->m_next);
      if (d->m_next != 0) d->m_next = device.m_next;
    }
  }
  device.m_next = 0;
}

void
NEXA::Receiver::dispatch()
{
  code_t cmd = m_code;
  for (Listener* device = m_first; device != 0; device = device->m_next)
    if (cmd == device->m_unit) {
      device->on_change(cmd.onoff);
      if (!cmd.group) return;
    }
}

void
NEXA::Receiver::recv(code_t& cmd)
{
  uint32_t start, stop;
  int32_t bits = 0L;
  uint16_t us;
  uint16_t ix;
  do {
    // Wait for the start condition
    while (is_low());
    stop = RTC::micros();

    // Collect the samples; high followed by low pulse
    ix = 0;
    while (ix < IX_MAX) {
      // Capture length of high period
      start = stop;
      while (is_high());
      stop = RTC::micros();
      us = stop - start;
      if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) break;
      m_sample[ix & IX_MASK] = us;
      ix += 1;
      // Capture length of low period
      start = stop;
      while (is_low());
      stop = RTC::micros();
      us = stop - start;
      if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) break;
      m_sample[ix & IX_MASK] = us;
      ix += 1;
      // Decode every four samples to a code bit
      if ((ix & IX_MASK) == 0) {
	int8_t bit = decode_bit();
	if (bit < 0) break;
	bits = (bits << 1) | bit;
      }
    }
  } while (ix != IX_MAX);
  m_code = bits;
  cmd = bits;
}

void
NEXA::Transmitter::send_code(code_t cmd, int8_t onoff, uint8_t mode)
{
  // Send the code four times with a pause between each
  for (uint8_t i = 0; i < SEND_CODE_MAX; i++) {
    const uint8_t BITS_MAX = 32;
    const uint8_t ONOFF_POS = 27;
    int32_t bits = cmd.as_long;
    // Send start pulse with extended delay, code bits and stop pulse
    send_pulse(0);
    DELAY(START);
    for (uint8_t j = 0; j < BITS_MAX; j++) {
      // Check for dim level (-1..-15)
      if ((j == ONOFF_POS) && (onoff < 0)) {
	send_pulse(0);
	send_pulse(0);
      }
      else send_bit(bits < 0);
      bits <<= 1;
    }
    // Check for dim level transmission; level encoded as -1..-15
    if (onoff < 0) {
      int8_t level = (-onoff) << 4;
      for (uint8_t j = 0; j < 4; j++) {
	send_bit(level < 0);
	level <<= 1;
      }
    }
    send_pulse(0);
    // Wait for the transmission of the code
    uint32_t start = RTC::millis();
    while ((RTC::millis() - start) < PAUSE) Power::sleep(mode);
  }
}
<|endoftext|>


<commit_before>/*
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */
#include "ApplicationFontsWorker.h"
#include "application_generate_fonts.h"

#define ONLYOFFICE_FONTS_VERSION_ 5

CApplicationFontsWorker::CApplicationFontsWorker()
{
    m_bIsUseSystemFonts = true;
    m_bIsNeedThumbnails = true;
    m_bIsUseOpenType    = true;
    m_bIsUseAllVersions = false;
}
CApplicationFontsWorker::~CApplicationFontsWorker()
{

}

NSFonts::IApplicationFonts* CApplicationFontsWorker::Check()
{
    if (m_sDirectory.empty())
        return NULL;

    std::wstring strAllFontsJSPath      = m_sDirectory + L"/AllFonts.js";
    std::wstring strFontsSelectionBin   = m_sDirectory + L"/font_selection.bin";

    std::vector<std::string> strFonts;
    std::wstring strFontsCheckPath = m_sDirectory + L"/fonts.log";

    if (true)
    {
        NSFile::CFileBinary oFile;
        if (oFile.OpenFile(strFontsCheckPath))
        {
            int nSize = oFile.GetFileSize();
            char* pBuffer = new char[nSize];
            DWORD dwReaden = 0;
            oFile.ReadFile((BYTE*)pBuffer, nSize, dwReaden);
            oFile.CloseFile();

            int nStart = 0;
            int nCur = nStart;
            for (; nCur < nSize; ++nCur)
            {
                if (pBuffer[nCur] == '\n')
                {
                    int nEnd = nCur - 1;
                    if (nEnd > nStart)
                    {
                        std::string s(pBuffer + nStart, nEnd - nStart + 1);
                        strFonts.push_back(s);
                    }
                    nStart = nCur + 1;
                }
            }

            delete[] pBuffer;
        }

#ifdef ONLYOFFICE_FONTS_VERSION_
        if (0 != strFonts.size())
        {
            // check version!!!
            std::string sOO_Version = strFonts[0];
            if (0 != sOO_Version.find("ONLYOFFICE_FONTS_VERSION_"))
            {
                strFonts.clear();
            }
            else
            {
                std::string sVersion = sOO_Version.substr(25);
                int nVersion = std::stoi(sVersion);
                if (nVersion != ONLYOFFICE_FONTS_VERSION_)
                    strFonts.clear();
                else
                    strFonts.erase(strFonts.begin());
            }
        }
#endif
    }

    NSFonts::IApplicationFonts* pApplicationF = NSFonts::NSApplication::Create();
    std::vector<std::wstring> strFontsW_Cur;

    if (m_bIsUseSystemFonts)
        strFontsW_Cur = pApplicationF->GetSetupFontFiles();

    for (std::vector<std::wstring>::iterator i = m_arAdditionalFolders.begin(); i != m_arAdditionalFolders.end(); i++)
    {
        NSDirectory::GetFiles2(*i, strFontsW_Cur, true);
    }

    std::sort(strFontsW_Cur.begin(), strFontsW_Cur.end());

    bool bIsEqual = true;
    if (strFonts.size() != strFontsW_Cur.size())
        bIsEqual = false;

    if (bIsEqual)
    {
        int nCount = (int)strFonts.size();
        for (int i = 0; i < nCount; ++i)
        {
            if (strFonts[i] != NSFile::CUtf8Converter::GetUtf8StringFromUnicode2(strFontsW_Cur[i].c_str(), strFontsW_Cur[i].length()))
            {
                bIsEqual = false;
                break;
            }
        }
    }

    if (bIsEqual)
    {
        if (!NSFile::CFileBinary::Exists(strFontsSelectionBin))
            bIsEqual = false;
    }

    if (!bIsEqual)
    {
        if (NSFile::CFileBinary::Exists(strFontsCheckPath))
            NSFile::CFileBinary::Remove(strFontsCheckPath);
        if (NSFile::CFileBinary::Exists(strAllFontsJSPath))
            NSFile::CFileBinary::Remove(strAllFontsJSPath);
        if (NSFile::CFileBinary::Exists(strFontsSelectionBin))
            NSFile::CFileBinary::Remove(strFontsSelectionBin);
        if (NSFile::CFileBinary::Exists(m_sDirectory + L"/fonts_thumbnail.png"))
            NSFile::CFileBinary::Remove(m_sDirectory + L"/fonts_thumbnail.png");
        if (NSFile::CFileBinary::Exists(m_sDirectory + L"/fonts_thumbnail@2x.png"))
            NSFile::CFileBinary::Remove(m_sDirectory + L"/fonts_thumbnail@2x.png");

        int nFlag = 3;
        if (!m_bIsUseOpenType)
            nFlag = 2;

        pApplicationF->InitializeFromArrayFiles(strFontsW_Cur, nFlag);

        NSCommon::SaveAllFontsJS(pApplicationF, strAllFontsJSPath, m_bIsNeedThumbnails ? m_sDirectory : L"", strFontsSelectionBin);

        if (m_bIsUseAllVersions)
        {
            NSCommon::SaveAllFontsJS(pApplicationF, strAllFontsJSPath + L".1", L"", L"", 0);
        }
    }

    NSFile::CFileBinary oFile;
    oFile.CreateFileW(strFontsCheckPath);
#ifdef ONLYOFFICE_FONTS_VERSION_
    oFile.WriteStringUTF8(L"ONLYOFFICE_FONTS_VERSION_");
    oFile.WriteStringUTF8(std::to_wstring(ONLYOFFICE_FONTS_VERSION_));
    oFile.WriteFile((BYTE*)"\n", 1);
#endif
    int nCount = (int)strFontsW_Cur.size();
    for (int i = 0; i < nCount; ++i)
    {
        oFile.WriteStringUTF8(strFontsW_Cur[i]);
        oFile.WriteFile((BYTE*)"\n", 1);
    }
    oFile.CloseFile();

    pApplicationF->Release();
    pApplicationF = NSFonts::NSApplication::Create();
    pApplicationF->InitializeFromFolder(m_sDirectory);

    return pApplicationF;
}

std::string CApplicationFontsWorker::GetAllFonts()
{
    std::string sAllFonts = "";
    NSFile::CFileBinary::ReadAllTextUtf8A(m_sDirectory + L"/AllFonts.js", sAllFonts);
    return sAllFonts;
}

std::vector<std::wstring> CApplicationFontsWorker::GetFontNames(NSFonts::IApplicationFonts* pFonts)
{
    std::vector<std::wstring> arNames;
    if (!pFonts || !pFonts->GetList())
        return arNames;
    std::vector<NSFonts::CFontInfo*>* arInfos = pFonts->GetList()->GetFonts();

    std::map<std::wstring, bool> map;

    for (std::vector<NSFonts::CFontInfo*>::iterator iter = arInfos->begin(); iter != arInfos->end(); iter++)
    {
        if (map.find((*iter)->m_wsFontName) == map.end())
            arNames.push_back((*iter)->m_wsFontName);
    }

    std::sort(arNames.begin(), arNames.end());
    return arNames;
}

std::vector<std::wstring> CApplicationFontsWorker::GetFontNamesWithExcludes(NSFonts::IApplicationFonts* pFonts, std::vector<std::wstring> excludes)
{
    std::vector<std::wstring> arNames;

    if (!pFonts || !pFonts->GetList())
        return arNames;

    std::vector<NSFonts::CFontInfo*>* arInfos = pFonts->GetList()->GetFonts();

    std::map<std::wstring, bool> map;

    for (std::vector<NSFonts::CFontInfo*>::iterator iter = arInfos->begin(); iter != arInfos->end(); iter++)
    {
        std::wstring fontName = (*iter)->m_wsFontName;

        bool isExclude = false;
        for (size_t i = 0; i < excludes.size(); ++i) {
            if (fontName.find(excludes[i]) != std::string::npos) {
                isExclude = true;
                break;
            }
        }

        if (isExclude) {
            continue;
        }

        if (map.find(fontName) == map.end()) {
            arNames.push_back(fontName);
            map[fontName] = true;
        }
    }

    std::sort(arNames.begin(), arNames.end());

    return arNames;
}
<commit_msg>Fix sysyem fonts checker<commit_after>/*
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */
#include "ApplicationFontsWorker.h"
#include "application_generate_fonts.h"

#define ONLYOFFICE_FONTS_VERSION_ 5

CApplicationFontsWorker::CApplicationFontsWorker()
{
    m_bIsUseSystemFonts = true;
    m_bIsNeedThumbnails = true;
    m_bIsUseOpenType    = true;
    m_bIsUseAllVersions = false;
}
CApplicationFontsWorker::~CApplicationFontsWorker()
{

}

NSFonts::IApplicationFonts* CApplicationFontsWorker::Check()
{
    if (m_sDirectory.empty())
        return NULL;

    std::wstring strAllFontsJSPath      = m_sDirectory + L"/AllFonts.js";
    std::wstring strFontsSelectionBin   = m_sDirectory + L"/font_selection.bin";

    std::vector<std::string> strFonts;
    std::wstring strFontsCheckPath = m_sDirectory + L"/fonts.log";

    if (true)
    {
        NSFile::CFileBinary oFile;
        if (oFile.OpenFile(strFontsCheckPath))
        {
            int nSize = oFile.GetFileSize();
            char* pBuffer = new char[nSize];
            DWORD dwReaden = 0;
            oFile.ReadFile((BYTE*)pBuffer, nSize, dwReaden);
            oFile.CloseFile();

            int nStart = 0;
            int nCur = nStart;
            for (; nCur < nSize; ++nCur)
            {
                if (pBuffer[nCur] == '\n')
                {
                    int nEnd = nCur - 1;
                    if (nEnd > nStart)
                    {
                        std::string s(pBuffer + nStart, nEnd - nStart + 1);
                        strFonts.push_back(s);
                    }
                    nStart = nCur + 1;
                }
            }

            delete[] pBuffer;
        }

#ifdef ONLYOFFICE_FONTS_VERSION_
        if (0 != strFonts.size())
        {
            // check version!!!
            std::string sOO_Version = strFonts[0];
            if (0 != sOO_Version.find("ONLYOFFICE_FONTS_VERSION_"))
            {
                strFonts.clear();
            }
            else
            {
                std::string sVersion = sOO_Version.substr(25);
                int nVersion = std::stoi(sVersion);
                if (nVersion != ONLYOFFICE_FONTS_VERSION_)
                    strFonts.clear();
                else
                    strFonts.erase(strFonts.begin());
            }
        }
#endif
    }

    NSFonts::IApplicationFonts* pApplicationF = NSFonts::NSApplication::Create();
    std::vector<std::wstring> strFontsW_Cur;

    if (m_bIsUseSystemFonts)
        strFontsW_Cur = pApplicationF->GetSetupFontFiles();

    for (std::vector<std::wstring>::iterator i = m_arAdditionalFolders.begin(); i != m_arAdditionalFolders.end(); i++)
    {
        NSDirectory::GetFiles2(*i, strFontsW_Cur, true);
    }

    std::sort(strFontsW_Cur.begin(), strFontsW_Cur.end());

    bool bIsEqual = true;
    if (strFonts.size() != strFontsW_Cur.size())
        bIsEqual = false;

    if (bIsEqual)
    {
        int nCount = (int)strFonts.size();
        for (int i = 0; i < nCount; ++i)
        {
            if (strFonts[i] != NSFile::CUtf8Converter::GetUtf8StringFromUnicode2(strFontsW_Cur[i].c_str(), strFontsW_Cur[i].length()))
            {
                bIsEqual = false;
                break;
            }
        }
    }

    if (bIsEqual)
    {
        if (!NSFile::CFileBinary::Exists(strFontsSelectionBin))
            bIsEqual = false;
    }

    if (!bIsEqual)
    {
        if (NSFile::CFileBinary::Exists(strFontsCheckPath))
            NSFile::CFileBinary::Remove(strFontsCheckPath);
        if (NSFile::CFileBinary::Exists(strAllFontsJSPath))
            NSFile::CFileBinary::Remove(strAllFontsJSPath);
        if (NSFile::CFileBinary::Exists(strFontsSelectionBin))
            NSFile::CFileBinary::Remove(strFontsSelectionBin);
        if (NSFile::CFileBinary::Exists(m_sDirectory + L"/fonts_thumbnail.png"))
            NSFile::CFileBinary::Remove(m_sDirectory + L"/fonts_thumbnail.png");
        if (NSFile::CFileBinary::Exists(m_sDirectory + L"/fonts_thumbnail@2x.png"))
            NSFile::CFileBinary::Remove(m_sDirectory + L"/fonts_thumbnail@2x.png");

        int nFlag = 3;
        if (!m_bIsUseOpenType)
            nFlag = 2;

        NSStringUtils::CStringBuilder oFontsLog;
#ifdef ONLYOFFICE_FONTS_VERSION_
        oFontsLog.WriteString(L"ONLYOFFICE_FONTS_VERSION_");
        oFontsLog.WriteString(std::to_wstring(ONLYOFFICE_FONTS_VERSION_));
        oFontsLog.WriteString(L"\n");
#endif
        int nCount = (int)strFontsW_Cur.size();
        for (int i = 0; i < nCount; ++i)
        {
            oFontsLog.WriteString(strFontsW_Cur[i]);
            oFontsLog.WriteString(L"\n");
        }

        pApplicationF->InitializeFromArrayFiles(strFontsW_Cur, nFlag);

        NSCommon::SaveAllFontsJS(pApplicationF, strAllFontsJSPath, m_bIsNeedThumbnails ? m_sDirectory : L"", strFontsSelectionBin);

        if (m_bIsUseAllVersions)
        {
            NSCommon::SaveAllFontsJS(pApplicationF, strAllFontsJSPath + L".1", L"", L"", 0);
        }

        NSFile::CFileBinary::SaveToFile(strFontsCheckPath, oFontsLog.GetData());
    }

    pApplicationF->Release();
    pApplicationF = NSFonts::NSApplication::Create();
    pApplicationF->InitializeFromFolder(m_sDirectory);

    return pApplicationF;
}

std::string CApplicationFontsWorker::GetAllFonts()
{
    std::string sAllFonts = "";
    NSFile::CFileBinary::ReadAllTextUtf8A(m_sDirectory + L"/AllFonts.js", sAllFonts);
    return sAllFonts;
}

std::vector<std::wstring> CApplicationFontsWorker::GetFontNames(NSFonts::IApplicationFonts* pFonts)
{
    std::vector<std::wstring> arNames;
    if (!pFonts || !pFonts->GetList())
        return arNames;
    std::vector<NSFonts::CFontInfo*>* arInfos = pFonts->GetList()->GetFonts();

    std::map<std::wstring, bool> map;

    for (std::vector<NSFonts::CFontInfo*>::iterator iter = arInfos->begin(); iter != arInfos->end(); iter++)
    {
        if (map.find((*iter)->m_wsFontName) == map.end())
            arNames.push_back((*iter)->m_wsFontName);
    }

    std::sort(arNames.begin(), arNames.end());
    return arNames;
}

std::vector<std::wstring> CApplicationFontsWorker::GetFontNamesWithExcludes(NSFonts::IApplicationFonts* pFonts, std::vector<std::wstring> excludes)
{
    std::vector<std::wstring> arNames;

    if (!pFonts || !pFonts->GetList())
        return arNames;

    std::vector<NSFonts::CFontInfo*>* arInfos = pFonts->GetList()->GetFonts();

    std::map<std::wstring, bool> map;

    for (std::vector<NSFonts::CFontInfo*>::iterator iter = arInfos->begin(); iter != arInfos->end(); iter++)
    {
        std::wstring fontName = (*iter)->m_wsFontName;

        bool isExclude = false;
        for (size_t i = 0; i < excludes.size(); ++i) {
            if (fontName.find(excludes[i]) != std::string::npos) {
                isExclude = true;
                break;
            }
        }

        if (isExclude) {
            continue;
        }

        if (map.find(fontName) == map.end()) {
            arNames.push_back(fontName);
            map[fontName] = true;
        }
    }

    std::sort(arNames.begin(), arNames.end());

    return arNames;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <tuple>
#include <condition_variable>

#include "input_file_reader.hpp"
#include "minimize.hpp"
#include "comparator.hpp"
#include "result.hpp"

// mutex for shared resources
static std::mutex g_resource_mutex;

// mutex for result vector
static std::mutex g_result_mutex;

// global queue with two pointers to the sequences
// they are compared directly if the both sequence lengths are small enough
static std::queue<std::tuple<uint32_t, OLC::Sequence*, uint32_t, OLC::Sequence*>> g_sequence_pairs;

// global queue with two pointers to vectors of minimizers
// we use this instead if the sequences are too long
static std::queue<std::tuple<uint32_t, std::vector<OLC::Minimizer>*, uint32_t, std::vector<OLC::Minimizer>*>> g_minimizer_pairs;

// global vector with results
static std::vector<OLC::Result*> g_results;

void worker()
{
  while(true)
  {
    // Get the task and remove it from the pool
    uint32_t first_read_number;
    OLC::Sequence* first_sequence;
    std::vector<OLC::Minimizer>* first_minimizer;

    uint32_t second_read_number;
    OLC::Sequence* second_sequence;
    std::vector<OLC::Minimizer>* second_minimizer;

    {
      std::lock_guard<std::mutex> resource_lock(g_resource_mutex);

      if (g_sequence_pairs.empty())
        return;

      std::tie(first_read_number, first_sequence, second_read_number, second_sequence) = g_sequence_pairs.front();
      g_sequence_pairs.pop();
      std::tie(first_read_number, first_minimizer, second_read_number, second_minimizer) = g_minimizer_pairs.front();
      g_minimizer_pairs.pop();
    }

    // Pull out the wrapped nucleotide vectors
    const std::vector<OLC::Nucleotide> nucleotides1 = first_sequence->getNucleotides()->getSequence();
    const std::vector<OLC::Nucleotide> nucleotides2 = second_sequence->getNucleotides()->getSequence();

    // If small enough, no need to use minimizers
    if (nucleotides1.size() < 20000 && nucleotides2.size() < 20000)
    {
      const OLC::Overlap overlap = compare(nucleotides1, nucleotides2);
      const uint32_t overlapFirstEnd = overlap.getEndFirst();
      const uint32_t overlapSecondEnd = overlap.getEndSecond();
      const uint32_t overlapFirstStart = overlap.getStartFirst();
      const uint32_t overlapSecondStart = overlap.getStartSecond();
      const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1;

      int32_t ahang = overlapFirstStart;
      int32_t bhang = nucleotides2.size() - overlapSecondEnd;

      if (overlapSecondStart > overlapFirstStart)
        ahang *= -1;

      if (nucleotides1.size() > overlapSecondEnd)
        bhang *= -1;

      OLC::Result* result = new OLC::Result(first_read_number, second_read_number, overlapLength, ahang, bhang);

      {
        std::lock_guard<std::mutex> result_lock(g_result_mutex);
        g_results.push_back(result);
      }
    }
    else
    {

    }
  }
}

int main(int argc, char** argv)
{
  std::ios_base::sync_with_stdio(false);

  if (argc != 3)
  {
    std::cout << "Usage: " << argv[0] << " <minimum overlap length L> <FASTQ or FASTA file>\n";
    return 1;
  }

  // file with the data
  const std::string file = std::string(argv[2]);

  // L is the minimum overlap length
  const uint32_t L = std::stoi(argv[1]);

  // window size
  const uint32_t w = (L + 1) / 2;

  // size of the k-mer
  const uint32_t k = (L + 1) / 2;

  // read phase
  OLC::InputFileReader reader(file);
  const std::vector<OLC::Sequence*> sequences = reader.readSequences();
  std::vector<std::vector<OLC::Minimizer>> minimizers;

  for (size_t i = 0; i < sequences.size(); ++i)
  {
    const auto sequence = sequences[i]->getNucleotides()->getSequence();

    // calculate minimizers - both interior and end minimizers
    minimizers.push_back(minimize(sequence, w, k));
  }

  // generate tasks so we can do this in parallel if possible
  std::queue<std::tuple<uint32_t, uint32_t>> tasks;

  for (uint32_t i = 0; i < sequences.size(); ++i)
  {
    for (uint32_t j = i + 1; j < sequences.size(); ++j)
    {
      g_sequence_pairs.emplace(i, sequences[i], j, sequences[j]);
      g_minimizer_pairs.emplace(i, &minimizers[i], j, &minimizers[j]);
    }
  }

  // use concurrent minimizer matching
  std::vector<std::thread> threads(std::thread::hardware_concurrency());

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i] = std::thread(worker);

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i].join();

  // cleanup
  for (size_t i = 0; i < sequences.size(); ++i)
    delete sequences[i];

  for (size_t i = 0; i < g_results.size(); ++i)
    delete g_results[i];

  return 0;
}
<commit_msg>main: print out results and fix read identifiers<commit_after>#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <tuple>
#include <condition_variable>

#include "input_file_reader.hpp"
#include "minimize.hpp"
#include "comparator.hpp"
#include "result.hpp"

// mutex for shared resources
static std::mutex g_resource_mutex;

// mutex for result vector
static std::mutex g_result_mutex;

// global queue with two pointers to the sequences
// they are compared directly if the both sequence lengths are small enough
static std::queue<std::tuple<uint32_t, OLC::Sequence*, uint32_t, OLC::Sequence*>> g_sequence_pairs;

// global queue with two pointers to vectors of minimizers
// we use this instead if the sequences are too long
static std::queue<std::tuple<uint32_t, std::vector<OLC::Minimizer>*, uint32_t, std::vector<OLC::Minimizer>*>> g_minimizer_pairs;

// global vector with results
static std::vector<OLC::Result*> g_results;

void worker()
{
  while(true)
  {
    // Get the task and remove it from the pool
    uint32_t first_read_number;
    OLC::Sequence* first_sequence;
    std::vector<OLC::Minimizer>* first_minimizer;

    uint32_t second_read_number;
    OLC::Sequence* second_sequence;
    std::vector<OLC::Minimizer>* second_minimizer;

    {
      std::lock_guard<std::mutex> resource_lock(g_resource_mutex);

      if (g_sequence_pairs.empty())
        return;

      std::tie(first_read_number, first_sequence, second_read_number, second_sequence) = g_sequence_pairs.front();
      g_sequence_pairs.pop();
      std::tie(first_read_number, first_minimizer, second_read_number, second_minimizer) = g_minimizer_pairs.front();
      g_minimizer_pairs.pop();
    }

    // Pull out the wrapped nucleotide vectors
    const std::vector<OLC::Nucleotide> nucleotides1 = first_sequence->getNucleotides()->getSequence();
    const std::vector<OLC::Nucleotide> nucleotides2 = second_sequence->getNucleotides()->getSequence();

    // If small enough, no need to use minimizers
    if (nucleotides1.size() < 20000 && nucleotides2.size() < 20000)
    {
      const OLC::Overlap overlap = compare(nucleotides1, nucleotides2);
      const uint32_t overlapFirstEnd = overlap.getEndFirst();
      const uint32_t overlapSecondEnd = overlap.getEndSecond();
      const uint32_t overlapFirstStart = overlap.getStartFirst();
      const uint32_t overlapSecondStart = overlap.getStartSecond();
      const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1;

      int32_t ahang = overlapFirstStart;
      int32_t bhang = nucleotides2.size() - overlapSecondEnd;

      if (overlapSecondStart > overlapFirstStart)
        ahang *= -1;

      if (nucleotides1.size() > overlapSecondEnd)
        bhang *= -1;

      OLC::Result* result = new OLC::Result(first_read_number, second_read_number, overlapLength, ahang, bhang);

      {
        std::lock_guard<std::mutex> result_lock(g_result_mutex);
        g_results.push_back(result);
      }
    }
    else
    {

    }
  }
}

int main(int argc, char** argv)
{
  std::ios_base::sync_with_stdio(false);

  if (argc != 3)
  {
    std::cout << "Usage: " << argv[0] << " <minimum overlap length L> <FASTQ or FASTA file>\n";
    return 1;
  }

  // file with the data
  const std::string file = std::string(argv[2]);

  // L is the minimum overlap length
  const uint32_t L = std::stoi(argv[1]);

  // window size
  const uint32_t w = (L + 1) / 2;

  // size of the k-mer
  const uint32_t k = (L + 1) / 2;

  // read phase
  OLC::InputFileReader reader(file);
  const std::vector<OLC::Sequence*> sequences = reader.readSequences();
  std::vector<std::vector<OLC::Minimizer>> minimizers;

  for (size_t i = 0; i < sequences.size(); ++i)
  {
    const auto sequence = sequences[i]->getNucleotides()->getSequence();

    // calculate minimizers - both interior and end minimizers
    minimizers.push_back(minimize(sequence, w, k));
  }

  // generate tasks so we can do this in parallel if possible
  std::queue<std::tuple<uint32_t, uint32_t>> tasks;

  for (uint32_t i = 0; i < sequences.size(); ++i)
  {
    for (uint32_t j = i + 1; j < sequences.size(); ++j)
    {
      g_sequence_pairs.emplace(i + 1, sequences[i], j + 1, sequences[j]);
      g_minimizer_pairs.emplace(i + 1, &minimizers[i], j + 1, &minimizers[j]);
    }
  }

  // use concurrent minimizer matching
  std::vector<std::thread> threads(std::thread::hardware_concurrency());

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i] = std::thread(worker);

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i].join();

  for (size_t i = 0; i < g_results.size(); ++i)
  {
    auto identifiers = g_results[i]->getIdentifiers();

    std::cout << "Found overlap with length of " << g_results[i]->getLength() << " between " << std::get<0>(identifiers) << " and " << std::get<1>(identifiers) << "\n";
  }

  // cleanup
  for (size_t i = 0; i < sequences.size(); ++i)
    delete sequences[i];

  for (size_t i = 0; i < g_results.size(); ++i)
    delete g_results[i];

  return 0;
}
<|endoftext|>